0bf79b2da826e99cd1cbc4e78a6861ee12832981
[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 Psr\Log\LoggerInterface;
18 use TYPO3\CMS\Backend\Routing\UriBuilder;
19 use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
20 use TYPO3\CMS\Core\Cache\CacheManager;
21 use TYPO3\CMS\Core\Cache\Frontend\FrontendInterface;
22 use TYPO3\CMS\Core\Database\Connection;
23 use TYPO3\CMS\Core\Database\ConnectionPool;
24 use TYPO3\CMS\Core\Database\Query\QueryBuilder;
25 use TYPO3\CMS\Core\Database\Query\QueryHelper;
26 use TYPO3\CMS\Core\Database\Query\Restriction\BackendWorkspaceRestriction;
27 use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
28 use TYPO3\CMS\Core\Database\Query\Restriction\HiddenRestriction;
29 use TYPO3\CMS\Core\Database\RelationHandler;
30 use TYPO3\CMS\Core\Imaging\Icon;
31 use TYPO3\CMS\Core\Imaging\IconFactory;
32 use TYPO3\CMS\Core\Imaging\ImageManipulation\CropVariantCollection;
33 use TYPO3\CMS\Core\Localization\LanguageService;
34 use TYPO3\CMS\Core\Log\LogManager;
35 use TYPO3\CMS\Core\Resource\AbstractFile;
36 use TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException;
37 use TYPO3\CMS\Core\Resource\File;
38 use TYPO3\CMS\Core\Resource\ProcessedFile;
39 use TYPO3\CMS\Core\Resource\ResourceFactory;
40 use TYPO3\CMS\Core\Type\Bitmask\Permission;
41 use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser;
42 use TYPO3\CMS\Core\Utility\ArrayUtility;
43 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
44 use TYPO3\CMS\Core\Utility\GeneralUtility;
45 use TYPO3\CMS\Core\Utility\MathUtility;
46 use TYPO3\CMS\Core\Utility\PathUtility;
47 use TYPO3\CMS\Core\Versioning\VersionState;
48 use TYPO3\CMS\Frontend\Page\PageRepository;
49
50 /**
51 * Standard functions available for the TYPO3 backend.
52 * You are encouraged to use this class in your own applications (Backend Modules)
53 * Don't instantiate - call functions with "\TYPO3\CMS\Backend\Utility\BackendUtility::" prefixed the function name.
54 *
55 * Call ALL methods without making an object!
56 * Eg. to get a page-record 51 do this: '\TYPO3\CMS\Backend\Utility\BackendUtility::getRecord('pages',51)'
57 */
58 class BackendUtility
59 {
60 /**
61 * Cache the TCA configuration of tables with their types during runtime
62 *
63 * @var array
64 * @see self::getTCAtypes()
65 */
66 protected static $tcaTableTypeConfigurationCache = [];
67
68 /*******************************************
69 *
70 * SQL-related, selecting records, searching
71 *
72 *******************************************/
73 /**
74 * Returns the WHERE clause " AND NOT [tablename].[deleted-field]" if a deleted-field
75 * is configured in $GLOBALS['TCA'] for the tablename, $table
76 * This function should ALWAYS be called in the backend for selection on tables which
77 * are configured in $GLOBALS['TCA'] since it will ensure consistent selection of records,
78 * even if they are marked deleted (in which case the system must always treat them as non-existent!)
79 * In the frontend a function, ->enableFields(), is known to filter hidden-field, start- and endtime
80 * and fe_groups as well. But that is a job of the frontend, not the backend. If you need filtering
81 * on those fields as well in the backend you can use ->BEenableFields() though.
82 *
83 * @param string $table Table name present in $GLOBALS['TCA']
84 * @param string $tableAlias Table alias if any
85 * @return string WHERE clause for filtering out deleted records, eg " AND tablename.deleted=0
86 * @deprecated since TYPO3 v9, will be removed in TYPO3 v10, the DeletedRestriction functionality should be used instead.
87 */
88 public static function deleteClause($table, $tableAlias = '')
89 {
90 trigger_error('This method will be removed in TYPO3 v10. Add the delete statement directly in your SQL statement via the DeletedRestriction', E_USER_DEPRECATED);
91 if (empty($GLOBALS['TCA'][$table]['ctrl']['delete'])) {
92 return '';
93 }
94 $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
95 ->getQueryBuilderForTable($table)
96 ->expr();
97 return ' AND ' . $expressionBuilder->eq(
98 ($tableAlias ?: $table) . '.' . $GLOBALS['TCA'][$table]['ctrl']['delete'],
99 0
100 );
101 }
102
103 /**
104 * Gets record with uid = $uid from $table
105 * You can set $field to a list of fields (default is '*')
106 * Additional WHERE clauses can be added by $where (fx. ' AND blabla = 1')
107 * Will automatically check if records has been deleted and if so, not return anything.
108 * $table must be found in $GLOBALS['TCA']
109 *
110 * @param string $table Table name present in $GLOBALS['TCA']
111 * @param int $uid UID of record
112 * @param string $fields List of fields to select
113 * @param string $where Additional WHERE clause, eg. " AND blablabla = 0
114 * @param bool $useDeleteClause Use the deleteClause to check if a record is deleted (default TRUE)
115 * @return array|null Returns the row if found, otherwise NULL
116 */
117 public static function getRecord($table, $uid, $fields = '*', $where = '', $useDeleteClause = true)
118 {
119 // Ensure we have a valid uid (not 0 and not NEWxxxx) and a valid TCA
120 if ((int)$uid && !empty($GLOBALS['TCA'][$table])) {
121 $queryBuilder = static::getQueryBuilderForTable($table);
122
123 // do not use enabled fields here
124 $queryBuilder->getRestrictions()->removeAll();
125
126 // should the delete clause be used
127 if ($useDeleteClause) {
128 $queryBuilder->getRestrictions()->add(GeneralUtility::makeInstance(DeletedRestriction::class));
129 }
130
131 // set table and where clause
132 $queryBuilder
133 ->select(...GeneralUtility::trimExplode(',', $fields, true))
134 ->from($table)
135 ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter((int)$uid, \PDO::PARAM_INT)));
136
137 // add custom where clause
138 if ($where) {
139 $queryBuilder->andWhere(QueryHelper::stripLogicalOperatorPrefix($where));
140 }
141
142 $row = $queryBuilder->execute()->fetch();
143 if ($row) {
144 return $row;
145 }
146 }
147 return null;
148 }
149
150 /**
151 * Like getRecord(), but overlays workspace version if any.
152 *
153 * @param string $table Table name present in $GLOBALS['TCA']
154 * @param int $uid UID of record
155 * @param string $fields List of fields to select
156 * @param string $where Additional WHERE clause, eg. " AND blablabla = 0
157 * @param bool $useDeleteClause Use the deleteClause to check if a record is deleted (default TRUE)
158 * @param bool $unsetMovePointers If TRUE the function does not return a "pointer" row for moved records in a workspace
159 * @return array Returns the row if found, otherwise nothing
160 */
161 public static function getRecordWSOL(
162 $table,
163 $uid,
164 $fields = '*',
165 $where = '',
166 $useDeleteClause = true,
167 $unsetMovePointers = false
168 ) {
169 if ($fields !== '*') {
170 $internalFields = GeneralUtility::uniqueList($fields . ',uid,pid');
171 $row = self::getRecord($table, $uid, $internalFields, $where, $useDeleteClause);
172 self::workspaceOL($table, $row, -99, $unsetMovePointers);
173 if (is_array($row)) {
174 foreach ($row as $key => $_) {
175 if (!GeneralUtility::inList($fields, $key) && $key[0] !== '_') {
176 unset($row[$key]);
177 }
178 }
179 }
180 } else {
181 $row = self::getRecord($table, $uid, $fields, $where, $useDeleteClause);
182 self::workspaceOL($table, $row, -99, $unsetMovePointers);
183 }
184 return $row;
185 }
186
187 /**
188 * Purges computed properties starting with underscore character ('_').
189 *
190 * @param array $record
191 * @return array
192 */
193 public static function purgeComputedPropertiesFromRecord(array $record): array
194 {
195 return array_filter(
196 $record,
197 function (string $propertyName): bool {
198 return $propertyName[0] !== '_';
199 },
200 ARRAY_FILTER_USE_KEY
201 );
202 }
203
204 /**
205 * Purges computed property names starting with underscore character ('_').
206 *
207 * @param array $propertyNames
208 * @return array
209 */
210 public static function purgeComputedPropertyNames(array $propertyNames): array
211 {
212 return array_filter(
213 $propertyNames,
214 function (string $propertyName): bool {
215 return $propertyName[0] !== '_';
216 }
217 );
218 }
219
220 /**
221 * Makes an backwards explode on the $str and returns an array with ($table, $uid).
222 * Example: tt_content_45 => array('tt_content', 45)
223 *
224 * @param string $str [tablename]_[uid] string to explode
225 * @return array
226 */
227 public static function splitTable_Uid($str)
228 {
229 list($uid, $table) = explode('_', strrev($str), 2);
230 return [strrev($table), strrev($uid)];
231 }
232
233 /**
234 * Backend implementation of enableFields()
235 * Notice that "fe_groups" is not selected for - only disabled, starttime and endtime.
236 * Notice that deleted-fields are NOT filtered - you must ALSO call deleteClause in addition.
237 * $GLOBALS["SIM_ACCESS_TIME"] is used for date.
238 *
239 * @param string $table The table from which to return enableFields WHERE clause. Table name must have a 'ctrl' section in $GLOBALS['TCA'].
240 * @param bool $inv Means that the query will select all records NOT VISIBLE records (inverted selection)
241 * @return string WHERE clause part
242 */
243 public static function BEenableFields($table, $inv = false)
244 {
245 $ctrl = $GLOBALS['TCA'][$table]['ctrl'];
246 $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
247 ->getConnectionForTable($table)
248 ->getExpressionBuilder();
249 $query = $expressionBuilder->andX();
250 $invQuery = $expressionBuilder->orX();
251
252 if (is_array($ctrl)) {
253 if (is_array($ctrl['enablecolumns'])) {
254 if ($ctrl['enablecolumns']['disabled']) {
255 $field = $table . '.' . $ctrl['enablecolumns']['disabled'];
256 $query->add($expressionBuilder->eq($field, 0));
257 $invQuery->add($expressionBuilder->neq($field, 0));
258 }
259 if ($ctrl['enablecolumns']['starttime']) {
260 $field = $table . '.' . $ctrl['enablecolumns']['starttime'];
261 $query->add($expressionBuilder->lte($field, (int)$GLOBALS['SIM_ACCESS_TIME']));
262 $invQuery->add(
263 $expressionBuilder->andX(
264 $expressionBuilder->neq($field, 0),
265 $expressionBuilder->gt($field, (int)$GLOBALS['SIM_ACCESS_TIME'])
266 )
267 );
268 }
269 if ($ctrl['enablecolumns']['endtime']) {
270 $field = $table . '.' . $ctrl['enablecolumns']['endtime'];
271 $query->add(
272 $expressionBuilder->orX(
273 $expressionBuilder->eq($field, 0),
274 $expressionBuilder->gt($field, (int)$GLOBALS['SIM_ACCESS_TIME'])
275 )
276 );
277 $invQuery->add(
278 $expressionBuilder->andX(
279 $expressionBuilder->neq($field, 0),
280 $expressionBuilder->lte($field, (int)$GLOBALS['SIM_ACCESS_TIME'])
281 )
282 );
283 }
284 }
285 }
286
287 if ($query->count() === 0) {
288 return '';
289 }
290
291 return ' AND ' . ($inv ? $invQuery : $query);
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 if (self::isTableLocalizable($table)) {
308 $tcaCtrl = $GLOBALS['TCA'][$table]['ctrl'];
309
310 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
311 ->getQueryBuilderForTable($table);
312 $queryBuilder->getRestrictions()
313 ->removeAll()
314 ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
315 ->add(GeneralUtility::makeInstance(BackendWorkspaceRestriction::class));
316
317 $queryBuilder->select('*')
318 ->from($table)
319 ->where(
320 $queryBuilder->expr()->eq(
321 $tcaCtrl['transOrigPointerField'],
322 $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
323 ),
324 $queryBuilder->expr()->eq(
325 $tcaCtrl['languageField'],
326 $queryBuilder->createNamedParameter((int)$language, \PDO::PARAM_INT)
327 )
328 )
329 ->setMaxResults(1);
330
331 if ($andWhereClause) {
332 $queryBuilder->andWhere(QueryHelper::stripLogicalOperatorPrefix($andWhereClause));
333 }
334
335 $recordLocalization = $queryBuilder->execute()->fetchAll();
336 }
337
338 return $recordLocalization;
339 }
340
341 /*******************************************
342 *
343 * Page tree, TCA related
344 *
345 *******************************************/
346 /**
347 * Returns what is called the 'RootLine'. That is an array with information about the page records from a page id
348 * ($uid) and back to the root.
349 * By default deleted pages are filtered.
350 * This RootLine will follow the tree all the way to the root. This is opposite to another kind of root line known
351 * from the frontend where the rootline stops when a root-template is found.
352 *
353 * @param int $uid Page id for which to create the root line.
354 * @param string $clause Clause can be used to select other criteria. It would typically be where-clauses that
355 * stops the process if we meet a page, the user has no reading access to.
356 * @param bool $workspaceOL If TRUE, version overlay is applied. This must be requested specifically because it is
357 * usually only wanted when the rootline is used for visual output while for permission checking you want the raw thing!
358 * @param string[] $additionalFields Additional Fields to select for rootline records
359 * @return array Root line array, all the way to the page tree root (or as far as $clause allows!)
360 */
361 public static function BEgetRootLine($uid, $clause = '', $workspaceOL = false, array $additionalFields = [])
362 {
363 static $BEgetRootLine_cache = [];
364 $output = [];
365 $pid = $uid;
366 $ident = $pid . '-' . $clause . '-' . $workspaceOL . ($additionalFields ? '-' . implode(',', $additionalFields) : '');
367 if (is_array($BEgetRootLine_cache[$ident] ?? false)) {
368 $output = $BEgetRootLine_cache[$ident];
369 } else {
370 $loopCheck = 100;
371 $theRowArray = [];
372 while ($uid != 0 && $loopCheck) {
373 $loopCheck--;
374 $row = self::getPageForRootline($uid, $clause, $workspaceOL, $additionalFields);
375 if (is_array($row)) {
376 $uid = $row['pid'];
377 $theRowArray[] = $row;
378 } else {
379 break;
380 }
381 }
382 if ($uid == 0) {
383 $theRowArray[] = [
384 'uid' => 0,
385 'pid' => null,
386 'title' => '',
387 'doktype' => null,
388 'tsconfig_includes' => null,
389 'TSconfig' => null,
390 'is_siteroot' => null,
391 't3ver_oid' => null,
392 't3ver_wsid' => null,
393 't3ver_state' => null,
394 't3ver_stage' => null,
395 'backend_layout_next_level' => null
396 ];
397 }
398 $c = count($theRowArray);
399 foreach ($theRowArray as $val) {
400 $c--;
401 $fields = [
402 'uid',
403 'pid',
404 'title',
405 'doktype',
406 'tsconfig_includes',
407 'TSconfig',
408 'is_siteroot',
409 't3ver_oid',
410 't3ver_wsid',
411 't3ver_state',
412 't3ver_stage',
413 'backend_layout_next_level',
414 ];
415 $fields = array_merge($fields, $additionalFields);
416 $output[$c] = array_intersect_key($val, array_combine($fields, $fields));
417 if (isset($val['_ORIG_pid'])) {
418 $output[$c]['_ORIG_pid'] = $val['_ORIG_pid'];
419 }
420 }
421 $BEgetRootLine_cache[$ident] = $output;
422 }
423 return $output;
424 }
425
426 /**
427 * Gets the cached page record for the rootline
428 *
429 * @param int $uid Page id for which to create the root line.
430 * @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.
431 * @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!
432 * @param string[] $additionalFields AdditionalFields to fetch from the root line
433 * @return array Cached page record for the rootline
434 * @see BEgetRootLine
435 */
436 protected static function getPageForRootline($uid, $clause, $workspaceOL, array $additionalFields = [])
437 {
438 static $getPageForRootline_cache = [];
439 $ident = $uid . '-' . $clause . '-' . $workspaceOL;
440 if (is_array($getPageForRootline_cache[$ident]) ?? false) {
441 $row = $getPageForRootline_cache[$ident];
442 } else {
443 $queryBuilder = static::getQueryBuilderForTable('pages');
444 $queryBuilder->getRestrictions()
445 ->removeAll()
446 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
447
448 $row = $queryBuilder
449 ->select(
450 'pid',
451 'uid',
452 'title',
453 'doktype',
454 'tsconfig_includes',
455 'TSconfig',
456 'is_siteroot',
457 't3ver_oid',
458 't3ver_wsid',
459 't3ver_state',
460 't3ver_stage',
461 'backend_layout_next_level',
462 ...$additionalFields
463 )
464 ->from('pages')
465 ->where(
466 $queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)),
467 QueryHelper::stripLogicalOperatorPrefix($clause)
468 )
469 ->execute()
470 ->fetch();
471
472 if ($row) {
473 $newLocation = false;
474 if ($workspaceOL) {
475 self::workspaceOL('pages', $row);
476 $newLocation = self::getMovePlaceholder('pages', $row['uid'], 'pid');
477 }
478 if (is_array($row)) {
479 if ($newLocation !== false) {
480 $row['pid'] = $newLocation['pid'];
481 } else {
482 self::fixVersioningPid('pages', $row);
483 }
484 $getPageForRootline_cache[$ident] = $row;
485 }
486 }
487 }
488 return $row;
489 }
490
491 /**
492 * Opens the page tree to the specified page id
493 *
494 * @param int $pid Page id.
495 * @param bool $clearExpansion If set, then other open branches are closed.
496 */
497 public static function openPageTree($pid, $clearExpansion)
498 {
499 $beUser = static::getBackendUserAuthentication();
500 // Get current expansion data:
501 if ($clearExpansion) {
502 $expandedPages = [];
503 } else {
504 $expandedPages = unserialize($beUser->uc['browseTrees']['browsePages']);
505 }
506 // Get rootline:
507 $rL = self::BEgetRootLine($pid);
508 // First, find out what mount index to use (if more than one DB mount exists):
509 $mountIndex = 0;
510 $mountKeys = array_flip($beUser->returnWebmounts());
511 foreach ($rL as $rLDat) {
512 if (isset($mountKeys[$rLDat['uid']])) {
513 $mountIndex = $mountKeys[$rLDat['uid']];
514 break;
515 }
516 }
517 // Traverse rootline and open paths:
518 foreach ($rL as $rLDat) {
519 $expandedPages[$mountIndex][$rLDat['uid']] = 1;
520 }
521 // Write back:
522 $beUser->uc['browseTrees']['browsePages'] = serialize($expandedPages);
523 $beUser->writeUC();
524 }
525
526 /**
527 * Returns the path (visually) of a page $uid, fx. "/First page/Second page/Another subpage"
528 * Each part of the path will be limited to $titleLimit characters
529 * Deleted pages are filtered out.
530 *
531 * @param int $uid Page uid for which to create record path
532 * @param string $clause Clause is additional where clauses, eg.
533 * @param int $titleLimit Title limit
534 * @param int $fullTitleLimit Title limit of Full title (typ. set to 1000 or so)
535 * @return mixed Path of record (string) OR array with short/long title if $fullTitleLimit is set.
536 */
537 public static function getRecordPath($uid, $clause, $titleLimit, $fullTitleLimit = 0)
538 {
539 if (!$titleLimit) {
540 $titleLimit = 1000;
541 }
542 $output = $fullOutput = '/';
543 $clause = trim($clause);
544 if ($clause !== '' && substr($clause, 0, 3) !== 'AND') {
545 $clause = 'AND ' . $clause;
546 }
547 $data = self::BEgetRootLine($uid, $clause);
548 foreach ($data as $record) {
549 if ($record['uid'] === 0) {
550 continue;
551 }
552 $output = '/' . GeneralUtility::fixed_lgd_cs(strip_tags($record['title']), $titleLimit) . $output;
553 if ($fullTitleLimit) {
554 $fullOutput = '/' . GeneralUtility::fixed_lgd_cs(strip_tags($record['title']), $fullTitleLimit) . $fullOutput;
555 }
556 }
557 if ($fullTitleLimit) {
558 return [$output, $fullOutput];
559 }
560 return $output;
561 }
562
563 /**
564 * Gets the original translation pointer table, which is always the same table
565 *
566 * @param string $table Name of the table
567 * @return string Pointer table (if any)
568 */
569 public static function getOriginalTranslationTable($table)
570 {
571 trigger_error('Starting with TYPO3 v9, the translation table is always the same as the original table, because pages_language_overlay has been migrated into pages table.', E_USER_DEPRECATED);
572 return $table;
573 }
574
575 /**
576 * Determines whether a table is localizable and has the languageField and transOrigPointerField set in $GLOBALS['TCA'].
577 *
578 * @param string $table The table to check
579 * @return bool Whether a table is localizable
580 */
581 public static function isTableLocalizable($table)
582 {
583 $isLocalizable = false;
584 if (isset($GLOBALS['TCA'][$table]['ctrl']) && is_array($GLOBALS['TCA'][$table]['ctrl'])) {
585 $tcaCtrl = $GLOBALS['TCA'][$table]['ctrl'];
586 $isLocalizable = isset($tcaCtrl['languageField']) && $tcaCtrl['languageField'] && isset($tcaCtrl['transOrigPointerField']) && $tcaCtrl['transOrigPointerField'];
587 }
588 return $isLocalizable;
589 }
590
591 /**
592 * 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.
593 * If $id is zero a pseudo root-page with "_thePath" set is returned IF the current BE_USER is admin.
594 * In any case ->isInWebMount must return TRUE for the user (regardless of $perms_clause)
595 *
596 * @param int $id Page uid for which to check read-access
597 * @param string $perms_clause This is typically a value generated with static::getBackendUserAuthentication()->getPagePermsClause(1);
598 * @return array|bool Returns page record if OK, otherwise FALSE.
599 */
600 public static function readPageAccess($id, $perms_clause)
601 {
602 if ((string)$id !== '') {
603 $id = (int)$id;
604 if (!$id) {
605 if (static::getBackendUserAuthentication()->isAdmin()) {
606 return ['_thePath' => '/'];
607 }
608 } else {
609 $pageinfo = self::getRecord('pages', $id, '*', $perms_clause);
610 if ($pageinfo['uid'] && static::getBackendUserAuthentication()->isInWebMount($id, $perms_clause)) {
611 self::workspaceOL('pages', $pageinfo);
612 if (is_array($pageinfo)) {
613 self::fixVersioningPid('pages', $pageinfo);
614 list($pageinfo['_thePath'], $pageinfo['_thePathFull']) = self::getRecordPath((int)$pageinfo['uid'], $perms_clause, 15, 1000);
615 return $pageinfo;
616 }
617 }
618 }
619 }
620 return false;
621 }
622
623 /**
624 * Returns the "types" configuration parsed into an array for the record, $rec, from table, $table
625 *
626 * @param string $table Table name (present in TCA)
627 * @param array $rec Record from $table
628 * @param bool $useFieldNameAsKey If $useFieldNameAsKey is set, then the fieldname is associative keys in the return array, otherwise just numeric keys.
629 * @return array|null
630 */
631 public static function getTCAtypes($table, $rec, $useFieldNameAsKey = false)
632 {
633 if ($GLOBALS['TCA'][$table]) {
634 // Get type value:
635 $fieldValue = self::getTCAtypeValue($table, $rec);
636 $cacheIdentifier = $table . '-type-' . $fieldValue . '-fnk-' . $useFieldNameAsKey;
637
638 // Fetch from first-level-cache if available
639 if (isset(self::$tcaTableTypeConfigurationCache[$cacheIdentifier])) {
640 return self::$tcaTableTypeConfigurationCache[$cacheIdentifier];
641 }
642
643 // Get typesConf
644 $typesConf = $GLOBALS['TCA'][$table]['types'][$fieldValue];
645 // Get fields list and traverse it
646 $fieldList = explode(',', $typesConf['showitem']);
647
648 // Add subtype fields e.g. for a valid RTE transformation
649 // The RTE runs the DB -> RTE transformation only, if the RTE field is part of the getTCAtypes array
650 if (isset($typesConf['subtype_value_field'])) {
651 $subType = $rec[$typesConf['subtype_value_field']];
652 if (isset($typesConf['subtypes_addlist'][$subType])) {
653 $subFields = GeneralUtility::trimExplode(',', $typesConf['subtypes_addlist'][$subType], true);
654 $fieldList = array_merge($fieldList, $subFields);
655 }
656 }
657
658 // Add palette fields e.g. for a valid RTE transformation
659 $paletteFieldList = [];
660 foreach ($fieldList as $fieldData) {
661 list($pFieldName, $pAltTitle, $pPalette) = GeneralUtility::trimExplode(';', $fieldData);
662 if ($pPalette
663 && isset($GLOBALS['TCA'][$table]['palettes'][$pPalette])
664 && is_array($GLOBALS['TCA'][$table]['palettes'][$pPalette])
665 && isset($GLOBALS['TCA'][$table]['palettes'][$pPalette]['showitem'])
666 ) {
667 $paletteFields = GeneralUtility::trimExplode(',', $GLOBALS['TCA'][$table]['palettes'][$pPalette]['showitem'], true);
668 foreach ($paletteFields as $paletteField) {
669 if ($paletteField !== '--linebreak--') {
670 $paletteFieldList[] = $paletteField;
671 }
672 }
673 }
674 }
675 $fieldList = array_merge($fieldList, $paletteFieldList);
676
677 $altFieldList = [];
678 // Traverse fields in types config and parse the configuration into a nice array:
679 foreach ($fieldList as $k => $v) {
680 list($pFieldName, $pAltTitle, $pPalette) = GeneralUtility::trimExplode(';', $v);
681 $fieldList[$k] = [
682 'field' => $pFieldName,
683 'title' => $pAltTitle,
684 'palette' => $pPalette,
685 'spec' => [],
686 'origString' => $v
687 ];
688 if ($useFieldNameAsKey) {
689 $altFieldList[$fieldList[$k]['field']] = $fieldList[$k];
690 }
691 }
692 if ($useFieldNameAsKey) {
693 $fieldList = $altFieldList;
694 }
695
696 // Add to first-level-cache
697 self::$tcaTableTypeConfigurationCache[$cacheIdentifier] = $fieldList;
698
699 // Return array:
700 return $fieldList;
701 }
702 return null;
703 }
704
705 /**
706 * Returns the "type" value of $rec from $table which can be used to look up the correct "types" rendering section in $GLOBALS['TCA']
707 * If no "type" field is configured in the "ctrl"-section of the $GLOBALS['TCA'] for the table, zero is used.
708 * 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)
709 *
710 * Note: This method is very similar to the type determination of FormDataProvider/DatabaseRecordTypeValue,
711 * however, it has two differences:
712 * 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).
713 * 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"
714 * and "group" field values are stored, which makes different processing of the "foreign pointer field" type field variant necessary.
715 *
716 * @param string $table Table name present in TCA
717 * @param array $row Record from $table
718 * @throws \RuntimeException
719 * @return string Field value
720 * @see getTCAtypes()
721 */
722 public static function getTCAtypeValue($table, $row)
723 {
724 $typeNum = 0;
725 if ($GLOBALS['TCA'][$table]) {
726 $field = $GLOBALS['TCA'][$table]['ctrl']['type'];
727 if (strpos($field, ':') !== false) {
728 list($pointerField, $foreignTableTypeField) = explode(':', $field);
729 // Get field value from database if field is not in the $row array
730 if (!isset($row[$pointerField])) {
731 $localRow = self::getRecord($table, $row['uid'], $pointerField);
732 $foreignUid = $localRow[$pointerField];
733 } else {
734 $foreignUid = $row[$pointerField];
735 }
736 if ($foreignUid) {
737 $fieldConfig = $GLOBALS['TCA'][$table]['columns'][$pointerField]['config'];
738 $relationType = $fieldConfig['type'];
739 if ($relationType === 'select') {
740 $foreignTable = $fieldConfig['foreign_table'];
741 } elseif ($relationType === 'group') {
742 $allowedTables = explode(',', $fieldConfig['allowed']);
743 $foreignTable = $allowedTables[0];
744 } else {
745 throw new \RuntimeException(
746 'TCA foreign field pointer fields are only allowed to be used with group or select field types.',
747 1325862240
748 );
749 }
750 $foreignRow = self::getRecord($foreignTable, $foreignUid, $foreignTableTypeField);
751 if ($foreignRow[$foreignTableTypeField]) {
752 $typeNum = $foreignRow[$foreignTableTypeField];
753 }
754 }
755 } else {
756 $typeNum = $row[$field];
757 }
758 // If that value is an empty string, set it to "0" (zero)
759 if (empty($typeNum)) {
760 $typeNum = 0;
761 }
762 }
763 // If current typeNum doesn't exist, set it to 0 (or to 1 for historical reasons, if 0 doesn't exist)
764 if (!$GLOBALS['TCA'][$table]['types'][$typeNum]) {
765 $typeNum = $GLOBALS['TCA'][$table]['types']['0'] ? 0 : 1;
766 }
767 // Force to string. Necessary for eg '-1' to be recognized as a type value.
768 $typeNum = (string)$typeNum;
769 return $typeNum;
770 }
771
772 /*******************************************
773 *
774 * Caching related
775 *
776 *******************************************/
777 /**
778 * Stores $data in the 'cache_hash' cache with the hash key, $hash
779 * and visual/symbolic identification, $ident
780 *
781 * @param string $hash 32 bit hash string (eg. a md5 hash of a serialized array identifying the data being stored)
782 * @param mixed $data The data to store
783 * @param string $ident $ident is just a textual identification in order to inform about the content!
784 * @deprecated since TYPO3 v9, will be removed in TYPO3 v10, use the Caching Framework directly
785 */
786 public static function storeHash($hash, $data, $ident)
787 {
788 trigger_error('This method will be removed in TYPO3 v10.0, use the Caching Framework directly.', E_USER_DEPRECATED);
789 $cacheManager = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Cache\CacheManager::class);
790 $cacheManager->getCache('cache_hash')->set($hash, $data, ['ident_' . $ident], 0);
791 }
792
793 /**
794 * Returns data stored for the hash string in the cache "cache_hash"
795 * Can be used to retrieved a cached value, array or object
796 *
797 * @param string $hash The hash-string which was used to store the data value
798 * @return mixed The "data" from the cache
799 * @deprecated since TYPO3 v9, will be removed in TYPO3 v10, use the Caching Framework directly
800 */
801 public static function getHash($hash)
802 {
803 trigger_error('This method will be removed in TYPO3 v10.0, use the Caching Framework directly.', E_USER_DEPRECATED);
804 $cacheManager = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Cache\CacheManager::class);
805 $cacheEntry = $cacheManager->getCache('cache_hash')->get($hash);
806 $hashContent = null;
807 if ($cacheEntry) {
808 $hashContent = $cacheEntry;
809 }
810 return $hashContent;
811 }
812
813 /*******************************************
814 *
815 * TypoScript related
816 *
817 *******************************************/
818 /**
819 * Returns the Page TSconfig for page with id, $id
820 *
821 * @param int $id Page uid for which to create Page TSconfig
822 * @param array $rootLine If $rootLine is an array, that is used as rootline, otherwise rootline is just calculated
823 * @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.
824 * @return array Page TSconfig
825 * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser
826 */
827 public static function getPagesTSconfig($id, $rootLine = null, $returnPartArray = false)
828 {
829 $id = (int)$id;
830
831 $cache = self::getRuntimeCache();
832 if ($returnPartArray === false
833 && $rootLine === null
834 && $cache->has('pagesTsConfigIdToHash' . $id)
835 ) {
836 return $cache->get('pagesTsConfigHashToContent' . $cache->get('pagesTsConfigIdToHash' . $id));
837 }
838 $tsConfig = [];
839 // No custom rootline, so the results can be cached
840 if (!is_array($rootLine)) {
841 $rootLine = self::BEgetRootLine($id, '', true);
842 $useCacheForCurrentPageId = true;
843 } else {
844 trigger_error('Calling TYPO3\CMS\Backend\Utility\BackendUtility::getPagesTSconfig() with a custom rootline handed over as second argument will be removed in TYPO3 v10. Use TYPO3\CMS\Backend\Utility\BackendUtility::getRawPagesTSconfig() instead and parse PageTS yourself.', E_USER_DEPRECATED);
845 $useCacheForCurrentPageId = false;
846 }
847
848 $TSdataArray = static::getRawPagesTSconfig($id, $rootLine);
849 if ($returnPartArray) {
850 trigger_error('Calling TYPO3\CMS\Backend\Utility\BackendUtility::getPagesTSconfig() with a third parameter to return the unparsed array directly will be removed in TYPO3 v10. Use TYPO3\CMS\Backend\Utility\BackendUtility::getRawPagesTSconfig() instead.', E_USER_DEPRECATED);
851 return $TSdataArray;
852 }
853 // Parsing the page TS-Config
854 $pageTs = implode(LF . '[GLOBAL]' . LF, $TSdataArray);
855 /* @var $parseObj \TYPO3\CMS\Backend\Configuration\TsConfigParser */
856 $parseObj = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Configuration\TsConfigParser::class);
857 $res = $parseObj->parseTSconfig($pageTs, 'PAGES', $id, $rootLine);
858 if ($res) {
859 $tsConfig = $res['TSconfig'];
860 }
861 $cacheHash = $res['hash'];
862 // Get User TSconfig overlay
863 $userTSconfig = static::getBackendUserAuthentication()->userTS['page.'] ?? null;
864 if (is_array($userTSconfig)) {
865 ArrayUtility::mergeRecursiveWithOverrule($tsConfig, $userTSconfig);
866 $cacheHash .= '_user' . static::getBackendUserAuthentication()->user['uid'];
867 }
868
869 if ($useCacheForCurrentPageId) {
870 // Many pages end up with the same ts config. To reduce memory usage, the cache
871 // entries are a linked list: One or more pids point to content hashes which then
872 // contain the cached content.
873 $cache->set('pagesTsConfigHashToContent' . $cacheHash, $tsConfig, ['pagesTsConfig']);
874 $cache->set('pagesTsConfigIdToHash' . $id, $cacheHash, ['pagesTsConfig']);
875 }
876
877 return $tsConfig;
878 }
879
880 /**
881 * Returns the non-parsed Page TSconfig for page with id, $id
882 *
883 * @param int $id Page uid for which to create Page TSconfig
884 * @param array $rootLine If $rootLine is an array, that is used as rootline, otherwise rootline is just calculated
885 * @return array Non-parsed Page TSconfig
886 */
887 public static function getRawPagesTSconfig($id, array $rootLine = null)
888 {
889 if (!is_array($rootLine)) {
890 $rootLine = self::BEgetRootLine($id, '', true);
891 }
892
893 // Order correctly
894 ksort($rootLine);
895 $tsDataArray = [];
896 // Setting default configuration
897 $tsDataArray['defaultPageTSconfig'] = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPageTSconfig'];
898 foreach ($rootLine as $k => $v) {
899 if (trim($v['tsconfig_includes'])) {
900 $includeTsConfigFileList = GeneralUtility::trimExplode(',', $v['tsconfig_includes'], true);
901 // Traversing list
902 foreach ($includeTsConfigFileList as $key => $includeTsConfigFile) {
903 if (strpos($includeTsConfigFile, 'EXT:') === 0) {
904 list($includeTsConfigFileExtensionKey, $includeTsConfigFilename) = explode(
905 '/',
906 substr($includeTsConfigFile, 4),
907 2
908 );
909 if ((string)$includeTsConfigFileExtensionKey !== ''
910 && ExtensionManagementUtility::isLoaded($includeTsConfigFileExtensionKey)
911 && (string)$includeTsConfigFilename !== ''
912 ) {
913 $includeTsConfigFileAndPath = ExtensionManagementUtility::extPath($includeTsConfigFileExtensionKey) .
914 $includeTsConfigFilename;
915 if (file_exists($includeTsConfigFileAndPath)) {
916 $tsDataArray['uid_' . $v['uid'] . '_static_' . $key] = file_get_contents($includeTsConfigFileAndPath);
917 }
918 }
919 }
920 }
921 }
922 $tsDataArray['uid_' . $v['uid']] = $v['TSconfig'];
923 }
924
925 $tsDataArray = static::emitGetPagesTSconfigPreIncludeSignal($tsDataArray, $id, $rootLine);
926 $tsDataArray = TypoScriptParser::checkIncludeLines_array($tsDataArray);
927
928 return $tsDataArray;
929 }
930
931 /*******************************************
932 *
933 * Users / Groups related
934 *
935 *******************************************/
936 /**
937 * Returns an array with be_users records of all user NOT DELETED sorted by their username
938 * Keys in the array is the be_users uid
939 *
940 * @param string $fields Optional $fields list (default: username,usergroup,usergroup_cached_list,uid) can be used to set the selected fields
941 * @param string $where Optional $where clause (fx. "AND username='pete'") can be used to limit query
942 * @return array
943 */
944 public static function getUserNames($fields = 'username,usergroup,usergroup_cached_list,uid', $where = '')
945 {
946 return self::getRecordsSortedByTitle(
947 GeneralUtility::trimExplode(',', $fields, true),
948 'be_users',
949 'username',
950 'AND pid=0 ' . $where
951 );
952 }
953
954 /**
955 * Returns an array with be_groups records (title, uid) of all groups NOT DELETED sorted by their title
956 *
957 * @param string $fields Field list
958 * @param string $where WHERE clause
959 * @return array
960 */
961 public static function getGroupNames($fields = 'title,uid', $where = '')
962 {
963 return self::getRecordsSortedByTitle(
964 GeneralUtility::trimExplode(',', $fields, true),
965 'be_groups',
966 'title',
967 'AND pid=0 ' . $where
968 );
969 }
970
971 /**
972 * Returns an array of all non-deleted records of a table sorted by a given title field.
973 * The value of the title field will be replaced by the return value
974 * of self::getRecordTitle() before the sorting is performed.
975 *
976 * @param array $fields Fields to select
977 * @param string $table Table name
978 * @param string $titleField Field that will contain the record title
979 * @param string $where Additional where clause
980 * @return array Array of sorted records
981 */
982 protected static function getRecordsSortedByTitle(array $fields, $table, $titleField, $where = '')
983 {
984 $fieldsIndex = array_flip($fields);
985 // Make sure the titleField is amongst the fields when getting sorted
986 $fieldsIndex[$titleField] = 1;
987
988 $result = [];
989
990 $queryBuilder = static::getQueryBuilderForTable($table);
991 $queryBuilder->getRestrictions()
992 ->removeAll()
993 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
994
995 $res = $queryBuilder
996 ->select('*')
997 ->from($table)
998 ->where(QueryHelper::stripLogicalOperatorPrefix($where))
999 ->execute();
1000
1001 while ($record = $res->fetch()) {
1002 // store the uid, because it might be unset if it's not among the requested $fields
1003 $recordId = $record['uid'];
1004 $record[$titleField] = self::getRecordTitle($table, $record);
1005
1006 // include only the requested fields in the result
1007 $result[$recordId] = array_intersect_key($record, $fieldsIndex);
1008 }
1009
1010 // sort records by $sortField. This is not done in the query because the title might have been overwritten by
1011 // self::getRecordTitle();
1012 return ArrayUtility::sortArraysByKey($result, $titleField);
1013 }
1014
1015 /**
1016 * Returns an array with be_groups records (like ->getGroupNames) but:
1017 * - 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.
1018 *
1019 * @param string $fields Field list; $fields specify the fields selected (default: title,uid)
1020 * @return array
1021 * @deprecated
1022 */
1023 public static function getListGroupNames($fields = 'title, uid')
1024 {
1025 trigger_error('This method will be removed in TYPO3 v10.0, you should generate the list of backend user groups by yourself.', E_USER_DEPRECATED);
1026 $beUser = static::getBackendUserAuthentication();
1027 $exQ = '';
1028 if (!$beUser->isAdmin()) {
1029 $exQ = ' AND uid IN (' . ($beUser->user['usergroup_cached_list'] ?: 0) . ')';
1030 }
1031 return self::getGroupNames($fields, $exQ);
1032 }
1033
1034 /**
1035 * Returns the array $usernames with the names of all users NOT IN $groupArray changed to the uid (hides the usernames!).
1036 * If $excludeBlindedFlag is set, then these records are unset from the array $usernames
1037 * 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
1038 *
1039 * @param array $usernames User names
1040 * @param array $groupArray Group names
1041 * @param bool $excludeBlindedFlag If $excludeBlindedFlag is set, then these records are unset from the array $usernames
1042 * @return array User names, blinded
1043 */
1044 public static function blindUserNames($usernames, $groupArray, $excludeBlindedFlag = false)
1045 {
1046 if (is_array($usernames) && is_array($groupArray)) {
1047 foreach ($usernames as $uid => $row) {
1048 $userN = $uid;
1049 $set = 0;
1050 if ($row['uid'] != static::getBackendUserAuthentication()->user['uid']) {
1051 foreach ($groupArray as $v) {
1052 if ($v && GeneralUtility::inList($row['usergroup_cached_list'], $v)) {
1053 $userN = $row['username'];
1054 $set = 1;
1055 }
1056 }
1057 } else {
1058 $userN = $row['username'];
1059 $set = 1;
1060 }
1061 $usernames[$uid]['username'] = $userN;
1062 if ($excludeBlindedFlag && !$set) {
1063 unset($usernames[$uid]);
1064 }
1065 }
1066 }
1067 return $usernames;
1068 }
1069
1070 /**
1071 * Corresponds to blindUserNames but works for groups instead
1072 *
1073 * @param array $groups Group names
1074 * @param array $groupArray Group names (reference)
1075 * @param bool $excludeBlindedFlag If $excludeBlindedFlag is set, then these records are unset from the array $usernames
1076 * @return array
1077 */
1078 public static function blindGroupNames($groups, $groupArray, $excludeBlindedFlag = false)
1079 {
1080 if (is_array($groups) && is_array($groupArray)) {
1081 foreach ($groups as $uid => $row) {
1082 $groupN = $uid;
1083 $set = 0;
1084 if (in_array($uid, $groupArray, false)) {
1085 $groupN = $row['title'];
1086 $set = 1;
1087 }
1088 $groups[$uid]['title'] = $groupN;
1089 if ($excludeBlindedFlag && !$set) {
1090 unset($groups[$uid]);
1091 }
1092 }
1093 }
1094 return $groups;
1095 }
1096
1097 /*******************************************
1098 *
1099 * Output related
1100 *
1101 *******************************************/
1102 /**
1103 * Returns the difference in days between input $tstamp and $EXEC_TIME
1104 *
1105 * @param int $tstamp Time stamp, seconds
1106 * @return int
1107 */
1108 public static function daysUntil($tstamp)
1109 {
1110 $delta_t = $tstamp - $GLOBALS['EXEC_TIME'];
1111 return ceil($delta_t / (3600 * 24));
1112 }
1113
1114 /**
1115 * Returns $tstamp formatted as "ddmmyy" (According to $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'])
1116 *
1117 * @param int $tstamp Time stamp, seconds
1118 * @return string Formatted time
1119 */
1120 public static function date($tstamp)
1121 {
1122 return date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'], (int)$tstamp);
1123 }
1124
1125 /**
1126 * Returns $tstamp formatted as "ddmmyy hhmm" (According to $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] AND $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'])
1127 *
1128 * @param int $value Time stamp, seconds
1129 * @return string Formatted time
1130 */
1131 public static function datetime($value)
1132 {
1133 return date(
1134 $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'],
1135 $value
1136 );
1137 }
1138
1139 /**
1140 * Returns $value (in seconds) formatted as hh:mm:ss
1141 * For instance $value = 3600 + 60*2 + 3 should return "01:02:03"
1142 *
1143 * @param int $value Time stamp, seconds
1144 * @param bool $withSeconds Output hh:mm:ss. If FALSE: hh:mm
1145 * @return string Formatted time
1146 */
1147 public static function time($value, $withSeconds = true)
1148 {
1149 return gmdate('H:i' . ($withSeconds ? ':s' : ''), (int)$value);
1150 }
1151
1152 /**
1153 * Returns the "age" in minutes / hours / days / years of the number of $seconds inputted.
1154 *
1155 * @param int $seconds Seconds could be the difference of a certain timestamp and time()
1156 * @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/Resources/Private/Language/locallang_core.xlf:labels.minutesHoursDaysYears")
1157 * @return string Formatted time
1158 */
1159 public static function calcAge($seconds, $labels = 'min|hrs|days|yrs|min|hour|day|year')
1160 {
1161 $labelArr = GeneralUtility::trimExplode('|', $labels, true);
1162 $absSeconds = abs($seconds);
1163 $sign = $seconds < 0 ? -1 : 1;
1164 if ($absSeconds < 3600) {
1165 $val = round($absSeconds / 60);
1166 $seconds = $sign * $val . ' ' . ($val == 1 ? $labelArr[4] : $labelArr[0]);
1167 } elseif ($absSeconds < 24 * 3600) {
1168 $val = round($absSeconds / 3600);
1169 $seconds = $sign * $val . ' ' . ($val == 1 ? $labelArr[5] : $labelArr[1]);
1170 } elseif ($absSeconds < 365 * 24 * 3600) {
1171 $val = round($absSeconds / (24 * 3600));
1172 $seconds = $sign * $val . ' ' . ($val == 1 ? $labelArr[6] : $labelArr[2]);
1173 } else {
1174 $val = round($absSeconds / (365 * 24 * 3600));
1175 $seconds = $sign * $val . ' ' . ($val == 1 ? $labelArr[7] : $labelArr[3]);
1176 }
1177 return $seconds;
1178 }
1179
1180 /**
1181 * Returns a formatted timestamp if $tstamp is set.
1182 * The date/datetime will be followed by the age in parenthesis.
1183 *
1184 * @param int $tstamp Time stamp, seconds
1185 * @param int $prefix 1/-1 depending on polarity of age.
1186 * @param string $date $date=="date" will yield "dd:mm:yy" formatting, otherwise "dd:mm:yy hh:mm
1187 * @return string
1188 */
1189 public static function dateTimeAge($tstamp, $prefix = 1, $date = '')
1190 {
1191 if (!$tstamp) {
1192 return '';
1193 }
1194 $label = static::getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.minutesHoursDaysYears');
1195 $age = ' (' . self::calcAge($prefix * ($GLOBALS['EXEC_TIME'] - $tstamp), $label) . ')';
1196 return ($date === 'date' ? self::date($tstamp) : self::datetime($tstamp)) . $age;
1197 }
1198
1199 /**
1200 * Resolves file references for a given record.
1201 *
1202 * @param string $tableName Name of the table of the record
1203 * @param string $fieldName Name of the field of the record
1204 * @param array $element Record data
1205 * @param int|null $workspaceId Workspace to fetch data for
1206 * @return \TYPO3\CMS\Core\Resource\FileReference[]|null
1207 */
1208 public static function resolveFileReferences($tableName, $fieldName, $element, $workspaceId = null)
1209 {
1210 if (empty($GLOBALS['TCA'][$tableName]['columns'][$fieldName]['config'])) {
1211 return null;
1212 }
1213 $configuration = $GLOBALS['TCA'][$tableName]['columns'][$fieldName]['config'];
1214 if (empty($configuration['type']) || $configuration['type'] !== 'inline'
1215 || empty($configuration['foreign_table']) || $configuration['foreign_table'] !== 'sys_file_reference'
1216 ) {
1217 return null;
1218 }
1219
1220 $fileReferences = [];
1221 /** @var $relationHandler RelationHandler */
1222 $relationHandler = GeneralUtility::makeInstance(RelationHandler::class);
1223 if ($workspaceId !== null) {
1224 $relationHandler->setWorkspaceId($workspaceId);
1225 }
1226 $relationHandler->start(
1227 $element[$fieldName],
1228 $configuration['foreign_table'],
1229 $configuration['MM'],
1230 $element['uid'],
1231 $tableName,
1232 $configuration
1233 );
1234 $relationHandler->processDeletePlaceholder();
1235 $referenceUids = $relationHandler->tableArray[$configuration['foreign_table']];
1236
1237 foreach ($referenceUids as $referenceUid) {
1238 try {
1239 $fileReference = ResourceFactory::getInstance()->getFileReferenceObject(
1240 $referenceUid,
1241 [],
1242 $workspaceId === 0
1243 );
1244 $fileReferences[$fileReference->getUid()] = $fileReference;
1245 } catch (\TYPO3\CMS\Core\Resource\Exception\FileDoesNotExistException $e) {
1246 /**
1247 * We just catch the exception here
1248 * Reasoning: There is nothing an editor or even admin could do
1249 */
1250 } catch (\InvalidArgumentException $e) {
1251 /**
1252 * The storage does not exist anymore
1253 * Log the exception message for admins as they maybe can restore the storage
1254 */
1255 self::getLogger()->error($e->getMessage(), ['table' => $tableName, 'fieldName' => $fieldName, 'referenceUid' => $referenceUid, 'exception' => $e]);
1256 }
1257 }
1258
1259 return $fileReferences;
1260 }
1261
1262 /**
1263 * 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
1264 * All $GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'] extension are made to thumbnails + ttf file (renders font-example)
1265 * Thumbsnails are linked to the show_item.php script which will display further details.
1266 *
1267 * @param array $row Row is the database row from the table, $table.
1268 * @param string $table Table name for $row (present in TCA)
1269 * @param string $field Field is pointing to the list of image files
1270 * @param string $backPath Back path prefix for image tag src="" field
1271 * @param string $thumbScript UNUSED since FAL
1272 * @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!)
1273 * @param int $abs UNUSED
1274 * @param string $tparams Optional: $tparams is additional attributes for the image tags
1275 * @param int|string $size Optional: $size is [w]x[h] of the thumbnail. 64 is default.
1276 * @param bool $linkInfoPopup Whether to wrap with a link opening the info popup
1277 * @return string Thumbnail image tag.
1278 */
1279 public static function thumbCode(
1280 $row,
1281 $table,
1282 $field,
1283 $backPath = '',
1284 $thumbScript = '',
1285 $uploaddir = null,
1286 $abs = 0,
1287 $tparams = '',
1288 $size = '',
1289 $linkInfoPopup = true
1290 ) {
1291 // Check and parse the size parameter
1292 $size = trim($size);
1293 $sizeParts = [64, 64];
1294 if ($size) {
1295 $sizeParts = explode('x', $size . 'x' . $size);
1296 }
1297 $thumbData = '';
1298 $fileReferences = static::resolveFileReferences($table, $field, $row);
1299 // FAL references
1300 $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
1301 if ($fileReferences !== null) {
1302 foreach ($fileReferences as $fileReferenceObject) {
1303 // Do not show previews of hidden references
1304 if ($fileReferenceObject->getProperty('hidden')) {
1305 continue;
1306 }
1307 $fileObject = $fileReferenceObject->getOriginalFile();
1308
1309 if ($fileObject->isMissing()) {
1310 $thumbData .= '<span class="label label-danger">'
1311 . htmlspecialchars(
1312 static::getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:warning.file_missing')
1313 )
1314 . '</span>&nbsp;' . htmlspecialchars($fileObject->getName()) . '<br />';
1315 continue;
1316 }
1317
1318 // Preview web image or media elements
1319 if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['thumbnails']
1320 && GeneralUtility::inList(
1321 $GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'],
1322 $fileReferenceObject->getExtension()
1323 )
1324 ) {
1325 $cropVariantCollection = CropVariantCollection::create((string)$fileReferenceObject->getProperty('crop'));
1326 $cropArea = $cropVariantCollection->getCropArea();
1327 $processedImage = $fileObject->process(
1328 ProcessedFile::CONTEXT_IMAGECROPSCALEMASK,
1329 [
1330 'width' => $sizeParts[0],
1331 'height' => $sizeParts[1] . 'c',
1332 'crop' => $cropArea->isEmpty() ? null : $cropArea->makeAbsoluteBasedOnFile($fileReferenceObject)
1333 ]
1334 );
1335 $imageUrl = $processedImage->getPublicUrl(true);
1336 $imgTag = '<img src="' . $imageUrl . '" '
1337 . 'width="' . $processedImage->getProperty('width') . '" '
1338 . 'height="' . $processedImage->getProperty('height') . '" '
1339 . 'alt="' . htmlspecialchars($fileReferenceObject->getName()) . '" />';
1340 } else {
1341 // Icon
1342 $imgTag = '<span title="' . htmlspecialchars($fileObject->getName()) . '">'
1343 . $iconFactory->getIconForResource($fileObject, Icon::SIZE_SMALL)->render()
1344 . '</span>';
1345 }
1346 if ($linkInfoPopup) {
1347 $onClick = 'top.TYPO3.InfoWindow.showItem(\'_FILE\',\'' . (int)$fileObject->getUid() . '\'); return false;';
1348 $thumbData .= '<a href="#" onclick="' . htmlspecialchars($onClick) . '">' . $imgTag . '</a> ';
1349 } else {
1350 $thumbData .= $imgTag;
1351 }
1352 }
1353 } else {
1354 // Find uploaddir automatically
1355 if ($uploaddir === null) {
1356 $uploaddir = $GLOBALS['TCA'][$table]['columns'][$field]['config']['uploadfolder'];
1357 }
1358 $uploaddir = rtrim($uploaddir, '/');
1359 // Traverse files:
1360 $thumbs = GeneralUtility::trimExplode(',', $row[$field], true);
1361 $thumbData = '';
1362 foreach ($thumbs as $theFile) {
1363 if ($theFile) {
1364 $fileName = trim($uploaddir . '/' . $theFile, '/');
1365 try {
1366 /** @var File $fileObject */
1367 $fileObject = ResourceFactory::getInstance()->retrieveFileOrFolderObject($fileName);
1368 // Skip the resource if it's not of type AbstractFile. One case where this can happen if the
1369 // storage has been externally modified and the field value now points to a folder
1370 // instead of a file.
1371 if (!$fileObject instanceof AbstractFile) {
1372 continue;
1373 }
1374 if ($fileObject->isMissing()) {
1375 $thumbData .= '<span class="label label-danger">'
1376 . htmlspecialchars(static::getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:warning.file_missing'))
1377 . '</span>&nbsp;' . htmlspecialchars($fileObject->getName()) . '<br />';
1378 continue;
1379 }
1380 } catch (ResourceDoesNotExistException $exception) {
1381 $thumbData .= '<span class="label label-danger">'
1382 . htmlspecialchars(static::getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:warning.file_missing'))
1383 . '</span>&nbsp;' . htmlspecialchars($fileName) . '<br />';
1384 continue;
1385 }
1386
1387 $fileExtension = $fileObject->getExtension();
1388 if ($fileExtension === 'ttf'
1389 || GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'], $fileExtension)
1390 ) {
1391 $imageUrl = $fileObject->process(
1392 ProcessedFile::CONTEXT_IMAGEPREVIEW,
1393 [
1394 'width' => $sizeParts[0],
1395 'height' => $sizeParts[1]
1396 ]
1397 )->getPublicUrl(true);
1398
1399 $image = '<img src="' . htmlspecialchars($imageUrl) . '" hspace="2" border="0" title="' . htmlspecialchars($fileObject->getName()) . '"' . $tparams . ' alt="" />';
1400 if ($linkInfoPopup) {
1401 $onClick = 'top.TYPO3.InfoWindow.showItem(\'_FILE\', ' . GeneralUtility::quoteJSvalue($fileName) . ',\'\');return false;';
1402 $thumbData .= '<a href="#" onclick="' . htmlspecialchars($onClick) . '">' . $image . '</a> ';
1403 } else {
1404 $thumbData .= $image;
1405 }
1406 } else {
1407 // Gets the icon
1408 $fileIcon = '<span title="' . htmlspecialchars($fileObject->getName()) . '">'
1409 . $iconFactory->getIconForResource($fileObject, Icon::SIZE_SMALL)->render()
1410 . '</span>';
1411 if ($linkInfoPopup) {
1412 $onClick = 'top.TYPO3.InfoWindow.showItem(\'_FILE\', ' . GeneralUtility::quoteJSvalue($fileName) . ',\'\'); return false;';
1413 $thumbData .= '<a href="#" onclick="' . htmlspecialchars($onClick) . '">' . $fileIcon . '</a> ';
1414 } else {
1415 $thumbData .= $fileIcon;
1416 }
1417 }
1418 }
1419 }
1420 }
1421 return $thumbData;
1422 }
1423
1424 /**
1425 * Returns title-attribute information for a page-record informing about id, alias, doktype, hidden, starttime, endtime, fe_group etc.
1426 *
1427 * @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)
1428 * @param string $perms_clause This is used to get the record path of the shortcut page, if any (and doktype==4)
1429 * @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
1430 * @return string
1431 */
1432 public static function titleAttribForPages($row, $perms_clause = '', $includeAttrib = true)
1433 {
1434 $lang = static::getLanguageService();
1435 $parts = [];
1436 $parts[] = 'id=' . $row['uid'];
1437 if ($row['alias']) {
1438 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['alias']['label']) . ' ' . $row['alias'];
1439 }
1440 if ($row['pid'] < 0) {
1441 $parts[] = 'v#1.' . $row['t3ver_id'];
1442 }
1443 switch (VersionState::cast($row['t3ver_state'])) {
1444 case new VersionState(VersionState::NEW_PLACEHOLDER):
1445 $parts[] = 'PLH WSID#' . $row['t3ver_wsid'];
1446 break;
1447 case new VersionState(VersionState::DELETE_PLACEHOLDER):
1448 $parts[] = 'Deleted element!';
1449 break;
1450 case new VersionState(VersionState::MOVE_PLACEHOLDER):
1451 $parts[] = 'NEW LOCATION (PLH) WSID#' . $row['t3ver_wsid'];
1452 break;
1453 case new VersionState(VersionState::MOVE_POINTER):
1454 $parts[] = 'OLD LOCATION (PNT) WSID#' . $row['t3ver_wsid'];
1455 break;
1456 case new VersionState(VersionState::NEW_PLACEHOLDER_VERSION):
1457 $parts[] = 'New element!';
1458 break;
1459 }
1460 if ($row['doktype'] == PageRepository::DOKTYPE_LINK) {
1461 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['url']['label']) . ' ' . $row['url'];
1462 } elseif ($row['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
1463 if ($perms_clause) {
1464 $label = self::getRecordPath((int)$row['shortcut'], $perms_clause, 20);
1465 } else {
1466 $row['shortcut'] = (int)$row['shortcut'];
1467 $lRec = self::getRecordWSOL('pages', $row['shortcut'], 'title');
1468 $label = $lRec['title'] . ' (id=' . $row['shortcut'] . ')';
1469 }
1470 if ($row['shortcut_mode'] != PageRepository::SHORTCUT_MODE_NONE) {
1471 $label .= ', ' . $lang->sL($GLOBALS['TCA']['pages']['columns']['shortcut_mode']['label']) . ' '
1472 . $lang->sL(self::getLabelFromItemlist('pages', 'shortcut_mode', $row['shortcut_mode']));
1473 }
1474 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['shortcut']['label']) . ' ' . $label;
1475 } elseif ($row['doktype'] == PageRepository::DOKTYPE_MOUNTPOINT) {
1476 if ($perms_clause) {
1477 $label = self::getRecordPath((int)$row['mount_pid'], $perms_clause, 20);
1478 } else {
1479 $lRec = self::getRecordWSOL('pages', (int)$row['mount_pid'], 'title');
1480 $label = $lRec['title'] . ' (id=' . $row['mount_pid'] . ')';
1481 }
1482 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['mount_pid']['label']) . ' ' . $label;
1483 if ($row['mount_pid_ol']) {
1484 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['mount_pid_ol']['label']);
1485 }
1486 }
1487 if ($row['nav_hide']) {
1488 $parts[] = rtrim($lang->sL($GLOBALS['TCA']['pages']['columns']['nav_hide']['label']), ':');
1489 }
1490 if ($row['hidden']) {
1491 $parts[] = $lang->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.hidden');
1492 }
1493 if ($row['starttime']) {
1494 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['starttime']['label'])
1495 . ' ' . self::dateTimeAge($row['starttime'], -1, 'date');
1496 }
1497 if ($row['endtime']) {
1498 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['endtime']['label']) . ' '
1499 . self::dateTimeAge($row['endtime'], -1, 'date');
1500 }
1501 if ($row['fe_group']) {
1502 $fe_groups = [];
1503 foreach (GeneralUtility::intExplode(',', $row['fe_group']) as $fe_group) {
1504 if ($fe_group < 0) {
1505 $fe_groups[] = $lang->sL(self::getLabelFromItemlist('pages', 'fe_group', $fe_group));
1506 } else {
1507 $lRec = self::getRecordWSOL('fe_groups', $fe_group, 'title');
1508 $fe_groups[] = $lRec['title'];
1509 }
1510 }
1511 $label = implode(', ', $fe_groups);
1512 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['fe_group']['label']) . ' ' . $label;
1513 }
1514 $out = htmlspecialchars(implode(' - ', $parts));
1515 return $includeAttrib ? 'title="' . $out . '"' : $out;
1516 }
1517
1518 /**
1519 * Returns the combined markup for Bootstraps tooltips
1520 *
1521 * @param array $row
1522 * @param string $table
1523 * @return string
1524 */
1525 public static function getRecordToolTip(array $row, $table = 'pages')
1526 {
1527 $toolTipText = self::getRecordIconAltText($row, $table);
1528 $toolTipCode = 'data-toggle="tooltip" data-title=" '
1529 . str_replace(' - ', '<br>', $toolTipText)
1530 . '" data-html="true" data-placement="right"';
1531 return $toolTipCode;
1532 }
1533
1534 /**
1535 * Returns title-attribute information for ANY record (from a table defined in TCA of course)
1536 * 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.
1537 * "pages" table can be used as well and will return the result of ->titleAttribForPages() for that page.
1538 *
1539 * @param array $row Table row; $row is a row from the table, $table
1540 * @param string $table Table name
1541 * @return string
1542 */
1543 public static function getRecordIconAltText($row, $table = 'pages')
1544 {
1545 if ($table === 'pages') {
1546 $out = self::titleAttribForPages($row, '', 0);
1547 } else {
1548 $out = !empty(trim($GLOBALS['TCA'][$table]['ctrl']['descriptionColumn'])) ? $row[$GLOBALS['TCA'][$table]['ctrl']['descriptionColumn']] . ' ' : '';
1549 $ctrl = $GLOBALS['TCA'][$table]['ctrl']['enablecolumns'];
1550 // Uid is added
1551 $out .= 'id=' . $row['uid'];
1552 if ($table === 'pages' && $row['alias']) {
1553 $out .= ' / ' . $row['alias'];
1554 }
1555 if (static::isTableWorkspaceEnabled($table) && $row['pid'] < 0) {
1556 $out .= ' - v#1.' . $row['t3ver_id'];
1557 }
1558 if (static::isTableWorkspaceEnabled($table)) {
1559 switch (VersionState::cast($row['t3ver_state'])) {
1560 case new VersionState(VersionState::NEW_PLACEHOLDER):
1561 $out .= ' - PLH WSID#' . $row['t3ver_wsid'];
1562 break;
1563 case new VersionState(VersionState::DELETE_PLACEHOLDER):
1564 $out .= ' - Deleted element!';
1565 break;
1566 case new VersionState(VersionState::MOVE_PLACEHOLDER):
1567 $out .= ' - NEW LOCATION (PLH) WSID#' . $row['t3ver_wsid'];
1568 break;
1569 case new VersionState(VersionState::MOVE_POINTER):
1570 $out .= ' - OLD LOCATION (PNT) WSID#' . $row['t3ver_wsid'];
1571 break;
1572 case new VersionState(VersionState::NEW_PLACEHOLDER_VERSION):
1573 $out .= ' - New element!';
1574 break;
1575 }
1576 }
1577 // Hidden
1578 $lang = static::getLanguageService();
1579 if ($ctrl['disabled']) {
1580 $out .= $row[$ctrl['disabled']] ? ' - ' . $lang->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.hidden') : '';
1581 }
1582 if ($ctrl['starttime']) {
1583 if ($row[$ctrl['starttime']] > $GLOBALS['EXEC_TIME']) {
1584 $out .= ' - ' . $lang->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.starttime') . ':' . self::date($row[$ctrl['starttime']]) . ' (' . self::daysUntil($row[$ctrl['starttime']]) . ' ' . $lang->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.days') . ')';
1585 }
1586 }
1587 if ($row[$ctrl['endtime']]) {
1588 $out .= ' - ' . $lang->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.endtime') . ': ' . self::date($row[$ctrl['endtime']]) . ' (' . self::daysUntil($row[$ctrl['endtime']]) . ' ' . $lang->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.days') . ')';
1589 }
1590 }
1591 return htmlspecialchars($out);
1592 }
1593
1594 /**
1595 * Returns the label of the first found entry in an "items" array from $GLOBALS['TCA'] (tablename = $table/fieldname = $col) where the value is $key
1596 *
1597 * @param string $table Table name, present in $GLOBALS['TCA']
1598 * @param string $col Field name, present in $GLOBALS['TCA']
1599 * @param string $key items-array value to match
1600 * @return string Label for item entry
1601 */
1602 public static function getLabelFromItemlist($table, $col, $key)
1603 {
1604 // Check, if there is an "items" array:
1605 if (is_array($GLOBALS['TCA'][$table]['columns'][$col]['config']['items'] ?? false)) {
1606 // Traverse the items-array...
1607 foreach ($GLOBALS['TCA'][$table]['columns'][$col]['config']['items'] as $v) {
1608 // ... and return the first found label where the value was equal to $key
1609 if ((string)$v[1] === (string)$key) {
1610 return $v[0];
1611 }
1612 }
1613 }
1614 return '';
1615 }
1616
1617 /**
1618 * Return the label of a field by additionally checking TsConfig values
1619 *
1620 * @param int $pageId Page id
1621 * @param string $table Table name
1622 * @param string $column Field Name
1623 * @param string $key item value
1624 * @return string Label for item entry
1625 */
1626 public static function getLabelFromItemListMerged($pageId, $table, $column, $key)
1627 {
1628 $pageTsConfig = static::getPagesTSconfig($pageId);
1629 $label = '';
1630 if (is_array($pageTsConfig['TCEFORM.'])
1631 && is_array($pageTsConfig['TCEFORM.'][$table . '.'])
1632 && is_array($pageTsConfig['TCEFORM.'][$table . '.'][$column . '.'])
1633 ) {
1634 if (is_array($pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['addItems.'])
1635 && isset($pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['addItems.'][$key])
1636 ) {
1637 $label = $pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['addItems.'][$key];
1638 } elseif (is_array($pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['altLabels.'])
1639 && isset($pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['altLabels.'][$key])
1640 ) {
1641 $label = $pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['altLabels.'][$key];
1642 }
1643 }
1644 if (empty($label)) {
1645 $tcaValue = self::getLabelFromItemlist($table, $column, $key);
1646 if (!empty($tcaValue)) {
1647 $label = $tcaValue;
1648 }
1649 }
1650 return $label;
1651 }
1652
1653 /**
1654 * Splits the given key with commas and returns the list of all the localized items labels, separated by a comma.
1655 * NOTE: this does not take itemsProcFunc into account
1656 *
1657 * @param string $table Table name, present in TCA
1658 * @param string $column Field name
1659 * @param string $keyList Key or comma-separated list of keys.
1660 * @param array $columnTsConfig page TSConfig for $column (TCEMAIN.<table>.<column>)
1661 * @return string Comma-separated list of localized labels
1662 */
1663 public static function getLabelsFromItemsList($table, $column, $keyList, array $columnTsConfig = [])
1664 {
1665 // Check if there is an "items" array
1666 if (
1667 !isset($GLOBALS['TCA'][$table]['columns'][$column]['config']['items'])
1668 || !is_array($GLOBALS['TCA'][$table]['columns'][$column]['config']['items'])
1669 || $keyList === ''
1670 ) {
1671 return '';
1672 }
1673
1674 $keys = GeneralUtility::trimExplode(',', $keyList, true);
1675 $labels = [];
1676 // Loop on all selected values
1677 foreach ($keys as $key) {
1678 $label = null;
1679 if ($columnTsConfig) {
1680 // Check if label has been defined or redefined via pageTsConfig
1681 if (isset($columnTsConfig['addItems.'][$key])) {
1682 $label = $columnTsConfig['addItems.'][$key];
1683 } elseif (isset($columnTsConfig['altLabels.'][$key])) {
1684 $label = $columnTsConfig['altLabels.'][$key];
1685 }
1686 }
1687 if ($label === null) {
1688 // Otherwise lookup the label in TCA items list
1689 foreach ($GLOBALS['TCA'][$table]['columns'][$column]['config']['items'] as $itemConfiguration) {
1690 list($currentLabel, $currentKey) = $itemConfiguration;
1691 if ((string)$key === (string)$currentKey) {
1692 $label = $currentLabel;
1693 break;
1694 }
1695 }
1696 }
1697 if ($label !== null) {
1698 $labels[] = static::getLanguageService()->sL($label);
1699 }
1700 }
1701 return implode(', ', $labels);
1702 }
1703
1704 /**
1705 * Returns the label-value for fieldname $col in table, $table
1706 * 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>'
1707 *
1708 * @param string $table Table name, present in $GLOBALS['TCA']
1709 * @param string $col Field name
1710 * @return string or NULL if $col is not found in the TCA table
1711 */
1712 public static function getItemLabel($table, $col)
1713 {
1714 // Check if column exists
1715 if (is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'][$col])) {
1716 return $GLOBALS['TCA'][$table]['columns'][$col]['label'];
1717 }
1718
1719 return null;
1720 }
1721
1722 /**
1723 * Returns the "title"-value in record, $row, from table, $table
1724 * The field(s) from which the value is taken is determined by the "ctrl"-entries 'label', 'label_alt' and 'label_alt_force'
1725 *
1726 * @param string $table Table name, present in TCA
1727 * @param array $row Row from table
1728 * @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
1729 * @param bool $forceResult If set, the function always returns an output. If no value is found for the title, '[No title]' is returned (localized).
1730 * @return string
1731 */
1732 public static function getRecordTitle($table, $row, $prep = false, $forceResult = true)
1733 {
1734 $recordTitle = '';
1735 if (isset($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table])) {
1736 // If configured, call userFunc
1737 if (!empty($GLOBALS['TCA'][$table]['ctrl']['label_userFunc'])) {
1738 $params['table'] = $table;
1739 $params['row'] = $row;
1740 $params['title'] = '';
1741 $params['options'] = $GLOBALS['TCA'][$table]['ctrl']['label_userFunc_options'] ?? [];
1742
1743 // Create NULL-reference
1744 $null = null;
1745 GeneralUtility::callUserFunction($GLOBALS['TCA'][$table]['ctrl']['label_userFunc'], $params, $null);
1746 $recordTitle = $params['title'];
1747 } else {
1748 // No userFunc: Build label
1749 $recordTitle = self::getProcessedValue(
1750 $table,
1751 $GLOBALS['TCA'][$table]['ctrl']['label'],
1752 $row[$GLOBALS['TCA'][$table]['ctrl']['label']],
1753 0,
1754 0,
1755 false,
1756 $row['uid'],
1757 $forceResult
1758 );
1759 if (!empty($GLOBALS['TCA'][$table]['ctrl']['label_alt'])
1760 && (!empty($GLOBALS['TCA'][$table]['ctrl']['label_alt_force']) || (string)$recordTitle === '')
1761 ) {
1762 $altFields = GeneralUtility::trimExplode(',', $GLOBALS['TCA'][$table]['ctrl']['label_alt'], true);
1763 $tA = [];
1764 if (!empty($recordTitle)) {
1765 $tA[] = $recordTitle;
1766 }
1767 foreach ($altFields as $fN) {
1768 $recordTitle = trim(strip_tags($row[$fN]));
1769 if ((string)$recordTitle !== '') {
1770 $recordTitle = self::getProcessedValue($table, $fN, $recordTitle, 0, 0, false, $row['uid']);
1771 if (!$GLOBALS['TCA'][$table]['ctrl']['label_alt_force']) {
1772 break;
1773 }
1774 $tA[] = $recordTitle;
1775 }
1776 }
1777 if ($GLOBALS['TCA'][$table]['ctrl']['label_alt_force']) {
1778 $recordTitle = implode(', ', $tA);
1779 }
1780 }
1781 }
1782 // If the current result is empty, set it to '[No title]' (localized) and prepare for output if requested
1783 if ($prep || $forceResult) {
1784 if ($prep) {
1785 $recordTitle = self::getRecordTitlePrep($recordTitle);
1786 }
1787 if (trim($recordTitle) === '') {
1788 $recordTitle = self::getNoRecordTitle($prep);
1789 }
1790 }
1791 }
1792
1793 return $recordTitle;
1794 }
1795
1796 /**
1797 * Crops a title string to a limited length and if it really was cropped, wrap it in a <span title="...">|</span>,
1798 * which offers a tooltip with the original title when moving mouse over it.
1799 *
1800 * @param string $title The title string to be cropped
1801 * @param int $titleLength Crop title after this length - if not set, BE_USER->uc['titleLen'] is used
1802 * @return string The processed title string, wrapped in <span title="...">|</span> if cropped
1803 */
1804 public static function getRecordTitlePrep($title, $titleLength = 0)
1805 {
1806 // If $titleLength is not a valid positive integer, use BE_USER->uc['titleLen']:
1807 if (!$titleLength || !MathUtility::canBeInterpretedAsInteger($titleLength) || $titleLength < 0) {
1808 $titleLength = static::getBackendUserAuthentication()->uc['titleLen'];
1809 }
1810 $titleOrig = htmlspecialchars($title);
1811 $title = htmlspecialchars(GeneralUtility::fixed_lgd_cs($title, $titleLength));
1812 // If title was cropped, offer a tooltip:
1813 if ($titleOrig != $title) {
1814 $title = '<span title="' . $titleOrig . '">' . $title . '</span>';
1815 }
1816 return $title;
1817 }
1818
1819 /**
1820 * Get a localized [No title] string, wrapped in <em>|</em> if $prep is TRUE.
1821 *
1822 * @param bool $prep Wrap result in <em>|</em>
1823 * @return string Localized [No title] string
1824 */
1825 public static function getNoRecordTitle($prep = false)
1826 {
1827 $noTitle = '[' .
1828 htmlspecialchars(static::getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.no_title'))
1829 . ']';
1830 if ($prep) {
1831 $noTitle = '<em>' . $noTitle . '</em>';
1832 }
1833 return $noTitle;
1834 }
1835
1836 /**
1837 * Returns a human readable output of a value from a record
1838 * 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.
1839 * $table/$col is tablename and fieldname
1840 * REMEMBER to pass the output through htmlspecialchars() if you output it to the browser! (To protect it from XSS attacks and be XHTML compliant)
1841 *
1842 * @param string $table Table name, present in TCA
1843 * @param string $col Field name, present in TCA
1844 * @param string $value The value of that field from a selected record
1845 * @param int $fixed_lgd_chars The max amount of characters the value may occupy
1846 * @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")
1847 * @param bool $noRecordLookup If set, no records will be looked up, UIDs are just shown.
1848 * @param int $uid Uid of the current record
1849 * @param bool $forceResult If BackendUtility::getRecordTitle is used to process the value, this parameter is forwarded.
1850 * @param int $pid Optional page uid is used to evaluate page TSConfig for the given field
1851 * @throws \InvalidArgumentException
1852 * @return string|null
1853 */
1854 public static function getProcessedValue(
1855 $table,
1856 $col,
1857 $value,
1858 $fixed_lgd_chars = 0,
1859 $defaultPassthrough = false,
1860 $noRecordLookup = false,
1861 $uid = 0,
1862 $forceResult = true,
1863 $pid = 0
1864 ) {
1865 if ($col === 'uid') {
1866 // uid is not in TCA-array
1867 return $value;
1868 }
1869 // Check if table and field is configured
1870 if (!isset($GLOBALS['TCA'][$table]['columns'][$col]) || !is_array($GLOBALS['TCA'][$table]['columns'][$col])) {
1871 return null;
1872 }
1873 // Depending on the fields configuration, make a meaningful output value.
1874 $theColConf = $GLOBALS['TCA'][$table]['columns'][$col]['config'] ?? [];
1875 /*****************
1876 *HOOK: pre-processing the human readable output from a record
1877 ****************/
1878 $null = null;
1879 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['preProcessValue'] ?? [] as $_funcRef) {
1880 GeneralUtility::callUserFunction($_funcRef, $theColConf, $null);
1881 }
1882
1883 $l = '';
1884 $lang = static::getLanguageService();
1885 switch ((string)($theColConf['type'] ?? '')) {
1886 case 'radio':
1887 $l = self::getLabelFromItemlist($table, $col, $value);
1888 $l = $lang->sL($l);
1889 break;
1890 case 'inline':
1891 case 'select':
1892 if (!empty($theColConf['MM'])) {
1893 if ($uid) {
1894 // Display the title of MM related records in lists
1895 if ($noRecordLookup) {
1896 $MMfields = [];
1897 $MMfields[] = $theColConf['foreign_table'] . '.uid';
1898 } else {
1899 $MMfields = [$theColConf['foreign_table'] . '.' . $GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label']];
1900 foreach (GeneralUtility::trimExplode(',', $GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label_alt'], true) as $f) {
1901 $MMfields[] = $theColConf['foreign_table'] . '.' . $f;
1902 }
1903 }
1904 /** @var $dbGroup RelationHandler */
1905 $dbGroup = GeneralUtility::makeInstance(RelationHandler::class);
1906 $dbGroup->start(
1907 $value,
1908 $theColConf['foreign_table'],
1909 $theColConf['MM'],
1910 $uid,
1911 $table,
1912 $theColConf
1913 );
1914 $selectUids = $dbGroup->tableArray[$theColConf['foreign_table']];
1915 if (is_array($selectUids) && !empty($selectUids)) {
1916 $queryBuilder = static::getQueryBuilderForTable($theColConf['foreign_table']);
1917 $queryBuilder->getRestrictions()
1918 ->removeAll()
1919 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1920
1921 $result = $queryBuilder
1922 ->select('uid', ...$MMfields)
1923 ->from($theColConf['foreign_table'])
1924 ->where(
1925 $queryBuilder->expr()->in(
1926 'uid',
1927 $queryBuilder->createNamedParameter($selectUids, Connection::PARAM_INT_ARRAY)
1928 )
1929 )
1930 ->execute();
1931
1932 $mmlA = [];
1933 while ($MMrow = $result->fetch()) {
1934 // Keep sorting of $selectUids
1935 $selectedUid = array_search($MMrow['uid'], $selectUids);
1936 $mmlA[$selectedUid] = $MMrow['uid'];
1937 if (!$noRecordLookup) {
1938 $mmlA[$selectedUid] = static::getRecordTitle(
1939 $theColConf['foreign_table'],
1940 $MMrow,
1941 false,
1942 $forceResult
1943 );
1944 }
1945 }
1946
1947 if (!empty($mmlA)) {
1948 ksort($mmlA);
1949 $l = implode('; ', $mmlA);
1950 } else {
1951 $l = 'N/A';
1952 }
1953 } else {
1954 $l = 'N/A';
1955 }
1956 } else {
1957 $l = 'N/A';
1958 }
1959 } else {
1960 $columnTsConfig = [];
1961 if ($pid) {
1962 $pageTsConfig = self::getPagesTSconfig($pid);
1963 if (isset($pageTsConfig['TCEFORM.'][$table . '.'][$col . '.']) && is_array($pageTsConfig['TCEFORM.'][$table . '.'][$col . '.'])) {
1964 $columnTsConfig = $pageTsConfig['TCEFORM.'][$table . '.'][$col . '.'];
1965 }
1966 }
1967 $l = self::getLabelsFromItemsList($table, $col, $value, $columnTsConfig);
1968 if (!empty($theColConf['foreign_table']) && !$l && !empty($GLOBALS['TCA'][$theColConf['foreign_table']])) {
1969 if ($noRecordLookup) {
1970 $l = $value;
1971 } else {
1972 $rParts = [];
1973 if ($uid && isset($theColConf['foreign_field']) && $theColConf['foreign_field'] !== '') {
1974 $queryBuilder = static::getQueryBuilderForTable($theColConf['foreign_table']);
1975 $queryBuilder->getRestrictions()
1976 ->removeAll()
1977 ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
1978 ->add(GeneralUtility::makeInstance(BackendWorkspaceRestriction::class));
1979 $constraints = [
1980 $queryBuilder->expr()->eq(
1981 $theColConf['foreign_field'],
1982 $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
1983 )
1984 ];
1985
1986 if (!empty($theColConf['foreign_table_field'])) {
1987 $constraints[] = $queryBuilder->expr()->eq(
1988 $theColConf['foreign_table_field'],
1989 $queryBuilder->createNamedParameter($table, \PDO::PARAM_STR)
1990 );
1991 }
1992
1993 // Add additional where clause if foreign_match_fields are defined
1994 $foreignMatchFields = [];
1995 if (is_array($theColConf['foreign_match_fields'])) {
1996 $foreignMatchFields = $theColConf['foreign_match_fields'];
1997 }
1998
1999 foreach ($foreignMatchFields as $matchField => $matchValue) {
2000 $constraints[] = $queryBuilder->expr()->eq(
2001 $matchField,
2002 $queryBuilder->createNamedParameter($matchValue)
2003 );
2004 }
2005
2006 $result = $queryBuilder
2007 ->select('*')
2008 ->from($theColConf['foreign_table'])
2009 ->where(...$constraints)
2010 ->execute();
2011
2012 while ($record = $result->fetch()) {
2013 $rParts[] = $record['uid'];
2014 }
2015 }
2016 if (empty($rParts)) {
2017 $rParts = GeneralUtility::trimExplode(',', $value, true);
2018 }
2019 $lA = [];
2020 foreach ($rParts as $rVal) {
2021 $rVal = (int)$rVal;
2022 $r = self::getRecordWSOL($theColConf['foreign_table'], $rVal);
2023 if (is_array($r)) {
2024 $lA[] = $lang->sL($theColConf['foreign_table_prefix'])
2025 . self::getRecordTitle($theColConf['foreign_table'], $r, false, $forceResult);
2026 } else {
2027 $lA[] = $rVal ? '[' . $rVal . '!]' : '';
2028 }
2029 }
2030 $l = implode(', ', $lA);
2031 }
2032 }
2033 if (empty($l) && !empty($value)) {
2034 // Use plain database value when label is empty
2035 $l = $value;
2036 }
2037 }
2038 break;
2039 case 'group':
2040 // resolve the titles for DB records
2041 if ($theColConf['internal_type'] === 'db') {
2042 if ($theColConf['MM']) {
2043 if ($uid) {
2044 // Display the title of MM related records in lists
2045 if ($noRecordLookup) {
2046 $MMfields = [];
2047 $MMfields[] = $theColConf['foreign_table'] . '.uid';
2048 } else {
2049 $MMfields = [$theColConf['foreign_table'] . '.' . $GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label']];
2050 $altLabelFields = explode(
2051 ',',
2052 $GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label_alt']
2053 );
2054 foreach ($altLabelFields as $f) {
2055 $f = trim($f);
2056 if ($f !== '') {
2057 $MMfields[] = $theColConf['foreign_table'] . '.' . $f;
2058 }
2059 }
2060 }
2061 /** @var $dbGroup RelationHandler */
2062 $dbGroup = GeneralUtility::makeInstance(RelationHandler::class);
2063 $dbGroup->start(
2064 $value,
2065 $theColConf['foreign_table'],
2066 $theColConf['MM'],
2067 $uid,
2068 $table,
2069 $theColConf
2070 );
2071 $selectUids = $dbGroup->tableArray[$theColConf['foreign_table']];
2072 if (!empty($selectUids) && is_array($selectUids)) {
2073 $queryBuilder = static::getQueryBuilderForTable($theColConf['foreign_table']);
2074 $queryBuilder->getRestrictions()
2075 ->removeAll()
2076 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
2077
2078 $result = $queryBuilder
2079 ->select('uid', ...$MMfields)
2080 ->from($theColConf['foreign_table'])
2081 ->where(
2082 $queryBuilder->expr()->in(
2083 'uid',
2084 $queryBuilder->createNamedParameter(
2085 $selectUids,
2086 Connection::PARAM_INT_ARRAY
2087 )
2088 )
2089 )
2090 ->execute();
2091
2092 $mmlA = [];
2093 while ($MMrow = $result->fetch()) {
2094 // Keep sorting of $selectUids
2095 $selectedUid = array_search($MMrow['uid'], $selectUids);
2096 $mmlA[$selectedUid] = $MMrow['uid'];
2097 if (!$noRecordLookup) {
2098 $mmlA[$selectedUid] = static::getRecordTitle(
2099 $theColConf['foreign_table'],
2100 $MMrow,
2101 false,
2102 $forceResult
2103 );
2104 }
2105 }
2106
2107 if (!empty($mmlA)) {
2108 ksort($mmlA);
2109 $l = implode('; ', $mmlA);
2110 } else {
2111 $l = 'N/A';
2112 }
2113 } else {
2114 $l = 'N/A';
2115 }
2116 } else {
2117 $l = 'N/A';
2118 }
2119 } else {
2120 $finalValues = [];
2121 $relationTableName = $theColConf['allowed'];
2122 $explodedValues = GeneralUtility::trimExplode(',', $value, true);
2123
2124 foreach ($explodedValues as $explodedValue) {
2125 if (MathUtility::canBeInterpretedAsInteger($explodedValue)) {
2126 $relationTableNameForField = $relationTableName;
2127 } else {
2128 list($relationTableNameForField, $explodedValue) = self::splitTable_Uid($explodedValue);
2129 }
2130
2131 $relationRecord = static::getRecordWSOL($relationTableNameForField, $explodedValue);
2132 $finalValues[] = static::getRecordTitle($relationTableNameForField, $relationRecord);
2133 }
2134 $l = implode(', ', $finalValues);
2135 }
2136 } else {
2137 $l = implode(', ', GeneralUtility::trimExplode(',', $value, true));
2138 }
2139 break;
2140 case 'check':
2141 if (!is_array($theColConf['items']) || count($theColConf['items']) === 1) {
2142 $l = $value ? $lang->sL('LLL:EXT:lang/Resources/Private/Language/locallang_common.xlf:yes') : $lang->sL('LLL:EXT:lang/Resources/Private/Language/locallang_common.xlf:no');
2143 } else {
2144 $lA = [];
2145 foreach ($theColConf['items'] as $key => $val) {
2146 if ($value & pow(2, $key)) {
2147 $lA[] = $lang->sL($val[0]);
2148 }
2149 }
2150 $l = implode(', ', $lA);
2151 }
2152 break;
2153 case 'input':
2154 // Hide value 0 for dates, but show it for everything else
2155 if (isset($value)) {
2156 $dateTimeFormats = QueryHelper::getDateTimeFormats();
2157
2158 if (GeneralUtility::inList($theColConf['eval'], 'date')) {
2159 // Handle native date field
2160 if (isset($theColConf['dbType']) && $theColConf['dbType'] === 'date') {
2161 $value = $value === $dateTimeFormats['date']['empty'] ? 0 : (int)strtotime($value);
2162 } else {
2163 $value = (int)$value;
2164 }
2165 if (!empty($value)) {
2166 $ageSuffix = '';
2167 $dateColumnConfiguration = $GLOBALS['TCA'][$table]['columns'][$col]['config'];
2168 $ageDisplayKey = 'disableAgeDisplay';
2169
2170 // generate age suffix as long as not explicitly suppressed
2171 if (!isset($dateColumnConfiguration[$ageDisplayKey])
2172 // non typesafe comparison on intention
2173 || $dateColumnConfiguration[$ageDisplayKey] == false
2174 ) {
2175 $ageSuffix = ' (' . ($GLOBALS['EXEC_TIME'] - $value > 0 ? '-' : '')
2176 . self::calcAge(
2177 abs($GLOBALS['EXEC_TIME'] - $value),
2178 $lang->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.minutesHoursDaysYears')
2179 )
2180 . ')';
2181 }
2182
2183 $l = self::date($value) . $ageSuffix;
2184 }
2185 } elseif (GeneralUtility::inList($theColConf['eval'], 'time')) {
2186 // Handle native time field
2187 if (isset($theColConf['dbType']) && $theColConf['dbType'] === 'time') {
2188 $value = $value === $dateTimeFormats['time']['empty'] ? 0 : (int)strtotime('1970-01-01 ' . $value);
2189 } else {
2190 $value = (int)$value;
2191 }
2192 if (!empty($value)) {
2193 $l = gmdate('H:i', (int)$value);
2194 }
2195 } elseif (GeneralUtility::inList($theColConf['eval'], 'timesec')) {
2196 // Handle native time field
2197 if (isset($theColConf['dbType']) && $theColConf['dbType'] === 'time') {
2198 $value = $value === $dateTimeFormats['time']['empty'] ? 0 : (int)strtotime('1970-01-01 ' . $value);
2199 } else {
2200 $value = (int)$value;
2201 }
2202 if (!empty($value)) {
2203 $l = gmdate('H:i:s', (int)$value);
2204 }
2205 } elseif (GeneralUtility::inList($theColConf['eval'], 'datetime')) {
2206 // Handle native datetime field
2207 if (isset($theColConf['dbType']) && $theColConf['dbType'] === 'datetime') {
2208 $value = $value === $dateTimeFormats['datetime']['empty'] ? 0 : (int)strtotime($value);
2209 } else {
2210 $value = (int)$value;
2211 }
2212 if (!empty($value)) {
2213 $l = self::datetime($value);
2214 }
2215 } else {
2216 $l = $value;
2217 }
2218 }
2219 break;
2220 case 'flex':
2221 $l = strip_tags($value);
2222 break;
2223 default:
2224 if ($defaultPassthrough) {
2225 $l = $value;
2226 } elseif (isset($theColConf['MM'])) {
2227 $l = 'N/A';
2228 } elseif ($value) {
2229 $l = GeneralUtility::fixed_lgd_cs(strip_tags($value), 200);
2230 }
2231 }
2232 // If this field is a password field, then hide the password by changing it to a random number of asterisk (*)
2233 if (!empty($theColConf['eval']) && stristr($theColConf['eval'], 'password')) {
2234 $l = '';
2235 $randomNumber = rand(5, 12);
2236 for ($i = 0; $i < $randomNumber; $i++) {
2237 $l .= '*';
2238 }
2239 }
2240 /*****************
2241 *HOOK: post-processing the human readable output from a record
2242 ****************/
2243 $null = null;
2244 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['postProcessValue'] ?? [] as $_funcRef) {
2245 $params = [
2246 'value' => $l,
2247 'colConf' => $theColConf
2248 ];
2249 $l = GeneralUtility::callUserFunction($_funcRef, $params, $null);
2250 }
2251 if ($fixed_lgd_chars) {
2252 return GeneralUtility::fixed_lgd_cs($l, $fixed_lgd_chars);
2253 }
2254 return $l;
2255 }
2256
2257 /**
2258 * 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.
2259 *
2260 * @param string $table Table name, present in TCA
2261 * @param string $fN Field name
2262 * @param string $fV Field value
2263 * @param int $fixed_lgd_chars The max amount of characters the value may occupy
2264 * @param int $uid Uid of the current record
2265 * @param bool $forceResult If BackendUtility::getRecordTitle is used to process the value, this parameter is forwarded.
2266 * @param int $pid Optional page uid is used to evaluate page TSConfig for the given field
2267 * @return string
2268 * @see getProcessedValue()
2269 */
2270 public static function getProcessedValueExtra(
2271 $table,
2272 $fN,
2273 $fV,
2274 $fixed_lgd_chars = 0,
2275 $uid = 0,
2276 $forceResult = true,
2277 $pid = 0
2278 ) {
2279 $fVnew = self::getProcessedValue($table, $fN, $fV, $fixed_lgd_chars, 1, 0, $uid, $forceResult, $pid);
2280 if (!isset($fVnew)) {
2281 if (is_array($GLOBALS['TCA'][$table])) {
2282 if ($fN == $GLOBALS['TCA'][$table]['ctrl']['tstamp'] || $fN == $GLOBALS['TCA'][$table]['ctrl']['crdate']) {
2283 $fVnew = self::datetime($fV);
2284 } elseif ($fN === 'pid') {
2285 // Fetches the path with no regard to the users permissions to select pages.
2286 $fVnew = self::getRecordPath($fV, '1=1', 20);
2287 } else {
2288 $fVnew = $fV;
2289 }
2290 }
2291 }
2292 return $fVnew;
2293 }
2294
2295 /**
2296 * Returns fields for a table, $table, which would typically be interesting to select
2297 * This includes uid, the fields defined for title, icon-field.
2298 * 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)
2299 *
2300 * @param string $table Table name, present in $GLOBALS['TCA']
2301 * @param string $prefix Table prefix
2302 * @param array $fields Preset fields (must include prefix if that is used)
2303 * @return string List of fields.
2304 */
2305 public static function getCommonSelectFields($table, $prefix = '', $fields = [])
2306 {
2307 $fields[] = $prefix . 'uid';
2308 if (isset($GLOBALS['TCA'][$table]['ctrl']['label']) && $GLOBALS['TCA'][$table]['ctrl']['label'] != '') {
2309 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['label'];
2310 }
2311 if (!empty($GLOBALS['TCA'][$table]['ctrl']['label_alt'])) {
2312 $secondFields = GeneralUtility::trimExplode(',', $GLOBALS['TCA'][$table]['ctrl']['label_alt'], true);
2313 foreach ($secondFields as $fieldN) {
2314 $fields[] = $prefix . $fieldN;
2315 }
2316 }
2317 if (static::isTableWorkspaceEnabled($table)) {
2318 $fields[] = $prefix . 't3ver_id';
2319 $fields[] = $prefix . 't3ver_state';
2320 $fields[] = $prefix . 't3ver_wsid';
2321 $fields[] = $prefix . 't3ver_count';
2322 }
2323 if (!empty($GLOBALS['TCA'][$table]['ctrl']['selicon_field'])) {
2324 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['selicon_field'];
2325 }
2326 if (!empty($GLOBALS['TCA'][$table]['ctrl']['typeicon_column'])) {
2327 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['typeicon_column'];
2328 }
2329 if (!empty($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['disabled'])) {
2330 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['disabled'];
2331 }
2332 if (!empty($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['starttime'])) {
2333 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['starttime'];
2334 }
2335 if (!empty($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['endtime'])) {
2336 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['endtime'];
2337 }
2338 if (!empty($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['fe_group'])) {
2339 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['fe_group'];
2340 }
2341 return implode(',', array_unique($fields));
2342 }
2343
2344 /*******************************************
2345 *
2346 * Backend Modules API functions
2347 *
2348 *******************************************/
2349
2350 /**
2351 * Returns CSH help text (description), if configured for, as an array (title, description)
2352 *
2353 * @param string $table Table name
2354 * @param string $field Field name
2355 * @return array With keys 'description' (raw, as available in locallang), 'title' (optional), 'moreInfo'
2356 */
2357 public static function helpTextArray($table, $field)
2358 {
2359 if (!isset($GLOBALS['TCA_DESCR'][$table]['columns'])) {
2360 static::getLanguageService()->loadSingleTableDescription($table);
2361 }
2362 $output = [
2363 'description' => null,
2364 'title' => null,
2365 'moreInfo' => false
2366 ];
2367 if (isset($GLOBALS['TCA_DESCR'][$table]['columns'][$field]) && is_array($GLOBALS['TCA_DESCR'][$table]['columns'][$field])) {
2368 $data = $GLOBALS['TCA_DESCR'][$table]['columns'][$field];
2369 // Add alternative title, if defined
2370 if ($data['alttitle']) {
2371 $output['title'] = $data['alttitle'];
2372 }
2373 // If we have more information to show and access to the cshmanual
2374 if (($data['image_descr'] || $data['seeAlso'] || $data['details'] || $data['syntax'])
2375 && static::getBackendUserAuthentication()->check('modules', 'help_CshmanualCshmanual')
2376 ) {
2377 $output['moreInfo'] = true;
2378 }
2379 // Add description
2380 if ($data['description']) {
2381 $output['description'] = $data['description'];
2382 }
2383 }
2384 return $output;
2385 }
2386
2387 /**
2388 * Returns CSH help text
2389 *
2390 * @param string $table Table name
2391 * @param string $field Field name
2392 * @return string HTML content for help text
2393 * @see cshItem()
2394 */
2395 public static function helpText($table, $field)
2396 {
2397 $helpTextArray = self::helpTextArray($table, $field);
2398 $output = '';
2399 $arrow = '';
2400 // Put header before the rest of the text
2401 if ($helpTextArray['title'] !== null) {
2402 $output .= '<h2>' . $helpTextArray['title'] . '</h2>';
2403 }
2404 // Add see also arrow if we have more info
2405 if ($helpTextArray['moreInfo']) {
2406 /** @var IconFactory $iconFactory */
2407 $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
2408 $arrow = $iconFactory->getIcon('actions-view-go-forward', Icon::SIZE_SMALL)->render();
2409 }
2410 // Wrap description and arrow in p tag
2411 if ($helpTextArray['description'] !== null || $arrow) {
2412 $output .= '<p class="t3-help-short">' . nl2br(htmlspecialchars($helpTextArray['description'])) . $arrow . '</p>';
2413 }
2414 return $output;
2415 }
2416
2417 /**
2418 * API function that wraps the text / html in help text, so if a user hovers over it
2419 * the help text will show up
2420 *
2421 * @param string $table The table name for which the help should be shown
2422 * @param string $field The field name for which the help should be shown
2423 * @param string $text The text which should be wrapped with the help text
2424 * @param array $overloadHelpText Array with text to overload help text
2425 * @return string the HTML code ready to render
2426 */
2427 public static function wrapInHelp($table, $field, $text = '', array $overloadHelpText = [])
2428 {
2429 // Initialize some variables
2430 $helpText = '';
2431 $abbrClassAdd = '';
2432 $hasHelpTextOverload = !empty($overloadHelpText);
2433 // Get the help text that should be shown on hover
2434 if (!$hasHelpTextOverload) {
2435 $helpText = self::helpText($table, $field);
2436 }
2437 // If there's a help text or some overload information, proceed with preparing an output
2438 // @todo: right now this is a hard dependency on csh manual, as the whole help system should be moved to
2439 // the extension. The core provides an API for adding help and rendering help, but the rendering
2440 // should be up to the extension itself
2441 if ((!empty($helpText) || $hasHelpTextOverload) && ExtensionManagementUtility::isLoaded('documentation')) {
2442 // If no text was given, just use the regular help icon
2443 if ($text == '') {
2444 /** @var IconFactory $iconFactory */
2445 $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
2446 $text = $iconFactory->getIcon('actions-system-help-open', Icon::SIZE_SMALL)->render();
2447 $abbrClassAdd = '-icon';
2448 }
2449 $text = '<abbr class="t3-help-teaser' . $abbrClassAdd . '">' . $text . '</abbr>';
2450 $wrappedText = '<span class="t3-help-link" href="#" data-table="' . $table . '" data-field="' . $field . '"';
2451 // The overload array may provide a title and a description
2452 // If either one is defined, add them to the "data" attributes
2453 if ($hasHelpTextOverload) {
2454 if (isset($overloadHelpText['title'])) {
2455 $wrappedText .= ' data-title="' . htmlspecialchars($overloadHelpText['title']) . '"';
2456 }
2457 if (isset($overloadHelpText['description'])) {
2458 $wrappedText .= ' data-description="' . htmlspecialchars($overloadHelpText['description']) . '"';
2459 }
2460 }
2461 $wrappedText .= '>' . $text . '</span>';
2462 return $wrappedText;
2463 }
2464 return $text;
2465 }
2466
2467 /**
2468 * API for getting CSH icons/text for use in backend modules.
2469 * TCA_DESCR will be loaded if it isn't already
2470 *
2471 * @param string $table Table name ('_MOD_'+module name)
2472 * @param string $field Field name (CSH locallang main key)
2473 * @param string $_ (unused)
2474 * @param string $wrap Wrap code for icon-mode, splitted by "|". Not used for full-text mode.
2475 * @return string HTML content for help text
2476 */
2477 public static function cshItem($table, $field, $_ = '', $wrap = '')
2478 {
2479 static::getLanguageService()->loadSingleTableDescription($table);
2480 if (is_array($GLOBALS['TCA_DESCR'][$table])
2481 && is_array($GLOBALS['TCA_DESCR'][$table]['columns'][$field])
2482 ) {
2483 // Creating short description
2484 $output = self::wrapInHelp($table, $field);
2485 if ($output && $wrap) {
2486 $wrParts = explode('|', $wrap);
2487 $output = $wrParts[0] . $output . $wrParts[1];
2488 }
2489 return $output;
2490 }
2491 return '';
2492 }
2493
2494 /**
2495 * Returns a JavaScript string (for an onClick handler) which will load the EditDocumentController script that shows the form for editing of the record(s) you have send as params.
2496 * REMEMBER to always htmlspecialchar() content in href-properties to ampersands get converted to entities (XHTML requirement and XSS precaution)
2497 *
2498 * @param string $params Parameters sent along to EditDocumentController. This requires a much more details description which you must seek in Inside TYPO3s documentation of the FormEngine API. And example could be '&edit[pages][123] = edit' which will show edit form for page record 123.
2499 * @param string $_ (unused)
2500 * @param string $requestUri An optional returnUrl you can set - automatically set to REQUEST_URI.
2501 *
2502 * @return string
2503 */
2504 public static function editOnClick($params, $_ = '', $requestUri = '')
2505 {
2506 if ($requestUri == -1) {
2507 $returnUrl = 'T3_THIS_LOCATION';
2508 } else {
2509 $returnUrl = GeneralUtility::quoteJSvalue(rawurlencode($requestUri ?: GeneralUtility::getIndpEnv('REQUEST_URI')));
2510 }
2511 $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
2512 return 'window.location.href=' . GeneralUtility::quoteJSvalue((string)$uriBuilder->buildUriFromRoute('record_edit') . $params . '&returnUrl=') . '+' . $returnUrl . '; return false;';
2513 }
2514
2515 /**
2516 * Returns a JavaScript string for viewing the page id, $id
2517 * It will detect the correct domain name if needed and provide the link with the right back path.
2518 * Also it will re-use any window already open.
2519 *
2520 * @param int $pageUid Page UID
2521 * @param string $backPath Must point back to TYPO3_mainDir (where the site is assumed to be one level above)
2522 * @param array|null $rootLine If root line is supplied the function will look for the first found domain record and use that URL instead (if found)
2523 * @param string $anchorSection Optional anchor to the URL
2524 * @param string $alternativeUrl An alternative URL that, if set, will ignore other parameters except $switchFocus: It will return the window.open command wrapped around this URL!
2525 * @param string $additionalGetVars Additional GET variables.
2526 * @param bool $switchFocus If TRUE, then the preview window will gain the focus.
2527 * @return string
2528 */
2529 public static function viewOnClick(
2530 $pageUid,
2531 $backPath = '',
2532 $rootLine = null,
2533 $anchorSection = '',
2534 $alternativeUrl = '',
2535 $additionalGetVars = '',
2536 $switchFocus = true
2537 ) {
2538 $viewScript = '/index.php?id=';
2539 if ($alternativeUrl) {
2540 $viewScript = $alternativeUrl;
2541 }
2542
2543 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['viewOnClickClass'] ?? [] as $className) {
2544 $hookObj = GeneralUtility::makeInstance($className);
2545 if (method_exists($hookObj, 'preProcess')) {
2546 $hookObj->preProcess(
2547 $pageUid,
2548 $backPath,
2549 $rootLine,
2550 $anchorSection,
2551 $viewScript,
2552 $additionalGetVars,
2553 $switchFocus
2554 );
2555 }
2556 }
2557
2558 if ($alternativeUrl) {
2559 $previewUrl = $viewScript;
2560 } else {
2561 $permissionClause = $GLOBALS['BE_USER']->getPagePermsClause(Permission::PAGE_SHOW);
2562 $pageInfo = self::readPageAccess($pageUid, $permissionClause);
2563 $additionalGetVars .= self::ADMCMD_previewCmds($pageInfo);
2564 $previewUrl = self::createPreviewUrl($pageUid, $rootLine, $anchorSection, $additionalGetVars, $viewScript);
2565 }
2566
2567 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['viewOnClickClass'] ?? [] as $className) {
2568 $hookObj = GeneralUtility::makeInstance($className);
2569 if (method_exists($hookObj, 'postProcess')) {
2570 $previewUrl = $hookObj->postProcess(
2571 $previewUrl,
2572 $pageUid,
2573 $rootLine,
2574 $anchorSection,
2575 $viewScript,
2576 $additionalGetVars,
2577 $switchFocus
2578 );
2579 }
2580 }
2581
2582 $onclickCode = 'var previewWin = window.open(' . GeneralUtility::quoteJSvalue($previewUrl) . ',\'newTYPO3frontendWindow\');' . ($switchFocus ? 'previewWin.focus();' : '') . LF
2583 . 'if (previewWin.location.href === ' . GeneralUtility::quoteJSvalue($previewUrl) . ') { previewWin.location.reload(); };';
2584 return $onclickCode;
2585 }
2586
2587 /**
2588 * Makes click menu link (context sensitive menu)
2589 *
2590 * Returns $str wrapped in a link which will activate the context sensitive
2591 * menu for the record ($table/$uid) or file ($table = file)
2592 * The link will load the top frame with the parameter "&item" which is the table, uid
2593 * and context arguments imploded by "|": rawurlencode($table.'|'.$uid.'|'.$context)
2594 *
2595 * @param string $content String to be wrapped in link, typ. image tag.
2596 * @param string $table Table name/File path. If the icon is for a database
2597 * record, enter the tablename from $GLOBALS['TCA']. If a file then enter
2598 * the absolute filepath
2599 * @param int|string $uid If icon is for database record this is the UID for the
2600 * record from $table or identifier for sys_file record
2601 * @param string $context Set tree if menu is called from tree view
2602 * @param string $_addParams NOT IN USE
2603 * @param string $_enDisItems NOT IN USE
2604 * @param bool $returnTagParameters If set, will return only the onclick
2605 * JavaScript, not the whole link.
2606 *
2607 * @return string The link wrapped input string.
2608 */
2609 public static function wrapClickMenuOnIcon(
2610 $content,
2611 $table,
2612 $uid = 0,
2613 $context = '',
2614 $_addParams = '',
2615 $_enDisItems = '',
2616 $returnTagParameters = false
2617 ) {
2618 $tagParameters = [
2619 'class' => 't3js-contextmenutrigger',
2620 'data-table' => $table,
2621 'data-uid' => $uid,
2622 'data-context' => $context
2623 ];
2624
2625 if ($returnTagParameters) {
2626 return $tagParameters;
2627 }
2628 return '<a href="#" ' . GeneralUtility::implodeAttributes($tagParameters, true) . '>' . $content . '</a>';
2629 }
2630
2631 /**
2632 * Returns a URL with a command to TYPO3 Datahandler
2633 *
2634 * @param string $parameters Set of GET params to send. Example: "&cmd[tt_content][123][move]=456" or "&data[tt_content][123][hidden]=1&data[tt_content][123][title]=Hello%20World
2635 * @param string|int $redirectUrl Redirect URL, default is to use GeneralUtility::getIndpEnv('REQUEST_URI'), -1 means to generate an URL for JavaScript using T3_THIS_LOCATION
2636 * @return string URL to BackendUtility::getModuleUrl('tce_db') + parameters
2637 */
2638 public static function getLinkToDataHandlerAction($parameters, $redirectUrl = '')
2639 {
2640 $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
2641 $url = (string)$uriBuilder->buildUriFromRoute('tce_db') . $parameters . '&redirect=';
2642 if ((int)$redirectUrl === -1) {
2643 $url = GeneralUtility::quoteJSvalue($url) . '+T3_THIS_LOCATION';
2644 } else {
2645 $url .= rawurlencode($redirectUrl ?: GeneralUtility::getIndpEnv('REQUEST_URI'));
2646 }
2647 return $url;
2648 }
2649
2650 /**
2651 * Creates the view-on-click preview URL without any alternative URL.
2652 *
2653 * @param int $pageUid Page UID
2654 * @param array $rootLine If rootline is supplied, the function will look for the first found domain record and use that URL instead
2655 * @param string $anchorSection Optional anchor to the URL
2656 * @param string $additionalGetVars Additional GET variables.
2657 * @param string $viewScript The path to the script used to view the page
2658 *
2659 * @return string The preview URL
2660 */
2661 protected static function createPreviewUrl($pageUid, $rootLine, $anchorSection, $additionalGetVars, $viewScript)
2662 {
2663 // Look if a fixed preview language should be added:
2664 $beUser = static::getBackendUserAuthentication();
2665 $viewLanguageOrder = $beUser->getTSConfigVal('options.view.languageOrder');
2666
2667 if ((string)$viewLanguageOrder !== '') {
2668 $suffix = '';
2669 // Find allowed languages (if none, all are allowed!)
2670 $allowedLanguages = null;
2671 if (!$beUser->isAdmin() && $beUser->groupData['allowed_languages'] !== '') {
2672 $allowedLanguages = array_flip(explode(',', $beUser->groupData['allowed_languages']));
2673 }
2674 // Traverse the view order, match first occurrence:
2675 $languageOrder = GeneralUtility::intExplode(',', $viewLanguageOrder);
2676 foreach ($languageOrder as $langUid) {
2677 if (is_array($allowedLanguages) && !empty($allowedLanguages)) {
2678 // Choose if set.
2679 if (isset($allowedLanguages[$langUid])) {
2680 $suffix = '&L=' . $langUid;
2681 break;
2682 }
2683 } else {
2684 // All allowed since no lang. are listed.
2685 $suffix = '&L=' . $langUid;
2686 break;
2687 }
2688 }
2689 // Add it
2690 $additionalGetVars .= $suffix;
2691 }
2692
2693 // Check a mount point needs to be previewed
2694 $sys_page = GeneralUtility::makeInstance(\TYPO3\CMS\Frontend\Page\PageRepository::class);
2695 $sys_page->init(false);
2696 $mountPointInfo = $sys_page->getMountPointInfo($pageUid);
2697
2698 if ($mountPointInfo && $mountPointInfo['overlay']) {
2699 $pageUid = $mountPointInfo['mount_pid'];
2700 $additionalGetVars .= '&MP=' . $mountPointInfo['MPvar'];
2701 }
2702 $viewDomain = self::getViewDomain($pageUid, $rootLine);
2703
2704 return $viewDomain . $viewScript . $pageUid . $additionalGetVars . $anchorSection;
2705 }
2706
2707 /**
2708 * Builds the frontend view domain for a given page ID with a given root
2709 * line.
2710 *
2711 * @param int $pageId The page ID to use, must be > 0
2712 * @param array|null $rootLine The root line structure to use
2713 * @return string The full domain including the protocol http:// or https://, but without the trailing '/'
2714 */
2715 public static function getViewDomain($pageId, $rootLine = null)
2716 {
2717 $domain = rtrim(GeneralUtility::getIndpEnv('TYPO3_SITE_URL'), '/');
2718 if (!is_array($rootLine)) {
2719 $rootLine = self::BEgetRootLine($pageId);
2720 }
2721 // Checks alternate domains
2722 if (!empty($rootLine)) {
2723 $urlParts = parse_url($domain);
2724 $protocol = GeneralUtility::getIndpEnv('TYPO3_SSL') ? 'https' : 'http';
2725 $previewDomainConfig = static::getBackendUserAuthentication()->getTSConfig(
2726 'TCEMAIN.previewDomain',
2727 self::getPagesTSconfig($pageId)
2728 );
2729 if ($previewDomainConfig['value']) {
2730 if (strpos($previewDomainConfig['value'], '://') !== false) {
2731 list($protocol, $domainName) = explode('://', $previewDomainConfig['value']);
2732 } else {
2733 $domainName = $previewDomainConfig['value'];
2734 }
2735 } else {
2736 $domainName = self::firstDomainRecord($rootLine);
2737 }
2738 if ($domainName) {
2739 $domain = $domainName;
2740 } else {
2741 $domainRecord = self::getDomainStartPage($urlParts['host'], $urlParts['path']);
2742 $domain = $domainRecord['domainName'];
2743 }
2744 if ($domain) {
2745 $domain = $protocol . '://' . $domain;
2746 } else {
2747 $domain = rtrim(GeneralUtility::getIndpEnv('TYPO3_SITE_URL'), '/');
2748 }
2749 // Append port number if lockSSLPort is not the standard port 443
2750 $portNumber = (int)$GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSLPort'];
2751 if ($portNumber > 0 && $portNumber !== 443 && $portNumber < 65536 && $protocol === 'https') {
2752 $domain .= ':' . strval($portNumber);
2753 }
2754 }
2755 return $domain;
2756 }
2757
2758 /**
2759 * Returns the merged User/Page TSconfig for page id, $id.
2760 * Please read details about module programming elsewhere!
2761 *
2762 * @param int $id Page uid
2763 * @param string $TSref An object string which determines the path of the TSconfig to return.
2764 * @return array
2765 */
2766 public static function getModTSconfig($id, $TSref)
2767 {
2768 $beUser = static::getBackendUserAuthentication();
2769 $pageTS_modOptions = $beUser->getTSConfig($TSref, static::getPagesTSconfig($id));
2770 $BE_USER_modOptions = $beUser->getTSConfig($TSref);
2771 if ($BE_USER_modOptions['value'] === null) {
2772 unset($BE_USER_modOptions['value']);
2773 }
2774 ArrayUtility::mergeRecursiveWithOverrule($pageTS_modOptions, $BE_USER_modOptions);
2775 return $pageTS_modOptions;
2776 }
2777
2778 /**
2779 * Returns a selector box "function menu" for a module
2780 * Requires the JS function jumpToUrl() to be available
2781 * See Inside TYPO3 for details about how to use / make Function menus
2782 *
2783 * @param mixed $mainParams The "&id=" parameter value to be sent to the module, but it can be also a parameter array which will be passed instead of the &id=...
2784 * @param string $elementName The form elements name, probably something like "SET[...]
2785 * @param string $currentValue The value to be selected currently.
2786 * @param array $menuItems An array with the menu items for the selector box
2787 * @param string $script The script to send the &id to, if empty it's automatically found
2788 * @param string $addParams Additional parameters to pass to the script.
2789 * @return string HTML code for selector box
2790 */
2791 public static function getFuncMenu(
2792 $mainParams,
2793 $elementName,
2794 $currentValue,
2795 $menuItems,
2796 $script = '',
2797 $addParams = ''
2798 ) {
2799 if (!is_array($menuItems) || count($menuItems) <= 1) {
2800 return '';
2801 }
2802 $scriptUrl = self::buildScriptUrl($mainParams, $addParams, $script);
2803 $options = [];
2804 foreach ($menuItems as $value => $label) {
2805 $options[] = '<option value="'
2806 . htmlspecialchars($value) . '"'
2807 . ((string)$currentValue === (string)$value ? ' selected="selected"' : '') . '>'
2808 . htmlspecialchars($label, ENT_COMPAT, 'UTF-8', false) . '</option>';
2809 }
2810 $dataMenuIdentifier = str_replace(['SET[', ']'], '', $elementName);
2811 $dataMenuIdentifier = GeneralUtility::camelCaseToLowerCaseUnderscored($dataMenuIdentifier);
2812 $dataMenuIdentifier = str_replace('_', '-', $dataMenuIdentifier);
2813 if (!empty($options)) {
2814 $onChange = 'jumpToUrl(' . GeneralUtility::quoteJSvalue($scriptUrl . '&' . $elementName . '=') . '+this.options[this.selectedIndex].value,this);';
2815 return '
2816
2817 <!-- Function Menu of module -->
2818 <select class="form-control" name="' . $elementName . '" onchange="' . htmlspecialchars($onChange) . '" data-menu-identifier="' . htmlspecialchars($dataMenuIdentifier) . '">
2819 ' . implode('
2820 ', $options) . '
2821 </select>
2822 ';
2823 }
2824 return '';
2825 }
2826
2827 /**
2828 * Returns a selector box to switch the view
2829 * Requires the JS function jumpToUrl() to be available
2830 * Based on BackendUtility::getFuncMenu() but done as new function because it has another purpose.
2831 * Mingling with getFuncMenu would harm the docHeader Menu.
2832 *
2833 * @param mixed $mainParams The "&id=" parameter value to be sent to the module, but it can be also a parameter array which will be passed instead of the &id=...
2834 * @param string $elementName The form elements name, probably something like "SET[...]
2835 * @param string $currentValue The value to be selected currently.
2836 * @param array $menuItems An array with the menu items for the selector box
2837 * @param string $script The script to send the &id to, if empty it's automatically found
2838 * @param string $addParams Additional parameters to pass to the script.
2839 * @return string HTML code for selector box
2840 */
2841 public static function getDropdownMenu(
2842 $mainParams,
2843 $elementName,
2844 $currentValue,
2845 $menuItems,
2846 $script = '',
2847 $addParams = ''
2848 ) {
2849 if (!is_array($menuItems) || count($menuItems) <= 1) {
2850 return '';
2851 }
2852 $scriptUrl = self::buildScriptUrl($mainParams, $addParams, $script);
2853 $options = [];
2854 foreach ($menuItems as $value => $label) {
2855 $options[] = '<option value="'
2856 . htmlspecialchars($value) . '"'
2857 . ((string)$currentValue === (string)$value ? ' selected="selected"' : '') . '>'
2858 . htmlspecialchars($label, ENT_COMPAT, 'UTF-8', false) . '</option>';
2859 }
2860 $dataMenuIdentifier = str_replace(['SET[', ']'], '', $elementName);
2861 $dataMenuIdentifier = GeneralUtility::camelCaseToLowerCaseUnderscored($dataMenuIdentifier);
2862 $dataMenuIdentifier = str_replace('_', '-', $dataMenuIdentifier);
2863 if (!empty($options)) {
2864 $onChange = 'jumpToUrl(' . GeneralUtility::quoteJSvalue($scriptUrl . '&' . $elementName . '=') . '+this.options[this.selectedIndex].value,this);';
2865 return '
2866 <div class="form-group">
2867 <!-- Function Menu of module -->
2868 <select class="form-control input-sm" name="' . htmlspecialchars($elementName) . '" onchange="' . htmlspecialchars($onChange) . '" data-menu-identifier="' . htmlspecialchars($dataMenuIdentifier) . '">
2869 ' . implode(LF, $options) . '
2870 </select>