[BUGFIX] Fix broken reload of save+preview links
[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 // Pages still stores translations in the pages_language_overlay table, all other tables store in themself
306 if ($table === 'pages') {
307 $table = 'pages_language_overlay';
308 }
309
310 if (self::isTableLocalizable($table)) {
311 $tcaCtrl = $GLOBALS['TCA'][$table]['ctrl'];
312
313 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
314 ->getQueryBuilderForTable($table);
315 $queryBuilder->getRestrictions()
316 ->removeAll()
317 ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
318 ->add(GeneralUtility::makeInstance(BackendWorkspaceRestriction::class));
319
320 $queryBuilder->select('*')
321 ->from($table)
322 ->where(
323 $queryBuilder->expr()->eq(
324 $tcaCtrl['transOrigPointerField'],
325 $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
326 ),
327 $queryBuilder->expr()->eq(
328 $tcaCtrl['languageField'],
329 $queryBuilder->createNamedParameter((int)$language, \PDO::PARAM_INT)
330 )
331 )
332 ->setMaxResults(1);
333
334 if ($andWhereClause) {
335 $queryBuilder->andWhere(QueryHelper::stripLogicalOperatorPrefix($andWhereClause));
336 }
337
338 $recordLocalization = $queryBuilder->execute()->fetchAll();
339 }
340
341 return $recordLocalization;
342 }
343
344 /*******************************************
345 *
346 * Page tree, TCA related
347 *
348 *******************************************/
349 /**
350 * Returns what is called the 'RootLine'. That is an array with information about the page records from a page id
351 * ($uid) and back to the root.
352 * By default deleted pages are filtered.
353 * This RootLine will follow the tree all the way to the root. This is opposite to another kind of root line known
354 * from the frontend where the rootline stops when a root-template is found.
355 *
356 * @param int $uid Page id for which to create the root line.
357 * @param string $clause Clause can be used to select other criteria. It would typically be where-clauses that
358 * stops the process if we meet a page, the user has no reading access to.
359 * @param bool $workspaceOL If TRUE, version overlay is applied. This must be requested specifically because it is
360 * usually only wanted when the rootline is used for visual output while for permission checking you want the raw thing!
361 * @return array Root line array, all the way to the page tree root (or as far as $clause allows!)
362 */
363 public static function BEgetRootLine($uid, $clause = '', $workspaceOL = false)
364 {
365 static $BEgetRootLine_cache = [];
366 $output = [];
367 $pid = $uid;
368 $ident = $pid . '-' . $clause . '-' . $workspaceOL;
369 if (is_array($BEgetRootLine_cache[$ident])) {
370 $output = $BEgetRootLine_cache[$ident];
371 } else {
372 $loopCheck = 100;
373 $theRowArray = [];
374 while ($uid != 0 && $loopCheck) {
375 $loopCheck--;
376 $row = self::getPageForRootline($uid, $clause, $workspaceOL);
377 if (is_array($row)) {
378 $uid = $row['pid'];
379 $theRowArray[] = $row;
380 } else {
381 break;
382 }
383 }
384 if ($uid == 0) {
385 $theRowArray[] = ['uid' => 0, 'title' => ''];
386 }
387 $c = count($theRowArray);
388 foreach ($theRowArray as $val) {
389 $c--;
390 $output[$c] = [
391 'uid' => $val['uid'],
392 'pid' => $val['pid'],
393 'title' => $val['title'],
394 'doktype' => $val['doktype'],
395 'tsconfig_includes' => $val['tsconfig_includes'],
396 'TSconfig' => $val['TSconfig'],
397 'is_siteroot' => $val['is_siteroot'],
398 't3ver_oid' => $val['t3ver_oid'],
399 't3ver_wsid' => $val['t3ver_wsid'],
400 't3ver_state' => $val['t3ver_state'],
401 't3ver_stage' => $val['t3ver_stage'],
402 'backend_layout_next_level' => $val['backend_layout_next_level']
403 ];
404 if (isset($val['_ORIG_pid'])) {
405 $output[$c]['_ORIG_pid'] = $val['_ORIG_pid'];
406 }
407 }
408 $BEgetRootLine_cache[$ident] = $output;
409 }
410 return $output;
411 }
412
413 /**
414 * Gets the cached page record for the rootline
415 *
416 * @param int $uid Page id for which to create the root line.
417 * @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.
418 * @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!
419 * @return array Cached page record for the rootline
420 * @see BEgetRootLine
421 */
422 protected static function getPageForRootline($uid, $clause, $workspaceOL)
423 {
424 static $getPageForRootline_cache = [];
425 $ident = $uid . '-' . $clause . '-' . $workspaceOL;
426 if (is_array($getPageForRootline_cache[$ident])) {
427 $row = $getPageForRootline_cache[$ident];
428 } else {
429 $queryBuilder = static::getQueryBuilderForTable('pages');
430 $queryBuilder->getRestrictions()
431 ->removeAll()
432 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
433
434 $row = $queryBuilder
435 ->select(
436 'pid',
437 'uid',
438 'title',
439 'doktype',
440 'tsconfig_includes',
441 'TSconfig',
442 'is_siteroot',
443 't3ver_oid',
444 't3ver_wsid',
445 't3ver_state',
446 't3ver_stage',
447 'backend_layout_next_level'
448 )
449 ->from('pages')
450 ->where(
451 $queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)),
452 QueryHelper::stripLogicalOperatorPrefix($clause)
453 )
454 ->execute()
455 ->fetch();
456
457 if ($row) {
458 $newLocation = false;
459 if ($workspaceOL) {
460 self::workspaceOL('pages', $row);
461 $newLocation = self::getMovePlaceholder('pages', $row['uid'], 'pid');
462 }
463 if (is_array($row)) {
464 if ($newLocation !== false) {
465 $row['pid'] = $newLocation['pid'];
466 } else {
467 self::fixVersioningPid('pages', $row);
468 }
469 $getPageForRootline_cache[$ident] = $row;
470 }
471 }
472 }
473 return $row;
474 }
475
476 /**
477 * Opens the page tree to the specified page id
478 *
479 * @param int $pid Page id.
480 * @param bool $clearExpansion If set, then other open branches are closed.
481 */
482 public static function openPageTree($pid, $clearExpansion)
483 {
484 $beUser = static::getBackendUserAuthentication();
485 // Get current expansion data:
486 if ($clearExpansion) {
487 $expandedPages = [];
488 } else {
489 $expandedPages = unserialize($beUser->uc['browseTrees']['browsePages']);
490 }
491 // Get rootline:
492 $rL = self::BEgetRootLine($pid);
493 // First, find out what mount index to use (if more than one DB mount exists):
494 $mountIndex = 0;
495 $mountKeys = array_flip($beUser->returnWebmounts());
496 foreach ($rL as $rLDat) {
497 if (isset($mountKeys[$rLDat['uid']])) {
498 $mountIndex = $mountKeys[$rLDat['uid']];
499 break;
500 }
501 }
502 // Traverse rootline and open paths:
503 foreach ($rL as $rLDat) {
504 $expandedPages[$mountIndex][$rLDat['uid']] = 1;
505 }
506 // Write back:
507 $beUser->uc['browseTrees']['browsePages'] = serialize($expandedPages);
508 $beUser->writeUC();
509 }
510
511 /**
512 * Returns the path (visually) of a page $uid, fx. "/First page/Second page/Another subpage"
513 * Each part of the path will be limited to $titleLimit characters
514 * Deleted pages are filtered out.
515 *
516 * @param int $uid Page uid for which to create record path
517 * @param string $clause Clause is additional where clauses, eg.
518 * @param int $titleLimit Title limit
519 * @param int $fullTitleLimit Title limit of Full title (typ. set to 1000 or so)
520 * @return mixed Path of record (string) OR array with short/long title if $fullTitleLimit is set.
521 */
522 public static function getRecordPath($uid, $clause, $titleLimit, $fullTitleLimit = 0)
523 {
524 if (!$titleLimit) {
525 $titleLimit = 1000;
526 }
527 $output = $fullOutput = '/';
528 $clause = trim($clause);
529 if ($clause !== '' && substr($clause, 0, 3) !== 'AND') {
530 $clause = 'AND ' . $clause;
531 }
532 $data = self::BEgetRootLine($uid, $clause);
533 foreach ($data as $record) {
534 if ($record['uid'] === 0) {
535 continue;
536 }
537 $output = '/' . GeneralUtility::fixed_lgd_cs(strip_tags($record['title']), $titleLimit) . $output;
538 if ($fullTitleLimit) {
539 $fullOutput = '/' . GeneralUtility::fixed_lgd_cs(strip_tags($record['title']), $fullTitleLimit) . $fullOutput;
540 }
541 }
542 if ($fullTitleLimit) {
543 return [$output, $fullOutput];
544 }
545 return $output;
546 }
547
548 /**
549 * Gets the original translation pointer table.
550 * That is now the same table, apart from pages_language_overlay
551 * where pages is the original.
552 *
553 * @param string $table Name of the table
554 * @return string Pointer table (if any)
555 */
556 public static function getOriginalTranslationTable($table)
557 {
558 return $table === 'pages_language_overlay' ? 'pages' : $table;
559 }
560
561 /**
562 * Determines whether a table is localizable and has the languageField and transOrigPointerField set in $GLOBALS['TCA'].
563 *
564 * @param string $table The table to check
565 * @return bool Whether a table is localizable
566 */
567 public static function isTableLocalizable($table)
568 {
569 $isLocalizable = false;
570 if (isset($GLOBALS['TCA'][$table]['ctrl']) && is_array($GLOBALS['TCA'][$table]['ctrl'])) {
571 $tcaCtrl = $GLOBALS['TCA'][$table]['ctrl'];
572 $isLocalizable = isset($tcaCtrl['languageField']) && $tcaCtrl['languageField'] && isset($tcaCtrl['transOrigPointerField']) && $tcaCtrl['transOrigPointerField'];
573 }
574 return $isLocalizable;
575 }
576
577 /**
578 * Returns the value of the property localizationMode in the given $config array ($GLOBALS['TCA'][<table>]['columns'][<field>]['config']).
579 * If the table is prepared for localization and no localizationMode is set, 'select' is returned by default.
580 * If the table is not prepared for localization or not defined at all in $GLOBALS['TCA'], FALSE is returned.
581 *
582 * @param string $table The name of the table to lookup in TCA
583 * @param mixed $fieldOrConfig The fieldname (string) or the configuration of the field to check (array)
584 * @return mixed If table is localizable, the set localizationMode is returned (if property is not set, 'select' is returned by default); if table is not localizable, FALSE is returned
585 * @deprecated: IRRE 'localizationMode' is deprecated and will be removed in TYPO3 CMS 9, migrate to l10n_mode or allowLanguageSynchronization
586 */
587 public static function getInlineLocalizationMode($table, $fieldOrConfig)
588 {
589 $localizationMode = false;
590 $config = null;
591 if (is_array($fieldOrConfig) && !empty($fieldOrConfig)) {
592 $config = $fieldOrConfig;
593 } elseif (is_string($fieldOrConfig) && isset($GLOBALS['TCA'][$table]['columns'][$fieldOrConfig]['config'])) {
594 $config = $GLOBALS['TCA'][$table]['columns'][$fieldOrConfig]['config'];
595 }
596 if (is_array($config) && isset($config['type']) && $config['type'] === 'inline' && self::isTableLocalizable($table)) {
597 $localizationMode = isset($config['behaviour']['localizationMode']) && $config['behaviour']['localizationMode']
598 ? $config['behaviour']['localizationMode']
599 : 'select';
600 // The mode 'select' is not possible when child table is not localizable at all:
601 if ($localizationMode === 'select' && !self::isTableLocalizable($config['foreign_table'])) {
602 $localizationMode = false;
603 }
604 }
605 return $localizationMode;
606 }
607
608 /**
609 * 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.
610 * If $id is zero a pseudo root-page with "_thePath" set is returned IF the current BE_USER is admin.
611 * In any case ->isInWebMount must return TRUE for the user (regardless of $perms_clause)
612 *
613 * @param int $id Page uid for which to check read-access
614 * @param string $perms_clause This is typically a value generated with static::getBackendUserAuthentication()->getPagePermsClause(1);
615 * @return array|bool Returns page record if OK, otherwise FALSE.
616 */
617 public static function readPageAccess($id, $perms_clause)
618 {
619 if ((string)$id !== '') {
620 $id = (int)$id;
621 if (!$id) {
622 if (static::getBackendUserAuthentication()->isAdmin()) {
623 $path = '/';
624 $pageinfo['_thePath'] = $path;
625 return $pageinfo;
626 }
627 } else {
628 $pageinfo = self::getRecord('pages', $id, '*', $perms_clause);
629 if ($pageinfo['uid'] && static::getBackendUserAuthentication()->isInWebMount($id, $perms_clause)) {
630 self::workspaceOL('pages', $pageinfo);
631 if (is_array($pageinfo)) {
632 self::fixVersioningPid('pages', $pageinfo);
633 list($pageinfo['_thePath'], $pageinfo['_thePathFull']) = self::getRecordPath((int)$pageinfo['uid'], $perms_clause, 15, 1000);
634 return $pageinfo;
635 }
636 }
637 }
638 }
639 return false;
640 }
641
642 /**
643 * Returns the "types" configuration parsed into an array for the record, $rec, from table, $table
644 *
645 * @param string $table Table name (present in TCA)
646 * @param array $rec Record from $table
647 * @param bool $useFieldNameAsKey If $useFieldNameAsKey is set, then the fieldname is associative keys in the return array, otherwise just numeric keys.
648 * @return array|NULL
649 */
650 public static function getTCAtypes($table, $rec, $useFieldNameAsKey = false)
651 {
652 if ($GLOBALS['TCA'][$table]) {
653 // Get type value:
654 $fieldValue = self::getTCAtypeValue($table, $rec);
655 $cacheIdentifier = $table . '-type-' . $fieldValue . '-fnk-' . $useFieldNameAsKey;
656
657 // Fetch from first-level-cache if available
658 if (isset(self::$tcaTableTypeConfigurationCache[$cacheIdentifier])) {
659 return self::$tcaTableTypeConfigurationCache[$cacheIdentifier];
660 }
661
662 // Get typesConf
663 $typesConf = $GLOBALS['TCA'][$table]['types'][$fieldValue];
664 // Get fields list and traverse it
665 $fieldList = explode(',', $typesConf['showitem']);
666
667 // Add subtype fields e.g. for a valid RTE transformation
668 // The RTE runs the DB -> RTE transformation only, if the RTE field is part of the getTCAtypes array
669 if (isset($typesConf['subtype_value_field'])) {
670 $subType = $rec[$typesConf['subtype_value_field']];
671 if (isset($typesConf['subtypes_addlist'][$subType])) {
672 $subFields = GeneralUtility::trimExplode(',', $typesConf['subtypes_addlist'][$subType], true);
673 $fieldList = array_merge($fieldList, $subFields);
674 }
675 }
676
677 // Add palette fields e.g. for a valid RTE transformation
678 $paletteFieldList = [];
679 foreach ($fieldList as $fieldData) {
680 list($pFieldName, $pAltTitle, $pPalette) = GeneralUtility::trimExplode(';', $fieldData);
681 if ($pPalette
682 && isset($GLOBALS['TCA'][$table]['palettes'][$pPalette])
683 && is_array($GLOBALS['TCA'][$table]['palettes'][$pPalette])
684 && isset($GLOBALS['TCA'][$table]['palettes'][$pPalette]['showitem'])
685 ) {
686 $paletteFields = GeneralUtility::trimExplode(',', $GLOBALS['TCA'][$table]['palettes'][$pPalette]['showitem'], true);
687 foreach ($paletteFields as $paletteField) {
688 if ($paletteField !== '--linebreak--') {
689 $paletteFieldList[] = $paletteField;
690 }
691 }
692 }
693 }
694 $fieldList = array_merge($fieldList, $paletteFieldList);
695
696 $altFieldList = [];
697 // Traverse fields in types config and parse the configuration into a nice array:
698 foreach ($fieldList as $k => $v) {
699 list($pFieldName, $pAltTitle, $pPalette) = GeneralUtility::trimExplode(';', $v);
700 $fieldList[$k] = [
701 'field' => $pFieldName,
702 'title' => $pAltTitle,
703 'palette' => $pPalette,
704 'spec' => [],
705 'origString' => $v
706 ];
707 if ($useFieldNameAsKey) {
708 $altFieldList[$fieldList[$k]['field']] = $fieldList[$k];
709 }
710 }
711 if ($useFieldNameAsKey) {
712 $fieldList = $altFieldList;
713 }
714
715 // Add to first-level-cache
716 self::$tcaTableTypeConfigurationCache[$cacheIdentifier] = $fieldList;
717
718 // Return array:
719 return $fieldList;
720 }
721 return null;
722 }
723
724 /**
725 * Returns the "type" value of $rec from $table which can be used to look up the correct "types" rendering section in $GLOBALS['TCA']
726 * If no "type" field is configured in the "ctrl"-section of the $GLOBALS['TCA'] for the table, zero is used.
727 * 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)
728 *
729 * Note: This method is very similar to the type determination of FormDataProvider/DatabaseRecordTypeValue,
730 * however, it has two differences:
731 * 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).
732 * 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"
733 * and "group" field values are stored, which makes different processing of the "foreign pointer field" type field variant necessary.
734 *
735 * @param string $table Table name present in TCA
736 * @param array $row Record from $table
737 * @throws \RuntimeException
738 * @return string Field value
739 * @see getTCAtypes()
740 */
741 public static function getTCAtypeValue($table, $row)
742 {
743 $typeNum = 0;
744 if ($GLOBALS['TCA'][$table]) {
745 $field = $GLOBALS['TCA'][$table]['ctrl']['type'];
746 if (strpos($field, ':') !== false) {
747 list($pointerField, $foreignTableTypeField) = explode(':', $field);
748 // Get field value from database if field is not in the $row array
749 if (!isset($row[$pointerField])) {
750 $localRow = self::getRecord($table, $row['uid'], $pointerField);
751 $foreignUid = $localRow[$pointerField];
752 } else {
753 $foreignUid = $row[$pointerField];
754 }
755 if ($foreignUid) {
756 $fieldConfig = $GLOBALS['TCA'][$table]['columns'][$pointerField]['config'];
757 $relationType = $fieldConfig['type'];
758 if ($relationType === 'select') {
759 $foreignTable = $fieldConfig['foreign_table'];
760 } elseif ($relationType === 'group') {
761 $allowedTables = explode(',', $fieldConfig['allowed']);
762 $foreignTable = $allowedTables[0];
763 } else {
764 throw new \RuntimeException(
765 'TCA foreign field pointer fields are only allowed to be used with group or select field types.',
766 1325862240
767 );
768 }
769 $foreignRow = self::getRecord($foreignTable, $foreignUid, $foreignTableTypeField);
770 if ($foreignRow[$foreignTableTypeField]) {
771 $typeNum = $foreignRow[$foreignTableTypeField];
772 }
773 }
774 } else {
775 $typeNum = $row[$field];
776 }
777 // If that value is an empty string, set it to "0" (zero)
778 if (empty($typeNum)) {
779 $typeNum = 0;
780 }
781 }
782 // If current typeNum doesn't exist, set it to 0 (or to 1 for historical reasons, if 0 doesn't exist)
783 if (!$GLOBALS['TCA'][$table]['types'][$typeNum]) {
784 $typeNum = $GLOBALS['TCA'][$table]['types']['0'] ? 0 : 1;
785 }
786 // Force to string. Necessary for eg '-1' to be recognized as a type value.
787 $typeNum = (string)$typeNum;
788 return $typeNum;
789 }
790
791 /*******************************************
792 *
793 * Caching related
794 *
795 *******************************************/
796 /**
797 * Stores $data in the 'cache_hash' cache with the hash key, $hash
798 * and visual/symbolic identification, $ident
799 *
800 * @param string $hash 32 bit hash string (eg. a md5 hash of a serialized array identifying the data being stored)
801 * @param mixed $data The data to store
802 * @param string $ident $ident is just a textual identification in order to inform about the content!
803 */
804 public static function storeHash($hash, $data, $ident)
805 {
806 /** @var CacheManager $cacheManager */
807 $cacheManager = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Cache\CacheManager::class);
808 $cacheManager->getCache('cache_hash')->set($hash, $data, ['ident_' . $ident], 0);
809 }
810
811 /**
812 * Returns data stored for the hash string in the cache "cache_hash"
813 * Can be used to retrieved a cached value, array or object
814 *
815 * @param string $hash The hash-string which was used to store the data value
816 * @return mixed The "data" from the cache
817 */
818 public static function getHash($hash)
819 {
820 /** @var CacheManager $cacheManager */
821 $cacheManager = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Cache\CacheManager::class);
822 $cacheEntry = $cacheManager->getCache('cache_hash')->get($hash);
823 $hashContent = null;
824 if ($cacheEntry) {
825 $hashContent = $cacheEntry;
826 }
827 return $hashContent;
828 }
829
830 /*******************************************
831 *
832 * TypoScript related
833 *
834 *******************************************/
835 /**
836 * Returns the Page TSconfig for page with id, $id
837 *
838 * @param int $id Page uid for which to create Page TSconfig
839 * @param array $rootLine If $rootLine is an array, that is used as rootline, otherwise rootline is just calculated
840 * @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.
841 * @return array Page TSconfig
842 * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser
843 */
844 public static function getPagesTSconfig($id, $rootLine = null, $returnPartArray = false)
845 {
846 static $pagesTSconfig_cacheReference = [];
847 static $combinedTSconfig_cache = [];
848
849 $id = (int)$id;
850 if ($returnPartArray === false
851 && $rootLine === null
852 && isset($pagesTSconfig_cacheReference[$id])
853 ) {
854 return $combinedTSconfig_cache[$pagesTSconfig_cacheReference[$id]];
855 }
856 $TSconfig = [];
857 if (!is_array($rootLine)) {
858 $useCacheForCurrentPageId = true;
859 $rootLine = self::BEgetRootLine($id, '', true);
860 } else {
861 $useCacheForCurrentPageId = false;
862 }
863
864 // Order correctly
865 ksort($rootLine);
866 $TSdataArray = [];
867 // Setting default configuration
868 $TSdataArray['defaultPageTSconfig'] = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPageTSconfig'];
869 foreach ($rootLine as $k => $v) {
870 if (trim($v['tsconfig_includes'])) {
871 $includeTsConfigFileList = GeneralUtility::trimExplode(',', $v['tsconfig_includes'], true);
872 // Traversing list
873 foreach ($includeTsConfigFileList as $key => $includeTsConfigFile) {
874 if (strpos($includeTsConfigFile, 'EXT:') === 0) {
875 list($includeTsConfigFileExtensionKey, $includeTsConfigFilename) = explode(
876 '/',
877 substr($includeTsConfigFile, 4),
878 2
879 );
880 if ((string)$includeTsConfigFileExtensionKey !== ''
881 && ExtensionManagementUtility::isLoaded($includeTsConfigFileExtensionKey)
882 && (string)$includeTsConfigFilename !== ''
883 ) {
884 $includeTsConfigFileAndPath = ExtensionManagementUtility::extPath($includeTsConfigFileExtensionKey) .
885 $includeTsConfigFilename;
886 if (file_exists($includeTsConfigFileAndPath)) {
887 $TSdataArray['uid_' . $v['uid'] . '_static_' . $key] = file_get_contents($includeTsConfigFileAndPath);
888 }
889 }
890 }
891 }
892 }
893 $TSdataArray['uid_' . $v['uid']] = $v['TSconfig'];
894 }
895 $TSdataArray = static::emitGetPagesTSconfigPreIncludeSignal($TSdataArray, $id, $rootLine, $returnPartArray);
896 $TSdataArray = TypoScriptParser::checkIncludeLines_array($TSdataArray);
897 if ($returnPartArray) {
898 return $TSdataArray;
899 }
900 // Parsing the page TS-Config
901 $pageTS = implode(LF . '[GLOBAL]' . LF, $TSdataArray);
902 /* @var $parseObj \TYPO3\CMS\Backend\Configuration\TsConfigParser */
903 $parseObj = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Configuration\TsConfigParser::class);
904 $res = $parseObj->parseTSconfig($pageTS, 'PAGES', $id, $rootLine);
905 if ($res) {
906 $TSconfig = $res['TSconfig'];
907 }
908 $cacheHash = $res['hash'];
909 // Get User TSconfig overlay
910 $userTSconfig = static::getBackendUserAuthentication()->userTS['page.'];
911 if (is_array($userTSconfig)) {
912 ArrayUtility::mergeRecursiveWithOverrule($TSconfig, $userTSconfig);
913 $cacheHash .= '_user' . $GLOBALS['BE_USER']->user['uid'];
914 }
915
916 if ($useCacheForCurrentPageId) {
917 if (!isset($combinedTSconfig_cache[$cacheHash])) {
918 $combinedTSconfig_cache[$cacheHash] = $TSconfig;
919 }
920 $pagesTSconfig_cacheReference[$id] = $cacheHash;
921 }
922
923 return $TSconfig;
924 }
925
926 /*******************************************
927 *
928 * Users / Groups related
929 *
930 *******************************************/
931 /**
932 * Returns an array with be_users records of all user NOT DELETED sorted by their username
933 * Keys in the array is the be_users uid
934 *
935 * @param string $fields Optional $fields list (default: username,usergroup,usergroup_cached_list,uid) can be used to set the selected fields
936 * @param string $where Optional $where clause (fx. "AND username='pete'") can be used to limit query
937 * @return array
938 */
939 public static function getUserNames($fields = 'username,usergroup,usergroup_cached_list,uid', $where = '')
940 {
941 return self::getRecordsSortedByTitle(
942 GeneralUtility::trimExplode(',', $fields, true),
943 'be_users',
944 'username',
945 'AND pid=0 ' . $where
946 );
947 }
948
949 /**
950 * Returns an array with be_groups records (title, uid) of all groups NOT DELETED sorted by their title
951 *
952 * @param string $fields Field list
953 * @param string $where WHERE clause
954 * @return array
955 */
956 public static function getGroupNames($fields = 'title,uid', $where = '')
957 {
958 return self::getRecordsSortedByTitle(
959 GeneralUtility::trimExplode(',', $fields, true),
960 'be_groups',
961 'title',
962 'AND pid=0 ' . $where
963 );
964 }
965
966 /**
967 * Returns an array of all non-deleted records of a table sorted by a given title field.
968 * The value of the title field will be replaced by the return value
969 * of self::getRecordTitle() before the sorting is performed.
970 *
971 * @param array $fields Fields to select
972 * @param string $table Table name
973 * @param string $titleField Field that will contain the record title
974 * @param string $where Additional where clause
975 * @return array Array of sorted records
976 */
977 protected static function getRecordsSortedByTitle(array $fields, $table, $titleField, $where = '')
978 {
979 $fieldsIndex = array_flip($fields);
980 // Make sure the titleField is amongst the fields when getting sorted
981 $fieldsIndex[$titleField] = 1;
982
983 $result = [];
984
985 $queryBuilder = static::getQueryBuilderForTable($table);
986 $queryBuilder->getRestrictions()
987 ->removeAll()
988 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
989
990 $res = $queryBuilder
991 ->select('*')
992 ->from($table)
993 ->where(QueryHelper::stripLogicalOperatorPrefix($where))
994 ->execute();
995
996 while ($record = $res->fetch()) {
997 // store the uid, because it might be unset if it's not among the requested $fields
998 $recordId = $record['uid'];
999 $record[$titleField] = self::getRecordTitle($table, $record);
1000
1001 // include only the requested fields in the result
1002 $result[$recordId] = array_intersect_key($record, $fieldsIndex);
1003 }
1004
1005 // sort records by $sortField. This is not done in the query because the title might have been overwritten by
1006 // self::getRecordTitle();
1007 return ArrayUtility::sortArraysByKey($result, $titleField);
1008 }
1009
1010 /**
1011 * Returns an array with be_groups records (like ->getGroupNames) but:
1012 * - 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.
1013 *
1014 * @param string $fields Field list; $fields specify the fields selected (default: title,uid)
1015 * @return array
1016 * @deprecated since TYPO3 9, will be removed in TYPO3 10
1017 */
1018 public static function getListGroupNames($fields = 'title, uid')
1019 {
1020 GeneralUtility::logDeprecatedFunction();
1021 $beUser = static::getBackendUserAuthentication();
1022 $exQ = '';
1023 if (!$beUser->isAdmin()) {
1024 $exQ = ' AND uid IN (' . ($beUser->user['usergroup_cached_list'] ?: 0) . ')';
1025 }
1026 return self::getGroupNames($fields, $exQ);
1027 }
1028
1029 /**
1030 * Returns the array $usernames with the names of all users NOT IN $groupArray changed to the uid (hides the usernames!).
1031 * If $excludeBlindedFlag is set, then these records are unset from the array $usernames
1032 * 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
1033 *
1034 * @param array $usernames User names
1035 * @param array $groupArray Group names
1036 * @param bool $excludeBlindedFlag If $excludeBlindedFlag is set, then these records are unset from the array $usernames
1037 * @return array User names, blinded
1038 */
1039 public static function blindUserNames($usernames, $groupArray, $excludeBlindedFlag = false)
1040 {
1041 if (is_array($usernames) && is_array($groupArray)) {
1042 foreach ($usernames as $uid => $row) {
1043 $userN = $uid;
1044 $set = 0;
1045 if ($row['uid'] != static::getBackendUserAuthentication()->user['uid']) {
1046 foreach ($groupArray as $v) {
1047 if ($v && GeneralUtility::inList($row['usergroup_cached_list'], $v)) {
1048 $userN = $row['username'];
1049 $set = 1;
1050 }
1051 }
1052 } else {
1053 $userN = $row['username'];
1054 $set = 1;
1055 }
1056 $usernames[$uid]['username'] = $userN;
1057 if ($excludeBlindedFlag && !$set) {
1058 unset($usernames[$uid]);
1059 }
1060 }
1061 }
1062 return $usernames;
1063 }
1064
1065 /**
1066 * Corresponds to blindUserNames but works for groups instead
1067 *
1068 * @param array $groups Group names
1069 * @param array $groupArray Group names (reference)
1070 * @param bool $excludeBlindedFlag If $excludeBlindedFlag is set, then these records are unset from the array $usernames
1071 * @return array
1072 */
1073 public static function blindGroupNames($groups, $groupArray, $excludeBlindedFlag = false)
1074 {
1075 if (is_array($groups) && is_array($groupArray)) {
1076 foreach ($groups as $uid => $row) {
1077 $groupN = $uid;
1078 $set = 0;
1079 if (in_array($uid, $groupArray, false)) {
1080 $groupN = $row['title'];
1081 $set = 1;
1082 }
1083 $groups[$uid]['title'] = $groupN;
1084 if ($excludeBlindedFlag && !$set) {
1085 unset($groups[$uid]);
1086 }
1087 }
1088 }
1089 return $groups;
1090 }
1091
1092 /*******************************************
1093 *
1094 * Output related
1095 *
1096 *******************************************/
1097 /**
1098 * Returns the difference in days between input $tstamp and $EXEC_TIME
1099 *
1100 * @param int $tstamp Time stamp, seconds
1101 * @return int
1102 */
1103 public static function daysUntil($tstamp)
1104 {
1105 $delta_t = $tstamp - $GLOBALS['EXEC_TIME'];
1106 return ceil($delta_t / (3600 * 24));
1107 }
1108
1109 /**
1110 * Returns $tstamp formatted as "ddmmyy" (According to $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'])
1111 *
1112 * @param int $tstamp Time stamp, seconds
1113 * @return string Formatted time
1114 */
1115 public static function date($tstamp)
1116 {
1117 return date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'], (int)$tstamp);
1118 }
1119
1120 /**
1121 * Returns $tstamp formatted as "ddmmyy hhmm" (According to $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] AND $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'])
1122 *
1123 * @param int $value Time stamp, seconds
1124 * @return string Formatted time
1125 */
1126 public static function datetime($value)
1127 {
1128 return date(
1129 $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'],
1130 $value
1131 );
1132 }
1133
1134 /**
1135 * Returns $value (in seconds) formatted as hh:mm:ss
1136 * For instance $value = 3600 + 60*2 + 3 should return "01:02:03"
1137 *
1138 * @param int $value Time stamp, seconds
1139 * @param bool $withSeconds Output hh:mm:ss. If FALSE: hh:mm
1140 * @return string Formatted time
1141 */
1142 public static function time($value, $withSeconds = true)
1143 {
1144 return gmdate('H:i' . ($withSeconds ? ':s' : ''), (int)$value);
1145 }
1146
1147 /**
1148 * Returns the "age" in minutes / hours / days / years of the number of $seconds inputted.
1149 *
1150 * @param int $seconds Seconds could be the difference of a certain timestamp and time()
1151 * @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")
1152 * @return string Formatted time
1153 */
1154 public static function calcAge($seconds, $labels = ' min| hrs| days| yrs| min| hour| day| year')
1155 {
1156 $labelArr = explode('|', $labels);
1157 $absSeconds = abs($seconds);
1158 $sign = $seconds < 0 ? -1 : 1;
1159 if ($absSeconds < 3600) {
1160 $val = round($absSeconds / 60);
1161 $seconds = $sign * $val . ($val == 1 ? $labelArr[4] : $labelArr[0]);
1162 } elseif ($absSeconds < 24 * 3600) {
1163 $val = round($absSeconds / 3600);
1164 $seconds = $sign * $val . ($val == 1 ? $labelArr[5] : $labelArr[1]);
1165 } elseif ($absSeconds < 365 * 24 * 3600) {
1166 $val = round($absSeconds / (24 * 3600));
1167 $seconds = $sign * $val . ($val == 1 ? $labelArr[6] : $labelArr[2]);
1168 } else {
1169 $val = round($absSeconds / (365 * 24 * 3600));
1170 $seconds = $sign * $val . ($val == 1 ? $labelArr[7] : $labelArr[3]);
1171 }
1172 return $seconds;
1173 }
1174
1175 /**
1176 * Returns a formatted timestamp if $tstamp is set.
1177 * The date/datetime will be followed by the age in parenthesis.
1178 *
1179 * @param int $tstamp Time stamp, seconds
1180 * @param int $prefix 1/-1 depending on polarity of age.
1181 * @param string $date $date=="date" will yield "dd:mm:yy" formatting, otherwise "dd:mm:yy hh:mm
1182 * @return string
1183 */
1184 public static function dateTimeAge($tstamp, $prefix = 1, $date = '')
1185 {
1186 if (!$tstamp) {
1187 return '';
1188 }
1189 $label = static::getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.minutesHoursDaysYears');
1190 $age = ' (' . self::calcAge($prefix * ($GLOBALS['EXEC_TIME'] - $tstamp), $label) . ')';
1191 return ($date === 'date' ? self::date($tstamp) : self::datetime($tstamp)) . $age;
1192 }
1193
1194 /**
1195 * Resolves file references for a given record.
1196 *
1197 * @param string $tableName Name of the table of the record
1198 * @param string $fieldName Name of the field of the record
1199 * @param array $element Record data
1200 * @param NULL|int $workspaceId Workspace to fetch data for
1201 * @return NULL|\TYPO3\CMS\Core\Resource\FileReference[]
1202 */
1203 public static function resolveFileReferences($tableName, $fieldName, $element, $workspaceId = null)
1204 {
1205 if (empty($GLOBALS['TCA'][$tableName]['columns'][$fieldName]['config'])) {
1206 return null;
1207 }
1208 $configuration = $GLOBALS['TCA'][$tableName]['columns'][$fieldName]['config'];
1209 if (empty($configuration['type']) || $configuration['type'] !== 'inline'
1210 || empty($configuration['foreign_table']) || $configuration['foreign_table'] !== 'sys_file_reference'
1211 ) {
1212 return null;
1213 }
1214
1215 $fileReferences = [];
1216 /** @var $relationHandler RelationHandler */
1217 $relationHandler = GeneralUtility::makeInstance(RelationHandler::class);
1218 if ($workspaceId !== null) {
1219 $relationHandler->setWorkspaceId($workspaceId);
1220 }
1221 $relationHandler->start(
1222 $element[$fieldName],
1223 $configuration['foreign_table'],
1224 $configuration['MM'],
1225 $element['uid'],
1226 $tableName,
1227 $configuration
1228 );
1229 $relationHandler->processDeletePlaceholder();
1230 $referenceUids = $relationHandler->tableArray[$configuration['foreign_table']];
1231
1232 foreach ($referenceUids as $referenceUid) {
1233 try {
1234 $fileReference = ResourceFactory::getInstance()->getFileReferenceObject(
1235 $referenceUid,
1236 [],
1237 ($workspaceId === 0)
1238 );
1239 $fileReferences[$fileReference->getUid()] = $fileReference;
1240 } catch (\TYPO3\CMS\Core\Resource\Exception\FileDoesNotExistException $e) {
1241 /**
1242 * We just catch the exception here
1243 * Reasoning: There is nothing an editor or even admin could do
1244 */
1245 } catch (\InvalidArgumentException $e) {
1246 /**
1247 * The storage does not exist anymore
1248 * Log the exception message for admins as they maybe can restore the storage
1249 */
1250 self::getLogger()->error($e->getMessage(), ['table' => $tableName, 'fieldName' => $fieldName, 'referenceUid' => $referenceUid, 'exception' => $e]);
1251 }
1252 }
1253
1254 return $fileReferences;
1255 }
1256
1257 /**
1258 * 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
1259 * All $GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'] extension are made to thumbnails + ttf file (renders font-example)
1260 * Thumbsnails are linked to the show_item.php script which will display further details.
1261 *
1262 * @param array $row Row is the database row from the table, $table.
1263 * @param string $table Table name for $row (present in TCA)
1264 * @param string $field Field is pointing to the list of image files
1265 * @param string $backPath Back path prefix for image tag src="" field
1266 * @param string $thumbScript UNUSED since FAL
1267 * @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!)
1268 * @param int $abs UNUSED
1269 * @param string $tparams Optional: $tparams is additional attributes for the image tags
1270 * @param int|string $size Optional: $size is [w]x[h] of the thumbnail. 64 is default.
1271 * @param bool $linkInfoPopup Whether to wrap with a link opening the info popup
1272 * @return string Thumbnail image tag.
1273 */
1274 public static function thumbCode(
1275 $row,
1276 $table,
1277 $field,
1278 $backPath = '',
1279 $thumbScript = '',
1280 $uploaddir = null,
1281 $abs = 0,
1282 $tparams = '',
1283 $size = '',
1284 $linkInfoPopup = true
1285 ) {
1286 // Check and parse the size parameter
1287 $size = trim($size);
1288 $sizeParts = [64, 64];
1289 if ($size) {
1290 $sizeParts = explode('x', $size . 'x' . $size);
1291 }
1292 $thumbData = '';
1293 $fileReferences = static::resolveFileReferences($table, $field, $row);
1294 // FAL references
1295 $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
1296 if ($fileReferences !== null) {
1297 foreach ($fileReferences as $fileReferenceObject) {
1298 // Do not show previews of hidden references
1299 if ($fileReferenceObject->getProperty('hidden')) {
1300 continue;
1301 }
1302 $fileObject = $fileReferenceObject->getOriginalFile();
1303
1304 if ($fileObject->isMissing()) {
1305 $thumbData .= '<span class="label label-danger">'
1306 . htmlspecialchars(
1307 static::getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:warning.file_missing')
1308 )
1309 . '</span>&nbsp;' . htmlspecialchars($fileObject->getName()) . '<br />';
1310 continue;
1311 }
1312
1313 // Preview web image or media elements
1314 if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['thumbnails']
1315 && GeneralUtility::inList(
1316 $GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'],
1317 $fileReferenceObject->getExtension()
1318 )
1319 ) {
1320 $cropVariantCollection = CropVariantCollection::create((string)$fileReferenceObject->getProperty('crop'));
1321 $cropArea = $cropVariantCollection->getCropArea();
1322 $processedImage = $fileObject->process(
1323 ProcessedFile::CONTEXT_IMAGECROPSCALEMASK,
1324 [
1325 'width' => $sizeParts[0],
1326 'height' => $sizeParts[1] . 'c',
1327 'crop' => $cropArea->isEmpty() ? null : $cropArea->makeAbsoluteBasedOnFile($fileReferenceObject)
1328 ]
1329 );
1330 $imageUrl = $processedImage->getPublicUrl(true);
1331 $imgTag = '<img src="' . $imageUrl . '" '
1332 . 'width="' . $processedImage->getProperty('width') . '" '
1333 . 'height="' . $processedImage->getProperty('height') . '" '
1334 . 'alt="' . htmlspecialchars($fileReferenceObject->getName()) . '" />';
1335 } else {
1336 // Icon
1337 $imgTag = '<span title="' . htmlspecialchars($fileObject->getName()) . '">'
1338 . $iconFactory->getIconForResource($fileObject, Icon::SIZE_SMALL)->render()
1339 . '</span>';
1340 }
1341 if ($linkInfoPopup) {
1342 $onClick = 'top.launchView(\'_FILE\',\'' . (int)$fileObject->getUid() . '\'); return false;';
1343 $thumbData .= '<a href="#" onclick="' . htmlspecialchars($onClick) . '">' . $imgTag . '</a> ';
1344 } else {
1345 $thumbData .= $imgTag;
1346 }
1347 }
1348 } else {
1349 // Find uploaddir automatically
1350 if (is_null($uploaddir)) {
1351 $uploaddir = $GLOBALS['TCA'][$table]['columns'][$field]['config']['uploadfolder'];
1352 }
1353 $uploaddir = rtrim($uploaddir, '/');
1354 // Traverse files:
1355 $thumbs = GeneralUtility::trimExplode(',', $row[$field], true);
1356 $thumbData = '';
1357 foreach ($thumbs as $theFile) {
1358 if ($theFile) {
1359 $fileName = trim($uploaddir . '/' . $theFile, '/');
1360 try {
1361 /** @var File $fileObject */
1362 $fileObject = ResourceFactory::getInstance()->retrieveFileOrFolderObject($fileName);
1363 // Skip the resource if it's not of type AbstractFile. One case where this can happen if the
1364 // storage has been externally modified and the field value now points to a folder
1365 // instead of a file.
1366 if (!$fileObject instanceof AbstractFile) {
1367 continue;
1368 }
1369 if ($fileObject->isMissing()) {
1370 $thumbData .= '<span class="label label-danger">'
1371 . htmlspecialchars(static::getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:warning.file_missing'))
1372 . '</span>&nbsp;' . htmlspecialchars($fileObject->getName()) . '<br />';
1373 continue;
1374 }
1375 } catch (ResourceDoesNotExistException $exception) {
1376 $thumbData .= '<span class="label label-danger">'
1377 . htmlspecialchars(static::getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:warning.file_missing'))
1378 . '</span>&nbsp;' . htmlspecialchars($fileName) . '<br />';
1379 continue;
1380 }
1381
1382 $fileExtension = $fileObject->getExtension();
1383 if ($fileExtension === 'ttf'
1384 || GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'], $fileExtension)
1385 ) {
1386 $imageUrl = $fileObject->process(
1387 ProcessedFile::CONTEXT_IMAGEPREVIEW,
1388 [
1389 'width' => $sizeParts[0],
1390 'height' => $sizeParts[1]
1391 ]
1392 )->getPublicUrl(true);
1393
1394 $image = '<img src="' . htmlspecialchars($imageUrl) . '" hspace="2" border="0" title="' . htmlspecialchars($fileObject->getName()) . '"' . $tparams . ' alt="" />';
1395 if ($linkInfoPopup) {
1396 $onClick = 'top.launchView(\'_FILE\', ' . GeneralUtility::quoteJSvalue($fileName) . ',\'\');return false;';
1397 $thumbData .= '<a href="#" onclick="' . htmlspecialchars($onClick) . '">' . $image . '</a> ';
1398 } else {
1399 $thumbData .= $image;
1400 }
1401 } else {
1402 // Gets the icon
1403 $fileIcon = '<span title="' . htmlspecialchars($fileObject->getName()) . '">'
1404 . $iconFactory->getIconForResource($fileObject, Icon::SIZE_SMALL)->render()
1405 . '</span>';
1406 if ($linkInfoPopup) {
1407 $onClick = 'top.launchView(\'_FILE\', ' . GeneralUtility::quoteJSvalue($fileName) . ',\'\'); return false;';
1408 $thumbData .= '<a href="#" onclick="' . htmlspecialchars($onClick) . '">' . $fileIcon . '</a> ';
1409 } else {
1410 $thumbData .= $fileIcon;
1411 }
1412 }
1413 }
1414 }
1415 }
1416 return $thumbData;
1417 }
1418
1419 /**
1420 * Returns title-attribute information for a page-record informing about id, alias, doktype, hidden, starttime, endtime, fe_group etc.
1421 *
1422 * @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)
1423 * @param string $perms_clause This is used to get the record path of the shortcut page, if any (and doktype==4)
1424 * @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
1425 * @return string
1426 */
1427 public static function titleAttribForPages($row, $perms_clause = '', $includeAttrib = true)
1428 {
1429 $lang = static::getLanguageService();
1430 $parts = [];
1431 $parts[] = 'id=' . $row['uid'];
1432 if ($row['alias']) {
1433 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['alias']['label']) . ' ' . $row['alias'];
1434 }
1435 if ($row['pid'] < 0) {
1436 $parts[] = 'v#1.' . $row['t3ver_id'];
1437 }
1438 switch (VersionState::cast($row['t3ver_state'])) {
1439 case new VersionState(VersionState::NEW_PLACEHOLDER):
1440 $parts[] = 'PLH WSID#' . $row['t3ver_wsid'];
1441 break;
1442 case new VersionState(VersionState::DELETE_PLACEHOLDER):
1443 $parts[] = 'Deleted element!';
1444 break;
1445 case new VersionState(VersionState::MOVE_PLACEHOLDER):
1446 $parts[] = 'NEW LOCATION (PLH) WSID#' . $row['t3ver_wsid'];
1447 break;
1448 case new VersionState(VersionState::MOVE_POINTER):
1449 $parts[] = 'OLD LOCATION (PNT) WSID#' . $row['t3ver_wsid'];
1450 break;
1451 case new VersionState(VersionState::NEW_PLACEHOLDER_VERSION):
1452 $parts[] = 'New element!';
1453 break;
1454 }
1455 if ($row['doktype'] == PageRepository::DOKTYPE_LINK) {
1456 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['url']['label']) . ' ' . $row['url'];
1457 } elseif ($row['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
1458 if ($perms_clause) {
1459 $label = self::getRecordPath((int)$row['shortcut'], $perms_clause, 20);
1460 } else {
1461 $row['shortcut'] = (int)$row['shortcut'];
1462 $lRec = self::getRecordWSOL('pages', $row['shortcut'], 'title');
1463 $label = $lRec['title'] . ' (id=' . $row['shortcut'] . ')';
1464 }
1465 if ($row['shortcut_mode'] != PageRepository::SHORTCUT_MODE_NONE) {
1466 $label .= ', ' . $lang->sL($GLOBALS['TCA']['pages']['columns']['shortcut_mode']['label']) . ' '
1467 . $lang->sL(self::getLabelFromItemlist('pages', 'shortcut_mode', $row['shortcut_mode']));
1468 }
1469 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['shortcut']['label']) . ' ' . $label;
1470 } elseif ($row['doktype'] == PageRepository::DOKTYPE_MOUNTPOINT) {
1471 if ($perms_clause) {
1472 $label = self::getRecordPath((int)$row['mount_pid'], $perms_clause, 20);
1473 } else {
1474 $lRec = self::getRecordWSOL('pages', (int)$row['mount_pid'], 'title');
1475 $label = $lRec['title'] . ' (id=' . $row['mount_pid'] . ')';
1476 }
1477 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['mount_pid']['label']) . ' ' . $label;
1478 if ($row['mount_pid_ol']) {
1479 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['mount_pid_ol']['label']);
1480 }
1481 }
1482 if ($row['nav_hide']) {
1483 $parts[] = rtrim($lang->sL($GLOBALS['TCA']['pages']['columns']['nav_hide']['label']), ':');
1484 }
1485 if ($row['hidden']) {
1486 $parts[] = $lang->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.hidden');
1487 }
1488 if ($row['starttime']) {
1489 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['starttime']['label'])
1490 . ' ' . self::dateTimeAge($row['starttime'], -1, 'date');
1491 }
1492 if ($row['endtime']) {
1493 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['endtime']['label']) . ' '
1494 . self::dateTimeAge($row['endtime'], -1, 'date');
1495 }
1496 if ($row['fe_group']) {
1497 $fe_groups = [];
1498 foreach (GeneralUtility::intExplode(',', $row['fe_group']) as $fe_group) {
1499 if ($fe_group < 0) {
1500 $fe_groups[] = $lang->sL(self::getLabelFromItemlist('pages', 'fe_group', $fe_group));
1501 } else {
1502 $lRec = self::getRecordWSOL('fe_groups', $fe_group, 'title');
1503 $fe_groups[] = $lRec['title'];
1504 }
1505 }
1506 $label = implode(', ', $fe_groups);
1507 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['fe_group']['label']) . ' ' . $label;
1508 }
1509 $out = htmlspecialchars(implode(' - ', $parts));
1510 return $includeAttrib ? 'title="' . $out . '"' : $out;
1511 }
1512
1513 /**
1514 * Returns the combined markup for Bootstraps tooltips
1515 *
1516 * @param array $row
1517 * @param string $table
1518 * @return string
1519 */
1520 public static function getRecordToolTip(array $row, $table = 'pages')
1521 {
1522 $toolTipText = self::getRecordIconAltText($row, $table);
1523 $toolTipCode = 'data-toggle="tooltip" data-title=" '
1524 . str_replace(' - ', '<br>', $toolTipText)
1525 . '" data-html="true" data-placement="right"';
1526 return $toolTipCode;
1527 }
1528
1529 /**
1530 * Returns title-attribute information for ANY record (from a table defined in TCA of course)
1531 * 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.
1532 * "pages" table can be used as well and will return the result of ->titleAttribForPages() for that page.
1533 *
1534 * @param array $row Table row; $row is a row from the table, $table
1535 * @param string $table Table name
1536 * @return string
1537 */
1538 public static function getRecordIconAltText($row, $table = 'pages')
1539 {
1540 if ($table === 'pages') {
1541 $out = self::titleAttribForPages($row, '', 0);
1542 } else {
1543 $out = !empty(trim($GLOBALS['TCA'][$table]['ctrl']['descriptionColumn'])) ? $row[$GLOBALS['TCA'][$table]['ctrl']['descriptionColumn']] . ' ' : '';
1544 $ctrl = $GLOBALS['TCA'][$table]['ctrl']['enablecolumns'];
1545 // Uid is added
1546 $out .= 'id=' . $row['uid'];
1547 if ($table === 'pages' && $row['alias']) {
1548 $out .= ' / ' . $row['alias'];
1549 }
1550 if (static::isTableWorkspaceEnabled($table) && $row['pid'] < 0) {
1551 $out .= ' - v#1.' . $row['t3ver_id'];
1552 }
1553 if (static::isTableWorkspaceEnabled($table)) {
1554 switch (VersionState::cast($row['t3ver_state'])) {
1555 case new VersionState(VersionState::NEW_PLACEHOLDER):
1556 $out .= ' - PLH WSID#' . $row['t3ver_wsid'];
1557 break;
1558 case new VersionState(VersionState::DELETE_PLACEHOLDER):
1559 $out .= ' - Deleted element!';
1560 break;
1561 case new VersionState(VersionState::MOVE_PLACEHOLDER):
1562 $out .= ' - NEW LOCATION (PLH) WSID#' . $row['t3ver_wsid'];
1563 break;
1564 case new VersionState(VersionState::MOVE_POINTER):
1565 $out .= ' - OLD LOCATION (PNT) WSID#' . $row['t3ver_wsid'];
1566 break;
1567 case new VersionState(VersionState::NEW_PLACEHOLDER_VERSION):
1568 $out .= ' - New element!';
1569 break;
1570 }
1571 }
1572 // Hidden
1573 $lang = static::getLanguageService();
1574 if ($ctrl['disabled']) {
1575 $out .= $row[$ctrl['disabled']] ? ' - ' . $lang->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.hidden') : '';
1576 }
1577 if ($ctrl['starttime']) {
1578 if ($row[$ctrl['starttime']] > $GLOBALS['EXEC_TIME']) {
1579 $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') . ')';
1580 }
1581 }
1582 if ($row[$ctrl['endtime']]) {
1583 $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') . ')';
1584 }
1585 }
1586 return htmlspecialchars($out);
1587 }
1588
1589 /**
1590 * Returns the label of the first found entry in an "items" array from $GLOBALS['TCA'] (tablename = $table/fieldname = $col) where the value is $key
1591 *
1592 * @param string $table Table name, present in $GLOBALS['TCA']
1593 * @param string $col Field name, present in $GLOBALS['TCA']
1594 * @param string $key items-array value to match
1595 * @return string Label for item entry
1596 */
1597 public static function getLabelFromItemlist($table, $col, $key)
1598 {
1599 // Check, if there is an "items" array:
1600 if (is_array($GLOBALS['TCA'][$table])
1601 && is_array($GLOBALS['TCA'][$table]['columns'][$col])
1602 && is_array($GLOBALS['TCA'][$table]['columns'][$col]['config']['items'])
1603 ) {
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 ($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 ($GLOBALS['TCA'][$table]['ctrl']['label_alt']
1758 && ($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 ($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 ($theColConf['foreign_table'] && !$l && $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 (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('cshmanual')) {
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 $urlParameters = [
2643 'prErr' => 1,
2644 'uPT' => 1,
2645 ];
2646 $url = self::getModuleUrl('tce_db', $urlParameters) . $parameters . '&redirect=';
2647 if ((int)$redirectUrl === -1) {
2648 $url = GeneralUtility::quoteJSvalue($url) . '+T3_THIS_LOCATION';
2649 } else {
2650 $url .= rawurlencode($redirectUrl ?: GeneralUtility::getIndpEnv('REQUEST_URI'));
2651 }
2652 return $url;
2653 }
2654
2655 /**
2656 * Creates the view-on-click preview URL without any alternative URL.
2657 *
2658 * @param int $pageUid Page UID
2659 * @param array $rootLine If rootline is supplied, the function will look for the first found domain record and use that URL instead
2660 * @param string $anchorSection Optional anchor to the URL
2661 * @param string $additionalGetVars Additional GET variables.
2662 * @param string $viewScript The path to the script used to view the page
2663 *
2664 * @return string The preview URL
2665 */
2666 protected static function createPreviewUrl($pageUid, $rootLine, $anchorSection, $additionalGetVars, $viewScript)
2667 {
2668 // Look if a fixed preview language should be added:
2669 $beUser = static::getBackendUserAuthentication();
2670 $viewLanguageOrder = $beUser->getTSConfigVal('options.view.languageOrder');
2671
2672 if ((string)$viewLanguageOrder !== '') {
2673 $suffix = '';
2674 // Find allowed languages (if none, all are allowed!)
2675 $allowedLanguages = null;
2676 if (!$beUser->user['admin'] && $beUser->groupData['allowed_languages'] !== '') {
2677 $allowedLanguages = array_flip(explode(',', $beUser->groupData['allowed_languages']));
2678 }
2679 // Traverse the view order, match first occurrence:
2680 $languageOrder = GeneralUtility::intExplode(',', $viewLanguageOrder);
2681 foreach ($languageOrder as $langUid) {
2682 if (is_array($allowedLanguages) && !empty($allowedLanguages)) {
2683 // Choose if set.
2684 if (isset($allowedLanguages[$langUid])) {
2685 $suffix = '&L=' . $langUid;
2686 break;
2687 }
2688 } else {
2689 // All allowed since no lang. are listed.
2690 $suffix = '&L=' . $langUid;
2691 break;
2692 }
2693 }
2694 // Add it
2695 $additionalGetVars .= $suffix;
2696 }
2697
2698 // Check a mount point needs to be previewed
2699 $sys_page = GeneralUtility::makeInstance(\TYPO3\CMS\Frontend\Page\PageRepository::class);
2700 $sys_page->init(false);
2701 $mountPointInfo = $sys_page->getMountPointInfo($pageUid);
2702
2703 if ($mountPointInfo && $mountPointInfo['overlay']) {
2704 $pageUid = $mountPointInfo['mount_pid'];
2705 $additionalGetVars .= '&MP=' . $mountPointInfo['MPvar'];
2706 }
2707 $viewDomain = self::getViewDomain($pageUid, $rootLine);
2708
2709 return $viewDomain . $viewScript . $pageUid . $additionalGetVars . $anchorSection;
2710 }
2711
2712 /**
2713 * Builds the frontend view domain for a given page ID with a given root
2714 * line.
2715 *
2716 * @param int $pageId The page ID to use, must be > 0
2717 * @param array|NULL $rootLine The root line structure to use
2718 * @return string The full domain including the protocol http:// or https://, but without the trailing '/'
2719 */
2720 public static function getViewDomain($pageId, $rootLine = null)
2721 {
2722 $domain = rtrim(GeneralUtility::getIndpEnv('TYPO3_SITE_URL'), '/');
2723 if (!is_array($rootLine)) {
2724 $rootLine = self::BEgetRootLine($pageId);
2725 }
2726 // Checks alternate domains
2727 if (!empty($rootLine)) {
2728 $urlParts = parse_url($domain);
2729 $protocol = GeneralUtility::getIndpEnv('TYPO3_SSL') ? 'https' : 'http';
2730 $previewDomainConfig = static::getBackendUserAuthentication()->getTSConfig(
2731 'TCEMAIN.previewDomain',
2732 self::getPagesTSconfig($pageId)
2733 );
2734 if ($previewDomainConfig['value']) {
2735 if (strpos($previewDomainConfig['value'], '://') !== false) {
2736 list($protocol, $domainName) = explode('://', $previewDomainConfig['value']);
2737 } else {
2738 $domainName = $previewDomainConfig['value'];
2739 }
2740 } else {
2741 $domainName = self::firstDomainRecord($rootLine);
2742 }
2743 if ($domainName) {
2744 $domain = $domainName;
2745 } else {
2746 $domainRecord = self::getDomainStartPage($urlParts['host'], $urlParts['path']);
2747 $domain = $domainRecord['domainName'];
2748 }
2749 if ($domain) {
2750 $domain = $protocol . '://' . $domain;
2751 } else {
2752 $domain = rtrim(GeneralUtility::getIndpEnv('TYPO3_SITE_URL'), '/');
2753 }
2754 // Append port number if lockSSLPort is not the standard port 443
2755 $portNumber = (int)$GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSLPort'];
2756 if ($portNumber > 0 && $portNumber !== 443 && $portNumber < 65536 && $protocol === 'https') {
2757 $domain .= ':' . strval($portNumber);
2758 }
2759 }
2760 return $domain;
2761 }
2762
2763 /**
2764 * Returns the merged User/Page TSconfig for page id, $id.
2765 * Please read details about module programming elsewhere!
2766 *
2767 * @param int $id Page uid
2768 * @param string $TSref An object string which determines the path of the TSconfig to return.
2769 * @return array
2770 */
2771 public static function getModTSconfig($id, $TSref)
2772 {
2773 $beUser = static::getBackendUserAuthentication();
2774 $pageTS_modOptions = $beUser->getTSConfig($TSref, static::getPagesTSconfig($id));
2775 $BE_USER_modOptions = $beUser->getTSConfig($TSref);
2776 if (is_null($BE_USER_modOptions['value'])) {
2777 unset($BE_USER_modOptions['value']);
2778 }
2779 ArrayUtility::mergeRecursiveWithOverrule($pageTS_modOptions, $BE_USER_modOptions);
2780 return $pageTS_modOptions;
2781 }
2782
2783 /**
2784 * Returns a selector box "function menu" for a module
2785 * Requires the JS function jumpToUrl() to be available
2786 * See Inside TYPO3 for details about how to use / make Function menus
2787 *
2788 * @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=...
2789 * @param string $elementName The form elements name, probably something like "SET[...]
2790 * @param string $currentValue The value to be selected currently.
2791 * @param array $menuItems An array with the menu items for the selector box
2792 * @param string $script The script to send the &id to, if empty it's automatically found
2793 * @param string $addParams Additional parameters to pass to the script.
2794 * @return string HTML code for selector box
2795 */
2796 public static function getFuncMenu(
2797 $mainParams,
2798 $elementName,
2799 $currentValue,
2800 $menuItems,
2801 $script = '',
2802 $addParams = ''
2803 ) {
2804 if (!is_array($menuItems) || count($menuItems) <= 1) {
2805 return '';
2806 }
2807 $scriptUrl = self::buildScriptUrl($mainParams, $addParams, $script);
2808 $options = [];
2809 foreach ($menuItems as $value => $label) {
2810 $options[] = '<option value="'
2811 . htmlspecialchars($value) . '"'
2812 . ((string)$currentValue === (string)$value ? ' selected="selected"' : '') . '>'
2813 . htmlspecialchars($label, ENT_COMPAT, 'UTF-8', false) . '</option>';
2814 }
2815 if (!empty($options)) {
2816 $onChange = 'jumpToUrl(' . GeneralUtility::quoteJSvalue($scriptUrl . '&' . $elementName . '=') . '+this.options[this.selectedIndex].value,this);';
2817 return '
2818
2819 <!-- Function Menu of module -->
2820 <select class="form-control" name="' . $elementName . '" onchange="' . htmlspecialchars($onChange) . '">
2821 ' . implode('
2822 ', $options) . '
2823 </select>
2824 ';
2825 }
2826 return '';
2827 }
2828
2829 /**
2830 * Returns a selector box to switch the view
2831 * Requires the JS function jumpToUrl() to be available
2832 * Based on BackendUtility::getFuncMenu() but done as new function because it has another purpose.
2833 * Mingling with getFuncMenu would harm the docHeader Menu.
2834 *
2835 * @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=...
2836 * @param string $elementName The form elements name, probably something like "SET[...]
2837 * @param string $currentValue The value to be selected currently.
2838 * @param array $menuItems An array with the menu items for the selector box
2839 * @param string $script The script to send the &id to, if empty it's automatically found
2840 * @param string $addParams Additional parameters to pass to the script.
2841 * @return string HTML code for selector box
2842 */
2843 public static function getDropdownMenu(
2844 $mainParams,