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