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