459ad572e8d05f8e54133e015afcc1e508a5ee68
[Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Classes / Utility / BackendUtility.php
1 <?php
2 namespace TYPO3\CMS\Backend\Utility;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Backend\Configuration\TranslationConfigurationProvider;
18 use TYPO3\CMS\Backend\Routing\Generator\UrlGenerator;
19 use TYPO3\CMS\Backend\Routing\Router;
20 use TYPO3\CMS\Backend\Routing\UriBuilder;
21 use TYPO3\CMS\Backend\Template\DocumentTemplate;
22 use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
23 use TYPO3\CMS\Core\Cache\CacheManager;
24 use TYPO3\CMS\Core\Database\PreparedStatement;
25 use TYPO3\CMS\Core\Database\RelationHandler;
26 use TYPO3\CMS\Core\FormProtection\FormProtectionFactory;
27 use TYPO3\CMS\Core\Imaging\Icon;
28 use TYPO3\CMS\Core\Imaging\IconFactory;
29 use TYPO3\CMS\Core\Messaging\FlashMessage;
30 use TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException;
31 use TYPO3\CMS\Core\Resource\File;
32 use TYPO3\CMS\Core\Resource\ProcessedFile;
33 use TYPO3\CMS\Core\Resource\ResourceFactory;
34 use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser;
35 use TYPO3\CMS\Core\Utility\ArrayUtility;
36 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
37 use TYPO3\CMS\Core\Utility\GeneralUtility;
38 use TYPO3\CMS\Core\Utility\HttpUtility;
39 use TYPO3\CMS\Core\Utility\MathUtility;
40 use TYPO3\CMS\Core\Utility\PathUtility;
41 use TYPO3\CMS\Core\Utility\StringUtility;
42 use TYPO3\CMS\Core\Versioning\VersionState;
43 use TYPO3\CMS\Core\Database\DatabaseConnection;
44 use TYPO3\CMS\Frontend\Page\PageRepository;
45 use TYPO3\CMS\Lang\LanguageService;
46
47 /**
48 * Standard functions available for the TYPO3 backend.
49 * You are encouraged to use this class in your own applications (Backend Modules)
50 * Don't instantiate - call functions with "\TYPO3\CMS\Backend\Utility\BackendUtility::" prefixed the function name.
51 *
52 * Call ALL methods without making an object!
53 * Eg. to get a page-record 51 do this: '\TYPO3\CMS\Backend\Utility\BackendUtility::getRecord('pages',51)'
54 */
55 class BackendUtility {
56
57 /**
58 * Cache the TCA configuration of tables with their types during runtime
59 *
60 * @var array
61 * @see self::getTCAtypes()
62 */
63 static protected $tcaTableTypeConfigurationCache = array();
64
65 /**
66 * Cache the processed titles of records during runtime
67 *
68 * @var array
69 * @see self::getRecordTitle()
70 */
71 static protected $recordTitleCache = array();
72
73 /*******************************************
74 *
75 * SQL-related, selecting records, searching
76 *
77 *******************************************/
78 /**
79 * Returns the WHERE clause " AND NOT [tablename].[deleted-field]" if a deleted-field
80 * is configured in $GLOBALS['TCA'] for the tablename, $table
81 * This function should ALWAYS be called in the backend for selection on tables which
82 * are configured in $GLOBALS['TCA'] since it will ensure consistent selection of records,
83 * even if they are marked deleted (in which case the system must always treat them as non-existent!)
84 * In the frontend a function, ->enableFields(), is known to filter hidden-field, start- and endtime
85 * and fe_groups as well. But that is a job of the frontend, not the backend. If you need filtering
86 * on those fields as well in the backend you can use ->BEenableFields() though.
87 *
88 * @param string $table Table name present in $GLOBALS['TCA']
89 * @param string $tableAlias Table alias if any
90 * @return string WHERE clause for filtering out deleted records, eg " AND tablename.deleted=0
91 */
92 static public function deleteClause($table, $tableAlias = '') {
93 if ($GLOBALS['TCA'][$table]['ctrl']['delete']) {
94 return ' AND ' . ($tableAlias ?: $table) . '.' . $GLOBALS['TCA'][$table]['ctrl']['delete'] . '=0';
95 } else {
96 return '';
97 }
98 }
99
100 /**
101 * Gets record with uid = $uid from $table
102 * You can set $field to a list of fields (default is '*')
103 * Additional WHERE clauses can be added by $where (fx. ' AND blabla = 1')
104 * Will automatically check if records has been deleted and if so, not return anything.
105 * $table must be found in $GLOBALS['TCA']
106 *
107 * @param string $table Table name present in $GLOBALS['TCA']
108 * @param int $uid UID of record
109 * @param string $fields List of fields to select
110 * @param string $where Additional WHERE clause, eg. " AND blablabla = 0
111 * @param bool $useDeleteClause Use the deleteClause to check if a record is deleted (default TRUE)
112 * @return array|NULL Returns the row if found, otherwise NULL
113 */
114 static public function getRecord($table, $uid, $fields = '*', $where = '', $useDeleteClause = TRUE) {
115 // Ensure we have a valid uid (not 0 and not NEWxxxx) and a valid TCA
116 if ((int)$uid && !empty($GLOBALS['TCA'][$table])) {
117 $where = 'uid=' . (int)$uid . ($useDeleteClause ? self::deleteClause($table) : '') . $where;
118 $row = static::getDatabaseConnection()->exec_SELECTgetSingleRow($fields, $table, $where);
119 if ($row) {
120 return $row;
121 }
122 }
123 return NULL;
124 }
125
126 /**
127 * Like getRecord(), but overlays workspace version if any.
128 *
129 * @param string $table Table name present in $GLOBALS['TCA']
130 * @param int $uid UID of record
131 * @param string $fields List of fields to select
132 * @param string $where Additional WHERE clause, eg. " AND blablabla = 0
133 * @param bool $useDeleteClause Use the deleteClause to check if a record is deleted (default TRUE)
134 * @param bool $unsetMovePointers If TRUE the function does not return a "pointer" row for moved records in a workspace
135 * @return array Returns the row if found, otherwise nothing
136 */
137 static public function getRecordWSOL($table, $uid, $fields = '*', $where = '', $useDeleteClause = TRUE, $unsetMovePointers = FALSE) {
138 if ($fields !== '*') {
139 $internalFields = GeneralUtility::uniqueList($fields . ',uid,pid');
140 $row = self::getRecord($table, $uid, $internalFields, $where, $useDeleteClause);
141 self::workspaceOL($table, $row, -99, $unsetMovePointers);
142 if (is_array($row)) {
143 foreach ($row as $key => $_) {
144 if (!GeneralUtility::inList($fields, $key) && $key[0] !== '_') {
145 unset($row[$key]);
146 }
147 }
148 }
149 } else {
150 $row = self::getRecord($table, $uid, $fields, $where, $useDeleteClause);
151 self::workspaceOL($table, $row, -99, $unsetMovePointers);
152 }
153 return $row;
154 }
155
156 /**
157 * Returns the first record found from $table with $where as WHERE clause
158 * This function does NOT check if a record has the deleted flag set.
159 * $table does NOT need to be configured in $GLOBALS['TCA']
160 * The query used is simply this:
161 * $query = 'SELECT ' . $fields . ' FROM ' . $table . ' WHERE ' . $where;
162 *
163 * @param string $table Table name (not necessarily in TCA)
164 * @param string $where WHERE clause
165 * @param string $fields $fields is a list of fields to select, default is '*'
166 * @return array|bool First row found, if any, FALSE otherwise
167 */
168 static public function getRecordRaw($table, $where = '', $fields = '*') {
169 $row = FALSE;
170 $db = static::getDatabaseConnection();
171 if (FALSE !== ($res = $db->exec_SELECTquery($fields, $table, $where, '', '', '1'))) {
172 $row = $db->sql_fetch_assoc($res);
173 $db->sql_free_result($res);
174 }
175 return $row;
176 }
177
178 /**
179 * Returns records from table, $theTable, where a field ($theField) equals the value, $theValue
180 * The records are returned in an array
181 * If no records were selected, the function returns nothing
182 *
183 * @param string $theTable Table name present in $GLOBALS['TCA']
184 * @param string $theField Field to select on
185 * @param string $theValue Value that $theField must match
186 * @param string $whereClause Optional additional WHERE clauses put in the end of the query. DO NOT PUT IN GROUP BY, ORDER BY or LIMIT!
187 * @param string $groupBy Optional GROUP BY field(s), if none, supply blank string.
188 * @param string $orderBy Optional ORDER BY field(s), if none, supply blank string.
189 * @param string $limit Optional LIMIT value ([begin,]max), if none, supply blank string.
190 * @param bool $useDeleteClause Use the deleteClause to check if a record is deleted (default TRUE)
191 * @return mixed Multidimensional array with selected records (if any is selected)
192 */
193 static public function getRecordsByField($theTable, $theField, $theValue, $whereClause = '', $groupBy = '', $orderBy = '', $limit = '', $useDeleteClause = TRUE) {
194 if (is_array($GLOBALS['TCA'][$theTable])) {
195 $db = static::getDatabaseConnection();
196 $res = $db->exec_SELECTquery(
197 '*',
198 $theTable,
199 $theField . '=' . $db->fullQuoteStr($theValue, $theTable) .
200 ($useDeleteClause ? self::deleteClause($theTable) . ' ' : '') .
201 self::versioningPlaceholderClause($theTable) . ' ' .
202 $whereClause,
203 $groupBy,
204 $orderBy,
205 $limit
206 );
207 $rows = array();
208 while ($row = $db->sql_fetch_assoc($res)) {
209 $rows[] = $row;
210 }
211 $db->sql_free_result($res);
212 if (!empty($rows)) {
213 return $rows;
214 }
215 }
216 return NULL;
217 }
218
219 /**
220 * Makes an backwards explode on the $str and returns an array with ($table, $uid).
221 * Example: tt_content_45 => array('tt_content', 45)
222 *
223 * @param string $str [tablename]_[uid] string to explode
224 * @return array
225 */
226 static public function splitTable_Uid($str) {
227 list($uid, $table) = explode('_', strrev($str), 2);
228 return array(strrev($table), strrev($uid));
229 }
230
231 /**
232 * Returns a list of pure ints based on $in_list being a list of records with table-names prepended.
233 * 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.
234 *
235 * @param string $in_list Input list
236 * @param string $tablename Table name from which ids is returned
237 * @param string $default_tablename $default_tablename denotes what table the number '45' is from (if nothing is prepended on the value)
238 * @return string List of ids
239 */
240 static public function getSQLselectableList($in_list, $tablename, $default_tablename) {
241 $list = array();
242 if ((string)trim($in_list) != '') {
243 $tempItemArray = explode(',', trim($in_list));
244 foreach ($tempItemArray as $key => $val) {
245 $val = strrev($val);
246 $parts = explode('_', $val, 2);
247 if ((string)trim($parts[0]) != '') {
248 $theID = (int)strrev($parts[0]);
249 $theTable = trim($parts[1]) ? strrev(trim($parts[1])) : $default_tablename;
250 if ($theTable == $tablename) {
251 $list[] = $theID;
252 }
253 }
254 }
255 }
256 return implode(',', $list);
257 }
258
259 /**
260 * Backend implementation of enableFields()
261 * Notice that "fe_groups" is not selected for - only disabled, starttime and endtime.
262 * Notice that deleted-fields are NOT filtered - you must ALSO call deleteClause in addition.
263 * $GLOBALS["SIM_ACCESS_TIME"] is used for date.
264 *
265 * @param string $table The table from which to return enableFields WHERE clause. Table name must have a 'ctrl' section in $GLOBALS['TCA'].
266 * @param bool $inv Means that the query will select all records NOT VISIBLE records (inverted selection)
267 * @return string WHERE clause part
268 */
269 static public function BEenableFields($table, $inv = FALSE) {
270 $ctrl = $GLOBALS['TCA'][$table]['ctrl'];
271 $query = array();
272 $invQuery = array();
273 if (is_array($ctrl)) {
274 if (is_array($ctrl['enablecolumns'])) {
275 if ($ctrl['enablecolumns']['disabled']) {
276 $field = $table . '.' . $ctrl['enablecolumns']['disabled'];
277 $query[] = $field . '=0';
278 $invQuery[] = $field . '<>0';
279 }
280 if ($ctrl['enablecolumns']['starttime']) {
281 $field = $table . '.' . $ctrl['enablecolumns']['starttime'];
282 $query[] = '(' . $field . '<=' . $GLOBALS['SIM_ACCESS_TIME'] . ')';
283 $invQuery[] = '(' . $field . '<>0 AND ' . $field . '>' . $GLOBALS['SIM_ACCESS_TIME'] . ')';
284 }
285 if ($ctrl['enablecolumns']['endtime']) {
286 $field = $table . '.' . $ctrl['enablecolumns']['endtime'];
287 $query[] = '(' . $field . '=0 OR ' . $field . '>' . $GLOBALS['SIM_ACCESS_TIME'] . ')';
288 $invQuery[] = '(' . $field . '<>0 AND ' . $field . '<=' . $GLOBALS['SIM_ACCESS_TIME'] . ')';
289 }
290 }
291 }
292 $outQ = $inv ? '(' . implode(' OR ', $invQuery) . ')' : implode(' AND ', $query);
293 return $outQ ? ' AND ' . $outQ : '';
294 }
295
296 /**
297 * Fetches the localization for a given record.
298 *
299 * @param string $table Table name present in $GLOBALS['TCA']
300 * @param int $uid The uid of the record
301 * @param int $language The uid of the language record in sys_language
302 * @param string $andWhereClause Optional additional WHERE clause (default: '')
303 * @return mixed Multidimensional array with selected records; if none exist, FALSE is returned
304 */
305 static public function getRecordLocalization($table, $uid, $language, $andWhereClause = '') {
306 $recordLocalization = FALSE;
307
308 // Check if translations are stored in other table
309 if (isset($GLOBALS['TCA'][$table]['ctrl']['transForeignTable'])) {
310 $table = $GLOBALS['TCA'][$table]['ctrl']['transForeignTable'];
311 }
312
313 if (self::isTableLocalizable($table)) {
314 $tcaCtrl = $GLOBALS['TCA'][$table]['ctrl'];
315 $recordLocalization = self::getRecordsByField($table, $tcaCtrl['transOrigPointerField'], $uid, 'AND ' . $tcaCtrl['languageField'] . '=' . (int)$language . ($andWhereClause ? ' ' . $andWhereClause : ''), '', '', '1');
316 }
317 return $recordLocalization;
318 }
319
320 /*******************************************
321 *
322 * Page tree, TCA related
323 *
324 *******************************************/
325 /**
326 * 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.
327 * By default deleted pages are filtered.
328 * 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.
329 *
330 * @param int $uid Page id for which to create the root line.
331 * @param string $clause 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.
332 * @param bool $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!
333 * @return array Root line array, all the way to the page tree root (or as far as $clause allows!)
334 */
335 static public function BEgetRootLine($uid, $clause = '', $workspaceOL = FALSE) {
336 static $BEgetRootLine_cache = array();
337 $output = array();
338 $pid = $uid;
339 $ident = $pid . '-' . $clause . '-' . $workspaceOL;
340 if (is_array($BEgetRootLine_cache[$ident])) {
341 $output = $BEgetRootLine_cache[$ident];
342 } else {
343 $loopCheck = 100;
344 $theRowArray = array();
345 while ($uid != 0 && $loopCheck) {
346 $loopCheck--;
347 $row = self::getPageForRootline($uid, $clause, $workspaceOL);
348 if (is_array($row)) {
349 $uid = $row['pid'];
350 $theRowArray[] = $row;
351 } else {
352 break;
353 }
354 }
355 if ($uid == 0) {
356 $theRowArray[] = array('uid' => 0, 'title' => '');
357 }
358 $c = count($theRowArray);
359 foreach ($theRowArray as $val) {
360 $c--;
361 $output[$c] = array(
362 'uid' => $val['uid'],
363 'pid' => $val['pid'],
364 'title' => $val['title'],
365 'doktype' => $val['doktype'],
366 'tsconfig_includes' => $val['tsconfig_includes'],
367 'TSconfig' => $val['TSconfig'],
368 'is_siteroot' => $val['is_siteroot'],
369 't3ver_oid' => $val['t3ver_oid'],
370 't3ver_wsid' => $val['t3ver_wsid'],
371 't3ver_state' => $val['t3ver_state'],
372 't3ver_stage' => $val['t3ver_stage'],
373 'backend_layout_next_level' => $val['backend_layout_next_level']
374 );
375 if (isset($val['_ORIG_pid'])) {
376 $output[$c]['_ORIG_pid'] = $val['_ORIG_pid'];
377 }
378 }
379 $BEgetRootLine_cache[$ident] = $output;
380 }
381 return $output;
382 }
383
384 /**
385 * Gets the cached page record for the rootline
386 *
387 * @param int $uid Page id for which to create the root line.
388 * @param string $clause 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.
389 * @param bool $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!
390 * @return array Cached page record for the rootline
391 * @see BEgetRootLine
392 */
393 static protected function getPageForRootline($uid, $clause, $workspaceOL) {
394 static $getPageForRootline_cache = array();
395 $ident = $uid . '-' . $clause . '-' . $workspaceOL;
396 if (is_array($getPageForRootline_cache[$ident])) {
397 $row = $getPageForRootline_cache[$ident];
398 } else {
399 $db = static::getDatabaseConnection();
400 $res = $db->exec_SELECTquery('pid,uid,title,doktype,tsconfig_includes,TSconfig,is_siteroot,t3ver_oid,t3ver_wsid,t3ver_state,t3ver_stage,backend_layout_next_level', 'pages', 'uid=' . (int)$uid . ' ' . self::deleteClause('pages') . ' ' . $clause);
401 $row = $db->sql_fetch_assoc($res);
402 if ($row) {
403 $newLocation = FALSE;
404 if ($workspaceOL) {
405 self::workspaceOL('pages', $row);
406 $newLocation = self::getMovePlaceholder('pages', $row['uid'], 'pid');
407 }
408 if (is_array($row)) {
409 if ($newLocation !== FALSE) {
410 $row['pid'] = $newLocation['pid'];
411 } else {
412 self::fixVersioningPid('pages', $row);
413 }
414 $getPageForRootline_cache[$ident] = $row;
415 }
416 }
417 $db->sql_free_result($res);
418 }
419 return $row;
420 }
421
422 /**
423 * Opens the page tree to the specified page id
424 *
425 * @param int $pid Page id.
426 * @param bool $clearExpansion If set, then other open branches are closed.
427 * @return void
428 */
429 static public function openPageTree($pid, $clearExpansion) {
430 $beUser = static::getBackendUserAuthentication();
431 // Get current expansion data:
432 if ($clearExpansion) {
433 $expandedPages = array();
434 } else {
435 $expandedPages = unserialize($beUser->uc['browseTrees']['browsePages']);
436 }
437 // Get rootline:
438 $rL = self::BEgetRootLine($pid);
439 // First, find out what mount index to use (if more than one DB mount exists):
440 $mountIndex = 0;
441 $mountKeys = array_flip($beUser->returnWebmounts());
442 foreach ($rL as $rLDat) {
443 if (isset($mountKeys[$rLDat['uid']])) {
444 $mountIndex = $mountKeys[$rLDat['uid']];
445 break;
446 }
447 }
448 // Traverse rootline and open paths:
449 foreach ($rL as $rLDat) {
450 $expandedPages[$mountIndex][$rLDat['uid']] = 1;
451 }
452 // Write back:
453 $beUser->uc['browseTrees']['browsePages'] = serialize($expandedPages);
454 $beUser->writeUC();
455 }
456
457 /**
458 * Returns the path (visually) of a page $uid, fx. "/First page/Second page/Another subpage"
459 * Each part of the path will be limited to $titleLimit characters
460 * Deleted pages are filtered out.
461 *
462 * @param int $uid Page uid for which to create record path
463 * @param string $clause Clause is additional where clauses, eg.
464 * @param int $titleLimit Title limit
465 * @param int $fullTitleLimit Title limit of Full title (typ. set to 1000 or so)
466 * @return mixed Path of record (string) OR array with short/long title if $fullTitleLimit is set.
467 */
468 static public function getRecordPath($uid, $clause, $titleLimit, $fullTitleLimit = 0) {
469 if (!$titleLimit) {
470 $titleLimit = 1000;
471 }
472 $output = $fullOutput = '/';
473 $clause = trim($clause);
474 if ($clause !== '' && substr($clause, 0, 3) !== 'AND') {
475 $clause = 'AND ' . $clause;
476 }
477 $data = self::BEgetRootLine($uid, $clause);
478 foreach ($data as $record) {
479 if ($record['uid'] === 0) {
480 continue;
481 }
482 $output = '/' . GeneralUtility::fixed_lgd_cs(strip_tags($record['title']), $titleLimit) . $output;
483 if ($fullTitleLimit) {
484 $fullOutput = '/' . GeneralUtility::fixed_lgd_cs(strip_tags($record['title']), $fullTitleLimit) . $fullOutput;
485 }
486 }
487 if ($fullTitleLimit) {
488 return array($output, $fullOutput);
489 } else {
490 return $output;
491 }
492 }
493
494 /**
495 * Returns an array with the exclude-fields as defined in TCA and FlexForms
496 * Used for listing the exclude-fields in be_groups forms
497 *
498 * @return array Array of arrays with excludeFields (fieldname, table:fieldname) from all TCA entries and from FlexForms (fieldname, table:extkey;sheetname;fieldname)
499 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
500 */
501 static public function getExcludeFields() {
502 GeneralUtility::logDeprecatedFunction();
503 $finalExcludeArray = array();
504
505 // Fetch translations for table names
506 $tableToTranslation = array();
507 $lang = static::getLanguageService();
508 // All TCA keys
509 foreach ($GLOBALS['TCA'] as $table => $conf) {
510 $tableToTranslation[$table] = $lang->sl($conf['ctrl']['title']);
511 }
512 // Sort by translations
513 asort($tableToTranslation);
514 foreach ($tableToTranslation as $table => $translatedTable) {
515 $excludeArrayTable = array();
516
517 // All field names configured and not restricted to admins
518 if (is_array($GLOBALS['TCA'][$table]['columns'])
519 && empty($GLOBALS['TCA'][$table]['ctrl']['adminOnly'])
520 && (empty($GLOBALS['TCA'][$table]['ctrl']['rootLevel']) || !empty($GLOBALS['TCA'][$table]['ctrl']['security']['ignoreRootLevelRestriction']))
521 ) {
522 foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $_) {
523 if ($GLOBALS['TCA'][$table]['columns'][$field]['exclude']) {
524 // Get human readable names of fields
525 $translatedField = $lang->sl($GLOBALS['TCA'][$table]['columns'][$field]['label']);
526 // Add entry
527 $excludeArrayTable[] = array($translatedTable . ': ' . $translatedField, $table . ':' . $field);
528 }
529 }
530 }
531 // All FlexForm fields
532 $flexFormArray = static::getRegisteredFlexForms($table);
533 foreach ($flexFormArray as $tableField => $flexForms) {
534 // Prefix for field label, e.g. "Plugin Options:"
535 $labelPrefix = '';
536 if (!empty($GLOBALS['TCA'][$table]['columns'][$tableField]['label'])) {
537 $labelPrefix = $lang->sl($GLOBALS['TCA'][$table]['columns'][$tableField]['label']);
538 }
539 // Get all sheets and title
540 foreach ($flexForms as $extIdent => $extConf) {
541 $extTitle = $lang->sl($extConf['title']);
542 // Get all fields in sheet
543 foreach ($extConf['ds']['sheets'] as $sheetName => $sheet) {
544 if (empty($sheet['ROOT']['el']) || !is_array($sheet['ROOT']['el'])) {
545 continue;
546 }
547 foreach ($sheet['ROOT']['el'] as $fieldName => $field) {
548 // Use only fields that have exclude flag set
549 if (empty($field['TCEforms']['exclude'])) {
550 continue;
551 }
552 $fieldLabel = !empty($field['TCEforms']['label']) ? $lang->sl($field['TCEforms']['label']) : $fieldName;
553 $fieldIdent = $table . ':' . $tableField . ';' . $extIdent . ';' . $sheetName . ';' . $fieldName;
554 $excludeArrayTable[] = array(trim($labelPrefix . ' ' . $extTitle, ': ') . ': ' . $fieldLabel, $fieldIdent);
555 }
556 }
557 }
558 }
559 // Sort fields by the translated value
560 if (!empty($excludeArrayTable)) {
561 usort($excludeArrayTable, function (array $array1, array $array2) {
562 $array1 = reset($array1);
563 $array2 = reset($array2);
564 if (is_string($array1) && is_string($array2)) {
565 return strcasecmp($array1, $array2);
566 }
567 return 0;
568 });
569 $finalExcludeArray = array_merge($finalExcludeArray, $excludeArrayTable);
570 }
571 }
572
573 return $finalExcludeArray;
574 }
575
576 /**
577 * Returns an array with explicit Allow/Deny fields.
578 * Used for listing these field/value pairs in be_groups forms
579 *
580 * @return array Array with information from all of $GLOBALS['TCA']
581 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
582 */
583 static public function getExplicitAuthFieldValues() {
584 GeneralUtility::logDeprecatedFunction();
585 // Initialize:
586 $lang = static::getLanguageService();
587 $adLabel = array(
588 'ALLOW' => $lang->sl('LLL:EXT:lang/locallang_core.xlf:labels.allow'),
589 'DENY' => $lang->sl('LLL:EXT:lang/locallang_core.xlf:labels.deny')
590 );
591 // All TCA keys:
592 $allowDenyOptions = array();
593 foreach ($GLOBALS['TCA'] as $table => $_) {
594 // All field names configured:
595 if (is_array($GLOBALS['TCA'][$table]['columns'])) {
596 foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $_) {
597 $fCfg = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
598 if ($fCfg['type'] == 'select' && $fCfg['authMode']) {
599 // Check for items:
600 if (is_array($fCfg['items'])) {
601 // Get Human Readable names of fields and table:
602 $allowDenyOptions[$table . ':' . $field]['tableFieldLabel'] =
603 $lang->sl($GLOBALS['TCA'][$table]['ctrl']['title']) . ': '
604 . $lang->sl($GLOBALS['TCA'][$table]['columns'][$field]['label']);
605 // Check for items:
606 foreach ($fCfg['items'] as $iVal) {
607 // Values '' is not controlled by this setting.
608 if ((string)$iVal[1] !== '') {
609 // Find iMode
610 $iMode = '';
611 switch ((string)$fCfg['authMode']) {
612 case 'explicitAllow':
613 $iMode = 'ALLOW';
614 break;
615 case 'explicitDeny':
616 $iMode = 'DENY';
617 break;
618 case 'individual':
619 if ($iVal[4] === 'EXPL_ALLOW') {
620 $iMode = 'ALLOW';
621 } elseif ($iVal[4] === 'EXPL_DENY') {
622 $iMode = 'DENY';
623 }
624 break;
625 }
626 // Set iMode
627 if ($iMode) {
628 $allowDenyOptions[$table . ':' . $field]['items'][$iVal[1]] = array($iMode, $lang->sl($iVal[0]), $adLabel[$iMode]);
629 }
630 }
631 }
632 }
633 }
634 }
635 }
636 }
637 return $allowDenyOptions;
638 }
639
640 /**
641 * Returns an array with system languages:
642 *
643 * The property flagIcon returns a string <flags-xx>. The calling party should call
644 * \TYPO3\CMS\Backend\Utility\IconUtility::getSpriteIcon(<flags-xx>) to get an HTML
645 * which will represent the flag of this language.
646 *
647 * @return array Array with languages (title, uid, flagIcon - used with IconUtility::getSpriteIcon)
648 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
649 */
650 static public function getSystemLanguages() {
651 GeneralUtility::logDeprecatedFunction();
652 /** @var TranslationConfigurationProvider $translationConfigurationProvider */
653 $translationConfigurationProvider = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Configuration\TranslationConfigurationProvider::class);
654 $languages = $translationConfigurationProvider->getSystemLanguages();
655 $sysLanguages = array();
656 foreach ($languages as $language) {
657 if ($language['uid'] !== -1) {
658 $sysLanguages[] = array(
659 0 => htmlspecialchars($language['title']) . ' [' . $language['uid'] . ']',
660 1 => $language['uid'],
661 2 => $language['flagIcon']
662 );
663 }
664 }
665 return $sysLanguages;
666 }
667
668 /**
669 * Gets the original translation pointer table.
670 * For e.g. pages_language_overlay this would be pages.
671 *
672 * @param string $table Name of the table
673 * @return string Pointer table (if any)
674 */
675 static public function getOriginalTranslationTable($table) {
676 if (!empty($GLOBALS['TCA'][$table]['ctrl']['transOrigPointerTable'])) {
677 $table = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerTable'];
678 }
679
680 return $table;
681 }
682
683 /**
684 * Determines whether a table is localizable and has the languageField and transOrigPointerField set in $GLOBALS['TCA'].
685 *
686 * @param string $table The table to check
687 * @return bool Whether a table is localizable
688 */
689 static public function isTableLocalizable($table) {
690 $isLocalizable = FALSE;
691 if (isset($GLOBALS['TCA'][$table]['ctrl']) && is_array($GLOBALS['TCA'][$table]['ctrl'])) {
692 $tcaCtrl = $GLOBALS['TCA'][$table]['ctrl'];
693 $isLocalizable = isset($tcaCtrl['languageField']) && $tcaCtrl['languageField'] && isset($tcaCtrl['transOrigPointerField']) && $tcaCtrl['transOrigPointerField'];
694 }
695 return $isLocalizable;
696 }
697
698 /**
699 * Returns the value of the property localizationMode in the given $config array ($GLOBALS['TCA'][<table>]['columns'][<field>]['config']).
700 * If the table is prepared for localization and no localizationMode is set, 'select' is returned by default.
701 * If the table is not prepared for localization or not defined at all in $GLOBALS['TCA'], FALSE is returned.
702 *
703 * @param string $table The name of the table to lookup in TCA
704 * @param mixed $fieldOrConfig The fieldname (string) or the configuration of the field to check (array)
705 * @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
706 */
707 static public function getInlineLocalizationMode($table, $fieldOrConfig) {
708 $localizationMode = FALSE;
709 $config = NULL;
710 if (is_array($fieldOrConfig) && !empty($fieldOrConfig)) {
711 $config = $fieldOrConfig;
712 } elseif (is_string($fieldOrConfig) && isset($GLOBALS['TCA'][$table]['columns'][$fieldOrConfig]['config'])) {
713 $config = $GLOBALS['TCA'][$table]['columns'][$fieldOrConfig]['config'];
714 }
715 if (is_array($config) && isset($config['type']) && $config['type'] === 'inline' && self::isTableLocalizable($table)) {
716 $localizationMode = isset($config['behaviour']['localizationMode']) && $config['behaviour']['localizationMode']
717 ? $config['behaviour']['localizationMode']
718 : 'select';
719 // The mode 'select' is not possible when child table is not localizable at all:
720 if ($localizationMode === 'select' && !self::isTableLocalizable($config['foreign_table'])) {
721 $localizationMode = FALSE;
722 }
723 }
724 return $localizationMode;
725 }
726
727 /**
728 * 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.
729 * If $id is zero a pseudo root-page with "_thePath" set is returned IF the current BE_USER is admin.
730 * In any case ->isInWebMount must return TRUE for the user (regardless of $perms_clause)
731 *
732 * @param int $id Page uid for which to check read-access
733 * @param string $perms_clause This is typically a value generated with static::getBackendUserAuthentication()->getPagePermsClause(1);
734 * @return array Returns page record if OK, otherwise FALSE.
735 */
736 static public function readPageAccess($id, $perms_clause) {
737 if ((string)$id !== '') {
738 $id = (int)$id;
739 if (!$id) {
740 if (static::getBackendUserAuthentication()->isAdmin()) {
741 $path = '/';
742 $pageinfo['_thePath'] = $path;
743 return $pageinfo;
744 }
745 } else {
746 $pageinfo = self::getRecord('pages', $id, '*', $perms_clause ? ' AND ' . $perms_clause : '');
747 if ($pageinfo['uid'] && static::getBackendUserAuthentication()->isInWebMount($id, $perms_clause)) {
748 self::workspaceOL('pages', $pageinfo);
749 if (is_array($pageinfo)) {
750 self::fixVersioningPid('pages', $pageinfo);
751 list($pageinfo['_thePath'], $pageinfo['_thePathFull']) = self::getRecordPath((int)$pageinfo['uid'], $perms_clause, 15, 1000);
752 return $pageinfo;
753 }
754 }
755 }
756 }
757 return FALSE;
758 }
759
760 /**
761 * Returns the "types" configuration parsed into an array for the record, $rec, from table, $table
762 *
763 * @param string $table Table name (present in TCA)
764 * @param array $rec Record from $table
765 * @param bool $useFieldNameAsKey If $useFieldNameAsKey is set, then the fieldname is associative keys in the return array, otherwise just numeric keys.
766 * @return array|NULL
767 */
768 static public function getTCAtypes($table, $rec, $useFieldNameAsKey = FALSE) {
769 if ($GLOBALS['TCA'][$table]) {
770 // Get type value:
771 $fieldValue = self::getTCAtypeValue($table, $rec);
772 $cacheIdentifier = $table . '-type-' . $fieldValue . '-fnk-' . $useFieldNameAsKey;
773
774 // Fetch from first-level-cache if available
775 if (isset(self::$tcaTableTypeConfigurationCache[$cacheIdentifier])) {
776 return self::$tcaTableTypeConfigurationCache[$cacheIdentifier];
777 }
778
779 // Get typesConf
780 $typesConf = $GLOBALS['TCA'][$table]['types'][$fieldValue];
781 // Get fields list and traverse it
782 $fieldList = explode(',', $typesConf['showitem']);
783
784 // Add subtype fields e.g. for a valid RTE transformation
785 // The RTE runs the DB -> RTE transformation only, if the RTE field is part of the getTCAtypes array
786 if (isset($typesConf['subtype_value_field'])) {
787 $subType = $rec[$typesConf['subtype_value_field']];
788 if (isset($typesConf['subtypes_addlist'][$subType])) {
789 $subFields = GeneralUtility::trimExplode(',', $typesConf['subtypes_addlist'][$subType], TRUE);
790 $fieldList = array_merge($fieldList, $subFields);
791 }
792 }
793
794 $altFieldList = array();
795 // Traverse fields in types config and parse the configuration into a nice array:
796 foreach ($fieldList as $k => $v) {
797 list($pFieldName, $pAltTitle, $pPalette) = GeneralUtility::trimExplode(';', $v);
798 $defaultExtras = '';
799 if (!empty($typesConf['columnsOverrides'][$pFieldName]['defaultExtras'])) {
800 // Use defaultExtras from columnsOverrides if given
801 $defaultExtras = $typesConf['columnsOverrides'][$pFieldName]['defaultExtras'];
802 } elseif (!empty($GLOBALS['TCA'][$table]['columns'][$pFieldName]['defaultExtras'])) {
803 // Use defaultExtras from columns if given
804 $defaultExtras = $GLOBALS['TCA'][$table]['columns'][$pFieldName]['defaultExtras'];
805 }
806 $specConfParts = self::getSpecConfParts($defaultExtras);
807 $fieldList[$k] = array(
808 'field' => $pFieldName,
809 'title' => $pAltTitle,
810 'palette' => $pPalette,
811 'spec' => $specConfParts,
812 'origString' => $v
813 );
814 if ($useFieldNameAsKey) {
815 $altFieldList[$fieldList[$k]['field']] = $fieldList[$k];
816 }
817 }
818 if ($useFieldNameAsKey) {
819 $fieldList = $altFieldList;
820 }
821
822 // Add to first-level-cache
823 self::$tcaTableTypeConfigurationCache[$cacheIdentifier] = $fieldList;
824
825 // Return array:
826 return $fieldList;
827 }
828 return NULL;
829 }
830
831 /**
832 * Returns the "type" value of $rec from $table which can be used to look up the correct "types" rendering section in $GLOBALS['TCA']
833 * If no "type" field is configured in the "ctrl"-section of the $GLOBALS['TCA'] for the table, zero is used.
834 * 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)
835 *
836 * Note: This method is very similar to the type determination of FormDataProvider/DatabaseRecordTypeValue,
837 * however, it has two differences:
838 * 1) The method in TCEForms also takes care of localization (which is difficult to do here as the whole infrastructure for language overlays is only in TCEforms).
839 * 2) The $row array looks different in TCEForms, as in there it's not the raw record but the prepared data from other providers is handled, which changes e.g. how "select"
840 * and "group" field values are stored, which makes different processing of the "foreign pointer field" type field variant necessary.
841 *
842 * @param string $table Table name present in TCA
843 * @param array $row Record from $table
844 * @throws \RuntimeException
845 * @return string Field value
846 * @see getTCAtypes()
847 */
848 static public function getTCAtypeValue($table, $row) {
849 $typeNum = 0;
850 if ($GLOBALS['TCA'][$table]) {
851 $field = $GLOBALS['TCA'][$table]['ctrl']['type'];
852 if (strpos($field, ':') !== FALSE) {
853 list($pointerField, $foreignTableTypeField) = explode(':', $field);
854 // Get field value from database if field is not in the $row array
855 if (!isset($row[$pointerField])) {
856 $localRow = self::getRecord($table, $row['uid'], $pointerField);
857 $foreignUid = $localRow[$pointerField];
858 } else {
859 $foreignUid = $row[$pointerField];
860 }
861 if ($foreignUid) {
862 $fieldConfig = $GLOBALS['TCA'][$table]['columns'][$pointerField]['config'];
863 $relationType = $fieldConfig['type'];
864 if ($relationType === 'select') {
865 $foreignTable = $fieldConfig['foreign_table'];
866 } elseif ($relationType === 'group') {
867 $allowedTables = explode(',', $fieldConfig['allowed']);
868 $foreignTable = $allowedTables[0];
869 } else {
870 throw new \RuntimeException('TCA foreign field pointer fields are only allowed to be used with group or select field types.', 1325862240);
871 }
872 $foreignRow = self::getRecord($foreignTable, $foreignUid, $foreignTableTypeField);
873 if ($foreignRow[$foreignTableTypeField]) {
874 $typeNum = $foreignRow[$foreignTableTypeField];
875 }
876 }
877 } else {
878 $typeNum = $row[$field];
879 }
880 // If that value is an empty string, set it to "0" (zero)
881 if (empty($typeNum)) {
882 $typeNum = 0;
883 }
884 }
885 // If current typeNum doesn't exist, set it to 0 (or to 1 for historical reasons, if 0 doesn't exist)
886 if (!$GLOBALS['TCA'][$table]['types'][$typeNum]) {
887 $typeNum = $GLOBALS['TCA'][$table]['types']['0'] ? 0 : 1;
888 }
889 // Force to string. Necessary for eg '-1' to be recognized as a type value.
890 $typeNum = (string)$typeNum;
891 return $typeNum;
892 }
893
894 /**
895 * Parses "defaultExtras" of $GLOBALS['TCA'] columns config section to an array.
896 * Elements are split by ":" and within those parts, parameters are split by "|".
897 *
898 * See unit tests for details.
899 *
900 * @param string $defaultExtrasString "defaultExtras" string from columns config
901 * @param string $_ @deprecated since TYPO3 CMS 7, will be removed with TYPO3 CMS 8
902 * @return array
903 */
904 static public function getSpecConfParts($defaultExtrasString, $_ = '') {
905 if (!empty($_)) {
906 GeneralUtility::deprecationLog('Second parameter of BackendUtility::getSpecConfParts() is deprecated. Will be removed with TYPO3 CMS 8');
907 // Prepend old parameter, can be overwritten by casual defaultExtras string, then.
908 $defaultExtrasString = $_ . ':' . $defaultExtrasString;
909 }
910 $specConfParts = GeneralUtility::trimExplode(':', $defaultExtrasString, TRUE);
911 $reg = array();
912 if (!empty($specConfParts)) {
913 foreach ($specConfParts as $k2 => $v2) {
914 unset($specConfParts[$k2]);
915 if (preg_match('/(.*)\\[(.*)\\]/', $v2, $reg)) {
916 $specConfParts[trim($reg[1])] = array(
917 'parameters' => GeneralUtility::trimExplode('|', $reg[2], TRUE)
918 );
919 } else {
920 $specConfParts[trim($v2)] = 1;
921 }
922 }
923 } else {
924 $specConfParts = array();
925 }
926 return $specConfParts;
927 }
928
929 /**
930 * Takes an array of "[key] = [value]" strings and returns an array with the keys set as keys pointing to the value.
931 * Better see it in action! Find example in Inside TYPO3
932 *
933 * @param array $pArr Array of "[key] = [value]" strings to convert.
934 * @return array
935 */
936 static public function getSpecConfParametersFromArray($pArr) {
937 $out = array();
938 if (is_array($pArr)) {
939 foreach ($pArr as $k => $v) {
940 $parts = explode('=', $v, 2);
941 if (count($parts) === 2) {
942 $out[trim($parts[0])] = trim($parts[1]);
943 } else {
944 $out[$k] = $v;
945 }
946 }
947 }
948 return $out;
949 }
950
951 /**
952 * Finds the Data Structure for a FlexForm field
953 *
954 * NOTE ON data structures for deleted records: This function may fail to deliver the data structure
955 * for a record for a few reasons:
956 * a) The data structure could be deleted (either with deleted-flagged or hard-deleted),
957 * b) the data structure is fetched using the ds_pointerField_searchParent in which case any
958 * deleted record on the route to the final location of the DS will make it fail.
959 * In theory, we can solve the problem in the case where records that are deleted-flagged keeps us
960 * from finding the DS - this is done at the markers ###NOTE_A### where we make sure to also select deleted records.
961 * However, we generally want the DS lookup to fail for deleted records since for the working website we expect a
962 * deleted-flagged record to be as inaccessible as one that is completely deleted from the DB. Any way we look
963 * at it, this may lead to integrity problems of the reference index and even lost files if attached.
964 * However, that is not really important considering that a single change to a data structure can instantly
965 * invalidate large amounts of the reference index which we do accept as a cost for the flexform features.
966 * Other than requiring a reference index update, deletion of/changes in data structure or the failure to look
967 * them up when completely deleting records may lead to lost files in the uploads/ folders since those are now
968 * without a proper reference.
969 *
970 * @param array $conf Field config array
971 * @param array $row Record data
972 * @param string $table The table name
973 * @param string $fieldName Optional fieldname passed to hook object
974 * @param bool $WSOL 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.
975 * @param int $newRecordPidValue 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)
976 * @return mixed If array, the data structure was found and returned as an array. Otherwise (string) it is an error message.
977 * @todo: All those nasty details should be covered with tests, also it is very unfortunate the final $srcPointer is not exposed
978 */
979 static public function getFlexFormDS($conf, $row, $table, $fieldName = '', $WSOL = TRUE, $newRecordPidValue = 0) {
980 // Get pointer field etc from TCA-config:
981 $ds_pointerField = $conf['ds_pointerField'];
982 $ds_array = $conf['ds'];
983 $ds_tableField = $conf['ds_tableField'];
984 $ds_searchParentField = $conf['ds_pointerField_searchParent'];
985 // If there is a data source array, that takes precedence
986 if (is_array($ds_array)) {
987 // If a pointer field is set, take the value from that field in the $row array and use as key.
988 if ($ds_pointerField) {
989 // Up to two pointer fields can be specified in a comma separated list.
990 $pointerFields = GeneralUtility::trimExplode(',', $ds_pointerField);
991 // 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.
992 if (count($pointerFields) === 2) {
993 if ($ds_array[$row[$pointerFields[0]] . ',' . $row[$pointerFields[1]]]) {
994 // Check if we have a DS for the combination of both pointer fields values
995 $srcPointer = $row[$pointerFields[0]] . ',' . $row[$pointerFields[1]];
996 } elseif ($ds_array[$row[$pointerFields[1]] . ',*']) {
997 // Check if we have a DS for the value of the first pointer field suffixed with ",*"
998 $srcPointer = $row[$pointerFields[1]] . ',*';
999 } elseif ($ds_array['*,' . $row[$pointerFields[1]]]) {
1000 // Check if we have a DS for the value of the second pointer field prefixed with "*,"
1001 $srcPointer = '*,' . $row[$pointerFields[1]];
1002 } elseif ($ds_array[$row[$pointerFields[0]]]) {
1003 // Check if we have a DS for just the value of the first pointer field (mainly for backwards compatibility)
1004 $srcPointer = $row[$pointerFields[0]];
1005 } else {
1006 $srcPointer = NULL;
1007 }
1008 } else {
1009 $srcPointer = $row[$pointerFields[0]];
1010 }
1011 $srcPointer = $srcPointer !== NULL && isset($ds_array[$srcPointer]) ? $srcPointer : 'default';
1012 } else {
1013 $srcPointer = 'default';
1014 }
1015 // 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.
1016 if (substr($ds_array[$srcPointer], 0, 5) == 'FILE:') {
1017 $file = GeneralUtility::getFileAbsFileName(substr($ds_array[$srcPointer], 5));
1018 if ($file && @is_file($file)) {
1019 $dataStructArray = GeneralUtility::xml2array(GeneralUtility::getUrl($file));
1020 } else {
1021 $dataStructArray = 'The file "' . substr($ds_array[$srcPointer], 5) . '" in ds-array key "' . $srcPointer . '" was not found ("' . $file . '")';
1022 }
1023 } else {
1024 $dataStructArray = GeneralUtility::xml2array($ds_array[$srcPointer]);
1025 }
1026 } elseif ($ds_pointerField) {
1027 // If pointer field AND possibly a table/field is set:
1028 // Value of field pointed to:
1029 $srcPointer = $row[$ds_pointerField];
1030 // Searching recursively back if 'ds_pointerField_searchParent' is defined (typ. a page rootline, or maybe a tree-table):
1031 if ($ds_searchParentField && !$srcPointer) {
1032 $rr = self::getRecord($table, $row['uid'], 'uid,' . $ds_searchParentField);
1033 // Get the "pid" field - we cannot know that it is in the input record! ###NOTE_A###
1034 if ($WSOL) {
1035 self::workspaceOL($table, $rr);
1036 self::fixVersioningPid($table, $rr, TRUE);
1037 }
1038 $db = static::getDatabaseConnection();
1039 $uidAcc = array();
1040 // Used to avoid looping, if any should happen.
1041 $subFieldPointer = $conf['ds_pointerField_searchParent_subField'];
1042 while (!$srcPointer) {
1043 $res = $db->exec_SELECTquery('uid,' . $ds_pointerField . ',' . $ds_searchParentField . ($subFieldPointer ? ',' . $subFieldPointer : ''), $table, 'uid=' . (int)($newRecordPidValue ?: $rr[$ds_searchParentField]) . self::deleteClause($table));
1044 $newRecordPidValue = 0;
1045 $rr = $db->sql_fetch_assoc($res);
1046 $db->sql_free_result($res);
1047 // Break if no result from SQL db or if looping...
1048 if (!is_array($rr) || isset($uidAcc[$rr['uid']])) {
1049 break;
1050 }
1051 $uidAcc[$rr['uid']] = 1;
1052 if ($WSOL) {
1053 self::workspaceOL($table, $rr);
1054 self::fixVersioningPid($table, $rr, TRUE);
1055 }
1056 $srcPointer = $subFieldPointer && $rr[$subFieldPointer] ? $rr[$subFieldPointer] : $rr[$ds_pointerField];
1057 }
1058 }
1059 // If there is a srcPointer value:
1060 if ($srcPointer) {
1061 if (MathUtility::canBeInterpretedAsInteger($srcPointer)) {
1062 // If integer, then its a record we will look up:
1063 list($tName, $fName) = explode(':', $ds_tableField, 2);
1064 if ($tName && $fName && is_array($GLOBALS['TCA'][$tName])) {
1065 $dataStructRec = self::getRecord($tName, $srcPointer);
1066 if ($WSOL) {
1067 self::workspaceOL($tName, $dataStructRec);
1068 }
1069 if (strpos($dataStructRec[$fName], '<') === FALSE) {
1070 if (is_file(PATH_site . $dataStructRec[$fName])) {
1071 // The value is a pointer to a file
1072 $dataStructArray = GeneralUtility::xml2array(GeneralUtility::getUrl(PATH_site . $dataStructRec[$fName]));
1073 } else {
1074 $dataStructArray = sprintf('File \'%s\' was not found', $dataStructRec[$fName]);
1075 }
1076 } else {
1077 // No file pointer, handle as being XML (default behaviour)
1078 $dataStructArray = GeneralUtility::xml2array($dataStructRec[$fName]);
1079 }
1080 } else {
1081 $dataStructArray = 'No tablename (' . $tName . ') or fieldname (' . $fName . ') was found an valid!';
1082 }
1083 } else {
1084 // Otherwise expect it to be a file:
1085 $file = GeneralUtility::getFileAbsFileName($srcPointer);
1086 if ($file && @is_file($file)) {
1087 $dataStructArray = GeneralUtility::xml2array(GeneralUtility::getUrl($file));
1088 } else {
1089 // Error message.
1090 $dataStructArray = 'The file "' . $srcPointer . '" was not found ("' . $file . '")';
1091 }
1092 }
1093 } else {
1094 // Error message.
1095 $dataStructArray = 'No source value in fieldname "' . $ds_pointerField . '"';
1096 }
1097 } else {
1098 $dataStructArray = 'No proper configuration!';
1099 }
1100 // Hook for post-processing the Flexform DS. Introduces the possibility to configure Flexforms via TSConfig
1101 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['getFlexFormDSClass'])) {
1102 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['getFlexFormDSClass'] as $classRef) {
1103 $hookObj = GeneralUtility::getUserObj($classRef);
1104 if (method_exists($hookObj, 'getFlexFormDS_postProcessDS')) {
1105 $hookObj->getFlexFormDS_postProcessDS($dataStructArray, $conf, $row, $table, $fieldName);
1106 }
1107 }
1108 }
1109 return $dataStructArray;
1110 }
1111
1112 /**
1113 * Returns all registered FlexForm definitions with title and fields
1114 *
1115 * @param string $table The content table
1116 * @return array The data structures with speaking extension title
1117 * @see \TYPO3\CMS\Backend\Utility\BackendUtility::getExcludeFields()
1118 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
1119 */
1120 static public function getRegisteredFlexForms($table = 'tt_content') {
1121 GeneralUtility::logDeprecatedFunction();
1122 if (empty($table) || empty($GLOBALS['TCA'][$table]['columns'])) {
1123 return array();
1124 }
1125 $flexForms = array();
1126 foreach ($GLOBALS['TCA'][$table]['columns'] as $tableField => $fieldConf) {
1127 if (!empty($fieldConf['config']['type']) && !empty($fieldConf['config']['ds']) && $fieldConf['config']['type'] == 'flex') {
1128 $flexForms[$tableField] = array();
1129 unset($fieldConf['config']['ds']['default']);
1130 // Get pointer fields
1131 $pointerFields = !empty($fieldConf['config']['ds_pointerField']) ? $fieldConf['config']['ds_pointerField'] : 'list_type,CType';
1132 $pointerFields = GeneralUtility::trimExplode(',', $pointerFields);
1133 // Get FlexForms
1134 foreach ($fieldConf['config']['ds'] as $flexFormKey => $dataStruct) {
1135 // Get extension identifier (uses second value if it's not empty, "list" or "*", else first one)
1136 $identFields = GeneralUtility::trimExplode(',', $flexFormKey);
1137 $extIdent = $identFields[0];
1138 if (!empty($identFields[1]) && $identFields[1] != 'list' && $identFields[1] != '*') {
1139 $extIdent = $identFields[1];
1140 }
1141 // Load external file references
1142 if (!is_array($dataStruct)) {
1143 $file = GeneralUtility::getFileAbsFileName(str_ireplace('FILE:', '', $dataStruct));
1144 if ($file && @is_file($file)) {
1145 $dataStruct = GeneralUtility::getUrl($file);
1146 }
1147 $dataStruct = GeneralUtility::xml2array($dataStruct);
1148 if (!is_array($dataStruct)) {
1149 continue;
1150 }
1151 }
1152 // Get flexform content
1153 $dataStruct = GeneralUtility::resolveAllSheetsInDS($dataStruct);
1154 if (empty($dataStruct['sheets']) || !is_array($dataStruct['sheets'])) {
1155 continue;
1156 }
1157 // Use DS pointer to get extension title from TCA
1158 $title = $extIdent;
1159 $keyFields = GeneralUtility::trimExplode(',', $flexFormKey);
1160 foreach ($pointerFields as $pointerKey => $pointerName) {
1161 if (empty($keyFields[$pointerKey]) || $keyFields[$pointerKey] == '*' || $keyFields[$pointerKey] == 'list') {
1162 continue;
1163 }
1164 if (!empty($GLOBALS['TCA'][$table]['columns'][$pointerName]['config']['items'])) {
1165 $items = $GLOBALS['TCA'][$table]['columns'][$pointerName]['config']['items'];
1166 if (!is_array($items)) {
1167 continue;
1168 }
1169 foreach ($items as $itemConf) {
1170 if (!empty($itemConf[0]) && !empty($itemConf[1]) && $itemConf[1] == $keyFields[$pointerKey]) {
1171 $title = $itemConf[0];
1172 break 2;
1173 }
1174 }
1175 }
1176 }
1177 $flexForms[$tableField][$extIdent] = array(
1178 'title' => $title,
1179 'ds' => $dataStruct
1180 );
1181 }
1182 }
1183 }
1184 return $flexForms;
1185 }
1186
1187 /*******************************************
1188 *
1189 * Caching related
1190 *
1191 *******************************************/
1192 /**
1193 * Stores $data in the 'cache_hash' cache with the hash key, $hash
1194 * and visual/symbolic identification, $ident
1195 *
1196 * IDENTICAL to the function by same name found in \TYPO3\CMS\Frontend\Page\PageRepository
1197 *
1198 * @param string $hash 32 bit hash string (eg. a md5 hash of a serialized array identifying the data being stored)
1199 * @param mixed $data The data to store
1200 * @param string $ident $ident is just a textual identification in order to inform about the content!
1201 * @return void
1202 */
1203 static public function storeHash($hash, $data, $ident) {
1204 /** @var CacheManager $cacheManager */
1205 $cacheManager = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Cache\CacheManager::class);
1206 $cacheManager->getCache('cache_hash')->set($hash, $data, array('ident_' . $ident), 0);
1207 }
1208
1209 /**
1210 * Returns data stored for the hash string in the cache "cache_hash"
1211 * Can be used to retrieved a cached value, array or object
1212 *
1213 * IDENTICAL to the function by same name found in \TYPO3\CMS\Frontend\Page\PageRepository
1214 *
1215 * @param string $hash The hash-string which was used to store the data value
1216 * @return mixed The "data" from the cache
1217 */
1218 static public function getHash($hash) {
1219 /** @var CacheManager $cacheManager */
1220 $cacheManager = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Cache\CacheManager::class);
1221 $cacheEntry = $cacheManager->getCache('cache_hash')->get($hash);
1222 $hashContent = NULL;
1223 if ($cacheEntry) {
1224 $hashContent = $cacheEntry;
1225 }
1226 return $hashContent;
1227 }
1228
1229 /*******************************************
1230 *
1231 * TypoScript related
1232 *
1233 *******************************************/
1234 /**
1235 * Returns the Page TSconfig for page with id, $id
1236 *
1237 * @param int $id Page uid for which to create Page TSconfig
1238 * @param array $rootLine If $rootLine is an array, that is used as rootline, otherwise rootline is just calculated
1239 * @param bool $returnPartArray 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.
1240 * @return array Page TSconfig
1241 * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser
1242 */
1243 static public function getPagesTSconfig($id, $rootLine = NULL, $returnPartArray = FALSE) {
1244 static $pagesTSconfig_cacheReference = array();
1245 static $combinedTSconfig_cache = array();
1246
1247 $id = (int)$id;
1248 if ($returnPartArray === FALSE
1249 && $rootLine === NULL
1250 && isset($pagesTSconfig_cacheReference[$id])
1251 ) {
1252 return $combinedTSconfig_cache[$pagesTSconfig_cacheReference[$id]];
1253 } else {
1254 $TSconfig = array();
1255 if (!is_array($rootLine)) {
1256 $useCacheForCurrentPageId = TRUE;
1257 $rootLine = self::BEgetRootLine($id, '', TRUE);
1258 } else {
1259 $useCacheForCurrentPageId = FALSE;
1260 }
1261
1262 // Order correctly
1263 ksort($rootLine);
1264 $TSdataArray = array();
1265 // Setting default configuration
1266 $TSdataArray['defaultPageTSconfig'] = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPageTSconfig'];
1267 foreach ($rootLine as $k => $v) {
1268 if (trim($v['tsconfig_includes'])) {
1269 $includeTsConfigFileList = GeneralUtility::trimExplode(',', $v['tsconfig_includes'], TRUE);
1270 // Traversing list
1271 foreach ($includeTsConfigFileList as $key => $includeTsConfigFile) {
1272 if (StringUtility::beginsWith($includeTsConfigFile, 'EXT:')) {
1273 list($includeTsConfigFileExtensionKey, $includeTsConfigFilename) = explode(
1274 '/',
1275 substr($includeTsConfigFile, 4),
1276 2
1277 );
1278 if (
1279 (string)$includeTsConfigFileExtensionKey !== ''
1280 && ExtensionManagementUtility::isLoaded($includeTsConfigFileExtensionKey)
1281 && (string)$includeTsConfigFilename !== ''
1282 ) {
1283 $includeTsConfigFileAndPath = ExtensionManagementUtility::extPath($includeTsConfigFileExtensionKey) .
1284 $includeTsConfigFilename;
1285 if (file_exists($includeTsConfigFileAndPath)) {
1286 $TSdataArray['uid_' . $v['uid'] . '_static_' . $key] = GeneralUtility::getUrl($includeTsConfigFileAndPath);
1287 }
1288 }
1289 }
1290 }
1291 }
1292 $TSdataArray['uid_' . $v['uid']] = $v['TSconfig'];
1293 }
1294 $TSdataArray = static::emitGetPagesTSconfigPreIncludeSignal($TSdataArray, $id, $rootLine, $returnPartArray);
1295 $TSdataArray = TypoScriptParser::checkIncludeLines_array($TSdataArray);
1296 if ($returnPartArray) {
1297 return $TSdataArray;
1298 }
1299 // Parsing the page TS-Config
1300 $pageTS = implode(LF . '[GLOBAL]' . LF, $TSdataArray);
1301 /* @var $parseObj \TYPO3\CMS\Backend\Configuration\TsConfigParser */
1302 $parseObj = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Configuration\TsConfigParser::class);
1303 $res = $parseObj->parseTSconfig($pageTS, 'PAGES', $id, $rootLine);
1304 if ($res) {
1305 $TSconfig = $res['TSconfig'];
1306 }
1307 $cacheHash = $res['hash'];
1308 // Get User TSconfig overlay
1309 $userTSconfig = static::getBackendUserAuthentication()->userTS['page.'];
1310 if (is_array($userTSconfig)) {
1311 ArrayUtility::mergeRecursiveWithOverrule($TSconfig, $userTSconfig);
1312 $cacheHash .= '_user' . $GLOBALS['BE_USER']->user['uid'];
1313 }
1314
1315 if ($useCacheForCurrentPageId) {
1316 if (!isset($combinedTSconfig_cache[$cacheHash])) {
1317 $combinedTSconfig_cache[$cacheHash] = $TSconfig;
1318 }
1319 $pagesTSconfig_cacheReference[$id] = $cacheHash;
1320 }
1321 }
1322 return $TSconfig;
1323 }
1324
1325 /**
1326 * Implodes a multi dimensional TypoScript array, $p, into a one-dimensional array (return value)
1327 *
1328 * @param array $p TypoScript structure
1329 * @param string $k Prefix string
1330 * @return array Imploded TypoScript objectstring/values
1331 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
1332 */
1333 static public function implodeTSParams($p, $k = '') {
1334 GeneralUtility::logDeprecatedFunction();
1335 $implodeParams = array();
1336 if (is_array($p)) {
1337 foreach ($p as $kb => $val) {
1338 if (is_array($val)) {
1339 $implodeParams = array_merge($implodeParams, self::implodeTSParams($val, $k . $kb));
1340 } else {
1341 $implodeParams[$k . $kb] = $val;
1342 }
1343 }
1344 }
1345 return $implodeParams;
1346 }
1347
1348 /*******************************************
1349 *
1350 * Users / Groups related
1351 *
1352 *******************************************/
1353 /**
1354 * Returns an array with be_users records of all user NOT DELETED sorted by their username
1355 * Keys in the array is the be_users uid
1356 *
1357 * @param string $fields Optional $fields list (default: username,usergroup,usergroup_cached_list,uid) can be used to set the selected fields
1358 * @param string $where Optional $where clause (fx. "AND username='pete'") can be used to limit query
1359 * @return array
1360 */
1361 static public function getUserNames($fields = 'username,usergroup,usergroup_cached_list,uid', $where = '') {
1362 return self::getRecordsSortedByTitle(
1363 GeneralUtility::trimExplode(',', $fields, TRUE),
1364 'be_users',
1365 'username',
1366 'AND pid=0 ' . $where
1367 );
1368 }
1369
1370 /**
1371 * Returns an array with be_groups records (title, uid) of all groups NOT DELETED sorted by their title
1372 *
1373 * @param string $fields Field list
1374 * @param string $where WHERE clause
1375 * @return array
1376 */
1377 static public function getGroupNames($fields = 'title,uid', $where = '') {
1378 return self::getRecordsSortedByTitle(
1379 GeneralUtility::trimExplode(',', $fields, TRUE),
1380 'be_groups',
1381 'title',
1382 'AND pid=0 ' . $where
1383 );
1384 }
1385
1386 /**
1387 * Returns an array of all non-deleted records of a table sorted by a given title field.
1388 * The value of the title field will be replaced by the return value
1389 * of self::getRecordTitle() before the sorting is performed.
1390 *
1391 * @param array $fields Fields to select
1392 * @param string $table Table name
1393 * @param string $titleField Field that will contain the record title
1394 * @param string $where Additional where clause
1395 * @return array Array of sorted records
1396 */
1397 static protected function getRecordsSortedByTitle(array $fields, $table, $titleField, $where = '') {
1398 $fieldsIndex = array_flip($fields);
1399 // Make sure the titleField is amongst the fields when getting sorted
1400 $fieldsIndex[$titleField] = 1;
1401
1402 $result = array();
1403 $db = static::getDatabaseConnection();
1404 $res = $db->exec_SELECTquery('*', $table, '1=1 ' . $where . self::deleteClause($table));
1405 while ($record = $db->sql_fetch_assoc($res)) {
1406 // store the uid, because it might be unset if it's not among the requested $fields
1407 $recordId = $record['uid'];
1408 $record[$titleField] = self::getRecordTitle($table, $record);
1409
1410 // include only the requested fields in the result
1411 $result[$recordId] = array_intersect_key($record, $fieldsIndex);
1412 }
1413 $db->sql_free_result($res);
1414
1415 // sort records by $sortField. This is not done in the query because the title might have been overwritten by
1416 // self::getRecordTitle();
1417 return ArrayUtility::sortArraysByKey($result, $titleField);
1418 }
1419
1420 /**
1421 * Returns an array with be_groups records (like ->getGroupNames) but:
1422 * - 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.
1423 *
1424 * @param string $fields Field list; $fields specify the fields selected (default: title,uid)
1425 * @return array
1426 */
1427 static public function getListGroupNames($fields = 'title, uid') {
1428 $beUser = static::getBackendUserAuthentication();
1429 $exQ = ' AND hide_in_lists=0';
1430 if (!$beUser->isAdmin()) {
1431 $exQ .= ' AND uid IN (' . ($beUser->user['usergroup_cached_list'] ?: 0) . ')';
1432 }
1433 return self::getGroupNames($fields, $exQ);
1434 }
1435
1436 /**
1437 * Returns the array $usernames with the names of all users NOT IN $groupArray changed to the uid (hides the usernames!).
1438 * If $excludeBlindedFlag is set, then these records are unset from the array $usernames
1439 * Takes $usernames (array made by \TYPO3\CMS\Backend\Utility\BackendUtility::getUserNames()) and a $groupArray (array with the groups a certain user is member of) as input
1440 *
1441 * @param array $usernames User names
1442 * @param array $groupArray Group names
1443 * @param bool $excludeBlindedFlag If $excludeBlindedFlag is set, then these records are unset from the array $usernames
1444 * @return array User names, blinded
1445 */
1446 static public function blindUserNames($usernames, $groupArray, $excludeBlindedFlag = FALSE) {
1447 if (is_array($usernames) && is_array($groupArray)) {
1448 foreach ($usernames as $uid => $row) {
1449 $userN = $uid;
1450 $set = 0;
1451 if ($row['uid'] != static::getBackendUserAuthentication()->user['uid']) {
1452 foreach ($groupArray as $v) {
1453 if ($v && GeneralUtility::inList($row['usergroup_cached_list'], $v)) {
1454 $userN = $row['username'];
1455 $set = 1;
1456 }
1457 }
1458 } else {
1459 $userN = $row['username'];
1460 $set = 1;
1461 }
1462 $usernames[$uid]['username'] = $userN;
1463 if ($excludeBlindedFlag && !$set) {
1464 unset($usernames[$uid]);
1465 }
1466 }
1467 }
1468 return $usernames;
1469 }
1470
1471 /**
1472 * Corresponds to blindUserNames but works for groups instead
1473 *
1474 * @param array $groups Group names
1475 * @param array $groupArray Group names (reference)
1476 * @param bool $excludeBlindedFlag If $excludeBlindedFlag is set, then these records are unset from the array $usernames
1477 * @return array
1478 */
1479 static public function blindGroupNames($groups, $groupArray, $excludeBlindedFlag = FALSE) {
1480 if (is_array($groups) && is_array($groupArray)) {
1481 foreach ($groups as $uid => $row) {
1482 $groupN = $uid;
1483 $set = 0;
1484 if (ArrayUtility::inArray($groupArray, $uid)) {
1485 $groupN = $row['title'];
1486 $set = 1;
1487 }
1488 $groups[$uid]['title'] = $groupN;
1489 if ($excludeBlindedFlag && !$set) {
1490 unset($groups[$uid]);
1491 }
1492 }
1493 }
1494 return $groups;
1495 }
1496
1497 /*******************************************
1498 *
1499 * Output related
1500 *
1501 *******************************************/
1502 /**
1503 * Returns the difference in days between input $tstamp and $EXEC_TIME
1504 *
1505 * @param int $tstamp Time stamp, seconds
1506 * @return int
1507 */
1508 static public function daysUntil($tstamp) {
1509 $delta_t = $tstamp - $GLOBALS['EXEC_TIME'];
1510 return ceil($delta_t / (3600 * 24));
1511 }
1512
1513 /**
1514 * Returns $tstamp formatted as "ddmmyy" (According to $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'])
1515 *
1516 * @param int $tstamp Time stamp, seconds
1517 * @return string Formatted time
1518 */
1519 static public function date($tstamp) {
1520 return date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'], (int)$tstamp);
1521 }
1522
1523 /**
1524 * Returns $tstamp formatted as "ddmmyy hhmm" (According to $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] AND $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'])
1525 *
1526 * @param int $value Time stamp, seconds
1527 * @return string Formatted time
1528 */
1529 static public function datetime($value) {
1530 return date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'], $value);
1531 }
1532
1533 /**
1534 * Returns $value (in seconds) formatted as hh:mm:ss
1535 * For instance $value = 3600 + 60*2 + 3 should return "01:02:03"
1536 *
1537 * @param int $value Time stamp, seconds
1538 * @param bool $withSeconds Output hh:mm:ss. If FALSE: hh:mm
1539 * @return string Formatted time
1540 */
1541 static public function time($value, $withSeconds = TRUE) {
1542 $hh = floor($value / 3600);
1543 $min = floor(($value - $hh * 3600) / 60);
1544 $sec = $value - $hh * 3600 - $min * 60;
1545 $l = sprintf('%02d', $hh) . ':' . sprintf('%02d', $min);
1546 if ($withSeconds) {
1547 $l .= ':' . sprintf('%02d', $sec);
1548 }
1549 return $l;
1550 }
1551
1552 /**
1553 * Returns the "age" in minutes / hours / days / years of the number of $seconds inputted.
1554 *
1555 * @param int $seconds Seconds could be the difference of a certain timestamp and time()
1556 * @param string $labels 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.xlf:labels.minutesHoursDaysYears")
1557 * @return string Formatted time
1558 */
1559 static public function calcAge($seconds, $labels = ' min| hrs| days| yrs| min| hour| day| year') {
1560 $labelArr = explode('|', $labels);
1561 $absSeconds = abs($seconds);
1562 $sign = $seconds < 0 ? -1 : 1;
1563 if ($absSeconds < 3600) {
1564 $val = round($absSeconds / 60);
1565 $seconds = $sign * $val . ($val == 1 ? $labelArr[4] : $labelArr[0]);
1566 } elseif ($absSeconds < 24 * 3600) {
1567 $val = round($absSeconds / 3600);
1568 $seconds = $sign * $val . ($val == 1 ? $labelArr[5] : $labelArr[1]);
1569 } elseif ($absSeconds < 365 * 24 * 3600) {
1570 $val = round($absSeconds / (24 * 3600));
1571 $seconds = $sign * $val . ($val == 1 ? $labelArr[6] : $labelArr[2]);
1572 } else {
1573 $val = round($absSeconds / (365 * 24 * 3600));
1574 $seconds = $sign * $val . ($val == 1 ? $labelArr[7] : $labelArr[3]);
1575 }
1576 return $seconds;
1577 }
1578
1579 /**
1580 * Returns a formatted timestamp if $tstamp is set.
1581 * The date/datetime will be followed by the age in parenthesis.
1582 *
1583 * @param int $tstamp Time stamp, seconds
1584 * @param int $prefix 1/-1 depending on polarity of age.
1585 * @param string $date $date=="date" will yield "dd:mm:yy" formatting, otherwise "dd:mm:yy hh:mm
1586 * @return string
1587 */
1588 static public function dateTimeAge($tstamp, $prefix = 1, $date = '') {
1589 if (!$tstamp) {
1590 return '';
1591 }
1592 $label = static::getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:labels.minutesHoursDaysYears');
1593 $age = ' (' . self::calcAge($prefix * ($GLOBALS['EXEC_TIME'] - $tstamp), $label) . ')';
1594 return $date === 'date' ? self::date($tstamp) : self::datetime($tstamp) . $age;
1595 }
1596
1597 /**
1598 * Returns alt="" and title="" attributes with the value of $content.
1599 *
1600 * @param string $content Value for 'alt' and 'title' attributes (will be htmlspecialchars()'ed before output)
1601 * @return string
1602 */
1603 static public function titleAltAttrib($content) {
1604 $out = '';
1605 $out .= ' alt="' . htmlspecialchars($content) . '"';
1606 $out .= ' title="' . htmlspecialchars($content) . '"';
1607 return $out;
1608 }
1609
1610 /**
1611 * Resolves file references for a given record.
1612 *
1613 * @param string $tableName Name of the table of the record
1614 * @param string $fieldName Name of the field of the record
1615 * @param array $element Record data
1616 * @param NULL|int $workspaceId Workspace to fetch data for
1617 * @return NULL|\TYPO3\CMS\Core\Resource\FileReference[]
1618 */
1619 static public function resolveFileReferences($tableName, $fieldName, $element, $workspaceId = NULL) {
1620 if (empty($GLOBALS['TCA'][$tableName]['columns'][$fieldName]['config'])) {
1621 return NULL;
1622 }
1623 $configuration = $GLOBALS['TCA'][$tableName]['columns'][$fieldName]['config'];
1624 if (empty($configuration['type']) || $configuration['type'] !== 'inline'
1625 || empty($configuration['foreign_table']) || $configuration['foreign_table'] !== 'sys_file_reference') {
1626 return NULL;
1627 }
1628
1629 $fileReferences = array();
1630 /** @var $relationHandler RelationHandler */
1631 $relationHandler = GeneralUtility::makeInstance(RelationHandler::class);
1632 if ($workspaceId !== NULL) {
1633 $relationHandler->setWorkspaceId($workspaceId);
1634 }
1635 $relationHandler->start($element[$fieldName], $configuration['foreign_table'], $configuration['MM'], $element['uid'], $tableName, $configuration);
1636 $relationHandler->processDeletePlaceholder();
1637 $referenceUids = $relationHandler->tableArray[$configuration['foreign_table']];
1638
1639 foreach ($referenceUids as $referenceUid) {
1640 try {
1641 $fileReference = ResourceFactory::getInstance()->getFileReferenceObject($referenceUid, array(), ($workspaceId === 0));
1642 $fileReferences[$fileReference->getUid()] = $fileReference;
1643 } catch (\TYPO3\CMS\Core\Resource\Exception\FileDoesNotExistException $e) {
1644 /**
1645 * We just catch the exception here
1646 * Reasoning: There is nothing an editor or even admin could do
1647 */
1648 }
1649 }
1650
1651 return $fileReferences;
1652 }
1653
1654 /**
1655 * 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
1656 * All $GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'] extension are made to thumbnails + ttf file (renders font-example)
1657 * Thumbsnails are linked to the show_item.php script which will display further details.
1658 *
1659 * @param array $row Row is the database row from the table, $table.
1660 * @param string $table Table name for $row (present in TCA)
1661 * @param string $field Field is pointing to the list of image files
1662 * @param string $backPath Back path prefix for image tag src="" field
1663 * @param string $thumbScript UNUSED since FAL
1664 * @param string $uploaddir 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!)
1665 * @param int $abs UNUSED
1666 * @param string $tparams Optional: $tparams is additional attributes for the image tags
1667 * @param int|string $size Optional: $size is [w]x[h] of the thumbnail. 64 is default.
1668 * @param bool $linkInfoPopup Whether to wrap with a link opening the info popup
1669 * @return string Thumbnail image tag.
1670 */
1671 static public function thumbCode($row, $table, $field, $backPath = '', $thumbScript = '', $uploaddir = NULL, $abs = 0, $tparams = '', $size = '', $linkInfoPopup = TRUE) {
1672 // Check and parse the size parameter
1673 $size = trim($size);
1674 $sizeParts = array(64, 64);
1675 if ($size) {
1676 $sizeParts = explode('x', $size . 'x' . $size);
1677 }
1678 $thumbData = '';
1679 $fileReferences = static::resolveFileReferences($table, $field, $row);
1680 // FAL references
1681 if ($fileReferences !== NULL) {
1682 foreach ($fileReferences as $fileReferenceObject) {
1683 $fileObject = $fileReferenceObject->getOriginalFile();
1684
1685 if ($fileObject->isMissing()) {
1686 $flashMessage = \TYPO3\CMS\Core\Resource\Utility\BackendUtility::getFlashMessageForMissingFile($fileObject);
1687 $thumbData .= $flashMessage->render();
1688 continue;
1689 }
1690
1691 // Web image
1692 if (GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'], $fileReferenceObject->getExtension())) {
1693 $processedImage = $fileObject->process(ProcessedFile::CONTEXT_IMAGECROPSCALEMASK, array(
1694 'width' => $sizeParts[0],
1695 'height' => $sizeParts[1] . 'c',
1696 'crop' => $fileReferenceObject->getProperty('crop')
1697 ));
1698 $imageUrl = $processedImage->getPublicUrl(TRUE);
1699 $imgTag = '<img src="' . $imageUrl . '" ' .
1700 'width="' . $processedImage->getProperty('width') . '" ' .
1701 'height="' . $processedImage->getProperty('height') . '" ' .
1702 'alt="' . htmlspecialchars($fileReferenceObject->getName()) . '" />';
1703 } else {
1704 // Icon
1705 $imgTag = IconUtility::getSpriteIconForResource($fileObject, array('title' => $fileObject->getName()));
1706 }
1707 if ($linkInfoPopup) {
1708 $onClick = 'top.launchView(\'_FILE\',\'' . (int)$fileObject->getUid() . '\',' . GeneralUtility::quoteJSvalue($backPath) . '); return false;';
1709 $thumbData .= '<a href="#" onclick="' . htmlspecialchars($onClick) . '">' . $imgTag . '</a> ';
1710 } else {
1711 $thumbData .= $imgTag;
1712 }
1713 }
1714 } else {
1715 // Find uploaddir automatically
1716 if (is_null($uploaddir)) {
1717 $uploaddir = $GLOBALS['TCA'][$table]['columns'][$field]['config']['uploadfolder'];
1718 }
1719 $uploaddir = rtrim($uploaddir, '/');
1720 // Traverse files:
1721 $thumbs = GeneralUtility::trimExplode(',', $row[$field], TRUE);
1722 $thumbData = '';
1723 foreach ($thumbs as $theFile) {
1724 if ($theFile) {
1725 $fileName = trim($uploaddir . '/' . $theFile, '/');
1726 try {
1727 /** @var File $fileObject */
1728 $fileObject = ResourceFactory::getInstance()->retrieveFileOrFolderObject($fileName);
1729 if ($fileObject->isMissing()) {
1730 $flashMessage = \TYPO3\CMS\Core\Resource\Utility\BackendUtility::getFlashMessageForMissingFile($fileObject);
1731 $thumbData .= $flashMessage->render();
1732 continue;
1733 }
1734 } catch (ResourceDoesNotExistException $exception) {
1735 /** @var FlashMessage $flashMessage */
1736 $flashMessage = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Messaging\FlashMessage::class,
1737 htmlspecialchars($exception->getMessage()),
1738 static::getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:warning.file_missing', TRUE),
1739 FlashMessage::ERROR
1740 );
1741 $thumbData .= $flashMessage->render();
1742 continue;
1743 }
1744
1745 $fileExtension = $fileObject->getExtension();
1746 if ($fileExtension == 'ttf' || GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'], $fileExtension)) {
1747 $imageUrl = $fileObject->process(ProcessedFile::CONTEXT_IMAGEPREVIEW, array(
1748 'width' => $sizeParts[0],
1749 'height' => $sizeParts[1]
1750 ))->getPublicUrl(TRUE);
1751 $image = '<img src="' . htmlspecialchars($imageUrl) . '" hspace="2" border="0" title="' . htmlspecialchars($fileObject->getName()) . '"' . $tparams . ' alt="" />';
1752 if ($linkInfoPopup) {
1753 $onClick = 'top.launchView(\'_FILE\', ' . GeneralUtility::quoteJSvalue($fileName) . ',\'\',' . GeneralUtility::quoteJSvalue($backPath) . ');return false;';
1754 $thumbData .= '<a href="#" onclick="' . htmlspecialchars($onClick) . '">' . $image . '</a> ';
1755 } else {
1756 $thumbData .= $image;
1757 }
1758 } else {
1759 // Gets the icon
1760 $fileIcon = IconUtility::getSpriteIconForResource($fileObject, array('title' => $fileObject->getName()));
1761 if ($linkInfoPopup) {
1762 $onClick = 'top.launchView(\'_FILE\', ' . GeneralUtility::quoteJSvalue($fileName) . ',\'\',' . GeneralUtility::quoteJSvalue($backPath) . '); return false;';
1763 $thumbData .= '<a href="#" onclick="' . htmlspecialchars($onClick) . '">' . $fileIcon . '</a> ';
1764 } else {
1765 $thumbData .= $fileIcon;
1766 }
1767 }
1768 }
1769 }
1770 }
1771 return $thumbData;
1772 }
1773
1774 /**
1775 * Returns single image tag to thumbnail using a thumbnail script (like thumbs.php)
1776 *
1777 * @param string $thumbScript Must point to "thumbs.php" relative to the script position
1778 * @param string $theFile Must be the proper reference to the file that thumbs.php should show
1779 * @param string $tparams The additional attributes for the image tag
1780 * @param string $size The size of the thumbnail send along to thumbs.php
1781 * @return string Image tag
1782 * @deprecated since TYPO3 CMS 7, will be removed with TYPO3 CMS 8, use the corresponding Resource objects and Processing functionality
1783 */
1784 static public function getThumbNail($thumbScript, $theFile, $tparams = '', $size = '') {
1785 GeneralUtility::logDeprecatedFunction();
1786 $size = trim($size);
1787 $check = basename($theFile) . ':' . filemtime($theFile) . ':' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
1788 $params = '&file=' . rawurlencode($theFile);
1789 $params .= $size ? '&size=' . $size : '';
1790 $params .= '&md5sum=' . md5($check);
1791 $url = $thumbScript . '?' . $params;
1792 $th = '<img src="' . htmlspecialchars($url) . '" title="' . trim(basename($theFile)) . '"' . ($tparams ? ' ' . $tparams : '') . ' alt="" />';
1793 return $th;
1794 }
1795
1796 /**
1797 * Returns title-attribute information for a page-record informing about id, alias, doktype, hidden, starttime, endtime, fe_group etc.
1798 *
1799 * @param array $row Input must be a page row ($row) with the proper fields set (be sure - send the full range of fields for the table)
1800 * @param string $perms_clause This is used to get the record path of the shortcut page, if any (and doktype==4)
1801 * @param bool $includeAttrib If $includeAttrib is set, then the 'title=""' attribute is wrapped about the return value, which is in any case htmlspecialchar()'ed already
1802 * @return string
1803 */
1804 static public function titleAttribForPages($row, $perms_clause = '', $includeAttrib = TRUE) {
1805 $lang = static::getLanguageService();
1806 $parts = array();
1807 $parts[] = 'id=' . $row['uid'];
1808 if ($row['alias']) {
1809 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['alias']['label']) . ' ' . $row['alias'];
1810 }
1811 if ($row['pid'] < 0) {
1812 $parts[] = 'v#1.' . $row['t3ver_id'];
1813 }
1814 switch (VersionState::cast($row['t3ver_state'])) {
1815 case new VersionState(VersionState::NEW_PLACEHOLDER):
1816 $parts[] = 'PLH WSID#' . $row['t3ver_wsid'];
1817 break;
1818 case new VersionState(VersionState::DELETE_PLACEHOLDER):
1819 $parts[] = 'Deleted element!';
1820 break;
1821 case new VersionState(VersionState::MOVE_PLACEHOLDER):
1822 $parts[] = 'NEW LOCATION (PLH) WSID#' . $row['t3ver_wsid'];
1823 break;
1824 case new VersionState(VersionState::MOVE_POINTER):
1825 $parts[] = 'OLD LOCATION (PNT) WSID#' . $row['t3ver_wsid'];
1826 break;
1827 case new VersionState(VersionState::NEW_PLACEHOLDER_VERSION):
1828 $parts[] = 'New element!';
1829 break;
1830 }
1831 if ($row['doktype'] == PageRepository::DOKTYPE_LINK) {
1832 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['url']['label']) . ' ' . $row['url'];
1833 } elseif ($row['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
1834 if ($perms_clause) {
1835 $label = self::getRecordPath((int)$row['shortcut'], $perms_clause, 20);
1836 } else {
1837 $row['shortcut'] = (int)$row['shortcut'];
1838 $lRec = self::getRecordWSOL('pages', $row['shortcut'], 'title');
1839 $label = $lRec['title'] . ' (id=' . $row['shortcut'] . ')';
1840 }
1841 if ($row['shortcut_mode'] != PageRepository::SHORTCUT_MODE_NONE) {
1842 $label .= ', ' . $lang->sL($GLOBALS['TCA']['pages']['columns']['shortcut_mode']['label']) . ' ' . $lang->sL(self::getLabelFromItemlist('pages', 'shortcut_mode', $row['shortcut_mode']));
1843 }
1844 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['shortcut']['label']) . ' ' . $label;
1845 } elseif ($row['doktype'] == PageRepository::DOKTYPE_MOUNTPOINT) {
1846 if ($perms_clause) {
1847 $label = self::getRecordPath((int)$row['mount_pid'], $perms_clause, 20);
1848 } else {
1849 $lRec = self::getRecordWSOL('pages', (int)$row['mount_pid'], 'title');
1850 $label = $lRec['title'] . ' (id=' . $row['mount_pid'] . ')';
1851 }
1852 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['mount_pid']['label']) . ' ' . $label;
1853 if ($row['mount_pid_ol']) {
1854 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['mount_pid_ol']['label']);
1855 }
1856 }
1857 if ($row['nav_hide']) {
1858 $parts[] = rtrim($lang->sL($GLOBALS['TCA']['pages']['columns']['nav_hide']['label']), ':');
1859 }
1860 if ($row['hidden']) {
1861 $parts[] = $lang->sL('LLL:EXT:lang/locallang_core.xlf:labels.hidden');
1862 }
1863 if ($row['starttime']) {
1864 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['starttime']['label']) . ' ' . self::dateTimeAge($row['starttime'], -1, 'date');
1865 }
1866 if ($row['endtime']) {
1867 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['endtime']['label']) . ' ' . self::dateTimeAge($row['endtime'], -1, 'date');
1868 }
1869 if ($row['fe_group']) {
1870 $fe_groups = array();
1871 foreach (GeneralUtility::intExplode(',', $row['fe_group']) as $fe_group) {
1872 if ($fe_group < 0) {
1873 $fe_groups[] = $lang->sL(self::getLabelFromItemlist('pages', 'fe_group', $fe_group));
1874 } else {
1875 $lRec = self::getRecordWSOL('fe_groups', $fe_group, 'title');
1876 $fe_groups[] = $lRec['title'];
1877 }
1878 }
1879 $label = implode(', ', $fe_groups);
1880 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['fe_group']['label']) . ' ' . $label;
1881 }
1882 $out = htmlspecialchars(implode(' - ', $parts));
1883 return $includeAttrib ? 'title="' . $out . '"' : $out;
1884 }
1885
1886 /**
1887 * Returns title-attribute information for ANY record (from a table defined in TCA of course)
1888 * 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.
1889 * "pages" table can be used as well and will return the result of ->titleAttribForPages() for that page.
1890 *
1891 * @param array $row Table row; $row is a row from the table, $table
1892 * @param string $table Table name
1893 * @return string
1894 */
1895 static public function getRecordIconAltText($row, $table = 'pages') {
1896 if ($table == 'pages') {
1897 $out = self::titleAttribForPages($row, '', 0);
1898 } else {
1899 $out = !empty(trim($GLOBALS['TCA'][$table]['ctrl']['descriptionColumn'])) ? $row[$GLOBALS['TCA'][$table]['ctrl']['descriptionColumn']] . ' ' : '';
1900 $ctrl = $GLOBALS['TCA'][$table]['ctrl']['enablecolumns'];
1901 // Uid is added
1902 $out .= '(id=' . $row['uid'] . ')';
1903 if ($table == 'pages' && $row['alias']) {
1904 $out .= ' / ' . $row['alias'];
1905 }
1906 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS'] && $row['pid'] < 0) {
1907 $out .= ' - v#1.' . $row['t3ver_id'];
1908 }
1909 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
1910 switch (VersionState::cast($row['t3ver_state'])) {
1911 case new VersionState(VersionState::NEW_PLACEHOLDER):
1912 $out .= ' - PLH WSID#' . $row['t3ver_wsid'];
1913 break;
1914 case new VersionState(VersionState::DELETE_PLACEHOLDER):
1915 $out .= ' - Deleted element!';
1916 break;
1917 case new VersionState(VersionState::MOVE_PLACEHOLDER):
1918 $out .= ' - NEW LOCATION (PLH) WSID#' . $row['t3ver_wsid'];
1919 break;
1920 case new VersionState(VersionState::MOVE_POINTER):
1921 $out .= ' - OLD LOCATION (PNT) WSID#' . $row['t3ver_wsid'];
1922 break;
1923 case new VersionState(VersionState::NEW_PLACEHOLDER_VERSION):
1924 $out .= ' - New element!';
1925 break;
1926 }
1927 }
1928 // Hidden
1929 $lang = static::getLanguageService();
1930 if ($ctrl['disabled']) {
1931 $out .= $row[$ctrl['disabled']] ? ' - ' . $lang->sL('LLL:EXT:lang/locallang_core.xlf:labels.hidden') : '';
1932 }
1933 if ($ctrl['starttime']) {
1934 if ($row[$ctrl['starttime']] > $GLOBALS['EXEC_TIME']) {
1935 $out .= ' - ' . $lang->sL('LLL:EXT:lang/locallang_core.xlf:labels.starttime') . ':' . self::date($row[$ctrl['starttime']]) . ' (' . self::daysUntil($row[$ctrl['starttime']]) . ' ' . $lang->sL('LLL:EXT:lang/locallang_core.xlf:labels.days') . ')';
1936 }
1937 }
1938 if ($row[$ctrl['endtime']]) {
1939 $out .= ' - ' . $lang->sL('LLL:EXT:lang/locallang_core.xlf:labels.endtime') . ': ' . self::date($row[$ctrl['endtime']]) . ' (' . self::daysUntil($row[$ctrl['endtime']]) . ' ' . $lang->sL('LLL:EXT:lang/locallang_core.xlf:labels.days') . ')';
1940 }
1941 }
1942 return htmlspecialchars($out);
1943 }
1944
1945 /**
1946 * Returns the label of the first found entry in an "items" array from $GLOBALS['TCA'] (tablename = $table/fieldname = $col) where the value is $key
1947 *
1948 * @param string $table Table name, present in $GLOBALS['TCA']
1949 * @param string $col Field name, present in $GLOBALS['TCA']
1950 * @param string $key items-array value to match
1951 * @return string Label for item entry
1952 */
1953 static public function getLabelFromItemlist($table, $col, $key) {
1954 // Check, if there is an "items" array:
1955 if (is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'][$col]) && is_array($GLOBALS['TCA'][$table]['columns'][$col]['config']['items'])) {
1956 // Traverse the items-array...
1957 foreach ($GLOBALS['TCA'][$table]['columns'][$col]['config']['items'] as $v) {
1958 // ... and return the first found label where the value was equal to $key
1959 if ((string)$v[1] === (string)$key) {
1960 return $v[0];
1961 }
1962 }
1963 }
1964 return '';
1965 }
1966
1967 /**
1968 * Return the label of a field by additionally checking TsConfig values
1969 *
1970 * @param int $pageId Page id
1971 * @param string $table Table name
1972 * @param string $column Field Name
1973 * @param string $key item value
1974 * @return string Label for item entry
1975 */
1976 static public function getLabelFromItemListMerged($pageId, $table, $column, $key) {
1977 $pageTsConfig = static::getPagesTSconfig($pageId);
1978 $label = '';
1979 if (is_array($pageTsConfig['TCEFORM.']) && is_array($pageTsConfig['TCEFORM.'][$table . '.']) && is_array($pageTsConfig['TCEFORM.'][$table . '.'][$column . '.'])) {
1980 if (is_array($pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['addItems.']) && isset($pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['addItems.'][$key])) {
1981 $label = $pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['addItems.'][$key];
1982 } elseif (is_array($pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['altLabels.']) && isset($pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['altLabels.'][$key])) {
1983 $label = $pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['altLabels.'][$key];
1984 }
1985 }
1986 if (empty($label)) {
1987 $tcaValue = self::getLabelFromItemlist($table, $column, $key);
1988 if (!empty($tcaValue)) {
1989 $label = $tcaValue;
1990 }
1991 }
1992 return $label;
1993 }
1994
1995 /**
1996 * Splits the given key with commas and returns the list of all the localized items labels, separated by a comma.
1997 * NOTE: this does not take itemsProcFunc into account
1998 *
1999 * @param string $table Table name, present in TCA
2000 * @param string $column Field name
2001 * @param string $keyList Key or comma-separated list of keys.
2002 * @param array $columnTsConfig page TSConfig for $column (TCEMAIN.<table>.<column>)
2003 * @return string Comma-separated list of localized labels
2004 */
2005 static public function getLabelsFromItemsList($table, $column, $keyList, array $columnTsConfig = array()) {
2006 // Check if there is an "items" array
2007 if (
2008 !isset($GLOBALS['TCA'][$table]['columns'][$column]['config']['items'])
2009 || !is_array($GLOBALS['TCA'][$table]['columns'][$column]['config']['items'])
2010 || $keyList === ''
2011 ) {
2012 return '';
2013 }
2014
2015 $keys = GeneralUtility::trimExplode(',', $keyList, TRUE);
2016 $labels = array();
2017 // Loop on all selected values
2018 foreach ($keys as $key) {
2019 $label = NULL;
2020 if ($columnTsConfig) {
2021 // Check if label has been defined or redefined via pageTsConfig
2022 if (isset($columnTsConfig['addItems.'][$key])) {
2023 $label = $columnTsConfig['addItems.'][$key];
2024 } elseif (isset($columnTsConfig['altLabels.'][$key])) {
2025 $label = $columnTsConfig['altLabels.'][$key];
2026 }
2027 }
2028 if ($label === NULL) {
2029 // Otherwise lookup the label in TCA items list
2030 foreach ($GLOBALS['TCA'][$table]['columns'][$column]['config']['items'] as $itemConfiguration) {
2031 list($currentLabel, $currentKey) = $itemConfiguration;
2032 if ((string)$key === (string)$currentKey) {
2033 $label = $currentLabel;
2034 break;
2035 }
2036 }
2037 }
2038 if ($label !== NULL) {
2039 $labels[] = static::getLanguageService()->sL($label);
2040 }
2041 }
2042 return implode(', ', $labels);
2043 }
2044
2045 /**
2046 * Returns the label-value for fieldname $col in table, $table
2047 * 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>'
2048 *
2049 * @param string $table Table name, present in $GLOBALS['TCA']
2050 * @param string $col Field name
2051 * @param string $printAllWrap Wrap value - set function description - this parameter is deprecated since TYPO3 6.2 and is removed two versions later. This parameter is a conceptual failure, as the content can then never be HSCed afterwards (which is how the method is used all the time), and then the code would be HSCed twice.
2052 * @return string or NULL if $col is not found in the TCA table
2053 */
2054 static public function getItemLabel($table, $col, $printAllWrap = '') {
2055 // Check if column exists
2056 if (is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'][$col])) {
2057 return $GLOBALS['TCA'][$table]['columns'][$col]['label'];
2058 }
2059 if ($printAllWrap) {
2060 GeneralUtility::deprecationLog('The third parameter of getItemLabel() is deprecated with TYPO3 CMS 6.2 and will be removed two versions later.');
2061 $parts = explode('|', $printAllWrap);
2062 return $parts[0] . $col . $parts[1];
2063 }
2064
2065 return NULL;
2066 }
2067
2068 /**
2069 * Replace field values in given row with values from the original language
2070 * if l10n_mode TCA settings require to do so.
2071 *
2072 * @param string $table Table name
2073 * @param array $row Row to fill with original language values
2074 * @return array Row with values from the original language
2075 */
2076 static protected function replaceL10nModeFields($table, array $row) {
2077 $originalUidField = isset($GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'])
2078 ? $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']
2079 : '';
2080 if (empty($row[$originalUidField])) {
2081 return $row;
2082 }
2083
2084 $originalTable = self::getOriginalTranslationTable($table);
2085 $originalRow = self::getRecord($originalTable, $row[$originalUidField]);
2086 foreach ($row as $field => $_) {
2087 $l10n_mode = isset($GLOBALS['TCA'][$originalTable]['columns'][$field]['l10n_mode'])
2088 ? $GLOBALS['TCA'][$originalTable]['columns'][$field]['l10n_mode']
2089 : '';
2090 if ($l10n_mode === 'exclude' || ($l10n_mode === 'mergeIfNotBlank' && trim($row[$field]) === '')) {
2091 $row[$field] = $originalRow[$field];
2092 }
2093 }
2094 return $row;
2095 }
2096
2097 /**
2098 * Returns the "title"-value in record, $row, from table, $table
2099 * The field(s) from which the value is taken is determined by the "ctrl"-entries 'label', 'label_alt' and 'label_alt_force'
2100 *
2101 * @param string $table Table name, present in TCA
2102 * @param array $row Row from table
2103 * @param bool $prep If set, result is prepared for output: The output is cropped to a limited length (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
2104 * @param bool $forceResult If set, the function always returns an output. If no value is found for the title, '[No title]' is returned (localized).
2105 * @return string
2106 */
2107 static public function getRecordTitle($table, $row, $prep = FALSE, $forceResult = TRUE) {
2108 $cacheIdentifier = $table . '-' . $row['uid'] . '-prep-' . (int)$prep . '-forceResult-' . (int)$forceResult;
2109 if (isset(self::$recordTitleCache[$cacheIdentifier])) {
2110 return self::$recordTitleCache[$cacheIdentifier];
2111 }
2112
2113 $recordTitle = '';
2114 if (is_array($GLOBALS['TCA'][$table])) {
2115 // If configured, call userFunc
2116 if ($GLOBALS['TCA'][$table]['ctrl']['label_userFunc']) {
2117 $params['table'] = $table;
2118 $params['row'] = $row;
2119 $params['title'] = '';
2120 $params['options'] = isset($GLOBALS['TCA'][$table]['ctrl']['label_userFunc_options']) ? $GLOBALS['TCA'][$table]['ctrl']['label_userFunc_options'] : array();
2121
2122 // Create NULL-reference
2123 $null = NULL;
2124 GeneralUtility::callUserFunction($GLOBALS['TCA'][$table]['ctrl']['label_userFunc'], $params, $null);
2125 $recordTitle = $params['title'];
2126 } else {
2127 if (is_array($row)) {
2128 $row = self::replaceL10nModeFields($table, $row);
2129 }
2130
2131 // No userFunc: Build label
2132 $recordTitle = self::getProcessedValue($table, $GLOBALS['TCA'][$table]['ctrl']['label'], $row[$GLOBALS['TCA'][$table]['ctrl']['label']], 0, 0, FALSE, $row['uid'], $forceResult);
2133 if ($GLOBALS['TCA'][$table]['ctrl']['label_alt'] && ($GLOBALS['TCA'][$table]['ctrl']['label_alt_force'] || (string)$recordTitle === '')) {
2134 $altFields = GeneralUtility::trimExplode(',', $GLOBALS['TCA'][$table]['ctrl']['label_alt'], TRUE);
2135 $tA = array();
2136 if (!empty($recordTitle)) {
2137 $tA[] = $recordTitle;
2138 }
2139 foreach ($altFields as $fN) {
2140 $recordTitle = trim(strip_tags($row[$fN]));
2141 if ((string)$recordTitle !== '') {
2142 $recordTitle = self::getProcessedValue($table, $fN, $recordTitle, 0, 0, FALSE, $row['uid']);
2143 if (!$GLOBALS['TCA'][$table]['ctrl']['label_alt_force']) {
2144 break;
2145 }
2146 $tA[] = $recordTitle;
2147 }
2148 }
2149 if ($GLOBALS['TCA'][$table]['ctrl']['label_alt_force']) {
2150 $recordTitle = implode(', ', $tA);
2151 }
2152 }
2153 }
2154 // If the current result is empty, set it to '[No title]' (localized) and prepare for output if requested
2155 if ($prep || $forceResult) {
2156 if ($prep) {
2157 $recordTitle = self::getRecordTitlePrep($recordTitle);
2158 }
2159 if (trim($recordTitle) === '') {
2160 $recordTitle = self::getNoRecordTitle($prep);
2161 }
2162 }
2163 }
2164 self::$recordTitleCache[$cacheIdentifier] = $recordTitle;
2165
2166 return $recordTitle;
2167 }
2168
2169 /**
2170 * Crops a title string to a limited length and if it really was cropped, wrap it in a <span title="...">|</span>,
2171 * which offers a tooltip with the original title when moving mouse over it.
2172 *
2173 * @param string $title The title string to be cropped
2174 * @param int $titleLength Crop title after this length - if not set, BE_USER->uc['titleLen'] is used
2175 * @return string The processed title string, wrapped in <span title="...">|</span> if cropped
2176 */
2177 static public function getRecordTitlePrep($title, $titleLength = 0) {
2178 // If $titleLength is not a valid positive integer, use BE_USER->uc['titleLen']:
2179 if (!$titleLength || !MathUtility::canBeInterpretedAsInteger($titleLength) || $titleLength < 0) {
2180 $titleLength = static::getBackendUserAuthentication()->uc['titleLen'];
2181 }
2182 $titleOrig = htmlspecialchars($title);
2183 $title = htmlspecialchars(GeneralUtility::fixed_lgd_cs($title, $titleLength));
2184 // If title was cropped, offer a tooltip:
2185 if ($titleOrig != $title) {
2186 $title = '<span title="' . $titleOrig . '">' . $title . '</span>';
2187 }
2188 return $title;
2189 }
2190
2191 /**
2192 * Get a localized [No title] string, wrapped in <em>|</em> if $prep is TRUE.
2193 *
2194 * @param bool $prep Wrap result in <em>|</em>
2195 * @return string Localized [No title] string
2196 */
2197 static public function getNoRecordTitle($prep = FALSE) {
2198 $noTitle = '[' . static::getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:labels.no_title', TRUE) . ']';
2199 if ($prep) {
2200 $noTitle = '<em>' . $noTitle . '</em>';
2201 }
2202 return $noTitle;
2203 }
2204
2205 /**
2206 * Returns a human readable output of a value from a record
2207 * 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.
2208 * $table/$col is tablename and fieldname
2209 * REMEMBER to pass the output through htmlspecialchars() if you output it to the browser! (To protect it from XSS attacks and be XHTML compliant)
2210 *
2211 * @param string $table Table name, present in TCA
2212 * @param string $col Field name, present in TCA
2213 * @param string $value The value of that field from a selected record
2214 * @param int $fixed_lgd_chars The max amount of characters the value may occupy
2215 * @param bool $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")
2216 * @param bool $noRecordLookup If set, no records will be looked up, UIDs are just shown.
2217 * @param int $uid Uid of the current record
2218 * @param bool $forceResult If BackendUtility::getRecordTitle is used to process the value, this parameter is forwarded.
2219 * @param int $pid Optional page uid is used to evaluate page TSConfig for the given field
2220 * @throws \InvalidArgumentException
2221 * @return string|NULL
2222 */
2223 static public function getProcessedValue($table, $col, $value, $fixed_lgd_chars = 0, $defaultPassthrough = FALSE, $noRecordLookup = FALSE, $uid = 0, $forceResult = TRUE, $pid = 0) {
2224 if ($col === 'uid') {
2225 // uid is not in TCA-array
2226 return $value;
2227 }
2228 // Check if table and field is configured
2229 if (!is_array($GLOBALS['TCA'][$table]) || !is_array($GLOBALS['TCA'][$table]['columns'][$col])) {
2230 return NULL;
2231 }
2232 // Depending on the fields configuration, make a meaningful output value.
2233 $theColConf = $GLOBALS['TCA'][$table]['columns'][$col]['config'];
2234 /*****************
2235 *HOOK: pre-processing the human readable output from a record
2236 ****************/
2237 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['preProcessValue'])) {
2238 // Create NULL-reference
2239 $null = NULL;
2240 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['preProcessValue'] as $_funcRef) {
2241 GeneralUtility::callUserFunction($_funcRef, $theColConf, $null);
2242 }
2243 }
2244 $l = '';
2245 $db = static::getDatabaseConnection();
2246 $lang = static::getLanguageService();
2247 switch ((string)$theColConf['type']) {
2248 case 'radio':
2249 $l = self::getLabelFromItemlist($table, $col, $value);
2250 $l = $lang->sL($l);
2251 break;
2252 case 'inline':
2253 case 'select':
2254 if ($theColConf['MM']) {
2255 if ($uid) {
2256 // Display the title of MM related records in lists
2257 if ($noRecordLookup) {
2258 $MMfield = $theColConf['foreign_table'] . '.uid';
2259 } else {
2260 $MMfields = array($theColConf['foreign_table'] . '.' . $GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label']);
2261 foreach (GeneralUtility::trimExplode(',', $GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label_alt'], TRUE) as $f) {
2262 $MMfields[] = $theColConf['foreign_table'] . '.' . $f;
2263 }
2264 $MMfield = join(',', $MMfields);
2265 }
2266 /** @var $dbGroup RelationHandler */
2267 $dbGroup = GeneralUtility::makeInstance(RelationHandler::class);
2268 $dbGroup->start($value, $theColConf['foreign_table'], $theColConf['MM'], $uid, $table, $theColConf);
2269 $selectUids = $dbGroup->tableArray[$theColConf['foreign_table']];
2270 if (is_array($selectUids) && !empty($selectUids)) {
2271 $MMres = $db->exec_SELECTquery('uid, ' . $MMfield, $theColConf['foreign_table'], 'uid IN (' . implode(',', $selectUids) . ')' . self::deleteClause($theColConf['foreign_table']));
2272 $mmlA = array();
2273 while ($MMrow = $db->sql_fetch_assoc($MMres)) {
2274 // Keep sorting of $selectUids
2275 $mmlA[array_search($MMrow['uid'], $selectUids)] = $noRecordLookup ?
2276 $MMrow['uid'] :
2277 static::getRecordTitle($theColConf['foreign_table'], $MMrow, FALSE, $forceResult);
2278 }
2279 $db->sql_free_result($MMres);
2280 if (!empty($mmlA)) {
2281 ksort($mmlA);
2282 $l = implode('; ', $mmlA);
2283 } else {
2284 $l = 'N/A';
2285 }
2286 } else {
2287 $l = 'N/A';
2288 }
2289 } else {
2290 $l = 'N/A';
2291 }
2292 } else {
2293 $columnTsConfig = array();
2294 if ($pid) {
2295 $pageTsConfig = self::getPagesTSconfig($pid);
2296 if (isset($pageTsConfig['TCEFORM.'][$table . '.'][$col . '.']) && is_array($pageTsConfig['TCEFORM.'][$table . '.'][$col . '.'])) {
2297 $columnTsConfig = $pageTsConfig['TCEFORM.'][$table . '.'][$col . '.'];
2298 }
2299 }
2300 $l = self::getLabelsFromItemsList($table, $col, $value, $columnTsConfig);
2301 if ($theColConf['foreign_table'] && !$l && $GLOBALS['TCA'][$theColConf['foreign_table']]) {
2302 if ($noRecordLookup) {
2303 $l = $value;
2304 } else {
2305 $rParts = array();
2306 if ($uid && isset($theColConf['foreign_field']) && $theColConf['foreign_field'] !== '') {
2307 $whereClause = '';
2308 if (!empty($theColConf['foreign_table_field'])) {
2309 $whereClause .= ' AND ' . $theColConf['foreign_table_field'] . ' = ' . static::getDatabaseConnection()->fullQuoteStr($table, $theColConf['foreign_table']);
2310 }
2311 // Add additional where clause if foreign_match_fields are defined
2312 $foreignMatchFields = is_array($theColConf['foreign_match_fields']) ? $theColConf['foreign_match_fields'] : array();
2313 foreach ($foreignMatchFields as $matchField => $matchValue) {
2314 $whereClause .= ' AND ' . $matchField . '=' . static::getDatabaseConnection()->fullQuoteStr($matchValue, $theColConf['foreign_table']);
2315 }
2316 $records = self::getRecordsByField($theColConf['foreign_table'], $theColConf['foreign_field'], $uid, $whereClause);
2317 if (!empty($records)) {
2318 foreach ($records as $record) {
2319 $rParts[] = $record['uid'];
2320 }
2321 }
2322 }
2323 if (empty($rParts)) {
2324 $rParts = GeneralUtility::trimExplode(',', $value, TRUE);
2325 }
2326 $lA = array();
2327 foreach ($rParts as $rVal) {
2328 $rVal = (int)$rVal;
2329 $r = self::getRecordWSOL($theColConf['foreign_table'], $rVal);
2330 if (is_array($r)) {
2331 $lA[] = $lang->sL($theColConf['foreign_table_prefix']) . self::getRecordTitle($theColConf['foreign_table'], $r, FALSE, $forceResult);
2332 } else {
2333 $lA[] = $rVal ? '[' . $rVal . '!]' : '';
2334 }
2335 }
2336 $l = implode(', ', $lA);
2337 }
2338 }
2339 if (empty($l) && !empty($value)) {
2340 // Use plain database value when label is empty
2341 $l = $value;
2342 }
2343 }
2344 break;
2345 case 'group':
2346 // resolve the titles for DB records
2347 if ($theColConf['internal_type'] === 'db') {
2348 if ($theColConf['MM']) {
2349 if ($uid) {
2350 // Display the title of MM related records in lists
2351 if ($noRecordLookup) {
2352 $MMfield = $theColConf['foreign_table'] . '.uid';
2353 } else {
2354 $MMfields = array($theColConf['foreign_table'] . '.' . $GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label']);
2355 $altLabelFields = explode(',', $GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label_alt']);
2356 foreach ($altLabelFields as $f) {
2357 $f = trim($f);
2358 if ($f !== '') {
2359 $MMfields[] = $theColConf['foreign_table'] . '.' . $f;
2360 }
2361 }
2362 $MMfield = join(',', $MMfields);
2363 }
2364 /** @var $dbGroup RelationHandler */
2365 $dbGroup = GeneralUtility::makeInstance(RelationHandler::class);
2366 $dbGroup->start($value, $theColConf['foreign_table'], $theColConf['MM'], $uid, $table, $theColConf);
2367 $selectUids = $dbGroup->tableArray[$theColConf['foreign_table']];
2368 if (!empty($selectUids) && is_array($selectUids)) {
2369 $MMres = $db->exec_SELECTquery(
2370 'uid, ' . $MMfield,
2371 $theColConf['foreign_table'],
2372 'uid IN (' . implode(',', $selectUids) . ')' . static::deleteClause($theColConf['foreign_table'])
2373 );
2374 $mmlA = array();
2375 while ($MMrow = $db->sql_fetch_assoc($MMres)) {
2376 // Keep sorting of $selectUids
2377 $mmlA[array_search($MMrow['uid'], $selectUids)] = $noRecordLookup
2378 ? $MMrow['uid']
2379 : static::getRecordTitle($theColConf['foreign_table'], $MMrow, FALSE, $forceResult);
2380 }
2381 $db->sql_free_result($MMres);
2382 if (!empty($mmlA)) {
2383 ksort($mmlA);
2384 $l = implode('; ', $mmlA);
2385 } else {
2386 $l = 'N/A';
2387 }
2388 } else {
2389 $l = 'N/A';
2390 }
2391 } else {
2392 $l = 'N/A';
2393 }
2394 } else {
2395 $finalValues = array();
2396 $relationTableName = $theColConf['allowed'];
2397 $explodedValues = GeneralUtility::trimExplode(',', $value, TRUE);
2398
2399 foreach ($explodedValues as $explodedValue) {
2400 if (MathUtility::canBeInterpretedAsInteger($explodedValue)) {
2401 $relationTableNameForField = $relationTableName;
2402 } else {
2403 list($relationTableNameForField, $explodedValue) = self::splitTable_Uid($explodedValue);
2404 }
2405
2406 $relationRecord = static::getRecordWSOL($relationTableNameForField, $explodedValue);
2407 $finalValues[] = static::getRecordTitle($relationTableNameForField, $relationRecord);
2408 }
2409 $l = implode(', ', $finalValues);
2410 }
2411 } else {
2412 $l = implode(', ', GeneralUtility::trimExplode(',', $value, TRUE));
2413 }
2414 break;
2415 case 'check':
2416 if (!is_array($theColConf['items']) || count($theColConf['items']) === 1) {
2417 $l = $value ? $lang->sL('LLL:EXT:lang/locallang_common.xlf:yes') : $lang->sL('LLL:EXT:lang/locallang_common.xlf:no');
2418 } else {
2419 $lA = array();
2420 foreach ($theColConf['items'] as $key => $val) {
2421 if ($value & pow(2, $key)) {
2422 $lA[] = $lang->sL($val[0]);
2423 }
2424 }
2425 $l = implode(', ', $lA);
2426 }
2427 break;
2428 case 'input':
2429 // Hide value 0 for dates, but show it for everything else
2430 if (isset($value)) {
2431 if (GeneralUtility::inList($theColConf['eval'], 'date')) {
2432 // Handle native date field
2433 if (isset($theColConf['dbType']) && $theColConf['dbType'] === 'date') {
2434 $dateTimeFormats = $db->getDateTimeFormats($table);
2435 $emptyValue = $dateTimeFormats['date']['empty'];
2436 $value = $value !== $emptyValue ? strtotime($value) : 0;
2437 }
2438 if (!empty($value)) {
2439 $ageSuffix = '';
2440 $dateColumnConfiguration = $GLOBALS['TCA'][$table]['columns'][$col]['config'];
2441 $ageDisplayKey = 'disableAgeDisplay';
2442
2443 // generate age suffix as long as not explicitly suppressed
2444 if (!isset($dateColumnConfiguration[$ageDisplayKey])
2445 // non typesafe comparison on intention
2446 || $dateColumnConfiguration[$ageDisplayKey] == FALSE) {
2447 $ageSuffix = ' (' . ($GLOBALS['EXEC_TIME'] - $value > 0 ? '-' : '') . self::calcAge(abs(($GLOBALS['EXEC_TIME'] - $value)), $lang->sL('LLL:EXT:lang/locallang_core.xlf:labels.minutesHoursDaysYears')) . ')';
2448 }
2449
2450 $l = self::date($value) . $ageSuffix;
2451 }
2452 } elseif (GeneralUtility::inList($theColConf['eval'], 'time')) {
2453 if (!empty($value)) {
2454 $l = self::time($value, FALSE);
2455 }
2456 } elseif (GeneralUtility::inList($theColConf['eval'], 'timesec')) {
2457 if (!empty($value)) {
2458 $l = self::time($value);
2459 }
2460 } elseif (GeneralUtility::inList($theColConf['eval'], 'datetime')) {
2461 // Handle native date/time field
2462 if (isset($theColConf['dbType']) && $theColConf['dbType'] === 'datetime') {
2463 $dateTimeFormats = $db->getDateTimeFormats($table);
2464 $emptyValue = $dateTimeFormats['datetime']['empty'];
2465 $value = $value !== $emptyValue ? strtotime($value) : 0;
2466 }
2467 if (!empty($value)) {
2468 $l = self::datetime($value);
2469 }
2470 } else {
2471 $l = $value;
2472 }
2473 }
2474 break;
2475 case 'flex':
2476 $l = strip_tags($value);
2477 break;
2478 default:
2479 if ($defaultPassthrough) {
2480 $l = $value;
2481 } elseif ($theColConf['MM']) {
2482 $l = 'N/A';
2483 } elseif ($value) {
2484 $l = GeneralUtility::fixed_lgd_cs(strip_tags($value), 200);
2485 }
2486 }
2487 // If this field is a password field, then hide the password by changing it to a random number of asterisk (*)
2488 if (stristr($theColConf['eval'], 'password')) {
2489 $l = '';
2490 $randomNumber = rand(5, 12);
2491 for ($i = 0; $i < $randomNumber; $i++) {
2492 $l .= '*';
2493 }
2494 }
2495 /*****************
2496 *HOOK: post-processing the human readable output from a record
2497 ****************/
2498 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['postProcessValue'])) {
2499 // Create NULL-reference
2500 $null = NULL;
2501 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['postProcessValue'] as $_funcRef) {
2502 $params = array(
2503 'value' => $l,
2504 'colConf' => $theColConf
2505 );
2506 $l = GeneralUtility::callUserFunction($_funcRef, $params, $null);
2507 }
2508 }
2509 if ($fixed_lgd_chars) {
2510 return GeneralUtility::fixed_lgd_cs($l, $fixed_lgd_chars);
2511 } else {
2512 return $l;
2513 }
2514 }
2515
2516 /**
2517 * 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.
2518 *
2519 * @param string $table Table name, present in TCA
2520 * @param string $fN Field name
2521 * @param string $fV Field value
2522 * @param int $fixed_lgd_chars The max amount of characters the value may occupy
2523 * @param int $uid Uid of the current record
2524 * @param bool $forceResult If BackendUtility::getRecordTitle is used to process the value, this parameter is forwarded.
2525 * @param int $pid Optional page uid is used to evaluate page TSConfig for the given field
2526 * @return string
2527 * @see getProcessedValue()
2528 */
2529 static public function getProcessedValueExtra($table, $fN, $fV, $fixed_lgd_chars = 0, $uid = 0, $forceResult = TRUE, $pid = 0) {
2530 $fVnew = self::getProcessedValue($table, $fN, $fV, $fixed_lgd_chars, 1, 0, $uid, $forceResult, $pid);
2531 if (!isset($fVnew)) {
2532 if (is_array($GLOBALS['TCA'][$table])) {
2533 if ($fN == $GLOBALS['TCA'][$table]['ctrl']['tstamp'] || $fN == $GLOBALS['TCA'][$table]['ctrl']['crdate']) {
2534 $fVnew = self::datetime($fV);
2535 } elseif ($fN == 'pid') {
2536 // Fetches the path with no regard to the users permissions to select pages.
2537 $fVnew = self::getRecordPath($fV, '1=1', 20);
2538 } else {
2539 $fVnew = $fV;
2540 }
2541 }
2542 }
2543 return $fVnew;
2544 }
2545
2546 /**
2547 * Returns fields for a table, $table, which would typically be interesting to select
2548 * This includes uid, the fields defined for title, icon-field.
2549 * 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)
2550 *
2551 * @param string $table Table name, present in $GLOBALS['TCA']
2552 * @param string $prefix Table prefix
2553 * @param array $fields Preset fields (must include prefix if that is used)
2554 * @return string List of fields.
2555 */
2556 static public function getCommonSelectFields($table, $prefix = '', $fields = array()) {
2557 $fields[] = $prefix . 'uid';
2558 if (isset($GLOBALS['TCA'][$table]['ctrl']['label']) && $GLOBALS['TCA'][$table]['ctrl']['label'] != '') {
2559 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['label'];
2560 }
2561 if ($GLOBALS['TCA'][$table]['ctrl']['label_alt']) {
2562 $secondFields = GeneralUtility::trimExplode(',', $GLOBALS['TCA'][$table]['ctrl']['label_alt'], TRUE);
2563 foreach ($secondFields as $fieldN) {
2564 $fields[] = $prefix . $fieldN;
2565 }
2566 }
2567 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
2568 $fields[] = $prefix . 't3ver_id';
2569 $fields[] = $prefix . 't3ver_state';
2570 $fields[] = $prefix . 't3ver_wsid';
2571 $fields[] = $prefix . 't3ver_count';
2572 }
2573 if ($GLOBALS['TCA'][$table]['ctrl']['selicon_field']) {
2574 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['selicon_field'];
2575 }
2576 if ($GLOBALS['TCA'][$table]['ctrl']['typeicon_column']) {
2577 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['typeicon_column'];
2578 }
2579 if (is_array($GLOBALS['TCA'][$table]['ctrl']['enablecolumns'])) {
2580 if ($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['disabled']) {
2581 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['disabled'];
2582 }
2583 if ($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['starttime']) {
2584 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['starttime'];
2585 }
2586 if ($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['endtime']) {
2587 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['endtime'];
2588 }
2589 if ($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['fe_group']) {
2590 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['fe_group'];
2591 }
2592 }
2593 return implode(',', array_unique($fields));
2594 }
2595
2596 /**
2597 * Makes a form for configuration of some values based on configuration found in the array $configArray,
2598 * with default values from $defaults and a data-prefix $dataPrefix
2599 * <form>-tags must be supplied separately
2600 * Needs more documentation and examples, in particular syntax for configuration array. See Inside TYPO3.
2601 * That's were you can expect to find example, if anywhere.
2602 *
2603 * @param array $configArray Field configuration code.
2604 * @param array $defaults Defaults
2605 * @param string $dataPrefix Prefix for formfields
2606 * @return string HTML for a form.
2607 */
2608 static public function makeConfigForm($configArray, $defaults, $dataPrefix) {
2609 $params = $defaults;
2610 $lines = array();
2611 if (is_array($configArray)) {
2612 foreach ($configArray as $fname => $config) {
2613 if (is_array($config)) {
2614 $lines[$fname] = '<strong>' . htmlspecialchars($config[1]) . '</strong><br />';
2615 $lines[$fname] .= $config[2] . '<br />';
2616 switch ($config[0]) {
2617 case 'string':
2618
2619 case 'short':
2620 $formEl = '<input type="text" name="' . $dataPrefix . '[' . $fname . ']" value="' . $params[$fname] . '"' . static::getDocumentTemplate()->formWidth(($config[0] == 'short' ? 24 : 48)) . ' />';
2621 break;
2622 case 'check':
2623 $formEl = '<input type="hidden" name="' .