0c9b5cdb39b04f64acfcc80d24c39e3041d6af18
[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['uid'] === 0) {
1492 $out = htmlspecialchars($parts[0]);
1493 return $includeAttrib ? 'title="' . $out . '"' : $out;
1494 }
1495 if ($row['alias']) {
1496 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['alias']['label']) . ' ' . $row['alias'];
1497 }
1498 if ($row['pid'] < 0) {
1499 $parts[] = 'v#1.' . $row['t3ver_id'];
1500 }
1501 switch (VersionState::cast($row['t3ver_state'])) {
1502 case new VersionState(VersionState::NEW_PLACEHOLDER):
1503 $parts[] = 'PLH WSID#' . $row['t3ver_wsid'];
1504 break;
1505 case new VersionState(VersionState::DELETE_PLACEHOLDER):
1506 $parts[] = 'Deleted element!';
1507 break;
1508 case new VersionState(VersionState::MOVE_PLACEHOLDER):
1509 $parts[] = 'NEW LOCATION (PLH) WSID#' . $row['t3ver_wsid'];
1510 break;
1511 case new VersionState(VersionState::MOVE_POINTER):
1512 $parts[] = 'OLD LOCATION (PNT) WSID#' . $row['t3ver_wsid'];
1513 break;
1514 case new VersionState(VersionState::NEW_PLACEHOLDER_VERSION):
1515 $parts[] = 'New element!';
1516 break;
1517 }
1518 if ($row['doktype'] == PageRepository::DOKTYPE_LINK) {
1519 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['url']['label']) . ' ' . $row['url'];
1520 } elseif ($row['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
1521 if ($perms_clause) {
1522 $label = self::getRecordPath((int)$row['shortcut'], $perms_clause, 20);
1523 } else {
1524 $row['shortcut'] = (int)$row['shortcut'];
1525 $lRec = self::getRecordWSOL('pages', $row['shortcut'], 'title');
1526 $label = $lRec['title'] . ' (id=' . $row['shortcut'] . ')';
1527 }
1528 if ($row['shortcut_mode'] != PageRepository::SHORTCUT_MODE_NONE) {
1529 $label .= ', ' . $lang->sL($GLOBALS['TCA']['pages']['columns']['shortcut_mode']['label']) . ' '
1530 . $lang->sL(self::getLabelFromItemlist('pages', 'shortcut_mode', $row['shortcut_mode']));
1531 }
1532 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['shortcut']['label']) . ' ' . $label;
1533 } elseif ($row['doktype'] == PageRepository::DOKTYPE_MOUNTPOINT) {
1534 if ((int)$row['mount_pid'] > 0) {
1535 if ($perms_clause) {
1536 $label = self::getRecordPath((int)$row['mount_pid'], $perms_clause, 20);
1537 } else {
1538 $lRec = self::getRecordWSOL('pages', (int)$row['mount_pid'], 'title');
1539 $label = $lRec['title'] . ' (id=' . $row['mount_pid'] . ')';
1540 }
1541 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['mount_pid']['label']) . ' ' . $label;
1542 if ($row['mount_pid_ol']) {
1543 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['mount_pid_ol']['label']);
1544 }
1545 } else {
1546 $parts[] = $lang->sl('LLL:EXT:frontend/Resources/Private/Language/locallang_tca.xlf:no_mount_pid');
1547 }
1548 }
1549 if ($row['nav_hide']) {
1550 $parts[] = rtrim($lang->sL($GLOBALS['TCA']['pages']['columns']['nav_hide']['label']), ':');
1551 }
1552 if ($row['hidden']) {
1553 $parts[] = $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.hidden');
1554 }
1555 if ($row['starttime']) {
1556 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['starttime']['label'])
1557 . ' ' . self::dateTimeAge($row['starttime'], -1, 'date');
1558 }
1559 if ($row['endtime']) {
1560 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['endtime']['label']) . ' '
1561 . self::dateTimeAge($row['endtime'], -1, 'date');
1562 }
1563 if ($row['fe_group']) {
1564 $fe_groups = [];
1565 foreach (GeneralUtility::intExplode(',', $row['fe_group']) as $fe_group) {
1566 if ($fe_group < 0) {
1567 $fe_groups[] = $lang->sL(self::getLabelFromItemlist('pages', 'fe_group', $fe_group));
1568 } else {
1569 $lRec = self::getRecordWSOL('fe_groups', $fe_group, 'title');
1570 $fe_groups[] = $lRec['title'];
1571 }
1572 }
1573 $label = implode(', ', $fe_groups);
1574 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['fe_group']['label']) . ' ' . $label;
1575 }
1576 $out = htmlspecialchars(implode(' - ', $parts));
1577 return $includeAttrib ? 'title="' . $out . '"' : $out;
1578 }
1579
1580 /**
1581 * Returns the combined markup for Bootstraps tooltips
1582 *
1583 * @param array $row
1584 * @param string $table
1585 * @return string
1586 */
1587 public static function getRecordToolTip(array $row, $table = 'pages')
1588 {
1589 $toolTipText = self::getRecordIconAltText($row, $table);
1590 $toolTipCode = 'data-toggle="tooltip" data-title=" '
1591 . str_replace(' - ', '<br>', $toolTipText)
1592 . '" data-html="true" data-placement="right"';
1593 return $toolTipCode;
1594 }
1595
1596 /**
1597 * Returns title-attribute information for ANY record (from a table defined in TCA of course)
1598 * 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.
1599 * "pages" table can be used as well and will return the result of ->titleAttribForPages() for that page.
1600 *
1601 * @param array $row Table row; $row is a row from the table, $table
1602 * @param string $table Table name
1603 * @return string
1604 */
1605 public static function getRecordIconAltText($row, $table = 'pages')
1606 {
1607 if ($table === 'pages') {
1608 $out = self::titleAttribForPages($row, '', 0);
1609 } else {
1610 $out = !empty(trim($GLOBALS['TCA'][$table]['ctrl']['descriptionColumn'])) ? $row[$GLOBALS['TCA'][$table]['ctrl']['descriptionColumn']] . ' ' : '';
1611 $ctrl = $GLOBALS['TCA'][$table]['ctrl']['enablecolumns'];
1612 // Uid is added
1613 $out .= 'id=' . $row['uid'];
1614 if ($table === 'pages' && $row['alias']) {
1615 $out .= ' / ' . $row['alias'];
1616 }
1617 if (static::isTableWorkspaceEnabled($table) && $row['pid'] < 0) {
1618 $out .= ' - v#1.' . $row['t3ver_id'];
1619 }
1620 if (static::isTableWorkspaceEnabled($table)) {
1621 switch (VersionState::cast($row['t3ver_state'])) {
1622 case new VersionState(VersionState::NEW_PLACEHOLDER):
1623 $out .= ' - PLH WSID#' . $row['t3ver_wsid'];
1624 break;
1625 case new VersionState(VersionState::DELETE_PLACEHOLDER):
1626 $out .= ' - Deleted element!';
1627 break;
1628 case new VersionState(VersionState::MOVE_PLACEHOLDER):
1629 $out .= ' - NEW LOCATION (PLH) WSID#' . $row['t3ver_wsid'];
1630 break;
1631 case new VersionState(VersionState::MOVE_POINTER):
1632 $out .= ' - OLD LOCATION (PNT) WSID#' . $row['t3ver_wsid'];
1633 break;
1634 case new VersionState(VersionState::NEW_PLACEHOLDER_VERSION):
1635 $out .= ' - New element!';
1636 break;
1637 }
1638 }
1639 // Hidden
1640 $lang = static::getLanguageService();
1641 if ($ctrl['disabled']) {
1642 $out .= $row[$ctrl['disabled']] ? ' - ' . $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.hidden') : '';
1643 }
1644 if ($ctrl['starttime']) {
1645 if ($row[$ctrl['starttime']] > $GLOBALS['EXEC_TIME']) {
1646 $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') . ')';
1647 }
1648 }
1649 if ($row[$ctrl['endtime']]) {
1650 $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') . ')';
1651 }
1652 }
1653 return htmlspecialchars($out);
1654 }
1655
1656 /**
1657 * Returns the label of the first found entry in an "items" array from $GLOBALS['TCA'] (tablename = $table/fieldname = $col) where the value is $key
1658 *
1659 * @param string $table Table name, present in $GLOBALS['TCA']
1660 * @param string $col Field name, present in $GLOBALS['TCA']
1661 * @param string $key items-array value to match
1662 * @return string Label for item entry
1663 */
1664 public static function getLabelFromItemlist($table, $col, $key)
1665 {
1666 // Check, if there is an "items" array:
1667 if (is_array($GLOBALS['TCA'][$table]['columns'][$col]['config']['items'] ?? false)) {
1668 // Traverse the items-array...
1669 foreach ($GLOBALS['TCA'][$table]['columns'][$col]['config']['items'] as $v) {
1670 // ... and return the first found label where the value was equal to $key
1671 if ((string)$v[1] === (string)$key) {
1672 return $v[0];
1673 }
1674 }
1675 }
1676 return '';
1677 }
1678
1679 /**
1680 * Return the label of a field by additionally checking TsConfig values
1681 *
1682 * @param int $pageId Page id
1683 * @param string $table Table name
1684 * @param string $column Field Name
1685 * @param string $key item value
1686 * @return string Label for item entry
1687 */
1688 public static function getLabelFromItemListMerged($pageId, $table, $column, $key)
1689 {
1690 $pageTsConfig = static::getPagesTSconfig($pageId);
1691 $label = '';
1692 if (isset($pageTsConfig['TCEFORM.'])
1693 && \is_array($pageTsConfig['TCEFORM.'])
1694 && \is_array($pageTsConfig['TCEFORM.'][$table . '.'])
1695 && \is_array($pageTsConfig['TCEFORM.'][$table . '.'][$column . '.'])
1696 ) {
1697 if (\is_array($pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['addItems.'])
1698 && isset($pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['addItems.'][$key])
1699 ) {
1700 $label = $pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['addItems.'][$key];
1701 } elseif (\is_array($pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['altLabels.'])
1702 && isset($pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['altLabels.'][$key])
1703 ) {
1704 $label = $pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['altLabels.'][$key];
1705 }
1706 }
1707 if (empty($label)) {
1708 $tcaValue = self::getLabelFromItemlist($table, $column, $key);
1709 if (!empty($tcaValue)) {
1710 $label = $tcaValue;
1711 }
1712 }
1713 return $label;
1714 }
1715
1716 /**
1717 * Splits the given key with commas and returns the list of all the localized items labels, separated by a comma.
1718 * NOTE: this does not take itemsProcFunc into account
1719 *
1720 * @param string $table Table name, present in TCA
1721 * @param string $column Field name
1722 * @param string $keyList Key or comma-separated list of keys.
1723 * @param array $columnTsConfig page TSConfig for $column (TCEMAIN.<table>.<column>)
1724 * @return string Comma-separated list of localized labels
1725 */
1726 public static function getLabelsFromItemsList($table, $column, $keyList, array $columnTsConfig = [])
1727 {
1728 // Check if there is an "items" array
1729 if (
1730 !isset($GLOBALS['TCA'][$table]['columns'][$column]['config']['items'])
1731 || !is_array($GLOBALS['TCA'][$table]['columns'][$column]['config']['items'])
1732 || $keyList === ''
1733 ) {
1734 return '';
1735 }
1736
1737 $keys = GeneralUtility::trimExplode(',', $keyList, true);
1738 $labels = [];
1739 // Loop on all selected values
1740 foreach ($keys as $key) {
1741 $label = null;
1742 if ($columnTsConfig) {
1743 // Check if label has been defined or redefined via pageTsConfig
1744 if (isset($columnTsConfig['addItems.'][$key])) {
1745 $label = $columnTsConfig['addItems.'][$key];
1746 } elseif (isset($columnTsConfig['altLabels.'][$key])) {
1747 $label = $columnTsConfig['altLabels.'][$key];
1748 }
1749 }
1750 if ($label === null) {
1751 // Otherwise lookup the label in TCA items list
1752 foreach ($GLOBALS['TCA'][$table]['columns'][$column]['config']['items'] as $itemConfiguration) {
1753 list($currentLabel, $currentKey) = $itemConfiguration;
1754 if ((string)$key === (string)$currentKey) {
1755 $label = $currentLabel;
1756 break;
1757 }
1758 }
1759 }
1760 if ($label !== null) {
1761 $labels[] = static::getLanguageService()->sL($label);
1762 }
1763 }
1764 return implode(', ', $labels);
1765 }
1766
1767 /**
1768 * Returns the label-value for fieldname $col in table, $table
1769 * 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>'
1770 *
1771 * @param string $table Table name, present in $GLOBALS['TCA']
1772 * @param string $col Field name
1773 * @return string or NULL if $col is not found in the TCA table
1774 */
1775 public static function getItemLabel($table, $col)
1776 {
1777 // Check if column exists
1778 if (is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'][$col])) {
1779 return $GLOBALS['TCA'][$table]['columns'][$col]['label'];
1780 }
1781
1782 return null;
1783 }
1784
1785 /**
1786 * Returns the "title"-value in record, $row, from table, $table
1787 * The field(s) from which the value is taken is determined by the "ctrl"-entries 'label', 'label_alt' and 'label_alt_force'
1788 *
1789 * @param string $table Table name, present in TCA
1790 * @param array $row Row from table
1791 * @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
1792 * @param bool $forceResult If set, the function always returns an output. If no value is found for the title, '[No title]' is returned (localized).
1793 * @return string
1794 */
1795 public static function getRecordTitle($table, $row, $prep = false, $forceResult = true)
1796 {
1797 $recordTitle = '';
1798 if (isset($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table])) {
1799 // If configured, call userFunc
1800 if (!empty($GLOBALS['TCA'][$table]['ctrl']['label_userFunc'])) {
1801 $params['table'] = $table;
1802 $params['row'] = $row;
1803 $params['title'] = '';
1804 $params['options'] = $GLOBALS['TCA'][$table]['ctrl']['label_userFunc_options'] ?? [];
1805
1806 // Create NULL-reference
1807 $null = null;
1808 GeneralUtility::callUserFunction($GLOBALS['TCA'][$table]['ctrl']['label_userFunc'], $params, $null);
1809 $recordTitle = $params['title'];
1810 } else {
1811 // No userFunc: Build label
1812 $recordTitle = self::getProcessedValue(
1813 $table,
1814 $GLOBALS['TCA'][$table]['ctrl']['label'],
1815 $row[$GLOBALS['TCA'][$table]['ctrl']['label']],
1816 0,
1817 0,
1818 false,
1819 $row['uid'],
1820 $forceResult
1821 );
1822 if (!empty($GLOBALS['TCA'][$table]['ctrl']['label_alt'])
1823 && (!empty($GLOBALS['TCA'][$table]['ctrl']['label_alt_force']) || (string)$recordTitle === '')
1824 ) {
1825 $altFields = GeneralUtility::trimExplode(',', $GLOBALS['TCA'][$table]['ctrl']['label_alt'], true);
1826 $tA = [];
1827 if (!empty($recordTitle)) {
1828 $tA[] = $recordTitle;
1829 }
1830 foreach ($altFields as $fN) {
1831 $recordTitle = trim(strip_tags($row[$fN]));
1832 if ((string)$recordTitle !== '') {
1833 $recordTitle = self::getProcessedValue($table, $fN, $recordTitle, 0, 0, false, $row['uid']);
1834 if (!$GLOBALS['TCA'][$table]['ctrl']['label_alt_force']) {
1835 break;
1836 }
1837 $tA[] = $recordTitle;
1838 }
1839 }
1840 if ($GLOBALS['TCA'][$table]['ctrl']['label_alt_force']) {
1841 $recordTitle = implode(', ', $tA);
1842 }
1843 }
1844 }
1845 // If the current result is empty, set it to '[No title]' (localized) and prepare for output if requested
1846 if ($prep || $forceResult) {
1847 if ($prep) {
1848 $recordTitle = self::getRecordTitlePrep($recordTitle);
1849 }
1850 if (trim($recordTitle) === '') {
1851 $recordTitle = self::getNoRecordTitle($prep);
1852 }
1853 }
1854 }
1855
1856 return $recordTitle;
1857 }
1858
1859 /**
1860 * Crops a title string to a limited length and if it really was cropped, wrap it in a <span title="...">|</span>,
1861 * which offers a tooltip with the original title when moving mouse over it.
1862 *
1863 * @param string $title The title string to be cropped
1864 * @param int $titleLength Crop title after this length - if not set, BE_USER->uc['titleLen'] is used
1865 * @return string The processed title string, wrapped in <span title="...">|</span> if cropped
1866 */
1867 public static function getRecordTitlePrep($title, $titleLength = 0)
1868 {
1869 // If $titleLength is not a valid positive integer, use BE_USER->uc['titleLen']:
1870 if (!$titleLength || !MathUtility::canBeInterpretedAsInteger($titleLength) || $titleLength < 0) {
1871 $titleLength = static::getBackendUserAuthentication()->uc['titleLen'];
1872 }
1873 $titleOrig = htmlspecialchars($title);
1874 $title = htmlspecialchars(GeneralUtility::fixed_lgd_cs($title, $titleLength));
1875 // If title was cropped, offer a tooltip:
1876 if ($titleOrig != $title) {
1877 $title = '<span title="' . $titleOrig . '">' . $title . '</span>';
1878 }
1879 return $title;
1880 }
1881
1882 /**
1883 * Get a localized [No title] string, wrapped in <em>|</em> if $prep is TRUE.
1884 *
1885 * @param bool $prep Wrap result in <em>|</em>
1886 * @return string Localized [No title] string
1887 */
1888 public static function getNoRecordTitle($prep = false)
1889 {
1890 $noTitle = '[' .
1891 htmlspecialchars(static::getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.no_title'))
1892 . ']';
1893 if ($prep) {
1894 $noTitle = '<em>' . $noTitle . '</em>';
1895 }
1896 return $noTitle;
1897 }
1898
1899 /**
1900 * Returns a human readable output of a value from a record
1901 * 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.
1902 * $table/$col is tablename and fieldname
1903 * REMEMBER to pass the output through htmlspecialchars() if you output it to the browser! (To protect it from XSS attacks and be XHTML compliant)
1904 *
1905 * @param string $table Table name, present in TCA
1906 * @param string $col Field name, present in TCA
1907 * @param string $value The value of that field from a selected record
1908 * @param int $fixed_lgd_chars The max amount of characters the value may occupy
1909 * @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")
1910 * @param bool $noRecordLookup If set, no records will be looked up, UIDs are just shown.
1911 * @param int $uid Uid of the current record
1912 * @param bool $forceResult If BackendUtility::getRecordTitle is used to process the value, this parameter is forwarded.
1913 * @param int $pid Optional page uid is used to evaluate page TSConfig for the given field
1914 * @throws \InvalidArgumentException
1915 * @return string|null
1916 */
1917 public static function getProcessedValue(
1918 $table,
1919 $col,
1920 $value,
1921 $fixed_lgd_chars = 0,
1922 $defaultPassthrough = false,
1923 $noRecordLookup = false,
1924 $uid = 0,
1925 $forceResult = true,
1926 $pid = 0
1927 ) {
1928 if ($col === 'uid') {
1929 // uid is not in TCA-array
1930 return $value;
1931 }
1932 // Check if table and field is configured
1933 if (!isset($GLOBALS['TCA'][$table]['columns'][$col]) || !is_array($GLOBALS['TCA'][$table]['columns'][$col])) {
1934 return null;
1935 }
1936 // Depending on the fields configuration, make a meaningful output value.
1937 $theColConf = $GLOBALS['TCA'][$table]['columns'][$col]['config'] ?? [];
1938 /*****************
1939 *HOOK: pre-processing the human readable output from a record
1940 ****************/
1941 $null = null;
1942 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['preProcessValue'] ?? [] as $_funcRef) {
1943 GeneralUtility::callUserFunction($_funcRef, $theColConf, $null);
1944 }
1945
1946 $l = '';
1947 $lang = static::getLanguageService();
1948 switch ((string)($theColConf['type'] ?? '')) {
1949 case 'radio':
1950 $l = self::getLabelFromItemlist($table, $col, $value);
1951 $l = $lang->sL($l);
1952 break;
1953 case 'inline':
1954 case 'select':
1955 if (!empty($theColConf['MM'])) {
1956 if ($uid) {
1957 // Display the title of MM related records in lists
1958 if ($noRecordLookup) {
1959 $MMfields = [];
1960 $MMfields[] = $theColConf['foreign_table'] . '.uid';
1961 } else {
1962 $MMfields = [$theColConf['foreign_table'] . '.' . $GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label']];
1963 if (isset($GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label_alt'])) {
1964 foreach (GeneralUtility::trimExplode(
1965 ',',
1966 $GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label_alt'],
1967 true
1968 ) as $f) {
1969 $MMfields[] = $theColConf['foreign_table'] . '.' . $f;
1970 }
1971 }
1972 }
1973 /** @var RelationHandler $dbGroup */
1974 $dbGroup = GeneralUtility::makeInstance(RelationHandler::class);
1975 $dbGroup->start(
1976 $value,
1977 $theColConf['foreign_table'],
1978 $theColConf['MM'],
1979 $uid,
1980 $table,
1981 $theColConf
1982 );
1983 $selectUids = $dbGroup->tableArray[$theColConf['foreign_table']];
1984 if (is_array($selectUids) && !empty($selectUids)) {
1985 $queryBuilder = static::getQueryBuilderForTable($theColConf['foreign_table']);
1986 $queryBuilder->getRestrictions()
1987 ->removeAll()
1988 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1989
1990 $result = $queryBuilder
1991 ->select('uid', ...$MMfields)
1992 ->from($theColConf['foreign_table'])
1993 ->where(
1994 $queryBuilder->expr()->in(
1995 'uid',
1996 $queryBuilder->createNamedParameter($selectUids, Connection::PARAM_INT_ARRAY)
1997 )
1998 )
1999 ->execute();
2000
2001 $mmlA = [];
2002 while ($MMrow = $result->fetch()) {
2003 // Keep sorting of $selectUids
2004 $selectedUid = array_search($MMrow['uid'], $selectUids);
2005 $mmlA[$selectedUid] = $MMrow['uid'];
2006 if (!$noRecordLookup) {
2007 $mmlA[$selectedUid] = static::getRecordTitle(
2008 $theColConf['foreign_table'],
2009 $MMrow,
2010 false,
2011 $forceResult
2012 );
2013 }
2014 }
2015
2016 if (!empty($mmlA)) {
2017 ksort($mmlA);
2018 $l = implode('; ', $mmlA);
2019 } else {
2020 $l = 'N/A';
2021 }
2022 } else {
2023 $l = 'N/A';
2024 }
2025 } else {
2026 $l = 'N/A';
2027 }
2028 } else {
2029 $columnTsConfig = [];
2030 if ($pid) {
2031 $pageTsConfig = self::getPagesTSconfig($pid);
2032 if (isset($pageTsConfig['TCEFORM.'][$table . '.'][$col . '.']) && is_array($pageTsConfig['TCEFORM.'][$table . '.'][$col . '.'])) {
2033 $columnTsConfig = $pageTsConfig['TCEFORM.'][$table . '.'][$col . '.'];
2034 }
2035 }
2036 $l = self::getLabelsFromItemsList($table, $col, $value, $columnTsConfig);
2037 if (!empty($theColConf['foreign_table']) && !$l && !empty($GLOBALS['TCA'][$theColConf['foreign_table']])) {
2038 if ($noRecordLookup) {
2039 $l = $value;
2040 } else {
2041 $rParts = [];
2042 if ($uid && isset($theColConf['foreign_field']) && $theColConf['foreign_field'] !== '') {
2043 $queryBuilder = static::getQueryBuilderForTable($theColConf['foreign_table']);
2044 $queryBuilder->getRestrictions()
2045 ->removeAll()
2046 ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
2047 ->add(GeneralUtility::makeInstance(BackendWorkspaceRestriction::class));
2048 $constraints = [
2049 $queryBuilder->expr()->eq(
2050 $theColConf['foreign_field'],
2051 $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
2052 )
2053 ];
2054
2055 if (!empty($theColConf['foreign_table_field'])) {
2056 $constraints[] = $queryBuilder->expr()->eq(
2057 $theColConf['foreign_table_field'],
2058 $queryBuilder->createNamedParameter($table, \PDO::PARAM_STR)
2059 );
2060 }
2061
2062 // Add additional where clause if foreign_match_fields are defined
2063 $foreignMatchFields = [];
2064 if (is_array($theColConf['foreign_match_fields'])) {
2065 $foreignMatchFields = $theColConf['foreign_match_fields'];
2066 }
2067
2068 foreach ($foreignMatchFields as $matchField => $matchValue) {
2069 $constraints[] = $queryBuilder->expr()->eq(
2070 $matchField,
2071 $queryBuilder->createNamedParameter($matchValue)
2072 );
2073 }
2074
2075 $result = $queryBuilder
2076 ->select('*')
2077 ->from($theColConf['foreign_table'])
2078 ->where(...$constraints)
2079 ->execute();
2080
2081 while ($record = $result->fetch()) {
2082 $rParts[] = $record['uid'];
2083 }
2084 }
2085 if (empty($rParts)) {
2086 $rParts = GeneralUtility::trimExplode(',', $value, true);
2087 }
2088 $lA = [];
2089 foreach ($rParts as $rVal) {
2090 $rVal = (int)$rVal;
2091 $r = self::getRecordWSOL($theColConf['foreign_table'], $rVal);
2092 if (is_array($r)) {
2093 $lA[] = $lang->sL($theColConf['foreign_table_prefix'])
2094 . self::getRecordTitle($theColConf['foreign_table'], $r, false, $forceResult);
2095 } else {
2096 $lA[] = $rVal ? '[' . $rVal . '!]' : '';
2097 }
2098 }
2099 $l = implode(', ', $lA);
2100 }
2101 }
2102 if (empty($l) && !empty($value)) {
2103 // Use plain database value when label is empty
2104 $l = $value;
2105 }
2106 }
2107 break;
2108 case 'group':
2109 // resolve the titles for DB records
2110 if (isset($theColConf['internal_type']) && $theColConf['internal_type'] === 'db') {
2111 if (isset($theColConf['MM']) && $theColConf['MM']) {
2112 if ($uid) {
2113 // Display the title of MM related records in lists
2114 if ($noRecordLookup) {
2115 $MMfields = [];
2116 $MMfields[] = $theColConf['foreign_table'] . '.uid';
2117 } else {
2118 $MMfields = [$theColConf['foreign_table'] . '.' . $GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label']];
2119 $altLabelFields = explode(
2120 ',',
2121 $GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label_alt']
2122 );
2123 foreach ($altLabelFields as $f) {
2124 $f = trim($f);
2125 if ($f !== '') {
2126 $MMfields[] = $theColConf['foreign_table'] . '.' . $f;
2127 }
2128 }
2129 }
2130 /** @var RelationHandler $dbGroup */
2131 $dbGroup = GeneralUtility::makeInstance(RelationHandler::class);
2132 $dbGroup->start(
2133 $value,
2134 $theColConf['foreign_table'],
2135 $theColConf['MM'],
2136 $uid,
2137 $table,
2138 $theColConf
2139 );
2140 $selectUids = $dbGroup->tableArray[$theColConf['foreign_table']];
2141 if (!empty($selectUids) && is_array($selectUids)) {
2142 $queryBuilder = static::getQueryBuilderForTable($theColConf['foreign_table']);
2143 $queryBuilder->getRestrictions()
2144 ->removeAll()
2145 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
2146
2147 $result = $queryBuilder
2148 ->select('uid', ...$MMfields)
2149 ->from($theColConf['foreign_table'])
2150 ->where(
2151 $queryBuilder->expr()->in(
2152 'uid',
2153 $queryBuilder->createNamedParameter(
2154 $selectUids,
2155 Connection::PARAM_INT_ARRAY
2156 )
2157 )
2158 )
2159 ->execute();
2160
2161 $mmlA = [];
2162 while ($MMrow = $result->fetch()) {
2163 // Keep sorting of $selectUids
2164 $selectedUid = array_search($MMrow['uid'], $selectUids);
2165 $mmlA[$selectedUid] = $MMrow['uid'];
2166 if (!$noRecordLookup) {
2167 $mmlA[$selectedUid] = static::getRecordTitle(
2168 $theColConf['foreign_table'],
2169 $MMrow,
2170 false,
2171 $forceResult
2172 );
2173 }
2174 }
2175
2176 if (!empty($mmlA)) {
2177 ksort($mmlA);
2178 $l = implode('; ', $mmlA);
2179 } else {
2180 $l = 'N/A';
2181 }
2182 } else {
2183 $l = 'N/A';
2184 }
2185 } else {
2186 $l = 'N/A';
2187 }
2188 } else {
2189 $finalValues = [];
2190 $relationTableName = $theColConf['allowed'];
2191 $explodedValues = GeneralUtility::trimExplode(',', $value, true);
2192
2193 foreach ($explodedValues as $explodedValue) {
2194 if (MathUtility::canBeInterpretedAsInteger($explodedValue)) {
2195 $relationTableNameForField = $relationTableName;
2196 } else {
2197 list($relationTableNameForField, $explodedValue) = self::splitTable_Uid($explodedValue);
2198 }
2199
2200 $relationRecord = static::getRecordWSOL($relationTableNameForField, $explodedValue);
2201 $finalValues[] = static::getRecordTitle($relationTableNameForField, $relationRecord);
2202 }
2203 $l = implode(', ', $finalValues);
2204 }
2205 } else {
2206 $l = implode(', ', GeneralUtility::trimExplode(',', $value, true));
2207 }
2208 break;
2209 case 'check':
2210 if (!is_array($theColConf['items'])) {
2211 $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');
2212 } elseif (count($theColConf['items']) === 1) {
2213 reset($theColConf['items']);
2214 $invertStateDisplay = current($theColConf['items'])['invertStateDisplay'] ?? false;
2215 if ($invertStateDisplay) {
2216 $value = !$value;
2217 }
2218 $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');
2219 } else {
2220 $lA = [];
2221 foreach ($theColConf['items'] as $key => $val) {
2222 if ($value & pow(2, $key)) {
2223 $lA[] = $lang->sL($val[0]);
2224 }
2225 }
2226 $l = implode(', ', $lA);
2227 }
2228 break;
2229 case 'input':
2230 // Hide value 0 for dates, but show it for everything else
2231 if (isset($value)) {
2232 $dateTimeFormats = QueryHelper::getDateTimeFormats();
2233
2234 if (GeneralUtility::inList($theColConf['eval'] ?? '', 'date')) {
2235 // Handle native date field
2236 if (isset($theColConf['dbType']) && $theColConf['dbType'] === 'date') {
2237 $value = $value === $dateTimeFormats['date']['empty'] ? 0 : (int)strtotime($value);
2238 } else {
2239 $value = (int)$value;
2240 }
2241 if (!empty($value)) {
2242 $ageSuffix = '';
2243 $dateColumnConfiguration = $GLOBALS['TCA'][$table]['columns'][$col]['config'];
2244 $ageDisplayKey = 'disableAgeDisplay';
2245
2246 // generate age suffix as long as not explicitly suppressed
2247 if (!isset($dateColumnConfiguration[$ageDisplayKey])
2248 // non typesafe comparison on intention
2249 || $dateColumnConfiguration[$ageDisplayKey] == false
2250 ) {
2251 $ageSuffix = ' (' . ($GLOBALS['EXEC_TIME'] - $value > 0 ? '-' : '')
2252 . self::calcAge(
2253 abs($GLOBALS['EXEC_TIME'] - $value),
2254 $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.minutesHoursDaysYears')
2255 )
2256 . ')';
2257 }
2258
2259 $l = self::date($value) . $ageSuffix;
2260 }
2261 } elseif (GeneralUtility::inList($theColConf['eval'] ?? '', 'time')) {
2262 // Handle native time field
2263 if (isset($theColConf['dbType']) && $theColConf['dbType'] === 'time') {
2264 $value = $value === $dateTimeFormats['time']['empty'] ? 0 : (int)strtotime('1970-01-01 ' . $value);
2265 } else {
2266 $value = (int)$value;
2267 }
2268 if (!empty($value)) {
2269 $l = gmdate('H:i', (int)$value);
2270 }
2271 } elseif (GeneralUtility::inList($theColConf['eval'] ?? '', 'timesec')) {
2272 // Handle native time field
2273 if (isset($theColConf['dbType']) && $theColConf['dbType'] === 'time') {
2274 $value = $value === $dateTimeFormats['time']['empty'] ? 0 : (int)strtotime('1970-01-01 ' . $value);
2275 } else {
2276 $value = (int)$value;
2277 }
2278 if (!empty($value)) {
2279 $l = gmdate('H:i:s', (int)$value);
2280 }
2281 } elseif (GeneralUtility::inList($theColConf['eval'] ?? '', 'datetime')) {
2282 // Handle native datetime field
2283 if (isset($theColConf['dbType']) && $theColConf['dbType'] === 'datetime') {
2284 $value = $value === $dateTimeFormats['datetime']['empty'] ? 0 : (int)strtotime($value);
2285 } else {
2286 $value = (int)$value;
2287 }
2288 if (!empty($value)) {
2289 $l = self::datetime($value);
2290 }
2291 } else {
2292 $l = $value;
2293 }
2294 }
2295 break;
2296 case 'flex':
2297 $l = strip_tags($value);
2298 break;
2299 default:
2300 if ($defaultPassthrough) {
2301 $l = $value;
2302 } elseif (isset($theColConf['MM'])) {
2303 $l = 'N/A';
2304 } elseif ($value) {
2305 $l = GeneralUtility::fixed_lgd_cs(strip_tags($value), 200);
2306 }
2307 }
2308 // If this field is a password field, then hide the password by changing it to a random number of asterisk (*)
2309 if (!empty($theColConf['eval']) && stristr($theColConf['eval'], 'password')) {
2310 $l = '';
2311 $randomNumber = rand(5, 12);
2312 for ($i = 0; $i < $randomNumber; $i++) {
2313 $l .= '*';
2314 }
2315 }
2316 /*****************
2317 *HOOK: post-processing the human readable output from a record
2318 ****************/
2319 $null = null;
2320 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['postProcessValue'] ?? [] as $_funcRef) {
2321 $params = [
2322 'value' => $l,
2323 'colConf' => $theColConf
2324 ];
2325 $l = GeneralUtility::callUserFunction($_funcRef, $params, $null);
2326 }
2327 if ($fixed_lgd_chars) {
2328 return GeneralUtility::fixed_lgd_cs($l, $fixed_lgd_chars);
2329 }
2330 return $l;
2331 }
2332
2333 /**
2334 * 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.
2335 *
2336 * @param string $table Table name, present in TCA
2337 * @param string $fN Field name
2338 * @param string $fV Field value
2339 * @param int $fixed_lgd_chars The max amount of characters the value may occupy
2340 * @param int $uid Uid of the current record
2341 * @param bool $forceResult If BackendUtility::getRecordTitle is used to process the value, this parameter is forwarded.
2342 * @param int $pid Optional page uid is used to evaluate page TSConfig for the given field
2343 * @return string
2344 * @see getProcessedValue()
2345 */
2346 public static function getProcessedValueExtra(
2347 $table,
2348 $fN,
2349 $fV,
2350 $fixed_lgd_chars = 0,
2351 $uid = 0,
2352 $forceResult = true,
2353 $pid = 0
2354 ) {
2355 $fVnew = self::getProcessedValue($table, $fN, $fV, $fixed_lgd_chars, 1, 0, $uid, $forceResult, $pid);
2356 if (!isset($fVnew)) {
2357 if (is_array($GLOBALS['TCA'][$table])) {
2358 if ($fN == $GLOBALS['TCA'][$table]['ctrl']['tstamp'] || $fN == $GLOBALS['TCA'][$table]['ctrl']['crdate']) {
2359 $fVnew = self::datetime($fV);
2360 } elseif ($fN === 'pid') {
2361 // Fetches the path with no regard to the users permissions to select pages.
2362 $fVnew = self::getRecordPath($fV, '1=1', 20);
2363 } else {
2364 $fVnew = $fV;
2365 }
2366 }
2367 }
2368 return $fVnew;
2369 }
2370
2371 /**
2372 * Returns fields for a table, $table, which would typically be interesting to select
2373 * This includes uid, the fields defined for title, icon-field.
2374 * 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)
2375 *
2376 * @param string $table Table name, present in $GLOBALS['TCA']
2377 * @param string $prefix Table prefix
2378 * @param array $fields Preset fields (must include prefix if that is used)
2379 * @return string List of fields.
2380 */
2381 public static function getCommonSelectFields($table, $prefix = '', $fields = [])
2382 {
2383 $fields[] = $prefix . 'uid';
2384 if (isset($GLOBALS['TCA'][$table]['ctrl']['label']) && $GLOBALS['TCA'][$table]['ctrl']['label'] != '') {
2385 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['label'];
2386 }
2387 if (!empty($GLOBALS['TCA'][$table]['ctrl']['label_alt'])) {
2388 $secondFields = GeneralUtility::trimExplode(',', $GLOBALS['TCA'][$table]['ctrl']['label_alt'], true);
2389 foreach ($secondFields as $fieldN) {
2390 $fields[] = $prefix . $fieldN;
2391 }
2392 }
2393 if (static::isTableWorkspaceEnabled($table)) {
2394 $fields[] = $prefix . 't3ver_id';
2395 $fields[] = $prefix . 't3ver_state';
2396 $fields[] = $prefix . 't3ver_wsid';
2397 $fields[] = $prefix . 't3ver_count';
2398 }
2399 if (!empty($GLOBALS['TCA'][$table]['ctrl']['selicon_field'])) {
2400 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['selicon_field'];
2401 }
2402 if (!empty($GLOBALS['TCA'][$table]['ctrl']['typeicon_column'])) {
2403 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['typeicon_column'];
2404 }
2405 if (!empty($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['disabled'])) {
2406 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['disabled'];
2407 }
2408 if (!empty($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['starttime'])) {
2409 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['starttime'];
2410 }
2411 if (!empty($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['endtime'])) {
2412 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['endtime'];
2413 }
2414 if (!empty($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['fe_group'])) {
2415 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['fe_group'];
2416 }
2417 return implode(',', array_unique($fields));
2418 }
2419
2420 /*******************************************
2421 *
2422 * Backend Modules API functions
2423 *
2424 *******************************************/
2425
2426 /**
2427 * Returns CSH help text (description), if configured for, as an array (title, description)
2428 *
2429 * @param string $table Table name
2430 * @param string $field Field name
2431 * @return array With keys 'description' (raw, as available in locallang), 'title' (optional), 'moreInfo'
2432 */
2433 public static function helpTextArray($table, $field)
2434 {
2435 if (!isset($GLOBALS['TCA_DESCR'][$table]['columns'])) {
2436 static::getLanguageService()->loadSingleTableDescription($table);
2437 }
2438 $output = [
2439 'description' => null,
2440 'title' => null,
2441 'moreInfo' => false
2442 ];
2443 if (isset($GLOBALS['TCA_DESCR'][$table]['columns'][$field]) && is_array($GLOBALS['TCA_DESCR'][$table]['columns'][$field])) {
2444 $data = $GLOBALS['TCA_DESCR'][$table]['columns'][$field];
2445 // Add alternative title, if defined
2446 if ($data['alttitle']) {
2447 $output['title'] = $data['alttitle'];
2448 }
2449 // If we have more information to show and access to the cshmanual
2450 if (($data['image_descr'] || $data['seeAlso'] || $data['details'] || $data['syntax'])
2451 && static::getBackendUserAuthentication()->check('modules', 'help_CshmanualCshmanual')
2452 ) {
2453 $output['moreInfo'] = true;
2454 }
2455 // Add description
2456 if ($data['description']) {
2457 $output['description'] = $data['description'];
2458 }
2459 }
2460 return $output;
2461 }
2462
2463 /**
2464 * Returns CSH help text
2465 *
2466 * @param string $table Table name
2467 * @param string $field Field name
2468 * @return string HTML content for help text
2469 * @see cshItem()
2470 */
2471 public static function helpText($table, $field)
2472 {
2473 $helpTextArray = self::helpTextArray($table, $field);
2474 $output = '';
2475 $arrow = '';
2476 // Put header before the rest of the text
2477 if ($helpTextArray['title'] !== null) {
2478 $output .= '<h2>' . $helpTextArray['title'] . '</h2>';
2479 }
2480 // Add see also arrow if we have more info
2481 if ($helpTextArray['moreInfo']) {
2482 /** @var IconFactory $iconFactory */
2483 $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
2484 $arrow = $iconFactory->getIcon('actions-view-go-forward', Icon::SIZE_SMALL)->render();
2485 }
2486 // Wrap description and arrow in p tag
2487 if ($helpTextArray['description'] !== null || $arrow) {
2488 $output .= '<p class="t3-help-short">' . nl2br(htmlspecialchars($helpTextArray['description'])) . $arrow . '</p>';
2489 }
2490 return $output;
2491 }
2492
2493 /**
2494 * API function that wraps the text / html in help text, so if a user hovers over it
2495 * the help text will show up
2496 *
2497 * @param string $table The table name for which the help should be shown
2498 * @param string $field The field name for which the help should be shown
2499 * @param string $text The text which should be wrapped with the help text
2500 * @param array $overloadHelpText Array with text to overload help text
2501 * @return string the HTML code ready to render
2502 */
2503 public static function wrapInHelp($table, $field, $text = '', array $overloadHelpText = [])
2504 {
2505 // Initialize some variables
2506 $helpText = '';
2507 $abbrClassAdd = '';
2508 $hasHelpTextOverload = !empty($overloadHelpText);
2509 // Get the help text that should be shown on hover
2510 if (!$hasHelpTextOverload) {
2511 $helpText = self::helpText($table, $field);
2512 }
2513 // If there's a help text or some overload information, proceed with preparing an output
2514 if (!empty($helpText) || $hasHelpTextOverload) {
2515 // If no text was given, just use the regular help icon
2516 if ($text == '') {
2517 $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
2518 $text = $iconFactory->getIcon('actions-system-help-open', Icon::SIZE_SMALL)->render();
2519 $abbrClassAdd = '-icon';
2520 }
2521 $text = '<abbr class="t3-help-teaser' . $abbrClassAdd . '">' . $text . '</abbr>';
2522 $wrappedText = '<span class="t3-help-link" href="#" data-table="' . $table . '" data-field="' . $field . '"';
2523 // The overload array may provide a title and a description
2524 // If either one is defined, add them to the "data" attributes
2525 if ($hasHelpTextOverload) {
2526 if (isset($overloadHelpText['title'])) {
2527 $wrappedText .= ' data-title="' . htmlspecialchars($overloadHelpText['title']) . '"';
2528 }
2529 if (isset($overloadHelpText['description'])) {
2530 $wrappedText .= ' data-description="' . htmlspecialchars($overloadHelpText['description']) . '"';
2531 }
2532 }
2533 $wrappedText .= '>' . $text . '</span>';
2534 return $wrappedText;
2535 }
2536 return $text;
2537 }
2538
2539 /**
2540 * API for getting CSH icons/text for use in backend modules.
2541 * TCA_DESCR will be loaded if it isn't already
2542 *
2543 * @param string $table Table name ('_MOD_'+module name)
2544 * @param string $field Field name (CSH locallang main key)
2545 * @param string $_ (unused)
2546 * @param string $wrap Wrap code for icon-mode, splitted by "|". Not used for full-text mode.
2547 * @return string HTML content for help text
2548 */
2549 public static function cshItem($table, $field, $_ = '', $wrap = '')
2550 {
2551 static::getLanguageService()->loadSingleTableDescription($table);
2552 if (is_array($GLOBALS['TCA_DESCR'][$table])
2553 && is_array($GLOBALS['TCA_DESCR'][$table]['columns'][$field])
2554 ) {
2555 // Creating short description
2556 $output = self::wrapInHelp($table, $field);
2557 if ($output && $wrap) {
2558 $wrParts = explode('|', $wrap);
2559 $output = $wrParts[0] . $output . $wrParts[1];
2560 }
2561 return $output;
2562 }
2563 return '';
2564 }
2565
2566 /**
2567 * 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.
2568 * REMEMBER to always htmlspecialchar() content in href-properties to ampersands get converted to entities (XHTML requirement and XSS precaution)
2569 *
2570 * @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.
2571 * @param string $_ (unused)
2572 * @param string $requestUri An optional returnUrl you can set - automatically set to REQUEST_URI.
2573 *
2574 * @return string
2575 */
2576 public static function editOnClick($params, $_ = '', $requestUri = '')
2577 {
2578 if ($requestUri == -1) {
2579 $returnUrl = 'T3_THIS_LOCATION';
2580 } else {
2581 $returnUrl = GeneralUtility::quoteJSvalue(rawurlencode($requestUri ?: GeneralUtility::getIndpEnv('REQUEST_URI')));
2582 }
2583 $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
2584 return 'window.location.href=' . GeneralUtility::quoteJSvalue((string)$uriBuilder->buildUriFromRoute('record_edit') . $params . '&returnUrl=') . '+' . $returnUrl . '; return false;';
2585 }
2586
2587 /**
2588 * Returns a JavaScript string for viewing the page id, $id
2589 * It will re-use any window already open.
2590 *
2591 * @param int $pageUid Page UID
2592 * @param string $backPath Must point back to TYPO3_mainDir (where the site is assumed to be one level above)
2593 * @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)
2594 * @param string $anchorSection Optional anchor to the URL
2595 * @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!
2596 * @param string $additionalGetVars Additional GET variables.
2597 * @param bool $switchFocus If TRUE, then the preview window will gain the focus.
2598 * @return string
2599 */
2600 public static function viewOnClick(
2601 $pageUid,
2602 $backPath = '',
2603 $rootLine = null,
2604 $anchorSection = '',
2605 $alternativeUrl = '',
2606 $additionalGetVars = '',
2607 $switchFocus = true
2608 ) {
2609 $previewUrl = self::getPreviewUrl(
2610 $pageUid,
2611 $backPath,
2612 $rootLine,
2613 $anchorSection,
2614 $alternativeUrl,
2615 $additionalGetVars,
2616 $switchFocus
2617 );
2618
2619 $onclickCode = 'var previewWin = window.open(' . GeneralUtility::quoteJSvalue($previewUrl) . ',\'newTYPO3frontendWindow\');'
2620 . ($switchFocus ? 'previewWin.focus();' : '') . LF
2621 . 'if (previewWin.location.href === ' . GeneralUtility::quoteJSvalue($previewUrl) . ') { previewWin.location.reload(); };';
2622
2623 return $onclickCode;
2624 }
2625
2626 /**
2627 * Returns the preview url
2628 *
2629 * It will detect the correct domain name if needed and provide the link with the right back path.
2630 *
2631 * @param int $pageUid Page UID
2632 * @param string $backPath Must point back to TYPO3_mainDir (where the site is assumed to be one level above)
2633 * @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)
2634 * @param string $anchorSection Optional anchor to the URL
2635 * @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!
2636 * @param string $additionalGetVars Additional GET variables.
2637 * @param bool $switchFocus If TRUE, then the preview window will gain the focus.
2638 * @return string
2639 */
2640 public static function getPreviewUrl(
2641 $pageUid,
2642 $backPath = '',
2643 $rootLine = null,
2644 $anchorSection = '',
2645 $alternativeUrl = '',
2646 $additionalGetVars = '',
2647 &$switchFocus = true
2648 ): string {
2649 $viewScript = '/index.php?id=';
2650 if ($alternativeUrl) {
2651 $viewScript = $alternativeUrl;
2652 }
2653
2654 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['viewOnClickClass'] ?? [] as $className) {
2655 $hookObj = GeneralUtility::makeInstance($className);
2656 if (method_exists($hookObj, 'preProcess')) {
2657 $hookObj->preProcess(
2658 $pageUid,
2659 $backPath,
2660 $rootLine,
2661 $anchorSection,
2662 $viewScript,
2663 $additionalGetVars,
2664 $switchFocus
2665 );
2666 }
2667 }
2668
2669 // If there is an alternative URL or the URL has been modified by a hook, use that one.
2670 if ($alternativeUrl || $viewScript !== '/index.php?id=') {
2671 $previewUrl = $viewScript;
2672 } else {
2673 $permissionClause = $GLOBALS['BE_USER']->getPagePermsClause(Permission::PAGE_SHOW);
2674 $pageInfo = self::readPageAccess($pageUid, $permissionClause);
2675 $additionalGetVars .= self::ADMCMD_previewCmds($pageInfo);
2676
2677 // Build the URL with a site as prefix, if configured
2678 $siteFinder = GeneralUtility::makeInstance(SiteFinder::class);
2679 // Check if the page (= its rootline) has a site attached, otherwise just keep the URL as is
2680 $rootLine = $rootLine ?? BackendUtility::BEgetRootLine($pageUid);
2681 try {
2682 $site = $siteFinder->getSiteByPageId((int)$pageUid, $rootLine);
2683 // Create a multi-dimensional array out of the additional get vars
2684 $additionalQueryParams = [];
2685 parse_str($additionalGetVars, $additionalQueryParams);
2686 if (isset($additionalQueryParams['L'])) {
2687 $additionalQueryParams['_language'] = $additionalQueryParams['_language'] ?? $additionalQueryParams['L'];
2688 unset($additionalQueryParams['L']);
2689 }
2690 $previewUrl = (string)$site->getRouter()->generateUri(
2691 $pageUid,
2692 $additionalQueryParams,
2693 $anchorSection,
2694 RouterInterface::ABSOLUTE_URL
2695 );
2696 } catch (SiteNotFoundException | InvalidRouteArgumentsException $e) {
2697 $previewUrl = self::createPreviewUrl($pageUid, $rootLine, $anchorSection, $additionalGetVars, $viewScript);
2698 }
2699 }
2700
2701 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['viewOnClickClass'] ?? [] as $className) {
2702 $hookObj = GeneralUtility::makeInstance($className);
2703 if (method_exists($hookObj, 'postProcess')) {
2704 $previewUrl = $hookObj->postProcess(
2705 $previewUrl,
2706 $pageUid,
2707 $rootLine,
2708 $anchorSection,
2709 $viewScript,
2710 $additionalGetVars,
2711 $switchFocus
2712 );
2713 }
2714 }
2715
2716 return $previewUrl;
2717 }
2718
2719 /**
2720 * Makes click menu link (context sensitive menu)
2721 *
2722 * Returns $str wrapped in a link which will activate the context sensitive
2723 * menu for the record ($table/$uid) or file ($table = file)
2724 * The link will load the top frame with the parameter "&item" which is the table, uid
2725 * and context arguments imploded by "|": rawurlencode($table.'|'.$uid.'|'.$context)
2726 *
2727 * @param string $content String to be wrapped in link, typ. image tag.
2728 * @param string $table Table name/File path. If the icon is for a database
2729 * record, enter the tablename from $GLOBALS['TCA']. If a file then enter
2730 * the absolute filepath
2731 * @param int|string $uid If icon is for database record this is the UID for the
2732 * record from $table or identifier for sys_file record
2733 * @param string $context Set tree if menu is called from tree view
2734 * @param string $_addParams NOT IN USE
2735 * @param string $_enDisItems NOT IN USE
2736 * @param bool $returnTagParameters If set, will return only the onclick
2737 * JavaScript, not the whole link.
2738 *
2739 * @return string The link wrapped input string.
2740 */
2741 public static function wrapClickMenuOnIcon(
2742 $content,
2743 $table,
2744 $uid = 0,
2745 $context = '',
2746 $_addParams = '',
2747 $_enDisItems = '',
2748 $returnTagParameters = false
2749 ) {
2750 $tagParameters = [
2751 'class' => 't3js-contextmenutrigger',
2752 'data-table' => $table,
2753 'data-uid' => $uid,
2754 'data-context' => $context
2755 ];
2756
2757 if ($returnTagParameters) {
2758 return $tagParameters;
2759 }
2760 return '<a href="#" ' . GeneralUtility::implodeAttributes($tagParameters, true) . '>' . $content . '</a>';
2761 }
2762
2763 /**
2764 * Returns a URL with a command to TYPO3 Datahandler
2765 *
2766 * @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
2767 * @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
2768 * @return string URL to BackendUtility::getModuleUrl('tce_db') + parameters
2769 */
2770 public static function getLinkToDataHandlerAction($parameters, $redirectUrl = '')
2771 {
2772 $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
2773 $url = (string)$uriBuilder->buildUriFromRoute('tce_db') . $parameters . '&redirect=';
2774 if ((int)$redirectUrl === -1) {
2775 $url = GeneralUtility::quoteJSvalue($url) . '+T3_THIS_LOCATION';
2776 } else {
2777 $url .= rawurlencode($redirectUrl ?: GeneralUtility::getIndpEnv('REQUEST_URI'));
2778 }
2779 return $url;
2780 }
2781
2782 /**
2783 * Creates the view-on-click preview URL without any alternative URL.
2784 *
2785 * @param int $pageUid Page UID
2786 * @param array $rootLine If rootline is supplied, the function will look for the first found domain record and use that URL instead
2787 * @param string $anchorSection Optional anchor to the URL
2788 * @param string $additionalGetVars Additional GET variables.
2789 * @param string $viewScript The path to the script used to view the page
2790 *
2791 * @return string The preview URL
2792 */
2793 protected static function createPreviewUrl($pageUid, $rootLine, $anchorSection, $additionalGetVars, $viewScript)
2794 {
2795 // Look if a fixed preview language should be added:
2796 $beUser = static::getBackendUserAuthentication();
2797 $viewLanguageOrder = (string)($beUser->getTSConfig()['options.']['view.']['languageOrder'] ?? '');
2798
2799 if (!empty($viewLanguageOrder)) {
2800 $suffix = '';
2801 // Find allowed languages (if none, all are allowed!)
2802 $allowedLanguages = null;
2803 if (!$beUser->isAdmin() && $beUser->groupData['allowed_languages'] !== '') {
2804 $allowedLanguages = array_flip(explode(',', $beUser->groupData['allowed_languages']));
2805 }
2806 // Traverse the view order, match first occurrence:
2807 $languageOrder = GeneralUtility::intExplode(',', $viewLanguageOrder);
2808 foreach ($languageOrder as $langUid) {
2809 if (is_array($allowedLanguages) && !empty($allowedLanguages)) {
2810 // Choose if set.
2811 if (isset($allowedLanguages[$langUid])) {
2812 $suffix = '&L=' . $langUid;
2813 break;
2814 }
2815 } else {
2816 // All allowed since no lang. are listed.
2817 $suffix = '&L=' . $langUid;
2818 break;
2819 }
2820 }
2821 // Add it
2822 $additionalGetVars .= $suffix;
2823 }
2824
2825 // Check a mount point needs to be previewed
2826 $pageRepository = GeneralUtility::makeInstance(PageRepository::class);
2827 $mountPointInfo = $pageRepository->getMountPointInfo($pageUid);
2828
2829 if ($mountPointInfo && $mountPointInfo['overlay']) {
2830 $pageUid = $mountPointInfo['mount_pid'];
2831 $additionalGetVars .= '&MP=' . $mountPointInfo['MPvar'];
2832 }
2833 $viewDomain = self::getViewDomain($pageUid, $rootLine);
2834
2835 return $viewDomain . $viewScript . $pageUid . $additionalGetVars . $anchorSection;
2836 }
2837
2838 /**
2839 * Builds the frontend view domain for a given page ID with a given root
2840 * line.
2841 *
2842 * @param int $pageId The page ID to use, must be > 0
2843 * @param array|null $rootLine The root line structure to use
2844 * @return string The full domain including the protocol http:// or https://, but without the trailing '/'
2845 */
2846 public static function getViewDomain($pageId, $rootLine = null)
2847 {
2848 $domain = rtrim(GeneralUtility::getIndpEnv('TYPO3_SITE_URL'), '/');
2849 if (!is_array($rootLine)) {
2850 $rootLine = self::BEgetRootLine($pageId);
2851 }
2852 // Checks alternate domains
2853 if (!empty($rootLine)) {
2854 $protocol = GeneralUtility::getIndpEnv('TYPO3_SSL') ? 'https' : 'http';
2855 $previewDomainConfig = self::getPagesTSconfig($pageId)['TCEMAIN.']['previewDomain'] ?? '';
2856 $domainName = null;
2857 if (!empty($previewDomainConfig)) {
2858 if (strpos($previewDomainConfig, '://') !== false) {
2859 list($protocol, $domainName) = explode('://', $previewDomainConfig);
2860 } else {
2861 $domainName = $previewDomainConfig;
2862 }
2863 } else {
2864 $domainResolver = GeneralUtility::makeInstance(LegacyDomainResolver::class);
2865 foreach ($rootLine as $row) {
2866 $domainRecord = $domainResolver->matchRootPageId((int)$row['uid']);
2867 if (is_array($domainRecord)) {
2868 $domainName = rtrim($domainRecord['domainName'], '/');
2869 break;
2870 }
2871 }
2872 }