[BUGFIX] "Show page" does not use a proper URL scheme
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_befunc.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 1999-2011 Kasper Skårhøj (kasperYYYY@typo3.com)
6 * All rights reserved
7 *
8 * This script is part of the TYPO3 project. The TYPO3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
16 * A copy is found in the textfile GPL.txt and important notices to the license
17 * from the author is found in LICENSE.txt distributed with these scripts.
18 *
19 *
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27
28 /**
29 * Standard functions available for the TYPO3 backend.
30 * You are encouraged to use this class in your own applications (Backend Modules)
31 * Don't instantiate - call functions with "t3lib_BEfunc::" prefixed the function name.
32 *
33 * Call ALL methods without making an object!
34 * Eg. to get a page-record 51 do this: 't3lib_BEfunc::getRecord('pages',51)'
35 *
36 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
37 * @package TYPO3
38 * @subpackage t3lib
39 */
40 final class t3lib_BEfunc {
41
42 /*******************************************
43 *
44 * SQL-related, selecting records, searching
45 *
46 *******************************************/
47
48
49 /**
50 * Returns the WHERE clause " AND NOT [tablename].[deleted-field]" if a deleted-field is configured in $GLOBALS['TCA'] for the tablename, $table
51 * This function should ALWAYS be called in the backend for selection on tables which are configured in $GLOBALS['TCA'] since it will ensure consistent selection of records, even if they are marked deleted (in which case the system must always treat them as non-existent!)
52 * In the frontend a function, ->enableFields(), is known to filter hidden-field, start- and endtime and fe_groups as well. But that is a job of the frontend, not the backend. If you need filtering on those fields as well in the backend you can use ->BEenableFields() though.
53 *
54 * @param string Table name present in $GLOBALS['TCA']
55 * @param string Table alias if any
56 * @return string WHERE clause for filtering out deleted records, eg " AND tablename.deleted=0"
57 */
58 public static function deleteClause($table, $tableAlias = '') {
59 if ($GLOBALS['TCA'][$table]['ctrl']['delete']) {
60 return ' AND ' . ($tableAlias ? $tableAlias : $table) . '.' . $GLOBALS['TCA'][$table]['ctrl']['delete'] . '=0';
61 } else {
62 return '';
63 }
64 }
65
66 /**
67 * Gets record with uid = $uid from $table
68 * You can set $field to a list of fields (default is '*')
69 * Additional WHERE clauses can be added by $where (fx. ' AND blabla = 1')
70 * Will automatically check if records has been deleted and if so, not return anything.
71 * $table must be found in $GLOBALS['TCA']
72 *
73 * @param string Table name present in $GLOBALS['TCA']
74 * @param integer UID of record
75 * @param string List of fields to select
76 * @param string Additional WHERE clause, eg. " AND blablabla = 0"
77 * @param boolean Use the deleteClause to check if a record is deleted (default TRUE)
78 * @return array Returns the row if found, otherwise nothing
79 */
80 public static function getRecord($table, $uid, $fields = '*', $where = '', $useDeleteClause = TRUE) {
81 if ($GLOBALS['TCA'][$table]) {
82 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
83 $fields,
84 $table,
85 'uid=' . intval($uid) . ($useDeleteClause ? self::deleteClause($table) : '') . $where
86 );
87 $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
88 $GLOBALS['TYPO3_DB']->sql_free_result($res);
89 if ($row) {
90 return $row;
91 }
92 }
93 }
94
95 /**
96 * Like getRecord(), but overlays workspace version if any.
97 *
98 * @param string Table name present in $GLOBALS['TCA']
99 * @param integer UID of record
100 * @param string List of fields to select
101 * @param string Additional WHERE clause, eg. " AND blablabla = 0"
102 * @param boolean Use the deleteClause to check if a record is deleted (default TRUE)
103 * @param boolean If TRUE the function does not return a "pointer" row for moved records in a workspace
104 * @return array Returns the row if found, otherwise nothing
105 */
106 public static function getRecordWSOL($table, $uid, $fields = '*', $where = '', $useDeleteClause = TRUE, $unsetMovePointers = FALSE) {
107 if ($fields !== '*') {
108 $internalFields = t3lib_div::uniqueList($fields . ',uid,pid' . ($table == 'pages' ? ',t3ver_swapmode' : ''));
109 $row = self::getRecord($table, $uid, $internalFields, $where, $useDeleteClause);
110 self::workspaceOL($table, $row, -99, $unsetMovePointers);
111
112 if (is_array($row)) {
113 foreach (array_keys($row) as $key) {
114 if (!t3lib_div::inList($fields, $key) && $key{0} !== '_') {
115 unset ($row[$key]);
116 }
117 }
118 }
119 } else {
120 $row = self::getRecord($table, $uid, $fields, $where, $useDeleteClause);
121 self::workspaceOL($table, $row, -99, $unsetMovePointers);
122 }
123 return $row;
124 }
125
126 /**
127 * Returns the first record found from $table with $where as WHERE clause
128 * This function does NOT check if a record has the deleted flag set.
129 * $table does NOT need to be configured in $GLOBALS['TCA']
130 * The query used is simply this:
131 * $query = 'SELECT '.$fields.' FROM '.$table.' WHERE '.$where;
132 *
133 * @param string Table name (not necessarily in TCA)
134 * @param string WHERE clause
135 * @param string $fields is a list of fields to select, default is '*'
136 * @return array First row found, if any, FALSE otherwise
137 */
138 public static function getRecordRaw($table, $where = '', $fields = '*') {
139 $row = FALSE;
140 if (FALSE !== ($res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fields, $table, $where, '', '', '1'))) {
141 $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
142 $GLOBALS['TYPO3_DB']->sql_free_result($res);
143 }
144 return $row;
145 }
146
147 /**
148 * Returns records from table, $theTable, where a field ($theField) equals the value, $theValue
149 * The records are returned in an array
150 * If no records were selected, the function returns nothing
151 *
152 * @param string Table name present in $GLOBALS['TCA']
153 * @param string Field to select on
154 * @param string Value that $theField must match
155 * @param string Optional additional WHERE clauses put in the end of the query. DO NOT PUT IN GROUP BY, ORDER BY or LIMIT!
156 * @param string Optional GROUP BY field(s), if none, supply blank string.
157 * @param string Optional ORDER BY field(s), if none, supply blank string.
158 * @param string Optional LIMIT value ([begin,]max), if none, supply blank string.
159 * @param boolean Use the deleteClause to check if a record is deleted (default TRUE)
160 * @return mixed Multidimensional array with selected records (if any is selected)
161 */
162 public static function getRecordsByField($theTable, $theField, $theValue, $whereClause = '', $groupBy = '', $orderBy = '', $limit = '', $useDeleteClause = TRUE) {
163 if (is_array($GLOBALS['TCA'][$theTable])) {
164 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
165 '*',
166 $theTable,
167 $theField . '=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($theValue, $theTable) .
168 ($useDeleteClause ? self::deleteClause($theTable) . ' ' : '') .
169 self::versioningPlaceholderClause($theTable) . ' ' .
170 $whereClause, // whereClauseMightContainGroupOrderBy
171 $groupBy,
172 $orderBy,
173 $limit
174 );
175 $rows = array();
176 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
177 $rows[] = $row;
178 }
179 $GLOBALS['TYPO3_DB']->sql_free_result($res);
180 if (count($rows)) {
181 return $rows;
182 }
183 }
184 }
185
186 /**
187 * Makes an backwards explode on the $str and returns an array with ($table, $uid).
188 * Example: tt_content_45 => array('tt_content', 45)
189 *
190 * @param string [tablename]_[uid] string to explode
191 * @return array
192 */
193 public static function splitTable_Uid($str) {
194 list($uid, $table) = explode('_', strrev($str), 2);
195 return array(strrev($table), strrev($uid));
196 }
197
198 /**
199 * Returns a list of pure integers based on $in_list being a list of records with table-names prepended.
200 * Ex: $in_list = "pages_4,tt_content_12,45" would result in a return value of "4,45" if $tablename is "pages" and $default_tablename is 'pages' as well.
201 *
202 * @param string Input list
203 * @param string Table name from which ids is returned
204 * @param string $default_tablename denotes what table the number '45' is from (if nothing is prepended on the value)
205 * @return string List of ids
206 */
207 public static function getSQLselectableList($in_list, $tablename, $default_tablename) {
208 $list = Array();
209 if ((string) trim($in_list) != '') {
210 $tempItemArray = explode(',', trim($in_list));
211 foreach ($tempItemArray as $key => $val) {
212 $val = strrev($val);
213 $parts = explode('_', $val, 2);
214 if ((string) trim($parts[0]) != '') {
215 $theID = intval(strrev($parts[0]));
216 $theTable = trim($parts[1]) ? strrev(trim($parts[1])) : $default_tablename;
217 if ($theTable == $tablename) {
218 $list[] = $theID;
219 }
220 }
221 }
222 }
223 return implode(',', $list);
224 }
225
226 /**
227 * Backend implementation of enableFields()
228 * Notice that "fe_groups" is not selected for - only disabled, starttime and endtime.
229 * Notice that deleted-fields are NOT filtered - you must ALSO call deleteClause in addition.
230 * $GLOBALS["SIM_ACCESS_TIME"] is used for date.
231 *
232 * @param string $table is the table from which to return enableFields WHERE clause. Table name must have a 'ctrl' section in $GLOBALS['TCA'].
233 * @param boolean $inv means that the query will select all records NOT VISIBLE records (inverted selection)
234 * @return string WHERE clause part
235 */
236 public static function BEenableFields($table, $inv = 0) {
237 $ctrl = $GLOBALS['TCA'][$table]['ctrl'];
238 $query = array();
239 $invQuery = array();
240 if (is_array($ctrl)) {
241 if (is_array($ctrl['enablecolumns'])) {
242 if ($ctrl['enablecolumns']['disabled']) {
243 $field = $table . '.' . $ctrl['enablecolumns']['disabled'];
244 $query[] = $field . '=0';
245 $invQuery[] = $field . '!=0';
246 }
247 if ($ctrl['enablecolumns']['starttime']) {
248 $field = $table . '.' . $ctrl['enablecolumns']['starttime'];
249 $query[] = '(' . $field . '<=' . $GLOBALS['SIM_ACCESS_TIME'] . ')';
250 $invQuery[] = '(' . $field . '!=0 AND ' . $field . '>' . $GLOBALS['SIM_ACCESS_TIME'] . ')';
251 }
252 if ($ctrl['enablecolumns']['endtime']) {
253 $field = $table . '.' . $ctrl['enablecolumns']['endtime'];
254 $query[] = '(' . $field . '=0 OR ' . $field . '>' . $GLOBALS['SIM_ACCESS_TIME'] . ')';
255 $invQuery[] = '(' . $field . '!=0 AND ' . $field . '<=' . $GLOBALS['SIM_ACCESS_TIME'] . ')';
256 }
257 }
258 }
259 $outQ = ($inv ? '(' . implode(' OR ', $invQuery) . ')' : implode(' AND ', $query));
260
261 return $outQ ? ' AND ' . $outQ : '';
262 }
263
264 /**
265 * Fetches the localization for a given record.
266 *
267 * @param string $table: Table name present in $GLOBALS['TCA']
268 * @param integer $uid: The uid of the record
269 * @param integer $language: The uid of the language record in sys_language
270 * @param string $andWhereClause: Optional additional WHERE clause (default: '')
271 * @return mixed Multidimensional array with selected records; if none exist, FALSE is returned
272 */
273 public static function getRecordLocalization($table, $uid, $language, $andWhereClause = '') {
274 $recordLocalization = FALSE;
275 if (self::isTableLocalizable($table)) {
276 $tcaCtrl = $GLOBALS['TCA'][$table]['ctrl'];
277 $recordLocalization = self::getRecordsByField(
278 $table,
279 $tcaCtrl['transOrigPointerField'],
280 $uid,
281 'AND ' . $tcaCtrl['languageField'] . '=' . intval($language) . ($andWhereClause ? ' ' . $andWhereClause : ''),
282 '',
283 '',
284 '1'
285 );
286 }
287 return $recordLocalization;
288 }
289
290
291 /*******************************************
292 *
293 * Page tree, TCA related
294 *
295 *******************************************/
296
297 /**
298 * Returns what is called the 'RootLine'. That is an array with information about the page records from a page id ($uid) and back to the root.
299 * By default deleted pages are filtered.
300 * This RootLine will follow the tree all the way to the root. This is opposite to another kind of root line known from the frontend where the rootline stops when a root-template is found.
301 *
302 * @param integer Page id for which to create the root line.
303 * @param string $clause can be used to select other criteria. It would typically be where-clauses that stops the process if we meet a page, the user has no reading access to.
304 * @param boolean If TRUE, version overlay is applied. This must be requested specifically because it is usually only wanted when the rootline is used for visual output while for permission checking you want the raw thing!
305 * @return array Root line array, all the way to the page tree root (or as far as $clause allows!)
306 */
307 public static function BEgetRootLine($uid, $clause = '', $workspaceOL = FALSE) {
308 static $BEgetRootLine_cache = array();
309
310 $output = array();
311 $pid = $uid;
312 $ident = $pid . '-' . $clause . '-' . $workspaceOL;
313
314 if (is_array($BEgetRootLine_cache[$ident])) {
315 $output = $BEgetRootLine_cache[$ident];
316 } else {
317 $loopCheck = 100;
318 $theRowArray = array();
319 while ($uid != 0 && $loopCheck) {
320 $loopCheck--;
321 $row = self::getPageForRootline($uid, $clause, $workspaceOL);
322 if (is_array($row)) {
323 $uid = $row['pid'];
324 $theRowArray[] = $row;
325 } else {
326 break;
327 }
328 }
329 if ($uid == 0) {
330 $theRowArray[] = array('uid' => 0, 'title' => '');
331 }
332 $c = count($theRowArray);
333
334 foreach ($theRowArray as $val) {
335 $c--;
336 $output[$c] = array(
337 'uid' => $val['uid'],
338 'pid' => $val['pid'],
339 'title' => $val['title'],
340 'TSconfig' => $val['TSconfig'],
341 'is_siteroot' => $val['is_siteroot'],
342 'storage_pid' => $val['storage_pid'],
343 't3ver_oid' => $val['t3ver_oid'],
344 't3ver_wsid' => $val['t3ver_wsid'],
345 't3ver_state' => $val['t3ver_state'],
346 't3ver_swapmode' => $val['t3ver_swapmode'],
347 't3ver_stage' => $val['t3ver_stage'],
348 'backend_layout_next_level' => $val['backend_layout_next_level']
349 );
350 if (isset($val['_ORIG_pid'])) {
351 $output[$c]['_ORIG_pid'] = $val['_ORIG_pid'];
352 }
353 }
354 $BEgetRootLine_cache[$ident] = $output;
355 }
356 return $output;
357 }
358
359 /**
360 * Gets the cached page record for the rootline
361 *
362 * @param integer $uid: Page id for which to create the root line.
363 * @param string $clause: can be used to select other criteria. It would typically be where-clauses that stops the process if we meet a page, the user has no reading access to.
364 * @param boolean $workspaceOL: If TRUE, version overlay is applied. This must be requested specifically because it is usually only wanted when the rootline is used for visual output while for permission checking you want the raw thing!
365 * @return array Cached page record for the rootline
366 * @see BEgetRootLine
367 */
368 protected static function getPageForRootline($uid, $clause, $workspaceOL) {
369 static $getPageForRootline_cache = array();
370 $ident = $uid . '-' . $clause . '-' . $workspaceOL;
371
372 if (is_array($getPageForRootline_cache[$ident])) {
373 $row = $getPageForRootline_cache[$ident];
374 } else {
375 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
376 'pid,uid,title,TSconfig,is_siteroot,storage_pid,t3ver_oid,t3ver_wsid,t3ver_state,t3ver_swapmode,t3ver_stage,backend_layout_next_level',
377 'pages',
378 'uid=' . intval($uid) . ' ' .
379 self::deleteClause('pages') . ' ' .
380 $clause // whereClauseMightContainGroupOrderBy
381 );
382
383 $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
384 if ($row) {
385 if ($workspaceOL) {
386 self::workspaceOL('pages', $row);
387 }
388 if (is_array($row)) {
389 self::fixVersioningPid('pages', $row);
390 $getPageForRootline_cache[$ident] = $row;
391 }
392 }
393 $GLOBALS['TYPO3_DB']->sql_free_result($res);
394 }
395 return $row;
396 }
397
398 /**
399 * Opens the page tree to the specified page id
400 *
401 * @param integer Page id.
402 * @param boolean If set, then other open branches are closed.
403 * @return void
404 */
405 public static function openPageTree($pid, $clearExpansion) {
406
407 // Get current expansion data:
408 if ($clearExpansion) {
409 $expandedPages = array();
410 } else {
411 $expandedPages = unserialize($GLOBALS['BE_USER']->uc['browseTrees']['browsePages']);
412 }
413
414 // Get rootline:
415 $rL = self::BEgetRootLine($pid);
416
417 // First, find out what mount index to use (if more than one DB mount exists):
418 $mountIndex = 0;
419 $mountKeys = array_flip($GLOBALS['BE_USER']->returnWebmounts());
420 foreach ($rL as $rLDat) {
421 if (isset($mountKeys[$rLDat['uid']])) {
422 $mountIndex = $mountKeys[$rLDat['uid']];
423 break;
424 }
425 }
426
427 // Traverse rootline and open paths:
428 foreach ($rL as $rLDat) {
429 $expandedPages[$mountIndex][$rLDat['uid']] = 1;
430 }
431
432 // Write back:
433 $GLOBALS['BE_USER']->uc['browseTrees']['browsePages'] = serialize($expandedPages);
434 $GLOBALS['BE_USER']->writeUC();
435 }
436
437 /**
438 * Returns the path (visually) of a page $uid, fx. "/First page/Second page/Another subpage"
439 * Each part of the path will be limited to $titleLimit characters
440 * Deleted pages are filtered out.
441 *
442 * @param integer Page uid for which to create record path
443 * @param string $clause is additional where clauses, eg. "
444 * @param integer Title limit
445 * @param integer Title limit of Full title (typ. set to 1000 or so)
446 * @return mixed Path of record (string) OR array with short/long title if $fullTitleLimit is set.
447 */
448 public static function getRecordPath($uid, $clause, $titleLimit, $fullTitleLimit = 0) {
449 if (!$titleLimit) {
450 $titleLimit = 1000;
451 }
452
453 $loopCheck = 100;
454 $output = $fullOutput = '/';
455
456 $clause = trim($clause);
457 if ($clause !== '' && substr($clause, 0, 3) !== 'AND') {
458 $clause = 'AND ' . $clause;
459 }
460 $data = self::BEgetRootLine($uid, $clause);
461
462 foreach ($data as $record) {
463 if ($record['uid'] === 0) {
464 continue;
465 }
466 if ($record['_ORIG_pid'] && $record['t3ver_swapmode'] > 0) { // Branch points
467 $output = ' [#VEP#]' . $output; // Adding visual token - Versioning Entry Point - that tells that THIS position was where the versionized branch got connected to the main tree. I will have to find a better name or something...
468 }
469 $output = '/' . t3lib_div::fixed_lgd_cs(strip_tags($record['title']), $titleLimit) . $output;
470 if ($fullTitleLimit) {
471 $fullOutput = '/' . t3lib_div::fixed_lgd_cs(strip_tags($record['title']), $fullTitleLimit) . $fullOutput;
472 }
473 }
474
475 if ($fullTitleLimit) {
476 return array($output, $fullOutput);
477 } else {
478 return $output;
479 }
480 }
481
482 /**
483 * Returns an array with the exclude-fields as defined in TCA and FlexForms
484 * Used for listing the exclude-fields in be_groups forms
485 *
486 * @return array Array of arrays with excludeFields (fieldname, table:fieldname) from all TCA entries and from FlexForms (fieldname, table:extkey;sheetname;fieldname)
487 */
488 public static function getExcludeFields() {
489 // All TCA keys:
490 $theExcludeArray = Array();
491 $tc_keys = array_keys($GLOBALS['TCA']);
492 foreach ($tc_keys as $table) {
493 // Load table
494 t3lib_div::loadTCA($table);
495 // All field names configured:
496 if (is_array($GLOBALS['TCA'][$table]['columns'])) {
497 $f_keys = array_keys($GLOBALS['TCA'][$table]['columns']);
498 foreach ($f_keys as $field) {
499 if ($GLOBALS['TCA'][$table]['columns'][$field]['exclude']) {
500 // Get Human Readable names of fields and table:
501 $Fname = $GLOBALS['LANG']->sl($GLOBALS['TCA'][$table]['ctrl']['title']) . ': ' . $GLOBALS['LANG']->sl($GLOBALS['TCA'][$table]['columns'][$field]['label']);
502 // add entry:
503 $theExcludeArray[] = Array($Fname, $table . ':' . $field);
504 }
505 }
506 }
507 }
508 // All FlexForm fields
509 $table = (!empty($GLOBALS['TYPO3_CONF_VARS']['SYS']['contentTable']) ? $GLOBALS['TYPO3_CONF_VARS']['SYS']['contentTable'] : 'tt_content');
510 $flexFormArray = self::getRegisteredFlexForms($table);
511 foreach ($flexFormArray as $tableField => $flexForms) {
512 // Prefix for field label, e.g. "Plugin Options:"
513 $labelPrefix = '';
514 if (!empty($GLOBALS['TCA'][$table]['columns'][$tableField]['label'])) {
515 $labelPrefix = $GLOBALS['LANG']->sl($GLOBALS['TCA'][$table]['columns'][$tableField]['label']);
516 }
517 // Get all sheets and title
518 foreach ($flexForms as $extIdent => $extConf) {
519 $extTitle = $GLOBALS['LANG']->sl($extConf['title']);
520 // Get all fields in sheet
521 foreach ($extConf['ds']['sheets'] as $sheetName => $sheet) {
522 if (empty($sheet['ROOT']['el']) || !is_array($sheet['ROOT']['el'])) {
523 continue;
524 }
525 foreach ($sheet['ROOT']['el'] as $fieldName => $field) {
526 // Use only excludeable fields
527 if (empty($field['TCEforms']['exclude'])) {
528 continue;
529 }
530 $fieldLabel = (!empty($field['TCEforms']['label']) ? $GLOBALS['LANG']->sl($field['TCEforms']['label']) : $fieldName);
531 $fieldIdent = $table . ':' . $tableField . ';' . $extIdent . ';' . $sheetName . ';' . $fieldName;
532 $theExcludeArray[] = array(trim($labelPrefix . ' ' . $extTitle, ': ') . ': ' . $fieldLabel, $fieldIdent);
533 }
534 }
535 }
536 }
537
538 // Sort fields by label
539 usort($theExcludeArray, array(t3lib_TCEforms_Flexforms, 'compareArraysByFirstValue'));
540
541 return $theExcludeArray;
542 }
543
544 /**
545 * Returns an array with explicit Allow/Deny fields.
546 * Used for listing these field/value pairs in be_groups forms
547 *
548 * @return array Array with information from all of $GLOBALS['TCA']
549 */
550 public static function getExplicitAuthFieldValues() {
551
552 // Initialize:
553 $adLabel = array(
554 'ALLOW' => $GLOBALS['LANG']->sl('LLL:EXT:lang/locallang_core.xml:labels.allow'),
555 'DENY' => $GLOBALS['LANG']->sl('LLL:EXT:lang/locallang_core.xml:labels.deny'),
556 );
557
558 // All TCA keys:
559 $allowDenyOptions = Array();
560 $tc_keys = array_keys($GLOBALS['TCA']);
561 foreach ($tc_keys as $table) {
562
563 // Load table
564 t3lib_div::loadTCA($table);
565
566 // All field names configured:
567 if (is_array($GLOBALS['TCA'][$table]['columns'])) {
568 $f_keys = array_keys($GLOBALS['TCA'][$table]['columns']);
569 foreach ($f_keys as $field) {
570 $fCfg = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
571 if ($fCfg['type'] == 'select' && $fCfg['authMode']) {
572
573 // Check for items:
574 if (is_array($fCfg['items'])) {
575 // Get Human Readable names of fields and table:
576 $allowDenyOptions[$table . ':' . $field]['tableFieldLabel'] = $GLOBALS['LANG']->sl($GLOBALS['TCA'][$table]['ctrl']['title']) . ': ' . $GLOBALS['LANG']->sl($GLOBALS['TCA'][$table]['columns'][$field]['label']);
577
578 // Check for items:
579 foreach ($fCfg['items'] as $iVal) {
580 if (strcmp($iVal[1], '')) { // Values '' is not controlled by this setting.
581
582 // Find iMode:
583 $iMode = '';
584 switch ((string) $fCfg['authMode']) {
585 case 'explicitAllow':
586 $iMode = 'ALLOW';
587 break;
588 case 'explicitDeny':
589 $iMode = 'DENY';
590 break;
591 case 'individual':
592 if (!strcmp($iVal[4], 'EXPL_ALLOW')) {
593 $iMode = 'ALLOW';
594 } elseif (!strcmp($iVal[4], 'EXPL_DENY')) {
595 $iMode = 'DENY';
596 }
597 break;
598 }
599
600 // Set iMode:
601 if ($iMode) {
602 $allowDenyOptions[$table . ':' . $field]['items'][$iVal[1]] = array($iMode, $GLOBALS['LANG']->sl($iVal[0]), $adLabel[$iMode]);
603 }
604 }
605 }
606 }
607 }
608 }
609 }
610 }
611
612 return $allowDenyOptions;
613 }
614
615 /**
616 * Returns an array with system languages:
617 *
618 * Since TYPO3 4.5 the flagIcon is not returned as a filename in "gfx/flags/*" anymore,
619 * but as a string <flags-xx>. The calling party should call
620 * t3lib_iconWorks::getSpriteIcon(<flags-xx>) to get an HTML which will represent
621 * the flag of this language.
622 *
623 * @return array Array with languages (title, uid, flagIcon)
624 */
625 public static function getSystemLanguages() {
626 $languages = t3lib_div::makeInstance('t3lib_transl8tools')->getSystemLanguages();
627 $sysLanguages = array();
628 foreach ($languages as $language) {
629 if ($language['uid'] !== -1) {
630 $sysLanguages[] = array(
631 0 => htmlspecialchars($language['title']) . ' [' . $language['uid'] . ']',
632 1 => $language['uid'],
633 2 => $language['flagIcon']
634 );
635 }
636 }
637
638 return $sysLanguages;
639 }
640
641 /**
642 * Determines whether a table is localizable and has the languageField and transOrigPointerField set in $GLOBALS['TCA'].
643 *
644 * @param string $table: The table to check
645 * @return boolean Whether a table is localizable
646 */
647 public static function isTableLocalizable($table) {
648 $isLocalizable = FALSE;
649 if (isset($GLOBALS['TCA'][$table]['ctrl']) && is_array($GLOBALS['TCA'][$table]['ctrl'])) {
650 $tcaCtrl = $GLOBALS['TCA'][$table]['ctrl'];
651 $isLocalizable = (isset($tcaCtrl['languageField']) && $tcaCtrl['languageField'] && isset($tcaCtrl['transOrigPointerField']) && $tcaCtrl['transOrigPointerField']);
652 }
653 return $isLocalizable;
654 }
655
656 /**
657 * Returns the value of the property localizationMode in the given $config array ($GLOBALS['TCA'][<table>]['columns'][<field>]['config']).
658 * If the table is prepared for localization and no localizationMode is set, 'select' is returned by default.
659 * If the table is not prepared for localization or not defined at all in $GLOBALS['TCA'], FALSE is returned.
660 *
661 * @param string $table: The name of the table to lookup in TCA
662 * @param mixed $fieldOrConfig: The fieldname (string) or the configuration of the field to check (array)
663 * @return mixed If table is localizable, the set localizationMode is returned (if property is not set, 'select' is returned by default); if table is not localizable, FALSE is returned
664 */
665 public static function getInlineLocalizationMode($table, $fieldOrConfig) {
666 $localizationMode = FALSE;
667 if (is_array($fieldOrConfig) && count($fieldOrConfig)) {
668 $config = $fieldOrConfig;
669 } elseif (is_string($fieldOrConfig) && isset($GLOBALS['TCA'][$table]['columns'][$fieldOrConfig]['config'])) {
670 $config = $GLOBALS['TCA'][$table]['columns'][$fieldOrConfig]['config'];
671 }
672 if (is_array($config) && isset($config['type']) && $config['type'] == 'inline' && self::isTableLocalizable($table)) {
673 $localizationMode = (isset($config['behaviour']['localizationMode']) && $config['behaviour']['localizationMode'] ? $config['behaviour']['localizationMode'] : 'select');
674 // The mode 'select' is not possible when child table is not localizable at all:
675 if ($localizationMode == 'select' && !self::isTableLocalizable($config['foreign_table'])) {
676 $localizationMode = FALSE;
677 }
678 }
679 return $localizationMode;
680 }
681
682 /**
683 * Returns a page record (of page with $id) with an extra field "_thePath" set to the record path IF the WHERE clause, $perms_clause, selects the record. Thus is works as an access check that returns a page record if access was granted, otherwise not.
684 * If $id is zero a pseudo root-page with "_thePath" set is returned IF the current BE_USER is admin.
685 * In any case ->isInWebMount must return TRUE for the user (regardless of $perms_clause)
686 *
687 * @param integer Page uid for which to check read-access
688 * @param string $perms_clause is typically a value generated with $GLOBALS['BE_USER']->getPagePermsClause(1);
689 * @return array Returns page record if OK, otherwise FALSE.
690 */
691 public static function readPageAccess($id, $perms_clause) {
692 if ((string) $id != '') {
693 $id = intval($id);
694 if (!$id) {
695 if ($GLOBALS['BE_USER']->isAdmin()) {
696 $path = '/';
697 $pageinfo['_thePath'] = $path;
698 return $pageinfo;
699 }
700 } else {
701 $pageinfo = self::getRecord('pages', $id, '*', ($perms_clause ? ' AND ' . $perms_clause : ''));
702 if ($pageinfo['uid'] && $GLOBALS['BE_USER']->isInWebMount($id, $perms_clause)) {
703 self::workspaceOL('pages', $pageinfo);
704 if (is_array($pageinfo)) {
705 self::fixVersioningPid('pages', $pageinfo);
706 list($pageinfo['_thePath'], $pageinfo['_thePathFull']) = self::getRecordPath(intval($pageinfo['uid']), $perms_clause, 15, 1000);
707 return $pageinfo;
708 }
709 }
710 }
711 }
712 return FALSE;
713 }
714
715 /**
716 * Returns the "types" configuration parsed into an array for the record, $rec, from table, $table
717 *
718 * @param string Table name (present in TCA)
719 * @param array Record from $table
720 * @param boolean If $useFieldNameAsKey is set, then the fieldname is associative keys in the return array, otherwise just numeric keys.
721 * @return array
722 */
723 public static function getTCAtypes($table, $rec, $useFieldNameAsKey = 0) {
724 t3lib_div::loadTCA($table);
725 if ($GLOBALS['TCA'][$table]) {
726
727 // Get type value:
728 $fieldValue = self::getTCAtypeValue($table, $rec);
729
730 // Get typesConf
731 $typesConf = $GLOBALS['TCA'][$table]['types'][$fieldValue];
732
733 // Get fields list and traverse it
734 $fieldList = explode(',', $typesConf['showitem']);
735 $altFieldList = array();
736
737 // Traverse fields in types config and parse the configuration into a nice array:
738 foreach ($fieldList as $k => $v) {
739 list($pFieldName, $pAltTitle, $pPalette, $pSpec) = t3lib_div::trimExplode(';', $v);
740 $defaultExtras = is_array($GLOBALS['TCA'][$table]['columns'][$pFieldName]) ? $GLOBALS['TCA'][$table]['columns'][$pFieldName]['defaultExtras'] : '';
741 $specConfParts = self::getSpecConfParts($pSpec, $defaultExtras);
742
743 $fieldList[$k] = array(
744 'field' => $pFieldName,
745 'title' => $pAltTitle,
746 'palette' => $pPalette,
747 'spec' => $specConfParts,
748 'origString' => $v
749 );
750 if ($useFieldNameAsKey) {
751 $altFieldList[$fieldList[$k]['field']] = $fieldList[$k];
752 }
753 }
754 if ($useFieldNameAsKey) {
755 $fieldList = $altFieldList;
756 }
757
758 // Return array:
759 return $fieldList;
760 }
761 }
762
763 /**
764 * Returns the "type" value of $rec from $table which can be used to look up the correct "types" rendering section in $GLOBALS['TCA']
765 * If no "type" field is configured in the "ctrl"-section of the $GLOBALS['TCA'] for the table, zero is used.
766 * If zero is not an index in the "types" section of $GLOBALS['TCA'] for the table, then the $fieldValue returned will default to 1 (no matter if that is an index or not)
767 *
768 * @param string Table name present in TCA
769 * @param array Record from $table
770 * @return string Field value
771 * @see getTCAtypes()
772 */
773 public static function getTCAtypeValue($table, $rec) {
774
775 // If no field-value, set it to zero. If there is no type matching the field-value (which now may be zero...) test field-value '1' as default.
776 t3lib_div::loadTCA($table);
777 if ($GLOBALS['TCA'][$table]) {
778 $field = $GLOBALS['TCA'][$table]['ctrl']['type'];
779 $fieldValue = $field ? ($rec[$field] ? $rec[$field] : 0) : 0;
780 if (!is_array($GLOBALS['TCA'][$table]['types'][$fieldValue])) {
781 $fieldValue = 1;
782 }
783 return $fieldValue;
784 }
785 }
786
787 /**
788 * Parses a part of the field lists in the "types"-section of $GLOBALS['TCA'] arrays, namely the "special configuration" at index 3 (position 4)
789 * Elements are splitted by ":" and within those parts, parameters are splitted by "|".
790 * Everything is returned in an array and you should rather see it visually than listen to me anymore now... Check out example in Inside TYPO3
791 *
792 * @param string Content from the "types" configuration of TCA (the special configuration) - see description of function
793 * @param string The ['defaultExtras'] value from field configuration
794 * @return array
795 */
796 public static function getSpecConfParts($str, $defaultExtras) {
797
798 // Add defaultExtras:
799 $specConfParts = t3lib_div::trimExplode(':', $defaultExtras . ':' . $str, 1);
800
801 $reg = array();
802 if (count($specConfParts)) {
803 foreach ($specConfParts as $k2 => $v2) {
804 unset($specConfParts[$k2]);
805 if (preg_match('/(.*)\[(.*)\]/', $v2, $reg)) {
806 $specConfParts[trim($reg[1])] = array(
807 'parameters' => t3lib_div::trimExplode('|', $reg[2], 1)
808 );
809 } else {
810 $specConfParts[trim($v2)] = 1;
811 }
812 }
813 } else {
814 $specConfParts = array();
815 }
816 return $specConfParts;
817 }
818
819 /**
820 * Takes an array of "[key] = [value]" strings and returns an array with the keys set as keys pointing to the value.
821 * Better see it in action! Find example in Inside TYPO3
822 *
823 * @param array Array of "[key] = [value]" strings to convert.
824 * @return array
825 */
826 public static function getSpecConfParametersFromArray($pArr) {
827 $out = array();
828 if (is_array($pArr)) {
829 foreach ($pArr as $k => $v) {
830 $parts = explode('=', $v, 2);
831 if (count($parts) == 2) {
832 $out[trim($parts[0])] = trim($parts[1]);
833 } else {
834 $out[$k] = $v;
835 }
836 }
837 }
838 return $out;
839 }
840
841 /**
842 * Finds the Data Structure for a FlexForm field
843 * NOTE ON data structures for deleted records: This function may fail to deliver the data structure for a record for a few reasons: a) The data structure could be deleted (either with deleted-flagged or hard-deleted), b) the data structure is fetched using the ds_pointerField_searchParent in which case any deleted record on the route to the final location of the DS will make it fail. In theory, we can solve the problem in the case where records that are deleted-flagged keeps us from finding the DS - this is done at the markers ###NOTE_A### where we make sure to also select deleted records. However, we generally want the DS lookup to fail for deleted records since for the working website we expect a deleted-flagged record to be as inaccessible as one that is completely deleted from the DB. Any way we look at it, this may lead to integrity problems of the reference index and even lost files if attached. However, that is not really important considering that a single change to a data structure can instantly invalidate large amounts of the reference index which we do accept as a cost for the flexform features. Other than requiring a reference index update, deletion of/changes in data structure or the failure to look them up when completely deleting records may lead to lost files in the uploads/ folders since those are now without a proper reference.
844 *
845 * @param array Field config array
846 * @param array Record data
847 * @param string The table name
848 * @param string Optional fieldname passed to hook object
849 * @param boolean Boolean; If set, workspace overlay is applied to records. This is correct behaviour for all presentation and export, but NOT if you want a TRUE reflection of how things are in the live workspace.
850 * @param integer SPECIAL CASES: Use this, if the DataStructure may come from a parent record and the INPUT row doesn't have a uid yet (hence, the pid cannot be looked up). Then it is necessary to supply a PID value to search recursively in for the DS (used from TCEmain)
851 * @return mixed If array, the data structure was found and returned as an array. Otherwise (string) it is an error message.
852 * @see t3lib_TCEforms::getSingleField_typeFlex()
853 */
854 public static function getFlexFormDS($conf, $row, $table, $fieldName = '', $WSOL = TRUE, $newRecordPidValue = 0) {
855 // Get pointer field etc from TCA-config:
856 $ds_pointerField = $conf['ds_pointerField'];
857 $ds_array = $conf['ds'];
858 $ds_tableField = $conf['ds_tableField'];
859 $ds_searchParentField = $conf['ds_pointerField_searchParent'];
860
861 // Find source value:
862 $dataStructArray = '';
863 if (is_array($ds_array)) { // If there is a data source array, that takes precedence
864 // If a pointer field is set, take the value from that field in the $row array and use as key.
865 if ($ds_pointerField) {
866
867 // Up to two pointer fields can be specified in a comma separated list.
868 $pointerFields = t3lib_div::trimExplode(',', $ds_pointerField);
869 if (count($pointerFields) == 2) { // If we have two pointer fields, the array keys should contain both field values separated by comma. The asterisk "*" catches all values. For backwards compatibility, it's also possible to specify only the value of the first defined ds_pointerField.
870 if ($ds_array[$row[$pointerFields[0]] . ',' . $row[$pointerFields[1]]]) { // Check if we have a DS for the combination of both pointer fields values
871 $srcPointer = $row[$pointerFields[0]] . ',' . $row[$pointerFields[1]];
872 } elseif ($ds_array[$row[$pointerFields[1]] . ',*']) { // Check if we have a DS for the value of the first pointer field suffixed with ",*"
873 $srcPointer = $row[$pointerFields[1]] . ',*';
874 } elseif ($ds_array['*,' . $row[$pointerFields[1]]]) { // Check if we have a DS for the value of the second pointer field prefixed with "*,"
875 $srcPointer = '*,' . $row[$pointerFields[1]];
876 } elseif ($ds_array[$row[$pointerFields[0]]]) { // Check if we have a DS for just the value of the first pointer field (mainly for backwards compatibility)
877 $srcPointer = $row[$pointerFields[0]];
878 }
879 } else {
880 $srcPointer = $row[$pointerFields[0]];
881 }
882
883 $srcPointer = isset($ds_array[$srcPointer]) ? $srcPointer : 'default';
884 } else {
885 $srcPointer = 'default';
886 }
887
888 // Get Data Source: Detect if it's a file reference and in that case read the file and parse as XML. Otherwise the value is expected to be XML.
889 if (substr($ds_array[$srcPointer], 0, 5) == 'FILE:') {
890 $file = t3lib_div::getFileAbsFileName(substr($ds_array[$srcPointer], 5));
891 if ($file && @is_file($file)) {
892 $dataStructArray = t3lib_div::xml2array(t3lib_div::getUrl($file));
893 } else {
894 $dataStructArray = 'The file "' . substr($ds_array[$srcPointer], 5) . '" in ds-array key "' . $srcPointer . '" was not found ("' . $file . '")';
895 } // Error message.
896 } else {
897 $dataStructArray = t3lib_div::xml2array($ds_array[$srcPointer]);
898 }
899
900 } elseif ($ds_pointerField) { // If pointer field AND possibly a table/field is set:
901 // Value of field pointed to:
902 $srcPointer = $row[$ds_pointerField];
903
904 // Searching recursively back if 'ds_pointerField_searchParent' is defined (typ. a page rootline, or maybe a tree-table):
905 if ($ds_searchParentField && !$srcPointer) {
906 $rr = self::getRecord($table, $row['uid'], 'uid,' . $ds_searchParentField); // Get the "pid" field - we cannot know that it is in the input record! ###NOTE_A###
907 if ($WSOL) {
908 self::workspaceOL($table, $rr);
909 self::fixVersioningPid($table, $rr, TRUE); // Added "TRUE" 23/03/06 before 4.0. (Also to similar call below!). Reason: When t3lib_refindex is scanning the system in Live workspace all Pages with FlexForms will not find their inherited datastructure. Thus all references from workspaces are removed! Setting TRUE means that versioning PID doesn't check workspace of the record. I can't see that this should give problems anywhere. See more information inside t3lib_refindex!
910 }
911 $uidAcc = array(); // Used to avoid looping, if any should happen.
912 $subFieldPointer = $conf['ds_pointerField_searchParent_subField'];
913 while (!$srcPointer) {
914
915 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
916 'uid,' . $ds_pointerField . ',' . $ds_searchParentField . ($subFieldPointer ? ',' . $subFieldPointer : ''),
917 $table,
918 'uid=' . intval($newRecordPidValue ? $newRecordPidValue : $rr[$ds_searchParentField]) . self::deleteClause($table) ###NOTE_A###
919 );
920 $newRecordPidValue = 0;
921 $rr = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
922 $GLOBALS['TYPO3_DB']->sql_free_result($res);
923
924 // break if no result from SQL db or if looping...
925 if (!is_array($rr) || isset($uidAcc[$rr['uid']])) {
926 break;
927 }
928 $uidAcc[$rr['uid']] = 1;
929
930 if ($WSOL) {
931 self::workspaceOL($table, $rr);
932 self::fixVersioningPid($table, $rr, TRUE);
933 }
934 $srcPointer = ($subFieldPointer && $rr[$subFieldPointer]) ? $rr[$subFieldPointer] : $rr[$ds_pointerField];
935 }
936 }
937
938 // If there is a srcPointer value:
939 if ($srcPointer) {
940 if (t3lib_utility_Math::canBeInterpretedAsInteger($srcPointer)) { // If integer, then its a record we will look up:
941 list($tName, $fName) = explode(':', $ds_tableField, 2);
942 if ($tName && $fName && is_array($GLOBALS['TCA'][$tName])) {
943 $dataStructRec = self::getRecord($tName, $srcPointer);
944 if ($WSOL) {
945 self::workspaceOL($tName, $dataStructRec);
946 }
947 if (strpos($dataStructRec[$fName], '<') === FALSE) {
948 if (is_file(PATH_site . $dataStructRec[$fName])) {
949 // The value is a pointer to a file
950 $dataStructArray = t3lib_div::xml2array(t3lib_div::getUrl(PATH_site . $dataStructRec[$fName]));
951 } else {
952 $dataStructArray = sprintf('File \'%s\' was not found', $dataStructRec[$fName]);
953 }
954 } else {
955 // No file pointer, handle as being XML (default behaviour)
956 $dataStructArray = t3lib_div::xml2array($dataStructRec[$fName]);
957 }
958 } else {
959 $dataStructArray = 'No tablename (' . $tName . ') or fieldname (' . $fName . ') was found an valid!';
960 }
961 } else { // Otherwise expect it to be a file:
962 $file = t3lib_div::getFileAbsFileName($srcPointer);
963 if ($file && @is_file($file)) {
964 $dataStructArray = t3lib_div::xml2array(t3lib_div::getUrl($file));
965 } else {
966 $dataStructArray = 'The file "' . $srcPointer . '" was not found ("' . $file . '")';
967 } // Error message.
968 }
969 } else {
970 $dataStructArray = 'No source value in fieldname "' . $ds_pointerField . '"';
971 } // Error message.
972 } else {
973 $dataStructArray = 'No proper configuration!';
974 }
975
976 // Hook for post-processing the Flexform DS. Introduces the possibility to configure Flexforms via TSConfig
977 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['getFlexFormDSClass'])) {
978 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['getFlexFormDSClass'] as $classRef) {
979 $hookObj = t3lib_div::getUserObj($classRef);
980 if (method_exists($hookObj, 'getFlexFormDS_postProcessDS')) {
981 $hookObj->getFlexFormDS_postProcessDS($dataStructArray, $conf, $row, $table, $fieldName);
982 }
983 }
984 }
985
986 return $dataStructArray;
987 }
988
989 /**
990 * Returns all registered FlexForm definitions with title and fields
991 *
992 * @param string The content table
993 * @return array The data structures with speaking extension title
994 * @see t3lib_BEfunc::getExcludeFields()
995 */
996 public static function getRegisteredFlexForms($table = 'tt_content') {
997 if (empty($table) || empty($GLOBALS['TCA'][$table]['columns'])) {
998 return array();
999 }
1000
1001
1002 $flexForms = array();
1003
1004 foreach ($GLOBALS['TCA'][$table]['columns'] as $tableField => $fieldConf) {
1005 if (!empty($fieldConf['config']['type']) && !empty($fieldConf['config']['ds']) && $fieldConf['config']['type'] == 'flex') {
1006 $flexForms[$tableField] = array();
1007
1008 unset($fieldConf['config']['ds']['default']);
1009
1010 // Get pointer fields
1011 $pointerFields = (!empty($fieldConf['config']['ds_pointerField']) ? $fieldConf['config']['ds_pointerField'] : 'list_type,CType');
1012 $pointerFields = t3lib_div::trimExplode(',', $pointerFields);
1013
1014 // Get FlexForms
1015 foreach ($fieldConf['config']['ds'] as $flexFormKey => $dataStruct) {
1016 // Get extension identifier (uses second value if it's not empty, "list" or "*", else first one)
1017 $identFields = t3lib_div::trimExplode(',', $flexFormKey);
1018 $extIdent = $identFields[0];
1019 if (!empty($identFields[1]) && $identFields[1] != 'list' && $identFields[1] != '*') {
1020 $extIdent = $identFields[1];
1021 }
1022
1023 // Load external file references
1024 if (!is_array($dataStruct)) {
1025 $file = t3lib_div::getFileAbsFileName(str_ireplace('FILE:', '', $dataStruct));
1026 if ($file && @is_file($file)) {
1027 $dataStruct = t3lib_div::getUrl($file);
1028 }
1029 $dataStruct = t3lib_div::xml2array($dataStruct);
1030 if (!is_array($dataStruct)) {
1031 continue;
1032 }
1033 }
1034 // Get flexform content
1035 $dataStruct = t3lib_div::resolveAllSheetsInDS($dataStruct);
1036 if (empty($dataStruct['sheets']) || !is_array($dataStruct['sheets'])) {
1037 continue;
1038 }
1039
1040 // Use DS pointer to get extension title from TCA
1041 $title = $extIdent;
1042 $keyFields = t3lib_div::trimExplode(',', $flexFormKey);
1043 foreach ($pointerFields as $pointerKey => $pointerName) {
1044 if (empty($keyFields[$pointerKey]) || $keyFields[$pointerKey] == '*' || $keyFields[$pointerKey] == 'list') {
1045 continue;
1046 }
1047 if (!empty($GLOBALS['TCA'][$table]['columns'][$pointerName]['config']['items'])) {
1048 $items = $GLOBALS['TCA'][$table]['columns'][$pointerName]['config']['items'];
1049 if (!is_array($items)) {
1050 continue;
1051 }
1052 foreach ($items as $itemConf) {
1053 if (!empty($itemConf[0]) && !empty($itemConf[1]) && $itemConf[1] == $keyFields[$pointerKey]) {
1054 $title = $itemConf[0];
1055 break 2;
1056 }
1057 }
1058 }
1059 }
1060
1061 $flexForms[$tableField][$extIdent] = array(
1062 'title' => $title,
1063 'ds' => $dataStruct,
1064 );
1065 }
1066 }
1067 }
1068
1069 return $flexForms;
1070 }
1071
1072
1073 /*******************************************
1074 *
1075 * Caching related
1076 *
1077 *******************************************/
1078
1079 /**
1080 * Stores the string value $data in the 'cache_hash' cache with the
1081 * hash key, $hash, and visual/symbolic identification, $ident
1082 * IDENTICAL to the function by same name found in t3lib_page:
1083 *
1084 * @param string 32 bit hash string (eg. a md5 hash of a serialized array identifying the data being stored)
1085 * @param string The data string. If you want to store an array, then just serialize it first.
1086 * @param string $ident is just a textual identification in order to inform about the content!
1087 * @return void
1088 */
1089 public static function storeHash($hash, $data, $ident) {
1090 $GLOBALS['typo3CacheManager']->getCache('cache_hash')->set(
1091 $hash,
1092 $data,
1093 array('ident_' . $ident),
1094 0 // unlimited lifetime
1095 );
1096 }
1097
1098 /**
1099 * Returns string value stored for the hash string in the cache "cache_hash"
1100 * Can be used to retrieved a cached value
1101 *
1102 * IDENTICAL to the function by same name found in t3lib_page
1103 *
1104 * @param string The hash-string which was used to store the data value
1105 * @return string
1106 */
1107 public static function getHash($hash, $expTime = 0) {
1108 $hashContent = NULL;
1109 $cacheEntry = $GLOBALS['typo3CacheManager']->getCache('cache_hash')->get($hash);
1110 if ($cacheEntry) {
1111 $hashContent = $cacheEntry;
1112 }
1113 return $hashContent;
1114 }
1115
1116
1117 /*******************************************
1118 *
1119 * TypoScript related
1120 *
1121 *******************************************/
1122
1123 /**
1124 * Returns the Page TSconfig for page with id, $id
1125 * Requires class "t3lib_TSparser"
1126 *
1127 * @param integer Page uid for which to create Page TSconfig
1128 * @param array If $rootLine is an array, that is used as rootline, otherwise rootline is just calculated
1129 * @param boolean If $returnPartArray is set, then the array with accumulated Page TSconfig is returned non-parsed. Otherwise the output will be parsed by the TypoScript parser.
1130 * @return array Page TSconfig
1131 * @see t3lib_TSparser
1132 */
1133 public static function getPagesTSconfig($id, $rootLine = '', $returnPartArray = 0) {
1134 $id = intval($id);
1135 if (!is_array($rootLine)) {
1136 $rootLine = self::BEgetRootLine($id, '', TRUE);
1137 }
1138 ksort($rootLine); // Order correctly
1139 $TSdataArray = array();
1140 $TSdataArray['defaultPageTSconfig'] = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPageTSconfig']; // Setting default configuration:
1141 foreach ($rootLine as $k => $v) {
1142 $TSdataArray['uid_' . $v['uid']] = $v['TSconfig'];
1143 }
1144 $TSdataArray = t3lib_TSparser::checkIncludeLines_array($TSdataArray);
1145 if ($returnPartArray) {
1146 return $TSdataArray;
1147 }
1148
1149 // Parsing the page TS-Config (or getting from cache)
1150 $pageTS = implode(LF . '[GLOBAL]' . LF, $TSdataArray);
1151 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['TSconfigConditions']) {
1152 /* @var $parseObj t3lib_TSparser_TSconfig */
1153 $parseObj = t3lib_div::makeInstance('t3lib_TSparser_TSconfig');
1154 $res = $parseObj->parseTSconfig($pageTS, 'PAGES', $id, $rootLine);
1155 if ($res) {
1156 $TSconfig = $res['TSconfig'];
1157 }
1158 } else {
1159 $hash = md5('pageTS:' . $pageTS);
1160 $cachedContent = self::getHash($hash);
1161 $TSconfig = array();
1162 if (isset($cachedContent)) {
1163 $TSconfig = unserialize($cachedContent);
1164 } else {
1165 $parseObj = t3lib_div::makeInstance('t3lib_TSparser');
1166 $parseObj->parse($pageTS);
1167 $TSconfig = $parseObj->setup;
1168 self::storeHash($hash, serialize($TSconfig), 'PAGES_TSconfig');
1169 }
1170 }
1171
1172 // get User TSconfig overlay
1173 $userTSconfig = $GLOBALS['BE_USER']->userTS['page.'];
1174 if (is_array($userTSconfig)) {
1175 $TSconfig = t3lib_div::array_merge_recursive_overrule($TSconfig, $userTSconfig);
1176 }
1177 return $TSconfig;
1178 }
1179
1180 /**
1181 * Updates Page TSconfig for a page with $id
1182 * The function seems to take $pageTS as an array with properties and compare the values with those that already exists for the "object string", $TSconfPrefix, for the page, then sets those values which were not present.
1183 * $impParams can be supplied as already known Page TSconfig, otherwise it's calculated.
1184 *
1185 * THIS DOES NOT CHECK ANY PERMISSIONS. SHOULD IT?
1186 * More documentation is needed.
1187 *
1188 * @param integer Page id
1189 * @param array Page TS array to write
1190 * @param string Prefix for object paths
1191 * @param array [Description needed.]
1192 * @return void
1193 * @internal
1194 * @see implodeTSParams(), getPagesTSconfig()
1195 */
1196 public static function updatePagesTSconfig($id, $pageTS, $TSconfPrefix, $impParams = '') {
1197 $id = intval($id);
1198 if (is_array($pageTS) && $id > 0) {
1199 if (!is_array($impParams)) {
1200 $impParams = self::implodeTSParams(self::getPagesTSconfig($id));
1201 }
1202 $set = array();
1203 foreach ($pageTS as $f => $v) {
1204 $f = $TSconfPrefix . $f;
1205 if ((!isset($impParams[$f]) && trim($v)) || strcmp(trim($impParams[$f]), trim($v))) {
1206 $set[$f] = trim($v);
1207 }
1208 }
1209 if (count($set)) {
1210 // Get page record and TS config lines
1211 $pRec = self::getRecord('pages', $id);
1212 $TSlines = explode(LF, $pRec['TSconfig']);
1213 $TSlines = array_reverse($TSlines);
1214 // Reset the set of changes.
1215 foreach ($set as $f => $v) {
1216 $inserted = 0;
1217 foreach ($TSlines as $ki => $kv) {
1218 if (substr($kv, 0, strlen($f) + 1) == $f . '=') {
1219 $TSlines[$ki] = $f . '=' . $v;
1220 $inserted = 1;
1221 break;
1222 }
1223 }
1224 if (!$inserted) {
1225 $TSlines = array_reverse($TSlines);
1226 $TSlines[] = $f . '=' . $v;
1227 $TSlines = array_reverse($TSlines);
1228 }
1229 }
1230 $TSlines = array_reverse($TSlines);
1231
1232 // store those changes
1233 $TSconf = implode(LF, $TSlines);
1234
1235 $GLOBALS['TYPO3_DB']->exec_UPDATEquery('pages', 'uid=' . intval($id), array('TSconfig' => $TSconf));
1236 }
1237 }
1238 }
1239
1240 /**
1241 * Implodes a multi dimensional TypoScript array, $p, into a one-dimentional array (return value)
1242 *
1243 * @param array TypoScript structure
1244 * @param string Prefix string
1245 * @return array Imploded TypoScript objectstring/values
1246 */
1247 public static function implodeTSParams($p, $k = '') {
1248 $implodeParams = array();
1249 if (is_array($p)) {
1250 foreach ($p as $kb => $val) {
1251 if (is_array($val)) {
1252 $implodeParams = array_merge($implodeParams, self::implodeTSParams($val, $k . $kb));
1253 } else {
1254 $implodeParams[$k . $kb] = $val;
1255 }
1256 }
1257 }
1258 return $implodeParams;
1259 }
1260
1261
1262 /*******************************************
1263 *
1264 * Users / Groups related
1265 *
1266 *******************************************/
1267
1268 /**
1269 * Returns an array with be_users records of all user NOT DELETED sorted by their username
1270 * Keys in the array is the be_users uid
1271 *
1272 * @param string Optional $fields list (default: username,usergroup,usergroup_cached_list,uid) can be used to set the selected fields
1273 * @param string Optional $where clause (fx. "AND username='pete'") can be used to limit query
1274 * @return array
1275 */
1276 public static function getUserNames($fields = 'username,usergroup,usergroup_cached_list,uid', $where = '') {
1277 $be_user_Array = Array();
1278
1279 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fields, 'be_users', 'pid=0 ' . $where . self::deleteClause('be_users'), '', 'username');
1280 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1281 $be_user_Array[$row['uid']] = $row;
1282 }
1283 $GLOBALS['TYPO3_DB']->sql_free_result($res);
1284
1285 return $be_user_Array;
1286 }
1287
1288 /**
1289 * Returns an array with be_groups records (title, uid) of all groups NOT DELETED sorted by their title
1290 *
1291 * @param string Field list
1292 * @param string WHERE clause
1293 * @return array
1294 */
1295 public static function getGroupNames($fields = 'title,uid', $where = '') {
1296 $be_group_Array = Array();
1297
1298 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fields, 'be_groups', 'pid=0 ' . $where . self::deleteClause('be_groups'), '', 'title');
1299 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1300 $be_group_Array[$row['uid']] = $row;
1301 }
1302 $GLOBALS['TYPO3_DB']->sql_free_result($res);
1303
1304 return $be_group_Array;
1305 }
1306
1307 /**
1308 * Returns an array with be_groups records (like ->getGroupNames) but:
1309 * - if the current BE_USER is admin, then all groups are returned, otherwise only groups that the current user is member of (usergroup_cached_list) will be returned.
1310 *
1311 * @param string Field list; $fields specify the fields selected (default: title,uid)
1312 * @return array
1313 */
1314 public static function getListGroupNames($fields = 'title, uid') {
1315 $exQ = ' AND hide_in_lists=0';
1316 if (!$GLOBALS['BE_USER']->isAdmin()) {
1317 $exQ .= ' AND uid IN (' . ($GLOBALS['BE_USER']->user['usergroup_cached_list'] ? $GLOBALS['BE_USER']->user['usergroup_cached_list'] : 0) . ')';
1318 }
1319 return self::getGroupNames($fields, $exQ);
1320 }
1321
1322 /**
1323 * Returns the array $usernames with the names of all users NOT IN $groupArray changed to the uid (hides the usernames!).
1324 * If $excludeBlindedFlag is set, then these records are unset from the array $usernames
1325 * Takes $usernames (array made by t3lib_BEfunc::getUserNames()) and a $groupArray (array with the groups a certain user is member of) as input
1326 *
1327 * @param array User names
1328 * @param array Group names
1329 * @param boolean If $excludeBlindedFlag is set, then these records are unset from the array $usernames
1330 * @return array User names, blinded
1331 */
1332 public static function blindUserNames($usernames, $groupArray, $excludeBlindedFlag = 0) {
1333 if (is_array($usernames) && is_array($groupArray)) {
1334 foreach ($usernames as $uid => $row) {
1335 $userN = $uid;
1336 $set = 0;
1337 if ($row['uid'] != $GLOBALS['BE_USER']->user['uid']) {
1338 foreach ($groupArray as $v) {
1339 if ($v && t3lib_div::inList($row['usergroup_cached_list'], $v)) {
1340 $userN = $row['username'];
1341 $set = 1;
1342 }
1343 }
1344 } else {
1345 $userN = $row['username'];
1346 $set = 1;
1347 }
1348 $usernames[$uid]['username'] = $userN;
1349 if ($excludeBlindedFlag && !$set) {
1350 unset($usernames[$uid]);
1351 }
1352 }
1353 }
1354 return $usernames;
1355 }
1356
1357 /**
1358 * Corresponds to blindUserNames but works for groups instead
1359 *
1360 * @param array Group names
1361 * @param array Group names (reference)
1362 * @param boolean If $excludeBlindedFlag is set, then these records are unset from the array $usernames
1363 * @return array
1364 */
1365 public static function blindGroupNames($groups, $groupArray, $excludeBlindedFlag = 0) {
1366 if (is_array($groups) && is_array($groupArray)) {
1367 foreach ($groups as $uid => $row) {
1368 $groupN = $uid;
1369 $set = 0;
1370 if (t3lib_div::inArray($groupArray, $uid)) {
1371 $groupN = $row['title'];
1372 $set = 1;
1373 }
1374 $groups[$uid]['title'] = $groupN;
1375 if ($excludeBlindedFlag && !$set) {
1376 unset($groups[$uid]);
1377 }
1378 }
1379 }
1380 return $groups;
1381 }
1382
1383
1384 /*******************************************
1385 *
1386 * Output related
1387 *
1388 *******************************************/
1389
1390 /**
1391 * Returns the difference in days between input $tstamp and $EXEC_TIME
1392 *
1393 * @param integer Time stamp, seconds
1394 * @return integer
1395 */
1396 public static function daysUntil($tstamp) {
1397 $delta_t = $tstamp - $GLOBALS['EXEC_TIME'];
1398 return ceil($delta_t / (3600 * 24));
1399 }
1400
1401 /**
1402 * Returns $tstamp formatted as "ddmmyy" (According to $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'])
1403 *
1404 * @param integer Time stamp, seconds
1405 * @return string Formatted time
1406 */
1407 public static function date($tstamp) {
1408 return date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'], (int) $tstamp);
1409 }
1410
1411 /**
1412 * Returns $tstamp formatted as "ddmmyy hhmm" (According to $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] AND $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'])
1413 *
1414 * @param integer Time stamp, seconds
1415 * @return string Formatted time
1416 */
1417 public static function datetime($value) {
1418 return date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'], $value);
1419 }
1420
1421 /**
1422 * Returns $value (in seconds) formatted as hh:mm:ss
1423 * For instance $value = 3600 + 60*2 + 3 should return "01:02:03"
1424 *
1425 * @param integer Time stamp, seconds
1426 * @param boolean Output hh:mm:ss. If FALSE: hh:mm
1427 * @return string Formatted time
1428 */
1429 public static function time($value, $withSeconds = TRUE) {
1430 $hh = floor($value / 3600);
1431 $min = floor(($value - $hh * 3600) / 60);
1432 $sec = $value - $hh * 3600 - $min * 60;
1433 $l = sprintf('%02d', $hh) . ':' . sprintf('%02d', $min);
1434 if ($withSeconds) {
1435 $l .= ':' . sprintf('%02d', $sec);
1436 }
1437 return $l;
1438 }
1439
1440 /**
1441 * Returns the "age" in minutes / hours / days / years of the number of $seconds inputted.
1442 *
1443 * @param integer $seconds could be the difference of a certain timestamp and time()
1444 * @param string $labels should be something like ' min| hrs| days| yrs| min| hour| day| year'. This value is typically delivered by this function call: $GLOBALS["LANG"]->sL("LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears")
1445 * @return string Formatted time
1446 */
1447 public static function calcAge($seconds, $labels = ' min| hrs| days| yrs| min| hour| day| year') {
1448 $labelArr = explode('|', $labels);
1449 $absSeconds = abs($seconds);
1450 $sign = ($seconds > 0 ? 1 : -1);
1451 if ($seconds < 3600) {
1452 $val = round($absSeconds / 60);
1453 $seconds = ($sign * $val) . ($val == 1 ? $labelArr[4] : $labelArr[0]);
1454 } elseif ($seconds < 24 * 3600) {
1455 $val = round($absSeconds / 3600);
1456 $seconds = ($sign * $val) . ($val == 1 ? $labelArr[5] : $labelArr[1]);
1457 } elseif ($seconds < 365 * 24 * 3600) {
1458 $val = round($absSeconds / (24 * 3600));
1459 $seconds = ($sign * $val) . ($val == 1 ? $labelArr[6] : $labelArr[2]);
1460 } else {
1461 $val = round($absSeconds / (365 * 24 * 3600));
1462 $seconds = ($sign * $val) . ($val == 1 ? $labelArr[7] : $labelArr[3]);
1463 }
1464 return $seconds;
1465 }
1466
1467 /**
1468 * Returns a formatted timestamp if $tstamp is set.
1469 * The date/datetime will be followed by the age in parenthesis.
1470 *
1471 * @param integer Time stamp, seconds
1472 * @param integer 1/-1 depending on polarity of age.
1473 * @param string $date=="date" will yield "dd:mm:yy" formatting, otherwise "dd:mm:yy hh:mm"
1474 * @return string
1475 */
1476 public static function dateTimeAge($tstamp, $prefix = 1, $date = '') {
1477 return $tstamp ?
1478 ($date == 'date' ? self::date($tstamp) : self::datetime($tstamp)) .
1479 ' (' . self::calcAge($prefix * ($GLOBALS['EXEC_TIME'] - $tstamp), $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears')) . ')'
1480 : '';
1481 }
1482
1483 /**
1484 * Returns alt="" and title="" attributes with the value of $content.
1485 *
1486 * @param string Value for 'alt' and 'title' attributes (will be htmlspecialchars()'ed before output)
1487 * @return string
1488 */
1489 public static function titleAltAttrib($content) {
1490 $out = '';
1491 $out .= ' alt="' . htmlspecialchars($content) . '"';
1492 $out .= ' title="' . htmlspecialchars($content) . '"';
1493 return $out;
1494 }
1495
1496 /**
1497 * Returns a linked image-tag for thumbnail(s)/fileicons/truetype-font-previews from a database row with a list of image files in a field
1498 * All $GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'] extension are made to thumbnails + ttf file (renders font-example)
1499 * Thumbsnails are linked to the show_item.php script which will display further details.
1500 *
1501 * @param array $row is the database row from the table, $table.
1502 * @param string Table name for $row (present in TCA)
1503 * @param string $field is pointing to the field with the list of image files
1504 * @param string Back path prefix for image tag src="" field
1505 * @param string Optional: $thumbScript os by default 'thumbs.php' if you don't set it otherwise
1506 * @param string Optional: $uploaddir is the directory relative to PATH_site where the image files from the $field value is found (Is by default set to the entry in $GLOBALS['TCA'] for that field! so you don't have to!)
1507 * @param boolean If set, uploaddir is NOT prepended with "../"
1508 * @param string Optional: $tparams is additional attributes for the image tags
1509 * @param integer Optional: $size is [w]x[h] of the thumbnail. 56 is default.
1510 * @return string Thumbnail image tag.
1511 */
1512 public static function thumbCode($row, $table, $field, $backPath, $thumbScript = '', $uploaddir = NULL, $abs = 0, $tparams = '', $size = '') {
1513 // Load table.
1514 t3lib_div::loadTCA($table);
1515
1516 // Find uploaddir automatically
1517 $uploaddir = (is_null($uploaddir)) ? $GLOBALS['TCA'][$table]['columns'][$field]['config']['uploadfolder'] : $uploaddir;
1518 $uploaddir = preg_replace('#/$#', '', $uploaddir);
1519
1520 // Set thumbs-script:
1521 if (!$GLOBALS['TYPO3_CONF_VARS']['GFX']['thumbnails']) {
1522 $thumbScript = 'gfx/notfound_thumb.gif';
1523 } elseif (!$thumbScript) {
1524 $thumbScript = 'thumbs.php';
1525 }
1526 // Check and parse the size parameter
1527 $sizeParts = array();
1528 if ($size = trim($size)) {
1529 $sizeParts = explode('x', $size . 'x' . $size);
1530 if (!intval($sizeParts[0])) {
1531 $size = '';
1532 }
1533 }
1534
1535 // Traverse files:
1536 $thumbs = explode(',', $row[$field]);
1537 $thumbData = '';
1538 foreach ($thumbs as $theFile) {
1539 if (trim($theFile)) {
1540 $fI = t3lib_div::split_fileref($theFile);
1541 $ext = $fI['fileext'];
1542 // New 190201 start
1543 $max = 0;
1544 if (t3lib_div::inList('gif,jpg,png', $ext)) {
1545 $imgInfo = @getimagesize(PATH_site . $uploaddir . '/' . $theFile);
1546 if (is_array($imgInfo)) {
1547 $max = max($imgInfo[0], $imgInfo[1]);
1548 }
1549 }
1550 // use the original image if it's size fits to the thumbnail size
1551 if ($max && $max <= (count($sizeParts) && max($sizeParts) ? max($sizeParts) : 56)) {
1552 $theFile = $url = ($abs ? '' : '../') . ($uploaddir ? $uploaddir . '/' : '') . trim($theFile);
1553 $onClick = 'top.launchView(\'' . $theFile . '\',\'\',\'' . $backPath . '\');return false;';
1554 $thumbData .= '<a href="#" onclick="' . htmlspecialchars($onClick) . '"><img src="' . $backPath . $url . '" ' . $imgInfo[3] . ' hspace="2" border="0" title="' . trim($url) . '"' . $tparams . ' alt="" /></a> ';
1555 // New 190201 stop
1556 } elseif ($ext == 'ttf' || t3lib_div::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'], $ext)) {
1557 $theFile_abs = PATH_site . ($uploaddir ? $uploaddir . '/' : '') . trim($theFile);
1558 $theFile = ($abs ? '' : '../') . ($uploaddir ? $uploaddir . '/' : '') . trim($theFile);
1559
1560 if (!is_readable($theFile_abs)) {
1561 $flashMessage = t3lib_div::makeInstance(
1562 't3lib_FlashMessage',
1563 $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xml:warning.file_missing_text') . ' <abbr title="' . $theFile_abs . '">' . $theFile . '</abbr>',
1564 $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xml:warning.file_missing'),
1565 t3lib_FlashMessage::ERROR
1566 );
1567 $thumbData .= $flashMessage->render();
1568 continue;
1569 }
1570
1571 $check = basename($theFile_abs) . ':' . filemtime($theFile_abs) . ':' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
1572 $params = '&file=' . rawurlencode($theFile);
1573 $params .= $size ? '&size=' . $size : '';
1574 $params .= '&md5sum=' . t3lib_div::shortMD5($check);
1575
1576 $url = $thumbScript . '?&dummy=' . $GLOBALS['EXEC_TIME'] . $params;
1577 $onClick = 'top.launchView(\'' . $theFile . '\',\'\',\'' . $backPath . '\');return false;';
1578 $thumbData .= '<a href="#" onclick="' . htmlspecialchars($onClick) . '"><img src="' . htmlspecialchars($backPath . $url) . '" hspace="2" border="0" title="' . trim($theFile) . '"' . $tparams . ' alt="" /></a> ';
1579 } else {
1580 // Icon
1581 $theFile_abs = PATH_site . ($uploaddir ? $uploaddir . '/' : '') . trim($theFile);
1582 $theFile = ($abs ? '' : '../') . ($uploaddir ? $uploaddir . '/' : '') . trim($theFile);
1583
1584 $fileIcon = t3lib_iconWorks::getSpriteIconForFile(
1585 strtolower($ext),
1586 array('title' => htmlspecialchars(trim($theFile)))
1587 );
1588
1589 $check = basename($theFile_abs) . ':' . filemtime($theFile_abs) . ':' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
1590 $params = '&file=' . rawurlencode($theFile);
1591 $params .= $size ? '&size=' . $size : '';
1592 $params .= '&md5sum=' . t3lib_div::shortMD5($check);
1593
1594 $url = $thumbScript . '?&dummy=' . $GLOBALS['EXEC_TIME'] . $params;
1595 $onClick = 'top.launchView(\'' . $theFile . '\',\'\',\'' . $backPath . '\');return false;';
1596 $thumbData .= '<a href="#" onclick="' . htmlspecialchars($onClick) . '">' . $fileIcon . '</a> ';
1597 }
1598 }
1599 }
1600 return $thumbData;
1601 }
1602
1603 /**
1604 * Returns single image tag to thumbnail using a thumbnail script (like thumbs.php)
1605 *
1606 * @param string $thumbScript must point to "thumbs.php" relative to the script position
1607 * @param string $theFile must be the proper reference to the file thumbs.php should show
1608 * @param string $tparams are additional attributes for the image tag
1609 * @param integer $size is the size of the thumbnail send along to "thumbs.php"
1610 * @return string Image tag
1611 */
1612 public static function getThumbNail($thumbScript, $theFile, $tparams = '', $size = '') {
1613 $check = basename($theFile) . ':' . filemtime($theFile) . ':' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
1614 $params = '&file=' . rawurlencode($theFile);
1615 $params .= trim($size) ? '&size=' . trim($size) : '';
1616 $params .= '&md5sum=' . t3lib_div::shortMD5($check);
1617
1618 $url = $thumbScript . '?&dummy=' . $GLOBALS['EXEC_TIME'] . $params;
1619 $th = '<img src="' . htmlspecialchars($url) . '" title="' . trim(basename($theFile)) . '"' . ($tparams ? " " . $tparams : "") . ' alt="" />';
1620 return $th;
1621 }
1622
1623 /**
1624 * Returns title-attribute information for a page-record informing about id, alias, doktype, hidden, starttime, endtime, fe_group etc.
1625 *
1626 * @param array Input must be a page row ($row) with the proper fields set (be sure - send the full range of fields for the table)
1627 * @param string $perms_clause is used to get the record path of the shortcut page, if any (and doktype==4)
1628 * @param boolean If $includeAttrib is set, then the 'title=""' attribute is wrapped about the return value, which is in any case htmlspecialchar()'ed already
1629 * @return string
1630 */
1631 public static function titleAttribForPages($row, $perms_clause = '', $includeAttrib = 1) {
1632 $parts = array();
1633 $parts[] = 'id=' . $row['uid'];
1634 if ($row['alias']) {
1635 $parts[] = $GLOBALS['LANG']->sL($GLOBALS['TCA']['pages']['columns']['alias']['label']) . ' ' . $row['alias'];
1636 }
1637 if ($row['pid'] < 0) {
1638 $parts[] = 'v#1.' . $row['t3ver_id'];
1639 }
1640
1641 switch ($row['t3ver_state']) {
1642 case 1:
1643 $parts[] = 'PLH WSID#' . $row['t3ver_wsid'];
1644 break;
1645 case 2:
1646 $parts[] = 'Deleted element!';
1647 break;
1648 case 3:
1649 $parts[] = 'NEW LOCATION (PLH) WSID#' . $row['t3ver_wsid'];
1650 break;
1651 case 4:
1652 $parts[] = 'OLD LOCATION (PNT) WSID#' . $row['t3ver_wsid'];
1653 break;
1654 case -1:
1655 $parts[] = 'New element!';
1656 break;
1657 }
1658
1659 if ($row['doktype'] == t3lib_pageSelect::DOKTYPE_LINK) {
1660 $parts[] = $GLOBALS['LANG']->sL($GLOBALS['TCA']['pages']['columns']['url']['label']) . ' ' . $row['url'];
1661 } elseif ($row['doktype'] == t3lib_pageSelect::DOKTYPE_SHORTCUT) {
1662 if ($perms_clause) {
1663 $label = self::getRecordPath(intval($row['shortcut']), $perms_clause, 20);
1664 } else {
1665 $row['shortcut'] = intval($row['shortcut']);
1666 $lRec = self::getRecordWSOL('pages', $row['shortcut'], 'title');
1667 $label = $lRec['title'] . ' (id=' . $row['shortcut'] . ')';
1668 }
1669 if ($row['shortcut_mode'] != t3lib_pageSelect::SHORTCUT_MODE_NONE) {
1670 $label .= ', ' . $GLOBALS['LANG']->sL($GLOBALS['TCA']['pages']['columns']['shortcut_mode']['label']) . ' ' .
1671 $GLOBALS['LANG']->sL(self::getLabelFromItemlist('pages', 'shortcut_mode', $row['shortcut_mode']));
1672 }
1673 $parts[] = $GLOBALS['LANG']->sL($GLOBALS['TCA']['pages']['columns']['shortcut']['label']) . ' ' . $label;
1674 } elseif ($row['doktype'] == t3lib_pageSelect::DOKTYPE_MOUNTPOINT) {
1675 if ($perms_clause) {
1676 $label = self::getRecordPath(intval($row['mount_pid']), $perms_clause, 20);
1677 } else {
1678 $lRec = self::getRecordWSOL('pages', intval($row['mount_pid']), 'title');
1679 $label = $lRec['title'];
1680 }
1681 $parts[] = $GLOBALS['LANG']->sL($GLOBALS['TCA']['pages']['columns']['mount_pid']['label']) . ' ' . $label;
1682 if ($row['mount_pid_ol']) {
1683 $parts[] = $GLOBALS['LANG']->sL($GLOBALS['TCA']['pages']['columns']['mount_pid_ol']['label']);
1684 }
1685 }
1686 if ($row['nav_hide']) {
1687 $parts[] = rtrim($GLOBALS['LANG']->sL($GLOBALS['TCA']['pages']['columns']['nav_hide']['label']), ':');
1688 }
1689 if ($row['hidden']) {
1690 $parts[] = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.hidden');
1691 }
1692 if ($row['starttime']) {
1693 $parts[] = $GLOBALS['LANG']->sL($GLOBALS['TCA']['pages']['columns']['starttime']['label']) . ' ' . self::dateTimeAge($row['starttime'], -1, 'date');
1694 }
1695 if ($row['endtime']) {
1696 $parts[] = $GLOBALS['LANG']->sL($GLOBALS['TCA']['pages']['columns']['endtime']['label']) . ' ' . self::dateTimeAge($row['endtime'], -1, 'date');
1697 }
1698 if ($row['fe_group']) {
1699 $fe_groups = array();
1700 foreach (t3lib_div::intExplode(',', $row['fe_group']) as $fe_group) {
1701 if ($fe_group < 0) {
1702 $fe_groups[] = $GLOBALS['LANG']->sL(self::getLabelFromItemlist('pages', 'fe_group', $fe_group));
1703 } else {
1704 $lRec = self::getRecordWSOL('fe_groups', $fe_group, 'title');
1705 $fe_groups[] = $lRec['title'];
1706 }
1707 }
1708 $label = implode(', ', $fe_groups);
1709 $parts[] = $GLOBALS['LANG']->sL($GLOBALS['TCA']['pages']['columns']['fe_group']['label']) . ' ' . $label;
1710 }
1711 $out = htmlspecialchars(implode(' - ', $parts));
1712 return $includeAttrib ? 'title="' . $out . '"' : $out;
1713 }
1714
1715 /**
1716 * Returns title-attribute information for ANY record (from a table defined in TCA of course)
1717 * The included information depends on features of the table, but if hidden, starttime, endtime and fe_group fields are configured for, information about the record status in regard to these features are is included.
1718 * "pages" table can be used as well and will return the result of ->titleAttribForPages() for that page.
1719 *
1720 * @param array Table row; $row is a row from the table, $table
1721 * @param string Table name
1722 * @return string
1723 */
1724 public static function getRecordIconAltText($row, $table = 'pages') {
1725 if ($table == 'pages') {
1726 $out = self::titleAttribForPages($row, '', 0);
1727 } else {
1728 $ctrl = $GLOBALS['TCA'][$table]['ctrl']['enablecolumns'];
1729
1730 $out = 'id=' . $row['uid']; // Uid is added
1731 if ($table == 'pages' && $row['alias']) {
1732 $out .= ' / ' . $row['alias'];
1733 }
1734 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS'] && $row['pid'] < 0) {
1735 $out .= ' - v#1.' . $row['t3ver_id'];
1736 }
1737 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
1738 switch ($row['t3ver_state']) {
1739 case 1:
1740 $out .= ' - PLH WSID#' . $row['t3ver_wsid'];
1741 break;
1742 case 2:
1743 $out .= ' - Deleted element!';
1744 break;
1745 case 3:
1746 $out .= ' - NEW LOCATION (PLH) WSID#' . $row['t3ver_wsid'];
1747 break;
1748 case 4:
1749 $out .= ' - OLD LOCATION (PNT) WSID#' . $row['t3ver_wsid'];
1750 break;
1751 case -1:
1752 $out .= ' - New element!';
1753 break;
1754 }
1755 }
1756
1757 if ($ctrl['disabled']) { // Hidden ...
1758 $out .= ($row[$ctrl['disabled']] ? ' - ' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.hidden') : '');
1759 }
1760 if ($ctrl['starttime']) {
1761 if ($row[$ctrl['starttime']] > $GLOBALS['EXEC_TIME']) {
1762 $out .= ' - ' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.starttime') . ':' .
1763 self::date($row[$ctrl['starttime']]) . ' (' . self::daysUntil($row[$ctrl['starttime']]) . ' ' .
1764 $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.days') . ')';
1765 }
1766 }
1767 if ($row[$ctrl['endtime']]) {
1768 $out .= ' - ' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.endtime') . ': ' .
1769 self::date($row[$ctrl['endtime']]) . ' (' . self::daysUntil($row[$ctrl['endtime']]) . ' ' .
1770 $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.days') . ')';
1771 }
1772 }
1773 return htmlspecialchars($out);
1774 }
1775
1776 /**
1777 * Returns the label of the first found entry in an "items" array from $GLOBALS['TCA'] (tablename = $table/fieldname = $col) where the value is $key
1778 *
1779 * @param string Table name, present in $GLOBALS['TCA']
1780 * @param string Field name, present in $GLOBALS['TCA']
1781 * @param string items-array value to match
1782 * @return string Label for item entry
1783 */
1784 public static function getLabelFromItemlist($table, $col, $key) {
1785 // Load full TCA for $table
1786 t3lib_div::loadTCA($table);
1787
1788 // Check, if there is an "items" array:
1789 if (is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'][$col]) && is_array($GLOBALS['TCA'][$table]['columns'][$col]['config']['items'])) {
1790 // Traverse the items-array...
1791 foreach ($GLOBALS['TCA'][$table]['columns'][$col]['config']['items'] as $k => $v) {
1792 // ... and return the first found label where the value was equal to $key
1793 if (!strcmp($v[1], $key)) {
1794 return $v[0];
1795 }
1796 }
1797 }
1798 }
1799
1800 /**
1801 * Splits the given key with commas and returns the list of all the localized items labels, separated by a comma.
1802 * NOTE: this does not take itemsProcFunc into account
1803 *
1804 * @static
1805 * @param string $table Table name, present in TCA
1806 * @param string $column Field name
1807 * @param string $key Key or comma-separated list of keys.
1808 * @return string Comma-separated list of localized labels
1809 */
1810 public static function getLabelsFromItemsList($table, $column, $key) {
1811 $labels = array();
1812 $values = t3lib_div::trimExplode(',', $key, TRUE);
1813 if (count($values) > 0) {
1814 // Load full TCA for $table
1815 t3lib_div::loadTCA($table);
1816 // Check if there is an "items" array
1817 if (is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'][$column]) && is_array($GLOBALS['TCA'][$table]['columns'][$column]['config']['items'])) {
1818 // Loop on all selected values
1819 foreach ($values as $aValue) {
1820 foreach ($GLOBALS['TCA'][$table]['columns'][$column]['config']['items'] as $itemConfiguration) {
1821 // Loop on all available items
1822 // Keep matches and move on to next value
1823 if ($aValue == $itemConfiguration[1]) {
1824 $labels[] = $GLOBALS['LANG']->sL($itemConfiguration[0]);
1825 break;
1826 }
1827 }
1828 }
1829
1830 }
1831 }
1832 return implode(', ', $labels);
1833 }
1834
1835 /**
1836 * Returns the label-value for fieldname $col in table, $table
1837 * If $printAllWrap is set (to a "wrap") then it's wrapped around the $col value IF THE COLUMN $col DID NOT EXIST in TCA!, eg. $printAllWrap = '<strong>|</strong>' and the fieldname was 'not_found_field' then the return value would be '<strong>not_found_field</strong>'
1838 *
1839 * @param string Table name, present in $GLOBALS['TCA']
1840 * @param string Field name
1841 * @param string Wrap value - set function description
1842 * @return string
1843 */
1844 public static function getItemLabel($table, $col, $printAllWrap = '') {
1845 // Load full TCA for $table
1846 t3lib_div::loadTCA($table);
1847 // Check if column exists
1848 if (is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'][$col])) {
1849 // Re
1850 return $GLOBALS['TCA'][$table]['columns'][$col]['label'];
1851 }
1852 if ($printAllWrap) {
1853 $parts = explode('|', $printAllWrap);
1854 return $parts[0] . $col . $parts[1];
1855 }
1856 }
1857
1858 /**
1859 * Returns the "title"-value in record, $row, from table, $table
1860 * The field(s) from which the value is taken is determined by the "ctrl"-entries 'label', 'label_alt' and 'label_alt_force'
1861 *
1862 * @param string Table name, present in TCA
1863 * @param array Row from table
1864 * @param boolean If set, result is prepared for output: The output is cropped to a limited lenght (depending on BE_USER->uc['titleLen']) and if no value is found for the title, '<em>[No title]</em>' is returned (localized). Further, the output is htmlspecialchars()'ed
1865 * @param boolean If set, the function always returns an output. If no value is found for the title, '[No title]' is returned (localized).
1866 * @return string
1867 */
1868 public static function getRecordTitle($table, $row, $prep = FALSE, $forceResult = TRUE) {
1869 if (is_array($GLOBALS['TCA'][$table])) {
1870
1871 // If configured, call userFunc
1872 if ($GLOBALS['TCA'][$table]['ctrl']['label_userFunc']) {
1873 $params['table'] = $table;
1874 $params['row'] = $row;
1875 $params['title'] = '';
1876 //create NULL-reference
1877 $null = NULL;
1878 t3lib_div::callUserFunction($GLOBALS['TCA'][$table]['ctrl']['label_userFunc'], $params, $null);
1879 $t = $params['title'];
1880 } else {
1881
1882 // No userFunc: Build label
1883 $t = self::getProcessedValue($table, $GLOBALS['TCA'][$table]['ctrl']['label'], $row[$GLOBALS['TCA'][$table]['ctrl']['label']], 0, 0, FALSE, $row['uid'], $forceResult);
1884 if ($GLOBALS['TCA'][$table]['ctrl']['label_alt'] && ($GLOBALS['TCA'][$table]['ctrl']['label_alt_force'] || !strcmp($t, ''))) {
1885 $altFields = t3lib_div::trimExplode(',', $GLOBALS['TCA'][$table]['ctrl']['label_alt'], 1);
1886 $tA = array();
1887 if (!empty($t)) {
1888 $tA[] = $t;
1889 }
1890 foreach ($altFields as $fN) {
1891 $t = trim(strip_tags($row[$fN]));
1892 if (strcmp($t, '')) {
1893 $t = self::getProcessedValue($table, $fN, $t, 0, 0, FALSE, $row['uid']);
1894 if (!$GLOBALS['TCA'][$table]['ctrl']['label_alt_force']) {
1895 break;
1896 }
1897 $tA[] = $t;
1898 }
1899 }
1900 if ($GLOBALS['TCA'][$table]['ctrl']['label_alt_force']) {
1901 $t = implode(', ', $tA);
1902 }
1903 }
1904 }
1905
1906 // If the current result is empty, set it to '[No title]' (localized) and prepare for output if requested
1907 if ($prep || $forceResult) {
1908 if ($prep) {
1909 $t = self::getRecordTitlePrep($t);
1910 }
1911 if (!strcmp(trim($t), '')) {
1912 $t = self::getNoRecordTitle($prep);
1913 }
1914 }
1915
1916 return $t;
1917 }
1918 }
1919
1920 /**
1921 * Crops a title string to a limited lenght and if it really was cropped, wrap it in a <span title="...">|</span>,
1922 * which offers a tooltip with the original title when moving mouse over it.
1923 *
1924 * @param string $title: The title string to be cropped
1925 * @param integer $titleLength: Crop title after this length - if not set, BE_USER->uc['titleLen'] is used
1926 * @return string The processed title string, wrapped in <span title="...">|</span> if cropped
1927 */
1928 public static function getRecordTitlePrep($title, $titleLength = 0) {
1929 // If $titleLength is not a valid positive integer, use BE_USER->uc['titleLen']:
1930 if (!$titleLength || !t3lib_utility_Math::canBeInterpretedAsInteger($titleLength) || $titleLength < 0) {
1931 $titleLength = $GLOBALS['BE_USER']->uc['titleLen'];
1932 }
1933 $titleOrig = htmlspecialchars($title);
1934 $title = htmlspecialchars(t3lib_div::fixed_lgd_cs($title, $titleLength));
1935 // If title was cropped, offer a tooltip:
1936 if ($titleOrig != $title) {
1937 $title = '<span title="' . $titleOrig . '">' . $title . '</span>';
1938 }
1939 return $title;
1940 }
1941
1942 /**
1943 * Get a localized [No title] string, wrapped in <em>|</em> if $prep is TRUE.
1944 *
1945 * @param boolean $prep: Wrap result in <em>|</em>
1946 * @return string Localized [No title] string
1947 */
1948 public static function getNoRecordTitle($prep = FALSE) {
1949 $noTitle = '[' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.no_title', 1) . ']';
1950 if ($prep) {
1951 $noTitle = '<em>' . $noTitle . '</em>';
1952 }
1953 return $noTitle;
1954 }
1955
1956 /**
1957 * Returns a human readable output of a value from a record
1958 * For instance a database record relation would be looked up to display the title-value of that record. A checkbox with a "1" value would be "Yes", etc.
1959 * $table/$col is tablename and fieldname
1960 * REMEMBER to pass the output through htmlspecialchars() if you output it to the browser! (To protect it from XSS attacks and be XHTML compliant)
1961 *
1962 * @param string Table name, present in TCA
1963 * @param string Field name, present in TCA
1964 * @param string $value is the value of that field from a selected record
1965 * @param integer $fixed_lgd_chars is the max amount of characters the value may occupy
1966 * @param boolean $defaultPassthrough flag means that values for columns that has no conversion will just be pass through directly (otherwise cropped to 200 chars or returned as "N/A")
1967 * @param boolean If set, no records will be looked up, UIDs are just shown.
1968 * @param integer uid of the current record
1969 * @param boolean If t3lib_BEfunc::getRecordTitle is used to process the value, this parameter is forwarded.
1970 * @return string
1971 */
1972 public static function getProcessedValue($table, $col, $value, $fixed_lgd_chars = 0, $defaultPassthrough = 0, $noRecordLookup = FALSE, $uid = 0, $forceResult = TRUE) {
1973 if ($col == 'uid') {
1974 // no need to load TCA as uid is not in TCA-array
1975 return $value;
1976 }
1977 // Load full TCA for $table
1978 t3lib_div::loadTCA($table);
1979 // Check if table and field is configured:
1980 if (is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'][$col])) {
1981 // Depending on the fields configuration, make a meaningful output value.
1982 $theColConf = $GLOBALS['TCA'][$table]['columns'][$col]['config'];
1983
1984 /*****************
1985 *HOOK: pre-processing the human readable output from a record
1986 ****************/
1987 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['preProcessValue'])) {
1988 // create NULL-reference
1989 $null = NULL;
1990 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['preProcessValue'] as $_funcRef) {
1991 t3lib_div::callUserFunction($_funcRef, $theColConf, $null);
1992 }
1993 }
1994
1995 $l = '';
1996 switch ((string) $theColConf['type']) {
1997 case 'radio':
1998 $l = self::getLabelFromItemlist($table, $col, $value);
1999 $l = $GLOBALS['LANG']->sL($l);
2000 break;
2001 case 'select':
2002 if ($theColConf['MM']) {
2003 if ($uid) {
2004 // Display the title of MM related records in lists
2005 if ($noRecordLookup) {
2006 $MMfield = $theColConf['foreign_table'] . '.uid';
2007 } else {
2008 $MMfields = array($theColConf['foreign_table'] . '.' . $GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label']);
2009 foreach (t3lib_div::trimExplode(',', $GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label_alt'], 1) as $f) {
2010 $MMfields[] = $theColConf['foreign_table'] . '.' . $f;
2011 }
2012 $MMfield = join(',', $MMfields);
2013 }
2014
2015 /** @var $dbGroup t3lib_loadDBGroup */
2016 $dbGroup = t3lib_div::makeInstance('t3lib_loadDBGroup');
2017 $dbGroup->start($value, $theColConf['foreign_table'], $theColConf['MM'], $uid, $table, $theColConf);
2018 $selectUids = $dbGroup->tableArray[$theColConf['foreign_table']];
2019
2020 if (is_array($selectUids) && count($selectUids) > 0) {
2021 $MMres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
2022 'uid, ' . $MMfield,
2023 $theColConf['foreign_table'],
2024 'uid IN (' . implode(',', $selectUids) . ')'
2025 );
2026 while ($MMrow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($MMres)) {
2027 $mmlA[] = ($noRecordLookup ? $MMrow['uid'] : self::getRecordTitle($theColConf['foreign_table'], $MMrow, FALSE, $forceResult));
2028 }
2029 $GLOBALS['TYPO3_DB']->sql_free_result($MMres);
2030
2031 if (is_array($mmlA)) {
2032 $l = implode('; ', $mmlA);
2033 } else {
2034 $l = '';
2035 }
2036 } else {
2037 $l = 'N/A';
2038 }
2039 } else {
2040 $l = 'N/A';
2041 }
2042 } else {
2043 $l = self::getLabelsFromItemsList($table, $col, $value);
2044
2045 if ($theColConf['foreign_table'] && !$l && $GLOBALS['TCA'][$theColConf['foreign_table']]) {
2046 if ($noRecordLookup) {
2047 $l = $value;
2048 } else {
2049 $rParts = t3lib_div::trimExplode(',', $value, 1);
2050 $lA = array();
2051 foreach ($rParts as $rVal) {
2052 $rVal = intval($rVal);
2053 if ($rVal > 0) {
2054 $r = self::getRecordWSOL($theColConf['foreign_table'], $rVal);
2055 } else {
2056 $r = self::getRecordWSOL($theColConf['neg_foreign_table'], -$rVal);
2057 }
2058 if (is_array($r)) {
2059 $lA[] = $GLOBALS['LANG']->sL($rVal > 0 ? $theColConf['foreign_table_prefix'] : $theColConf['neg_foreign_table_prefix']) . self::getRecordTitle($rVal > 0 ? $theColConf['foreign_table'] : $theColConf['neg_foreign_table'], $r, FALSE, $forceResult);
2060 } else {
2061 $lA[] = $rVal ? '[' . $rVal . '!]' : '';
2062 }
2063 }
2064 $l = implode(', ', $lA);
2065 }
2066 }
2067 }
2068 break;
2069 case 'group':
2070 $l = implode(', ', t3lib_div::trimExplode(',', $value, 1));
2071 break;
2072 case 'check':
2073 if (!is_array($theColConf['items']) || count($theColConf['items']) == 1) {
2074 $l = $value ? $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:yes') : $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:no');
2075 } else {
2076 $lA = Array();
2077 foreach ($theColConf['items'] as $key => $val) {
2078 if ($value & pow(2, $key)) {
2079 $lA[] = $GLOBALS['LANG']->sL($val[0]);
2080 }
2081 }
2082 $l = implode(', ', $lA);
2083 }
2084 break;
2085 case 'input':
2086 // hide value 0 for dates, but show it for everything else
2087 if (isset($value)) {
2088 if (t3lib_div::inList($theColConf['eval'], 'date')) {
2089 if (!empty($value)) {
2090 $l = self::date($value) .
2091 ' (' .
2092 ($GLOBALS['EXEC_TIME'] - $value > 0 ? '-' : '') .
2093 self::calcAge(abs($GLOBALS['EXEC_TIME'] - $value), $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears')) .
2094 ')';
2095 }
2096 } elseif (t3lib_div::inList($theColConf['eval'], 'time')) {
2097 if (!empty($value)) {
2098 $l = self::time($value, FALSE);
2099 }
2100 } elseif (t3lib_div::inList($theColConf['eval'], 'timesec')) {
2101 if (!empty($value)) {
2102 $l = self::time($value);
2103 }
2104 } elseif (t3lib_div::inList($theColConf['eval'], 'datetime')) {
2105 if (!empty($value)) {
2106 $l = self::datetime($value);
2107 }
2108 } else {
2109 $l = $value;
2110 }
2111 }
2112 break;
2113 case 'flex':
2114 $l = strip_tags($value);
2115 break;
2116 default:
2117 if ($defaultPassthrough) {
2118 $l = $value;
2119 } elseif ($theColConf['MM']) {
2120 $l = 'N/A';
2121 } elseif ($value) {
2122 $l = t3lib_div::fixed_lgd_cs(strip_tags($value), 200);
2123 }
2124 break;
2125 }
2126
2127 // If this field is a password field, then hide the password by changing it to a random number of asterisk (*)
2128 if (stristr($theColConf['eval'], 'password')) {
2129 $l = '';
2130 $randomNumber = rand(5, 12);
2131 for ($i = 0; $i < $randomNumber; $i++) {
2132 $l .= '*';
2133 }
2134 }
2135
2136 /*****************
2137 *HOOK: post-processing the human readable output from a record
2138 ****************/
2139 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['postProcessValue'])) {
2140 // create NULL-reference
2141 $null = NULL;
2142 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['postProcessValue'] as $_funcRef) {
2143 $params = array(
2144 'value' => $l,
2145 'colConf' => $theColConf
2146 );
2147 $l = t3lib_div::callUserFunction($_funcRef, $params, $null);
2148 }
2149 }
2150
2151 if ($fixed_lgd_chars) {
2152 return t3lib_div::fixed_lgd_cs($l, $fixed_lgd_chars);
2153 } else {
2154 return $l;
2155 }
2156 }
2157 }
2158
2159 /**
2160 * Same as ->getProcessedValue() but will go easy on fields like "tstamp" and "pid" which are not configured in TCA - they will be formatted by this function instead.
2161 *
2162 * @param string Table name, present in TCA
2163 * @param string Field name
2164 * @param string Field value
2165 * @param integer $fixed_lgd_chars is the max amount of characters the value may occupy
2166 * @param integer uid of the current record
2167 * @param boolean If t3lib_BEfunc::getRecordTitle is used to process the value, this parameter is forwarded.
2168 * @return string
2169 * @see getProcessedValue()
2170 */
2171 public static function getProcessedValueExtra($table, $fN, $fV, $fixed_lgd_chars = 0, $uid = 0, $forceResult = TRUE) {
2172 $fVnew = self::getProcessedValue($table, $fN, $fV, $fixed_lgd_chars, 1, 0, $uid, $forceResult);
2173 if (!isset($fVnew)) {
2174 if (is_array($GLOBALS['TCA'][$table])) {
2175 if ($fN == $GLOBALS['TCA'][$table]['ctrl']['tstamp'] || $fN == $GLOBALS['TCA'][$table]['ctrl']['crdate']) {
2176 $fVnew = self::datetime($fV);
2177 } elseif ($fN == 'pid') {
2178 $fVnew = self::getRecordPath($fV, '1=1', 20); // Fetches the path with no regard to the users permissions to select pages.
2179 } else {
2180 $fVnew = $fV;
2181 }
2182 }
2183 }
2184 return $fVnew;
2185 }
2186
2187 /**
2188 * Returns file icon name (from $FILEICONS) for the fileextension $ext
2189 *
2190 * @param string File extension, lowercase
2191 * @return string File icon filename
2192 */
2193 public static function getFileIcon($ext) {
2194 return $GLOBALS['FILEICONS'][$ext] ? $GLOBALS['FILEICONS'][$ext] : $GLOBALS['FILEICONS']['default'];
2195 }
2196
2197 /**
2198 * Returns fields for a table, $table, which would typically be interesting to select
2199 * This includes uid, the fields defined for title, icon-field.
2200 * Returned as a list ready for query ($prefix can be set to eg. "pages." if you are selecting from the pages table and want the table name prefixed)
2201 *
2202 * @param string Table name, present in $GLOBALS['TCA']
2203 * @param string Table prefix
2204 * @param array Preset fields (must include prefix if that is used)
2205 * @return string List of fields.
2206 */
2207 public static function getCommonSelectFields($table, $prefix = '', $fields = array()) {
2208 $fields[] = $prefix . 'uid';
2209 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['label'];
2210
2211 if ($GLOBALS['TCA'][$table]['ctrl']['label_alt']) {
2212 $secondFields = t3lib_div::trimExplode(',', $GLOBALS['TCA'][$table]['ctrl']['label_alt'], 1);
2213 foreach ($secondFields as $fieldN) {
2214 $fields[] = $prefix . $fieldN;
2215 }
2216 }
2217 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
2218 $fields[] = $prefix . 't3ver_id';
2219 $fields[] = $prefix . 't3ver_state';
2220 $fields[] = $prefix . 't3ver_wsid';
2221 $fields[] = $prefix . 't3ver_count';
2222 }
2223
2224 if ($GLOBALS['TCA'][$table]['ctrl']['selicon_field']) {
2225 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['selicon_field'];
2226 }
2227 if ($GLOBALS['TCA'][$table]['ctrl']['typeicon_column']) {
2228 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['typeicon_column'];
2229 }
2230
2231 if (is_array($GLOBALS['TCA'][$table]['ctrl']['enablecolumns'])) {
2232 if ($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['disabled']) {
2233 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['disabled'];
2234 }
2235 if ($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['starttime']) {
2236 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['starttime'];
2237 }
2238 if ($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['endtime']) {
2239 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['endtime'];
2240 }
2241 if ($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['fe_group']) {
2242 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['fe_group'];
2243 }
2244 }
2245
2246 return implode(',', array_unique($fields));
2247 }
2248
2249 /**
2250 * Makes a form for configuration of some values based on configuration found in the array $configArray, with default values from $defaults and a data-prefix $dataPrefix
2251 * <form>-tags must be supplied separately
2252 * Needs more documentation and examples, in particular syntax for configuration array. See Inside TYPO3. That's were you can expect to find example, if anywhere.
2253 *
2254 * @param array Field configuration code.
2255 * @param array Defaults
2256 * @param string Prefix for formfields
2257 * @return string HTML for a form.
2258 */
2259 public static function makeConfigForm($configArray, $defaults, $dataPrefix) {
2260 $params = $defaults;
2261 if (is_array($configArray)) {
2262 $lines = array();
2263 foreach ($configArray as $fname => $config) {
2264 if (is_array($config)) {
2265 $lines[$fname] = '<strong>' . htmlspecialchars($config[1]) . '</strong><br />';
2266 $lines[$fname] .= $config[2] . '<br />';
2267 switch ($config[0]) {
2268 case 'string':
2269 case 'short':
2270 $formEl = '<input type="text" name="' . $dataPrefix . '[' . $fname . ']" value="' . $params[$fname] . '"' . $GLOBALS['TBE_TEMPLATE']->formWidth($config[0] == 'short' ? 24 : 48) . ' />';
2271 break;
2272 case 'check':
2273 $formEl = '<input type="hidden" name="' . $dataPrefix . '[' . $fname . ']" value="0" /><input type="checkbox" name="' . $dataPrefix . '[' . $fname . ']" value="1"' . ($params[$fname] ? ' checked="checked"' : '') . ' />';
2274 break;
2275 case 'comment':
2276 $formEl = '';
2277 break;
2278 case 'select':
2279 $opt = array();
2280 foreach ($config[3] as $k => $v) {
2281 $opt[] = '<option value="' . htmlspecialchars($k) . '"' . ($params[$fname] == $k ? ' selected="selected"' : '') . '>' . htmlspecialchars($v) . '</option>';
2282 }
2283 $formEl = '<select name="' . $dataPrefix . '[' . $fname . ']">' . implode('', $opt) . '</select>';
2284 break;
2285 default:
2286 debug($config);
2287 break;
2288 }
2289 $lines[$fname] .= $formEl;
2290 $lines[$fname] .= '<br /><br />';
2291 } else {
2292 $lines[$fname] = '<hr />';
2293 if ($config) {
2294 $lines[$fname] .= '<strong>' . strtoupper(htmlspecialchars($config)) . '</strong><br />';
2295 }
2296 if ($config) {
2297 $lines[$fname] .= '<br />';
2298 }
2299 }
2300 }
2301 }
2302 $out = implode('', $lines);
2303 $out .= '<input type="submit" name="submit" value="Update configuration" />';
2304 return $out;
2305 }
2306
2307
2308 /*******************************************
2309 *
2310 * Backend Modules API functions
2311 *
2312 *******************************************/
2313
2314 /**
2315 * Returns help-text icon if configured for.
2316 * TCA_DESCR must be loaded prior to this function and $GLOBALS['BE_USER'] must
2317 * have 'edit_showFieldHelp' set to 'icon', otherwise nothing is returned
2318 *
2319 * Please note: since TYPO3 4.5 the UX team decided to not use CSH in its former way,
2320 * but to wrap the given text (where before the help icon was, and you could hover over it)
2321 * Please also note that since TYPO3 4.5 the option to enable help (none, icon only, full text)
2322 * was completely removed.
2323 *
2324 * @param string Table name
2325 * @param string Field name
2326 * @param string Back path
2327 * @param boolean Force display of icon no matter BE_USER setting for help
2328 * @return string HTML content for a help icon/text
2329 */
2330 public static function helpTextIcon($table, $field, $BACK_PATH, $force = 0) {
2331 if (is_array($GLOBALS['TCA_DESCR'][$table]) && is_array($GLOBALS['TCA_DESCR'][$table]['columns'][$field]) && (isset($GLOBALS['BE_USER']->uc['edit_showFieldHelp']) || $force)) {
2332 return self::wrapInHelp($table, $field);
2333 }
2334 }
2335
2336 /**
2337 * Returns CSH help text (description), if configured for, as an array (title, description)
2338 * Will automatically call t3lib_BEfunc::helpTextIcon() to get the icon for the text.
2339 *
2340 * @param string Table name
2341 * @param string Field name
2342 * @return array With keys 'description' (raw, as available in locallang), 'title' (optional), 'moreInfo'
2343 */
2344 public static function helpTextArray($table, $field) {
2345 if (!isset($GLOBALS['TCA_DESCR'][$table]['columns'])) {
2346 $GLOBALS['LANG']->loadSingleTableDescription($table);
2347 }
2348 $output = array(
2349 'description' => NULL,
2350 'title' => NULL,
2351 'moreInfo' => FALSE,
2352 );
2353 if (is_array($GLOBALS['TCA_DESCR'][$table]) && is_array($GLOBALS['TCA_DESCR'][$table]['columns'][$field])) {
2354 $data = $GLOBALS['TCA_DESCR'][$table]['columns'][$field];
2355
2356 // add alternative title, if defined
2357 if ($data['alttitle']) {
2358 $output['title'] = $data['alttitle'];
2359 }
2360
2361 // if we have more information to show
2362 if ($data['image_descr'] || $data['seeAlso'] || $data['details'] || $data['syntax']) {
2363 $output['moreInfo'] = TRUE;
2364 }
2365
2366 // add description
2367 if ($data['description']) {
2368 $output['description'] = $data['description'];
2369 }
2370 }
2371 return $output;
2372 }
2373
2374 /**
2375 * Returns CSH help text (description), if configured for.
2376 * $GLOBALS['TCA_DESCR'] must be loaded prior to this function and $GLOBALS['BE_USER'] must have "edit_showFieldHelp" set to "text",
2377 * otherwise nothing is returned
2378 * Will automatically call t3lib_BEfunc::helpTextIcon() to get the icon for the text.
2379 *
2380 * @param string Table name
2381 * @param string Field name
2382 * @param string Back path, deprecated since TYPO3 4.5, will be removed in TYPO3 4.7, because not used at all
2383 * @param string DEPRECATED: Additional style-attribute content for wrapping table (now: only in function cshItem needed)
2384 * @return string HTML content for help text
2385 */
2386 public static function helpText($table, $field, $BACK_PATH = '', $styleAttrib = '') {
2387 $helpTextArray = self::helpTextArray($table, $field);
2388
2389 $output = '';
2390
2391 // put header before the rest of the text
2392 if ($helpTextArray['title'] !== NULL) {
2393 $output .= '<h2 class="t3-row-header">' . $helpTextArray['title'] . '</h2>';
2394 }
2395 // add the content
2396 if ($helpTextArray['description'] !== NULL) {
2397 $output .= $helpTextArray['description'];
2398 }
2399 // add see also arrow if we have more info
2400 if ($helpTextArray['moreInfo']) {
2401 $arrow = t3lib_iconWorks::getSpriteIcon('actions-view-go-forward');
2402 }
2403 // add description text
2404 if ($helpTextArray['description'] || $arrow) {
2405 $output['description'] = '<p class="t3-help-short">' . nl2br(htmlspecialchars($helpTextArray['description'])) . $arrow . '</p>';
2406 }
2407
2408 return $output;
2409 }
2410
2411 /**
2412 * API function that wraps the text / html in help text, so if a user hovers over it
2413 * the help text will show up
2414 * This is the new help API function since TYPO3 4.5, and uses the new behaviour
2415 * (hover over text, no icon, no fulltext option, no option to disable the help)
2416 *
2417 * @param string $table The table name for which the help should be shown
2418 * @param string $field The field name for which the help should be shown
2419 * @param string $text the text which should be wrapped with the help text
2420 * @return string the HTML code ready to render
2421 * @api public
2422 */
2423 public static function wrapInHelp($table, $field, $text = '', array $overloadHelpText = array()) {
2424 // Initialize some variables
2425 $helpText = '';
2426 $abbrClassAdd = '';
2427 $wrappedText = $text;
2428 $hasHelpTextOverload = count($overloadHelpText) > 0;
2429
2430 // Get the help text that should be shown on hover
2431 if (!$hasHelpTextOverload) {
2432 $helpText = self::helpText($table, $field);
2433 }
2434
2435 // If there's a help text or some overload information, proceed with preparing an output
2436 if (!empty($helpText) || $hasHelpTextOverload) {
2437 // If no text was given, just use the regular help icon
2438 if ($text == '') {
2439 $text = t3lib_iconWorks::getSpriteIcon('actions-system-help-open');
2440 $abbrClassAdd = '-icon';
2441 }
2442 $text = '<abbr class="t3-help-teaser' . $abbrClassAdd . '">' . $text . '</abbr>';
2443 $wrappedText = '<span class="t3-help-link" href="#" data-table="' . $table . '" data-field="' . $field . '"';
2444 // The overload array may provide a title and a description
2445 // If either one is defined, add them to the "data" attributes
2446 if ($hasHelpTextOverload) {
2447 if (isset($overloadHelpText['title'])) {
2448 $wrappedText .= ' data-title="' . htmlspecialchars($overloadHelpText['title']) . '"';
2449 }
2450 if (isset($overloadHelpText['description'])) {
2451 $wrappedText .= ' data-description="' . htmlspecialchars($overloadHelpText['description']) . '"';
2452 }
2453 }
2454 $wrappedText .= '>' . $text . '</span>';
2455 }
2456
2457 return $wrappedText;
2458 }
2459
2460
2461 /**
2462 * API for getting CSH icons/text for use in backend modules.
2463 * TCA_DESCR will be loaded if it isn't already
2464 *
2465 * @param string Table name ('_MOD_'+module name)
2466 * @param string Field name (CSH locallang main key)
2467 * @param string Back path
2468 * @param string Wrap code for icon-mode, splitted by "|". Not used for full-text mode.
2469 * @param boolean If set, the full text will never be shown (only icon).
2470 * Useful for places where it will break the page if the table with full text is shown.
2471 * @param string Additional style-attribute content for wrapping table (full text mode only)
2472 * @return string HTML content for help text
2473 * @see helpText(), helpTextIcon()
2474 */
2475 public static function cshItem($table, $field, $BACK_PATH, $wrap = '', $onlyIconMode = FALSE, $styleAttrib = '') {
2476 if ($GLOBALS['BE_USER']->uc['edit_showFieldHelp']) {
2477 $GLOBALS['LANG']->loadSingleTableDescription($table);
2478
2479 if (is_array($GLOBALS['TCA_DESCR'][$table])) {
2480 // Creating CSH icon and short description:
2481 $fullText = self::helpText($table, $field, $BACK_PATH, '');
2482 $icon = self::helpTextIcon($table, $field, $BACK_PATH);
2483
2484 if ($fullText && !$onlyIconMode && $GLOBALS['BE_USER']->uc['edit_showFieldHelp'] == 'text') {
2485
2486 // Additional styles?
2487 $params = $styleAttrib ? ' style="' . $styleAttrib . '"' : '';
2488
2489 // Compile table with CSH information:
2490 $fullText = '<table border="0" cellpadding="0" cellspacing="0" class="typo3-csh-inline"' . $params . '>
2491 <tr>
2492 <td valign="top" width="14"><div class="t3-row-header">' . $icon . '</div></td>
2493 <td valign="top">' . $fullText . '</td>
2494 </tr>
2495 </table>';
2496
2497 $output = $fullText;
2498 } else {
2499 $output = $icon;
2500
2501 if ($output && $wrap) {
2502 $wrParts = explode('|', $wrap);
2503 $output = $wrParts[0] . $output . $wrParts[1];
2504 }
2505 }
2506
2507 return $output;
2508 }
2509 }
2510 }
2511
2512 /**
2513 * Returns a JavaScript string (for an onClick handler) which will load the alt_doc.php script that shows the form for editing of the record(s) you have send as params.
2514 * REMEMBER to always htmlspecialchar() content in href-properties to ampersands get converted to entities (XHTML requirement and XSS precaution)
2515 *
2516 * @param string $params is parameters sent along to alt_doc.php. This requires a much more details description which you must seek in Inside TYPO3s documentation of the alt_doc.php API. And example could be '&edit[pages][123] = edit' which will show edit form for page record 123.
2517 * @param string $backPath must point back to the TYPO3_mainDir directory (where alt_doc.php is)
2518 * @param string $requestUri is an optional returnUrl you can set - automatically set to REQUEST_URI.
2519 * @return string
2520 * @see template::issueCommand()
2521 */
2522 public static function editOnClick($params, $backPath = '', $requestUri = '') {
2523 $retUrl = 'returnUrl=' . ($requestUri == -1 ? "'+T3_THIS_LOCATION+'" : rawurlencode($requestUri ? $requestUri : t3lib_div::getIndpEnv('REQUEST_URI')));
2524 return "window.location.href='" . $backPath . "alt_doc.php?" . $retUrl . $params . "'; return false;";
2525 }
2526
2527 /**
2528 * Returns a JavaScript string for viewing the page id, $id
2529 * It will detect the correct domain name if needed and provide the link with the right back path. Also it will re-use any window already open.
2530 *
2531 * @param integer $pageUid is page id
2532 * @param string $backPath must point back to TYPO3_mainDir (where the site is assumed to be one level above)
2533 * @param array $rootLine If root line is supplied the function will look for the first found domain record and use that URL instead (if found)
2534 * @param string $anchorSection is optional anchor to the URL
2535 * @param string $alternativeUrl is an alternative URL which - if set - will make all other parameters ignored: The function will just return the window.open command wrapped around this URL!
2536 * @param string $additionalGetVars Additional GET variables.
2537 * @param boolean If TRUE, then the preview window will gain the focus.
2538 * @return string
2539 */
2540 public static function viewOnClick($pageUid, $backPath = '', $rootLine = '', $anchorSection = '', $alternativeUrl = '', $additionalGetVars = '', $switchFocus = TRUE) {
2541 $viewScript = '/index.php?id=';
2542 if ($alternativeUrl) {
2543 $viewScript = $alternativeUrl;
2544 }
2545
2546 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['viewOnClickClass'])
2547 && is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['viewOnClickClass'])) {
2548 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['viewOnClickClass'] as $funcRef) {
2549 $hookObj = t3lib_div::getUserObj($funcRef);
2550 if (method_exists($hookObj, 'preProcess')) {
2551 $hookObj->preProcess($pageUid, $backPath, $rootLine, $anchorSection, $viewScript, $additionalGetVars, $switchFocus);
2552 }
2553 }
2554 }
2555
2556 // Look if a fixed preview language should be added:
2557 $viewLanguageOrder = $GLOBALS['BE_USER']->getTSConfigVal('options.view.languageOrder');
2558 if (strlen($viewLanguageOrder)) {
2559 $suffix = '';
2560
2561 // Find allowed languages (if none, all are allowed!)
2562 if (!$GLOBALS['BE_USER']->user['admin'] &&
2563 strlen($GLOBALS['BE_USER']->groupData['allowed_languages'])) {
2564 $allowedLanguages = array_flip(explode(',', $GLOBALS['BE_USER']->groupData['allowed_languages']));
2565 }
2566
2567 // Traverse the view order, match first occurence:
2568 $languageOrder = t3lib_div::intExplode(',', $viewLanguageOrder);
2569 foreach ($languageOrder as $langUid) {
2570 if (is_array($allowedLanguages) && count($allowedLanguages)) {
2571 // Choose if set.
2572 if (isset($allowedLanguages[$langUid])) {
2573 $suffix = '&L=' . $langUid;
2574 break;
2575 }
2576 } else {
2577 // All allowed since no lang. are listed.
2578 $suffix = '&L=' . $langUid;
2579 break;
2580 }
2581 }
2582 // Add it:
2583 $additionalGetVars .= $suffix;
2584 }
2585
2586 // check a mount point needs to be previewed
2587 $sys_page = t3lib_div::makeInstance('t3lib_pageSelect');
2588 $sys_page->init(FALSE);
2589 $mountPointInfo = $sys_page->getMountPointInfo($pageUid);
2590 if ($mountPointInfo && $mountPointInfo['overlay']) {
2591 $pageUid = $mountPointInfo['mount_pid'];
2592 $additionalGetVars .= '&MP=' . $mountPointInfo['MPvar'];
2593 }
2594
2595 $viewDomain = self::getViewDomain($pageUid, $rootLine);
2596 $previewUrl = $viewDomain . $viewScript . $pageUid . $additionalGetVars . $anchorSection;
2597 $onclickCode = "var previewWin = window.open('" . $previewUrl . "','newTYPO3frontendWindow');" . ($switchFocus ? 'previewWin.focus();' : '');
2598 return $onclickCode;
2599 }
2600
2601 /**
2602 * Builds the frontend view domain for a given page ID with a given root
2603 * line.
2604 *
2605 * @param integer $pageId the page ID to use, must be > 0
2606 * @param array $rootLine the root line structure to use
2607 *
2608 * @return string the full domain including the protocol http:// or https://, but without the trailing '/'
2609 *
2610 * @author Michael Klapper <michael.klapper@aoemedia.de>
2611 */
2612 public static function getViewDomain($pageId, $rootLine = NULL) {
2613 $domain = rtrim(t3lib_div::getIndpEnv('TYPO3_SITE_URL'), '/');
2614
2615 if (!is_array($rootLine)) {
2616 $rootLine = self::BEgetRootLine($pageId);
2617 }
2618
2619 // checks alternate domains
2620 if (count($rootLine) > 0) {
2621 $urlParts = parse_url($domain);
2622 if (self::getDomainStartPage($urlParts['host'], $urlParts['path'])) {
2623 /** @var t3lib_pageSelect $sysPage */
2624 $sysPage = t3lib_div::makeInstance('t3lib_pageSelect');
2625
2626 $page = (array)$sysPage->getPage($pageId);
2627 $protocol = 'http';
2628 if ($page['url_scheme'] == t3lib_utility_Http::SCHEME_HTTPS || ($page['url_scheme'] == 0 && t3lib_div::getIndpEnv('TYPO3_SSL'))) {
2629 $protocol = 'https';
2630 }
2631
2632 $domain = $protocol . '://' . self::firstDomainRecord($rootLine);
2633 }
2634 }
2635
2636 return $domain;
2637 }
2638
2639 /**
2640 * Returns the merged User/Page TSconfig for page id, $id.
2641 * Please read details about module programming elsewhere!
2642 *
2643 * @param integer Page uid
2644 * @param string $TSref is an object string which determines the path of the TSconfig to return.
2645 * @return array
2646 */
2647 public static function getModTSconfig($id, $TSref) {
2648 $pageTS_modOptions = $GLOBALS['BE_USER']->getTSConfig($TSref, self::getPagesTSconfig($id));
2649 $BE_USER_modOptions = $GLOBALS['BE_USER']->getTSConfig($TSref);
2650 $modTSconfig = t3lib_div::array_merge_recursive_overrule($pageTS_modOptions, $BE_USER_modOptions);
2651 return $modTSconfig;
2652 }
2653
2654 /**
2655 * Returns a selector box "function menu" for a module
2656 * Requires the JS function jumpToUrl() to be available
2657 * See Inside TYPO3 for details about how to use / make Function menus
2658 *
2659 * @param mixed $id is the "&id=" parameter value to be sent to the module, but it can be also a parameter array which will be passed instead of the &id=...
2660 * @param string $elementName it the form elements name, probably something like "SET[...]"
2661 * @param string $currentValue is the value to be selected currently.
2662 * @param array $menuItems is an array with the menu items for the selector box
2663 * @param string $script is the script to send the &id to, if empty it's automatically found
2664 * @param string $addParams is additional parameters to pass to the script.
2665 * @return string HTML code for selector box
2666 */
2667 public static function getFuncMenu($mainParams, $elementName, $currentValue, $menuItems, $script = '', $addparams = '') {
2668 if (is_array($menuItems)) {
2669 if (!is_array($mainParams)) {
2670 $mainParams = array('id' => $mainParams);
2671 }
2672 $mainParams = t3lib_div::implodeArrayForUrl('', $mainParams);
2673
2674 if (!$script) {
2675 $script = basename(PATH_thisScript);
2676 $mainParams .= (t3lib_div::_GET('M') ? '&M=' . rawurlencode(t3lib_div::_GET('M')) : '');
2677 }
2678
2679 $options = array();
2680 foreach ($menuItems as $value => $label) {
2681 $options[] = '<option value="' . htmlspecialchars($value) . '"' . (!strcmp($currentValue, $value) ? ' selected="selected"' : '') . '>' .
2682 t3lib_div::deHSCentities(htmlspecialchars($label)) .
2683 '</option>';
2684 }
2685 if (count($options)) {
2686 $onChange = 'jumpToUrl(\'' . $script . '?' . $mainParams . $addparams . '&' . $elementName . '=\'+this.options[this.selectedIndex].value,this);';
2687 return '
2688
2689 <!-- Function Menu of module -->
2690 <select name="' . $elementName . '" onchange="' . htmlspecialchars($onChange) . '">
2691 ' . implode('
2692 ', $options) . '
2693 </select>
2694 ';
2695 }
2696 }
2697 }
2698
2699 /**
2700 * Checkbox function menu.
2701 * Works like ->getFuncMenu() but takes no $menuItem array since this is a simple checkbox.
2702 *
2703 * @param mixed $mainParams $id is the "&id=" parameter value to be sent to the module, but it can be also a parameter array which will be passed instead of the &id=...
2704 * @param string $elementName it the form elements name, probably something like "SET[...]"
2705 * @param string $currentValue is the value to be selected currently.
2706 * @param string $script is the script to send the &id to, if empty it's automatically found
2707 * @param string $addParams is additional parameters to pass to the script.
2708 * @param string Additional attributes for the checkbox input tag
2709 * @return string HTML code for checkbox
2710 * @see getFuncMenu()
2711 */
2712 public static function getFuncCheck($mainParams, $elementName, $currentValue, $script = '', $addparams = '', $tagParams = '') {
2713 if (!is_array($mainParams)) {
2714 $mainParams = array('id' => $mainParams);
2715 }
2716 $mainParams = t3lib_div::implodeArrayForUrl('', $mainParams);
2717
2718 if (!$script) {
2719 $script = basename(PATH_thisScript);
2720 $mainParams .= (t3lib_div::_GET('M') ? '&M=' . rawurlencode(t3lib_div::_GET('M')) : '');
2721 }
2722
2723 $onClick = 'jumpToUrl(\'' . $script . '?' . $mainParams . $addparams . '&' . $elementName . '=\'+(this.checked?1:0),this);';
2724 return '<input type="checkbox" class="checkbox" name="' . $elementName . '"' . ($currentValue ? ' checked="checked"' : '') . ' onclick="' . htmlspecialchars($onClick) . '"' . ($tagParams ? ' ' . $tagParams : '') . ' />';
2725 }
2726
2727 /**
2728 * Input field function menu
2729 * Works like ->getFuncMenu() / ->getFuncCheck() but displays a input field instead which updates the script "onchange"
2730 *
2731 * @param mixed $id is the "&id=" parameter value to be sent to the module, but it can be also a parameter array which will be passed instead of the &id=...
2732 * @param string $elementName it the form elements name, probably something like "SET[...]"
2733 * @param string $currentValue is the value to be selected currently.
2734 * @param integer Relative size of input field, max is 48
2735 * @param string $script is the script to send the &id to, if empty it's automatically found
2736 * @param string $addParams is additional parameters to pass to the script.
2737 * @return string HTML code for input text field.
2738 * @see getFuncMenu()
2739 */
2740 public static function getFuncInput($mainParams, $elementName, $currentValue, $size = 10, $script = "", $addparams = "") {
2741 if (!is_array($mainParams)) {
2742 $mainParams = array('id' => $mainParams);
2743 }
2744 $mainParams = t3lib_div::implodeArrayForUrl('', $mainParams);
2745
2746 if (!$script) {
2747 $script = basename(PATH_thisScript);
2748 $mainParams .= (t3lib_div::_GET('M') ? '&M=' . rawurlencode(t3lib_div::_GET('M')) : '');
2749 }
2750
2751 $onChange = 'jumpToUrl(\'' . $script . '?' . $mainParams . $addparams . '&' . $elementName . '=\'+escape(this.value),this);';
2752 return '<input type="text"' . $GLOBALS['TBE_TEMPLATE']->formWidth($size) . ' name="' . $elementName . '" value="' . htmlspecialchars($currentValue) . '" onchange="' . htmlspecialchars($onChange) . '" />';
2753 }
2754
2755 /**
2756 * Removes menu items from $itemArray if they are configured to be removed by TSconfig for the module ($modTSconfig)
2757 * See Inside TYPO3 about how to program modules and use this API.
2758 *
2759 * @param array Module TS config array
2760 * @param array Array of items from which to remove items.
2761 * @param string $TSref points to the "object string" in $modTSconfig
2762 * @return array The modified $itemArray is returned.
2763 */
2764 public static function unsetMenuItems($modTSconfig, $itemArray, $TSref) {
2765 // Getting TS-config options for this module for the Backend User:
2766 $conf = $GLOBALS['BE_USER']->getTSConfig($TSref, $modTSconfig);
2767 if (is_array($conf['properties'])) {
2768 foreach ($conf['properties'] as $key => $val) {
2769 if (!$val) {
2770 unset($itemArray[$key]);
2771 }
2772 }
2773 }
2774 return $itemArray;
2775 }
2776
2777 /**
2778 * Call to update the page tree frame (or something else..?) after
2779 * use 'updatePageTree' as a first parameter will set the page tree to be updated.
2780 *
2781 * @param string Key to set the update signal. When setting, this value contains strings telling WHAT to set. At this point it seems that the value "updatePageTree" is the only one it makes sense to set. If empty, all update signals will be removed.
2782 * @param mixed Additional information for the update signal, used to only refresh a branch of the tree
2783 * @return void
2784 * @see t3lib_BEfunc::getUpdateSignalCode()
2785 */
2786 public static function setUpdateSignal($set = '', $params = '') {
2787 $modData = $GLOBALS['BE_USER']->getModuleData('t3lib_BEfunc::getUpdateSignal', 'ses');
2788
2789 if ($set) {
2790 $modData[$set] = array(
2791 'set' => $set,
2792 'parameter' => $params);
2793 } else { // clear the module data
2794 $modData = array();
2795 }
2796 $GLOBALS['BE_USER']->pushModuleData('t3lib_BEfunc::getUpdateSignal', $modData);
2797 }
2798
2799
2800 /**
2801 * Call to update the page tree frame (or something else..?) if this is set by the function
2802 * setUpdateSignal(). It will return some JavaScript that does the update (called in the typo3/template.php file, end() function)
2803 *
2804 * @return string HTML javascript code
2805 * @see t3lib_BEfunc::setUpdateSignal()
2806 */
2807 public static function getUpdateSignalCode() {
2808 $signals = array();
2809 $modData = $GLOBALS['BE_USER']->getModuleData('t3lib_BEfunc::getUpdateSignal', 'ses');
2810 if (!count($modData)) {
2811 return '';
2812 }
2813
2814 // Hook: Allows to let TYPO3 execute your JS code
2815 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['updateSignalHook'])) {
2816 $updateSignals = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['updateSignalHook'];
2817 } else {
2818 $updateSignals = array();
2819 }
2820
2821 // loop through all setUpdateSignals and get the JS code
2822 foreach ($modData as $set => $val) {
2823 if (isset($updateSignals[$set])) {
2824 $params = array('set' => $set, 'parameter' => $val['parameter'], 'JScode' => '');
2825 $ref = NULL;
2826 t3lib_div::callUserFunction($updateSignals[$set], $params, $ref);
2827 $signals[] = $params['JScode'];
2828 } else {
2829 switch ($set) {
2830 case 'updatePageTree':
2831 $signals[] = '
2832 if (top && top.TYPO3.Backend.NavigationContainer.PageTree) {
2833 top.TYPO3.Backend.NavigationContainer.PageTree.refreshTree();
2834 }
2835 ';
2836 break;
2837 case 'updateFolderTree':
2838 $signals[] = '
2839 if (top && top.TYPO3.Backend.NavigationIframe) {
2840 top.TYPO3.Backend.NavigationIframe.refresh();
2841 }';
2842 break;
2843 case 'updateModuleMenu':
2844 $signals[] = '
2845 if (top && top.TYPO3.ModuleMenu.App) {
2846 top.TYPO3.ModuleMenu.App.refreshMenu();
2847 }';
2848 break;
2849 }
2850 }
2851 }
2852
2853 $content = implode(LF, $signals);
2854
2855 self::setUpdateSignal(); // for backwards compatibility, should be replaced
2856 return $content;
2857 }
2858
2859
2860 /**
2861 * Returns an array which is most backend modules becomes MOD_SETTINGS containing values from function menus etc. determining the function of the module.
2862 * This is kind of session variable management framework for the backend users.
2863 * If a key from MOD_MENU is set in the CHANGED_SETTINGS array (eg. a value is passed to the script from the outside), this value is put into the settings-array
2864 * Ultimately, see Inside TYPO3 for how to use this function in relation to your modules.
2865 *
2866 * @param array MOD_MENU is an array that defines the options in menus.
2867 * @param array CHANGED_SETTINGS represents the array used when passing values to the script from the menus.
2868 * @param string modName is the name of this module. Used to get the correct module data.
2869 * @param string If type is 'ses' then the data is stored as session-lasting data. This means that it'll be wiped out the next time the user logs in.
2870 * @param string dontValidateList can be used to list variables that should not be checked if their value is found in the MOD_MENU array. Used for dynamically generated menus.
2871 * @param string List of default values from $MOD_MENU to set in the output array (only if the values from MOD_MENU are not arrays)
2872 * @return array The array $settings, which holds a key for each MOD_MENU key and the values of each key will be within the range of values for each menuitem
2873 */
2874 public static function getModuleData($MOD_MENU, $CHANGED_SETTINGS, $modName, $type = '', $dontValidateList = '', $setDefaultList = '') {
2875
2876 if ($modName && is_string($modName)) {
2877 // GETTING stored user-data from this module:
2878 $settings = $GLOBALS['BE_USER']->getModuleData($modName, $type);
2879
2880 $changed = 0;
2881 if (!is_array($settings)) {
2882 $changed = 1;
2883 $settings = array();
2884 }
2885 if (is_array($MOD_MENU)) {
2886 foreach ($MOD_MENU as $key => $var) {
2887
2888 // If a global var is set before entering here. eg if submitted, then it's substituting the current value the array.
2889 if (is_array($CHANGED_SETTINGS) && isset($CHANGED_SETTINGS[$key])) {
2890 if (is_array($CHANGED_SETTINGS[$key])) {
2891 $serializedSettings = serialize($CHANGED_SETTINGS[$key]);
2892 if (strcmp($settings[$key], $serializedSettings)