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