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