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