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