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