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