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