68055be0e429e4564dcbe96772ea17d16853fa7b
[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 TYPO3\CMS\Backend\Routing\UriBuilder;
18 use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
19 use TYPO3\CMS\Core\Cache\CacheManager;
20 use TYPO3\CMS\Core\Cache\Frontend\VariableFrontend;
21 use TYPO3\CMS\Core\Database\Connection;
22 use TYPO3\CMS\Core\Database\ConnectionPool;
23 use TYPO3\CMS\Core\Database\Query\QueryBuilder;
24 use TYPO3\CMS\Core\Database\Query\QueryHelper;
25 use TYPO3\CMS\Core\Database\Query\Restriction\BackendWorkspaceRestriction;
26 use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
27 use TYPO3\CMS\Core\Database\Query\Restriction\HiddenRestriction;
28 use TYPO3\CMS\Core\Database\RelationHandler;
29 use TYPO3\CMS\Core\Imaging\Icon;
30 use TYPO3\CMS\Core\Imaging\IconFactory;
31 use TYPO3\CMS\Core\Imaging\ImageManipulation\CropVariantCollection;
32 use TYPO3\CMS\Core\Localization\LanguageService;
33 use TYPO3\CMS\Core\Resource\AbstractFile;
34 use TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException;
35 use TYPO3\CMS\Core\Resource\File;
36 use TYPO3\CMS\Core\Resource\ProcessedFile;
37 use TYPO3\CMS\Core\Resource\ResourceFactory;
38 use TYPO3\CMS\Core\Type\Bitmask\Permission;
39 use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser;
40 use TYPO3\CMS\Core\Utility\ArrayUtility;
41 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
42 use TYPO3\CMS\Core\Utility\GeneralUtility;
43 use TYPO3\CMS\Core\Utility\MathUtility;
44 use TYPO3\CMS\Core\Utility\PathUtility;
45 use TYPO3\CMS\Core\Versioning\VersionState;
46 use TYPO3\CMS\Frontend\Page\PageRepository;
47
48 /**
49 * Standard functions available for the TYPO3 backend.
50 * You are encouraged to use this class in your own applications (Backend Modules)
51 * Don't instantiate - call functions with "\TYPO3\CMS\Backend\Utility\BackendUtility::" prefixed the function name.
52 *
53 * Call ALL methods without making an object!
54 * Eg. to get a page-record 51 do this: '\TYPO3\CMS\Backend\Utility\BackendUtility::getRecord('pages',51)'
55 */
56 class BackendUtility
57 {
58 /**
59 * Cache the TCA configuration of tables with their types during runtime
60 *
61 * @var array
62 * @see self::getTCAtypes()
63 */
64 protected static $tcaTableTypeConfigurationCache = [];
65
66 /*******************************************
67 *
68 * SQL-related, selecting records, searching
69 *
70 *******************************************/
71 /**
72 * Returns the WHERE clause " AND NOT [tablename].[deleted-field]" if a deleted-field
73 * is configured in $GLOBALS['TCA'] for the tablename, $table
74 * This function should ALWAYS be called in the backend for selection on tables which
75 * are configured in $GLOBALS['TCA'] since it will ensure consistent selection of records,
76 * even if they are marked deleted (in which case the system must always treat them as non-existent!)
77 * In the frontend a function, ->enableFields(), is known to filter hidden-field, start- and endtime
78 * and fe_groups as well. But that is a job of the frontend, not the backend. If you need filtering
79 * on those fields as well in the backend you can use ->BEenableFields() though.
80 *
81 * @param string $table Table name present in $GLOBALS['TCA']
82 * @param string $tableAlias Table alias if any
83 * @return string WHERE clause for filtering out deleted records, eg " AND tablename.deleted=0
84 */
85 public static function deleteClause($table, $tableAlias = '')
86 {
87 if (empty($GLOBALS['TCA'][$table]['ctrl']['delete'])) {
88 return '';
89 }
90 $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
91 ->getQueryBuilderForTable($table)
92 ->expr();
93 return ' AND ' . $expressionBuilder->eq(
94 ($tableAlias ?: $table) . '.' . $GLOBALS['TCA'][$table]['ctrl']['delete'],
95 0
96 );
97 }
98
99 /**
100 * Gets record with uid = $uid from $table
101 * You can set $field to a list of fields (default is '*')
102 * Additional WHERE clauses can be added by $where (fx. ' AND blabla = 1')
103 * Will automatically check if records has been deleted and if so, not return anything.
104 * $table must be found in $GLOBALS['TCA']
105 *
106 * @param string $table Table name present in $GLOBALS['TCA']
107 * @param int $uid UID of record
108 * @param string $fields List of fields to select
109 * @param string $where Additional WHERE clause, eg. " AND blablabla = 0
110 * @param bool $useDeleteClause Use the deleteClause to check if a record is deleted (default TRUE)
111 * @return array|NULL Returns the row if found, otherwise NULL
112 */
113 public static function getRecord($table, $uid, $fields = '*', $where = '', $useDeleteClause = true)
114 {
115 // Ensure we have a valid uid (not 0 and not NEWxxxx) and a valid TCA
116 if ((int)$uid && !empty($GLOBALS['TCA'][$table])) {
117 $queryBuilder = static::getQueryBuilderForTable($table);
118
119 // do not use enabled fields here
120 $queryBuilder->getRestrictions()->removeAll();
121
122 // should the delete clause be used
123 if ($useDeleteClause) {
124 $queryBuilder->getRestrictions()->add(GeneralUtility::makeInstance(DeletedRestriction::class));
125 }
126
127 // set table and where clause
128 $queryBuilder
129 ->select(...GeneralUtility::trimExplode(',', $fields, true))
130 ->from($table)
131 ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)));
132
133 // add custom where clause
134 if ($where) {
135 $queryBuilder->andWhere(QueryHelper::stripLogicalOperatorPrefix($where));
136 }
137
138 $row = $queryBuilder->execute()->fetch();
139 if ($row) {
140 return $row;
141 }
142 }
143 return null;
144 }
145
146 /**
147 * Like getRecord(), but overlays workspace version if any.
148 *
149 * @param string $table Table name present in $GLOBALS['TCA']
150 * @param int $uid UID of record
151 * @param string $fields List of fields to select
152 * @param string $where Additional WHERE clause, eg. " AND blablabla = 0
153 * @param bool $useDeleteClause Use the deleteClause to check if a record is deleted (default TRUE)
154 * @param bool $unsetMovePointers If TRUE the function does not return a "pointer" row for moved records in a workspace
155 * @return array Returns the row if found, otherwise nothing
156 */
157 public static function getRecordWSOL(
158 $table,
159 $uid,
160 $fields = '*',
161 $where = '',
162 $useDeleteClause = true,
163 $unsetMovePointers = false
164 ) {
165 if ($fields !== '*') {
166 $internalFields = GeneralUtility::uniqueList($fields . ',uid,pid');
167 $row = self::getRecord($table, $uid, $internalFields, $where, $useDeleteClause);
168 self::workspaceOL($table, $row, -99, $unsetMovePointers);
169 if (is_array($row)) {
170 foreach ($row as $key => $_) {
171 if (!GeneralUtility::inList($fields, $key) && $key[0] !== '_') {
172 unset($row[$key]);
173 }
174 }
175 }
176 } else {
177 $row = self::getRecord($table, $uid, $fields, $where, $useDeleteClause);
178 self::workspaceOL($table, $row, -99, $unsetMovePointers);
179 }
180 return $row;
181 }
182
183 /**
184 * Purges computed properties starting with underscore character ('_').
185 *
186 * @param array $record
187 * @return array
188 */
189 public static function purgeComputedPropertiesFromRecord(array $record): array
190 {
191 return array_filter(
192 $record,
193 function (string $propertyName): bool {
194 return $propertyName[0] !== '_';
195 },
196 ARRAY_FILTER_USE_KEY
197 );
198 }
199
200 /**
201 * Purges computed property names starting with underscore character ('_').
202 *
203 * @param array $propertyNames
204 * @return array
205 */
206 public static function purgeComputedPropertyNames(array $propertyNames): array
207 {
208 return array_filter(
209 $propertyNames,
210 function (string $propertyName): bool {
211 return $propertyName[0] !== '_';
212 }
213 );
214 }
215
216 /**
217 * Makes an backwards explode on the $str and returns an array with ($table, $uid).
218 * Example: tt_content_45 => array('tt_content', 45)
219 *
220 * @param string $str [tablename]_[uid] string to explode
221 * @return array
222 */
223 public static function splitTable_Uid($str)
224 {
225 list($uid, $table) = explode('_', strrev($str), 2);
226 return [strrev($table), strrev($uid)];
227 }
228
229 /**
230 * Backend implementation of enableFields()
231 * Notice that "fe_groups" is not selected for - only disabled, starttime and endtime.
232 * Notice that deleted-fields are NOT filtered - you must ALSO call deleteClause in addition.
233 * $GLOBALS["SIM_ACCESS_TIME"] is used for date.
234 *
235 * @param string $table The table from which to return enableFields WHERE clause. Table name must have a 'ctrl' section in $GLOBALS['TCA'].
236 * @param bool $inv Means that the query will select all records NOT VISIBLE records (inverted selection)
237 * @return string WHERE clause part
238 */
239 public static function BEenableFields($table, $inv = false)
240 {
241 $ctrl = $GLOBALS['TCA'][$table]['ctrl'];
242 $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
243 ->getConnectionForTable($table)
244 ->getExpressionBuilder();
245 $query = $expressionBuilder->andX();
246 $invQuery = $expressionBuilder->orX();
247
248 if (is_array($ctrl)) {
249 if (is_array($ctrl['enablecolumns'])) {
250 if ($ctrl['enablecolumns']['disabled']) {
251 $field = $table . '.' . $ctrl['enablecolumns']['disabled'];
252 $query->add($expressionBuilder->eq($field, 0));
253 $invQuery->add($expressionBuilder->neq($field, 0));
254 }
255 if ($ctrl['enablecolumns']['starttime']) {
256 $field = $table . '.' . $ctrl['enablecolumns']['starttime'];
257 $query->add($expressionBuilder->lte($field, (int)$GLOBALS['SIM_ACCESS_TIME']));
258 $invQuery->add(
259 $expressionBuilder->andX(
260 $expressionBuilder->neq($field, 0),
261 $expressionBuilder->gt($field, (int)$GLOBALS['SIM_ACCESS_TIME'])
262 )
263 );
264 }
265 if ($ctrl['enablecolumns']['endtime']) {
266 $field = $table . '.' . $ctrl['enablecolumns']['endtime'];
267 $query->add(
268 $expressionBuilder->orX(
269 $expressionBuilder->eq($field, 0),
270 $expressionBuilder->gt($field, (int)$GLOBALS['SIM_ACCESS_TIME'])
271 )
272 );
273 $invQuery->add(
274 $expressionBuilder->andX(
275 $expressionBuilder->neq($field, 0),
276 $expressionBuilder->lte($field, (int)$GLOBALS['SIM_ACCESS_TIME'])
277 )
278 );
279 }
280 }
281 }
282
283 if ($query->count() === 0) {
284 return '';
285 }
286
287 return ' AND ' . ($inv ? $invQuery : $query);
288 }
289
290 /**
291 * Fetches the localization for a given record.
292 *
293 * @param string $table Table name present in $GLOBALS['TCA']
294 * @param int $uid The uid of the record
295 * @param int $language The uid of the language record in sys_language
296 * @param string $andWhereClause Optional additional WHERE clause (default: '')
297 * @return mixed Multidimensional array with selected records; if none exist, FALSE is returned
298 */
299 public static function getRecordLocalization($table, $uid, $language, $andWhereClause = '')
300 {
301 $recordLocalization = false;
302
303 // Pages still stores translations in the pages_language_overlay table, all other tables store in themself
304 if ($table === 'pages') {
305 $table = 'pages_language_overlay';
306 }
307
308 if (self::isTableLocalizable($table)) {
309 $tcaCtrl = $GLOBALS['TCA'][$table]['ctrl'];
310
311 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
312 ->getQueryBuilderForTable($table);
313 $queryBuilder->getRestrictions()
314 ->removeAll()
315 ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
316 ->add(GeneralUtility::makeInstance(BackendWorkspaceRestriction::class));
317
318 $queryBuilder->select('*')
319 ->from($table)
320 ->where(
321 $queryBuilder->expr()->eq(
322 $tcaCtrl['transOrigPointerField'],
323 $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
324 ),
325 $queryBuilder->expr()->eq(
326 $tcaCtrl['languageField'],
327 $queryBuilder->createNamedParameter((int)$language, \PDO::PARAM_INT)
328 )
329 )
330 ->setMaxResults(1);
331
332 if ($andWhereClause) {
333 $queryBuilder->andWhere(QueryHelper::stripLogicalOperatorPrefix($andWhereClause));
334 }
335
336 $recordLocalization = $queryBuilder->execute()->fetchAll();
337 }
338
339 return $recordLocalization;
340 }
341
342 /*******************************************
343 *
344 * Page tree, TCA related
345 *
346 *******************************************/
347 /**
348 * Returns what is called the 'RootLine'. That is an array with information about the page records from a page id
349 * ($uid) and back to the root.
350 * By default deleted pages are filtered.
351 * This RootLine will follow the tree all the way to the root. This is opposite to another kind of root line known
352 * from the frontend where the rootline stops when a root-template is found.
353 *
354 * @param int $uid Page id for which to create the root line.
355 * @param string $clause Clause can be used to select other criteria. It would typically be where-clauses that
356 * stops the process if we meet a page, the user has no reading access to.
357 * @param bool $workspaceOL If TRUE, version overlay is applied. This must be requested specifically because it is
358 * usually only wanted when the rootline is used for visual output while for permission checking you want the raw thing!
359 * @return array Root line array, all the way to the page tree root (or as far as $clause allows!)
360 */
361 public static function BEgetRootLine($uid, $clause = '', $workspaceOL = false)
362 {
363 static $BEgetRootLine_cache = [];
364 $output = [];
365 $pid = $uid;
366 $ident = $pid . '-' . $clause . '-' . $workspaceOL;
367 if (is_array($BEgetRootLine_cache[$ident])) {
368 $output = $BEgetRootLine_cache[$ident];
369 } else {
370 $loopCheck = 100;
371 $theRowArray = [];
372 while ($uid != 0 && $loopCheck) {
373 $loopCheck--;
374 $row = self::getPageForRootline($uid, $clause, $workspaceOL);
375 if (is_array($row)) {
376 $uid = $row['pid'];
377 $theRowArray[] = $row;
378 } else {
379 break;
380 }
381 }
382 if ($uid == 0) {
383 $theRowArray[] = ['uid' => 0, 'title' => ''];
384 }
385 $c = count($theRowArray);
386 foreach ($theRowArray as $val) {
387 $c--;
388 $output[$c] = [
389 'uid' => $val['uid'],
390 'pid' => $val['pid'],
391 'title' => $val['title'],
392 'doktype' => $val['doktype'],
393 'tsconfig_includes' => $val['tsconfig_includes'],
394 'TSconfig' => $val['TSconfig'],
395 'is_siteroot' => $val['is_siteroot'],
396 't3ver_oid' => $val['t3ver_oid'],
397 't3ver_wsid' => $val['t3ver_wsid'],
398 't3ver_state' => $val['t3ver_state'],
399 't3ver_stage' => $val['t3ver_stage'],
400 'backend_layout_next_level' => $val['backend_layout_next_level']
401 ];
402 if (isset($val['_ORIG_pid'])) {
403 $output[$c]['_ORIG_pid'] = $val['_ORIG_pid'];
404 }
405 }
406 $BEgetRootLine_cache[$ident] = $output;
407 }
408 return $output;
409 }
410
411 /**
412 * Gets the cached page record for the rootline
413 *
414 * @param int $uid Page id for which to create the root line.
415 * @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.
416 * @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!
417 * @return array Cached page record for the rootline
418 * @see BEgetRootLine
419 */
420 protected static function getPageForRootline($uid, $clause, $workspaceOL)
421 {
422 static $getPageForRootline_cache = [];
423 $ident = $uid . '-' . $clause . '-' . $workspaceOL;
424 if (is_array($getPageForRootline_cache[$ident])) {
425 $row = $getPageForRootline_cache[$ident];
426 } else {
427 $queryBuilder = static::getQueryBuilderForTable('pages');
428 $queryBuilder->getRestrictions()
429 ->removeAll()
430 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
431
432 $row = $queryBuilder
433 ->select(
434 'pid',
435 'uid',
436 'title',
437 'doktype',
438 'tsconfig_includes',
439 'TSconfig',
440 'is_siteroot',
441 't3ver_oid',
442 't3ver_wsid',
443 't3ver_state',
444 't3ver_stage',
445 'backend_layout_next_level'
446 )
447 ->from('pages')
448 ->where(
449 $queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)),
450 QueryHelper::stripLogicalOperatorPrefix($clause)
451 )
452 ->execute()
453 ->fetch();
454
455 if ($row) {
456 $newLocation = false;
457 if ($workspaceOL) {
458 self::workspaceOL('pages', $row);
459 $newLocation = self::getMovePlaceholder('pages', $row['uid'], 'pid');
460 }
461 if (is_array($row)) {
462 if ($newLocation !== false) {
463 $row['pid'] = $newLocation['pid'];
464 } else {
465 self::fixVersioningPid('pages', $row);
466 }
467 $getPageForRootline_cache[$ident] = $row;
468 }
469 }
470 }
471 return $row;
472 }
473
474 /**
475 * Opens the page tree to the specified page id
476 *
477 * @param int $pid Page id.
478 * @param bool $clearExpansion If set, then other open branches are closed.
479 */
480 public static function openPageTree($pid, $clearExpansion)
481 {
482 $beUser = static::getBackendUserAuthentication();
483 // Get current expansion data:
484 if ($clearExpansion) {
485 $expandedPages = [];
486 } else {
487 $expandedPages = unserialize($beUser->uc['browseTrees']['browsePages']);
488 }
489 // Get rootline:
490 $rL = self::BEgetRootLine($pid);
491 // First, find out what mount index to use (if more than one DB mount exists):
492 $mountIndex = 0;
493 $mountKeys = array_flip($beUser->returnWebmounts());
494 foreach ($rL as $rLDat) {
495 if (isset($mountKeys[$rLDat['uid']])) {
496 $mountIndex = $mountKeys[$rLDat['uid']];
497 break;
498 }
499 }
500 // Traverse rootline and open paths:
501 foreach ($rL as $rLDat) {
502 $expandedPages[$mountIndex][$rLDat['uid']] = 1;
503 }
504 // Write back:
505 $beUser->uc['browseTrees']['browsePages'] = serialize($expandedPages);
506 $beUser->writeUC();
507 }
508
509 /**
510 * Returns the path (visually) of a page $uid, fx. "/First page/Second page/Another subpage"
511 * Each part of the path will be limited to $titleLimit characters
512 * Deleted pages are filtered out.
513 *
514 * @param int $uid Page uid for which to create record path
515 * @param string $clause Clause is additional where clauses, eg.
516 * @param int $titleLimit Title limit
517 * @param int $fullTitleLimit Title limit of Full title (typ. set to 1000 or so)
518 * @return mixed Path of record (string) OR array with short/long title if $fullTitleLimit is set.
519 */
520 public static function getRecordPath($uid, $clause, $titleLimit, $fullTitleLimit = 0)
521 {
522 if (!$titleLimit) {
523 $titleLimit = 1000;
524 }
525 $output = $fullOutput = '/';
526 $clause = trim($clause);
527 if ($clause !== '' && substr($clause, 0, 3) !== 'AND') {
528 $clause = 'AND ' . $clause;
529 }
530 $data = self::BEgetRootLine($uid, $clause);
531 foreach ($data as $record) {
532 if ($record['uid'] === 0) {
533 continue;
534 }
535 $output = '/' . GeneralUtility::fixed_lgd_cs(strip_tags($record['title']), $titleLimit) . $output;
536 if ($fullTitleLimit) {
537 $fullOutput = '/' . GeneralUtility::fixed_lgd_cs(strip_tags($record['title']), $fullTitleLimit) . $fullOutput;
538 }
539 }
540 if ($fullTitleLimit) {
541 return [$output, $fullOutput];
542 } else {
543 return $output;
544 }
545 }
546
547 /**
548 * Gets the original translation pointer table.
549 * That is now the same table, apart from pages_language_overlay
550 * where pages is the original.
551 *
552 * @param string $table Name of the table
553 * @return string Pointer table (if any)
554 */
555 public static function getOriginalTranslationTable($table)
556 {
557 return $table === 'pages_language_overlay' ? 'pages' : $table;
558 }
559
560 /**
561 * Determines whether a table is localizable and has the languageField and transOrigPointerField set in $GLOBALS['TCA'].
562 *
563 * @param string $table The table to check
564 * @return bool Whether a table is localizable
565 */
566 public static function isTableLocalizable($table)
567 {
568 $isLocalizable = false;
569 if (isset($GLOBALS['TCA'][$table]['ctrl']) && is_array($GLOBALS['TCA'][$table]['ctrl'])) {
570 $tcaCtrl = $GLOBALS['TCA'][$table]['ctrl'];
571 $isLocalizable = isset($tcaCtrl['languageField']) && $tcaCtrl['languageField'] && isset($tcaCtrl['transOrigPointerField']) && $tcaCtrl['transOrigPointerField'];
572 }
573 return $isLocalizable;
574 }
575
576 /**
577 * Returns the value of the property localizationMode in the given $config array ($GLOBALS['TCA'][<table>]['columns'][<field>]['config']).
578 * If the table is prepared for localization and no localizationMode is set, 'select' is returned by default.
579 * If the table is not prepared for localization or not defined at all in $GLOBALS['TCA'], FALSE is returned.
580 *
581 * @param string $table The name of the table to lookup in TCA
582 * @param mixed $fieldOrConfig The fieldname (string) or the configuration of the field to check (array)
583 * @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
584 * @deprecated: IRRE 'localizationMode' is deprecated and will be removed in TYPO3 CMS 9, migrate to l10n_mode or allowLanguageSynchronization
585 */
586 public static function getInlineLocalizationMode($table, $fieldOrConfig)
587 {
588 $localizationMode = false;
589 $config = null;
590 if (is_array($fieldOrConfig) && !empty($fieldOrConfig)) {
591 $config = $fieldOrConfig;
592 } elseif (is_string($fieldOrConfig) && isset($GLOBALS['TCA'][$table]['columns'][$fieldOrConfig]['config'])) {
593 $config = $GLOBALS['TCA'][$table]['columns'][$fieldOrConfig]['config'];
594 }
595 if (is_array($config) && isset($config['type']) && $config['type'] === 'inline' && self::isTableLocalizable($table)) {
596 $localizationMode = isset($config['behaviour']['localizationMode']) && $config['behaviour']['localizationMode']
597 ? $config['behaviour']['localizationMode']
598 : 'select';
599 // The mode 'select' is not possible when child table is not localizable at all:
600 if ($localizationMode === 'select' && !self::isTableLocalizable($config['foreign_table'])) {
601 $localizationMode = false;
602 }
603 }
604 return $localizationMode;
605 }
606
607 /**
608 * 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.
609 * If $id is zero a pseudo root-page with "_thePath" set is returned IF the current BE_USER is admin.
610 * In any case ->isInWebMount must return TRUE for the user (regardless of $perms_clause)
611 *
612 * @param int $id Page uid for which to check read-access
613 * @param string $perms_clause This is typically a value generated with static::getBackendUserAuthentication()->getPagePermsClause(1);
614 * @return array|bool Returns page record if OK, otherwise FALSE.
615 */
616 public static function readPageAccess($id, $perms_clause)
617 {
618 if ((string)$id !== '') {
619 $id = (int)$id;
620 if (!$id) {
621 if (static::getBackendUserAuthentication()->isAdmin()) {
622 $path = '/';
623 $pageinfo['_thePath'] = $path;
624 return $pageinfo;
625 }
626 } else {
627 $pageinfo = self::getRecord('pages', $id, '*', $perms_clause);
628 if ($pageinfo['uid'] && static::getBackendUserAuthentication()->isInWebMount($id, $perms_clause)) {
629 self::workspaceOL('pages', $pageinfo);
630 if (is_array($pageinfo)) {
631 self::fixVersioningPid('pages', $pageinfo);
632 list($pageinfo['_thePath'], $pageinfo['_thePathFull']) = self::getRecordPath((int)$pageinfo['uid'], $perms_clause, 15, 1000);
633 return $pageinfo;
634 }
635 }
636 }
637 }
638 return false;
639 }
640
641 /**
642 * Returns the "types" configuration parsed into an array for the record, $rec, from table, $table
643 *
644 * @param string $table Table name (present in TCA)
645 * @param array $rec Record from $table
646 * @param bool $useFieldNameAsKey If $useFieldNameAsKey is set, then the fieldname is associative keys in the return array, otherwise just numeric keys.
647 * @return array|NULL
648 */
649 public static function getTCAtypes($table, $rec, $useFieldNameAsKey = false)
650 {
651 if ($GLOBALS['TCA'][$table]) {
652 // Get type value:
653 $fieldValue = self::getTCAtypeValue($table, $rec);
654 $cacheIdentifier = $table . '-type-' . $fieldValue . '-fnk-' . $useFieldNameAsKey;
655
656 // Fetch from first-level-cache if available
657 if (isset(self::$tcaTableTypeConfigurationCache[$cacheIdentifier])) {
658 return self::$tcaTableTypeConfigurationCache[$cacheIdentifier];
659 }
660
661 // Get typesConf
662 $typesConf = $GLOBALS['TCA'][$table]['types'][$fieldValue];
663 // Get fields list and traverse it
664 $fieldList = explode(',', $typesConf['showitem']);
665
666 // Add subtype fields e.g. for a valid RTE transformation
667 // The RTE runs the DB -> RTE transformation only, if the RTE field is part of the getTCAtypes array
668 if (isset($typesConf['subtype_value_field'])) {
669 $subType = $rec[$typesConf['subtype_value_field']];
670 if (isset($typesConf['subtypes_addlist'][$subType])) {
671 $subFields = GeneralUtility::trimExplode(',', $typesConf['subtypes_addlist'][$subType], true);
672 $fieldList = array_merge($fieldList, $subFields);
673 }
674 }
675
676 // Add palette fields e.g. for a valid RTE transformation
677 $paletteFieldList = [];
678 foreach ($fieldList as $fieldData) {
679 list($pFieldName, $pAltTitle, $pPalette) = GeneralUtility::trimExplode(';', $fieldData);
680 if ($pPalette
681 && isset($GLOBALS['TCA'][$table]['palettes'][$pPalette])
682 && is_array($GLOBALS['TCA'][$table]['palettes'][$pPalette])
683 && isset($GLOBALS['TCA'][$table]['palettes'][$pPalette]['showitem'])
684 ) {
685 $paletteFields = GeneralUtility::trimExplode(',', $GLOBALS['TCA'][$table]['palettes'][$pPalette]['showitem'], true);
686 foreach ($paletteFields as $paletteField) {
687 if ($paletteField !== '--linebreak--') {
688 $paletteFieldList[] = $paletteField;
689 }
690 }
691 }
692 }
693 $fieldList = array_merge($fieldList, $paletteFieldList);
694
695 $altFieldList = [];
696 // Traverse fields in types config and parse the configuration into a nice array:
697 foreach ($fieldList as $k => $v) {
698 list($pFieldName, $pAltTitle, $pPalette) = GeneralUtility::trimExplode(';', $v);
699 $fieldList[$k] = [
700 'field' => $pFieldName,
701 'title' => $pAltTitle,
702 'palette' => $pPalette,
703 'spec' => [],
704 'origString' => $v
705 ];
706 if ($useFieldNameAsKey) {
707 $altFieldList[$fieldList[$k]['field']] = $fieldList[$k];
708 }
709 }
710 if ($useFieldNameAsKey) {
711 $fieldList = $altFieldList;
712 }
713
714 // Add to first-level-cache
715 self::$tcaTableTypeConfigurationCache[$cacheIdentifier] = $fieldList;
716
717 // Return array:
718 return $fieldList;
719 }
720 return null;
721 }
722
723 /**
724 * Returns the "type" value of $rec from $table which can be used to look up the correct "types" rendering section in $GLOBALS['TCA']
725 * If no "type" field is configured in the "ctrl"-section of the $GLOBALS['TCA'] for the table, zero is used.
726 * 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)
727 *
728 * Note: This method is very similar to the type determination of FormDataProvider/DatabaseRecordTypeValue,
729 * however, it has two differences:
730 * 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).
731 * 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"
732 * and "group" field values are stored, which makes different processing of the "foreign pointer field" type field variant necessary.
733 *
734 * @param string $table Table name present in TCA
735 * @param array $row Record from $table
736 * @throws \RuntimeException
737 * @return string Field value
738 * @see getTCAtypes()
739 */
740 public static function getTCAtypeValue($table, $row)
741 {
742 $typeNum = 0;
743 if ($GLOBALS['TCA'][$table]) {
744 $field = $GLOBALS['TCA'][$table]['ctrl']['type'];
745 if (strpos($field, ':') !== false) {
746 list($pointerField, $foreignTableTypeField) = explode(':', $field);
747 // Get field value from database if field is not in the $row array
748 if (!isset($row[$pointerField])) {
749 $localRow = self::getRecord($table, $row['uid'], $pointerField);
750 $foreignUid = $localRow[$pointerField];
751 } else {
752 $foreignUid = $row[$pointerField];
753 }
754 if ($foreignUid) {
755 $fieldConfig = $GLOBALS['TCA'][$table]['columns'][$pointerField]['config'];
756 $relationType = $fieldConfig['type'];
757 if ($relationType === 'select') {
758 $foreignTable = $fieldConfig['foreign_table'];
759 } elseif ($relationType === 'group') {
760 $allowedTables = explode(',', $fieldConfig['allowed']);
761 $foreignTable = $allowedTables[0];
762 } else {
763 throw new \RuntimeException(
764 'TCA foreign field pointer fields are only allowed to be used with group or select field types.',
765 1325862240
766 );
767 }
768 $foreignRow = self::getRecord($foreignTable, $foreignUid, $foreignTableTypeField);
769 if ($foreignRow[$foreignTableTypeField]) {
770 $typeNum = $foreignRow[$foreignTableTypeField];
771 }
772 }
773 } else {
774 $typeNum = $row[$field];
775 }
776 // If that value is an empty string, set it to "0" (zero)
777 if (empty($typeNum)) {
778 $typeNum = 0;
779 }
780 }
781 // If current typeNum doesn't exist, set it to 0 (or to 1 for historical reasons, if 0 doesn't exist)
782 if (!$GLOBALS['TCA'][$table]['types'][$typeNum]) {
783 $typeNum = $GLOBALS['TCA'][$table]['types']['0'] ? 0 : 1;
784 }
785 // Force to string. Necessary for eg '-1' to be recognized as a type value.
786 $typeNum = (string)$typeNum;
787 return $typeNum;
788 }
789
790 /*******************************************
791 *
792 * Caching related
793 *
794 *******************************************/
795 /**
796 * Stores $data in the 'cache_hash' cache with the hash key, $hash
797 * and visual/symbolic identification, $ident
798 *
799 * @param string $hash 32 bit hash string (eg. a md5 hash of a serialized array identifying the data being stored)
800 * @param mixed $data The data to store
801 * @param string $ident $ident is just a textual identification in order to inform about the content!
802 */
803 public static function storeHash($hash, $data, $ident)
804 {
805 /** @var CacheManager $cacheManager */
806 $cacheManager = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Cache\CacheManager::class);
807 $cacheManager->getCache('cache_hash')->set($hash, $data, ['ident_' . $ident], 0);
808 }
809
810 /**
811 * Returns data stored for the hash string in the cache "cache_hash"
812 * Can be used to retrieved a cached value, array or object
813 *
814 * @param string $hash The hash-string which was used to store the data value
815 * @return mixed The "data" from the cache
816 */
817 public static function getHash($hash)
818 {
819 /** @var CacheManager $cacheManager */
820 $cacheManager = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Cache\CacheManager::class);
821 $cacheEntry = $cacheManager->getCache('cache_hash')->get($hash);
822 $hashContent = null;
823 if ($cacheEntry) {
824 $hashContent = $cacheEntry;
825 }
826 return $hashContent;
827 }
828
829 /*******************************************
830 *
831 * TypoScript related
832 *
833 *******************************************/
834 /**
835 * Returns the Page TSconfig for page with id, $id
836 *
837 * @param int $id Page uid for which to create Page TSconfig
838 * @param array $rootLine If $rootLine is an array, that is used as rootline, otherwise rootline is just calculated
839 * @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.
840 * @return array Page TSconfig
841 * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser
842 */
843 public static function getPagesTSconfig($id, $rootLine = null, $returnPartArray = false)
844 {
845 static $pagesTSconfig_cacheReference = [];
846 static $combinedTSconfig_cache = [];
847
848 $id = (int)$id;
849 if ($returnPartArray === false
850 && $rootLine === null
851 && isset($pagesTSconfig_cacheReference[$id])
852 ) {
853 return $combinedTSconfig_cache[$pagesTSconfig_cacheReference[$id]];
854 } else {
855 $TSconfig = [];
856 if (!is_array($rootLine)) {
857 $useCacheForCurrentPageId = true;
858 $rootLine = self::BEgetRootLine($id, '', true);
859 } else {
860 $useCacheForCurrentPageId = false;
861 }
862
863 // Order correctly
864 ksort($rootLine);
865 $TSdataArray = [];
866 // Setting default configuration
867 $TSdataArray['defaultPageTSconfig'] = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPageTSconfig'];
868 foreach ($rootLine as $k => $v) {
869 if (trim($v['tsconfig_includes'])) {
870 $includeTsConfigFileList = GeneralUtility::trimExplode(',', $v['tsconfig_includes'], true);
871 // Traversing list
872 foreach ($includeTsConfigFileList as $key => $includeTsConfigFile) {
873 if (strpos($includeTsConfigFile, 'EXT:') === 0) {
874 list($includeTsConfigFileExtensionKey, $includeTsConfigFilename) = explode(
875 '/',
876 substr($includeTsConfigFile, 4),
877 2
878 );
879 if ((string)$includeTsConfigFileExtensionKey !== ''
880 && ExtensionManagementUtility::isLoaded($includeTsConfigFileExtensionKey)
881 && (string)$includeTsConfigFilename !== ''
882 ) {
883 $includeTsConfigFileAndPath = ExtensionManagementUtility::extPath($includeTsConfigFileExtensionKey) .
884 $includeTsConfigFilename;
885 if (file_exists($includeTsConfigFileAndPath)) {
886 $TSdataArray['uid_' . $v['uid'] . '_static_' . $key] = file_get_contents($includeTsConfigFileAndPath);
887 }
888 }
889 }
890 }
891 }
892 $TSdataArray['uid_' . $v['uid']] = $v['TSconfig'];
893 }
894 $TSdataArray = static::emitGetPagesTSconfigPreIncludeSignal($TSdataArray, $id, $rootLine, $returnPartArray);
895 $TSdataArray = TypoScriptParser::checkIncludeLines_array($TSdataArray);
896 if ($returnPartArray) {
897 return $TSdataArray;
898 }
899 // Parsing the page TS-Config
900 $pageTS = implode(LF . '[GLOBAL]' . LF, $TSdataArray);
901 /* @var $parseObj \TYPO3\CMS\Backend\Configuration\TsConfigParser */
902 $parseObj = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Configuration\TsConfigParser::class);
903 $res = $parseObj->parseTSconfig($pageTS, 'PAGES', $id, $rootLine);
904 if ($res) {
905 $TSconfig = $res['TSconfig'];
906 }
907 $cacheHash = $res['hash'];
908 // Get User TSconfig overlay
909 $userTSconfig = static::getBackendUserAuthentication()->userTS['page.'];
910 if (is_array($userTSconfig)) {
911 ArrayUtility::mergeRecursiveWithOverrule($TSconfig, $userTSconfig);
912 $cacheHash .= '_user' . $GLOBALS['BE_USER']->user['uid'];
913 }
914
915 if ($useCacheForCurrentPageId) {
916 if (!isset($combinedTSconfig_cache[$cacheHash])) {
917 $combinedTSconfig_cache[$cacheHash] = $TSconfig;
918 }
919 $pagesTSconfig_cacheReference[$id] = $cacheHash;
920 }
921 }
922 return $TSconfig;
923 }
924
925 /*******************************************
926 *
927 * Users / Groups related
928 *
929 *******************************************/
930 /**
931 * Returns an array with be_users records of all user NOT DELETED sorted by their username
932 * Keys in the array is the be_users uid
933 *
934 * @param string $fields Optional $fields list (default: username,usergroup,usergroup_cached_list,uid) can be used to set the selected fields
935 * @param string $where Optional $where clause (fx. "AND username='pete'") can be used to limit query
936 * @return array
937 */
938 public static function getUserNames($fields = 'username,usergroup,usergroup_cached_list,uid', $where = '')
939 {
940 return self::getRecordsSortedByTitle(
941 GeneralUtility::trimExplode(',', $fields, true),
942 'be_users',
943 'username',
944 'AND pid=0 ' . $where
945 );
946 }
947
948 /**
949 * Returns an array with be_groups records (title, uid) of all groups NOT DELETED sorted by their title
950 *
951 * @param string $fields Field list
952 * @param string $where WHERE clause
953 * @return array
954 */
955 public static function getGroupNames($fields = 'title,uid', $where = '')
956 {
957 return self::getRecordsSortedByTitle(
958 GeneralUtility::trimExplode(',', $fields, true),
959 'be_groups',
960 'title',
961 'AND pid=0 ' . $where
962 );
963 }
964
965 /**
966 * Returns an array of all non-deleted records of a table sorted by a given title field.
967 * The value of the title field will be replaced by the return value
968 * of self::getRecordTitle() before the sorting is performed.
969 *
970 * @param array $fields Fields to select
971 * @param string $table Table name
972 * @param string $titleField Field that will contain the record title
973 * @param string $where Additional where clause
974 * @return array Array of sorted records
975 */
976 protected static function getRecordsSortedByTitle(array $fields, $table, $titleField, $where = '')
977 {
978 $fieldsIndex = array_flip($fields);
979 // Make sure the titleField is amongst the fields when getting sorted
980 $fieldsIndex[$titleField] = 1;
981
982 $result = [];
983
984 $queryBuilder = static::getQueryBuilderForTable($table);
985 $queryBuilder->getRestrictions()
986 ->removeAll()
987 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
988
989 $res = $queryBuilder
990 ->select('*')
991 ->from($table)
992 ->where(QueryHelper::stripLogicalOperatorPrefix($where))
993 ->execute();
994
995 while ($record = $res->fetch()) {
996 // store the uid, because it might be unset if it's not among the requested $fields
997 $recordId = $record['uid'];
998 $record[$titleField] = self::getRecordTitle($table, $record);
999
1000 // include only the requested fields in the result
1001 $result[$recordId] = array_intersect_key($record, $fieldsIndex);
1002 }
1003
1004 // sort records by $sortField. This is not done in the query because the title might have been overwritten by
1005 // self::getRecordTitle();
1006 return ArrayUtility::sortArraysByKey($result, $titleField);
1007 }
1008
1009 /**
1010 * Returns an array with be_groups records (like ->getGroupNames) but:
1011 * - 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.
1012 *
1013 * @param string $fields Field list; $fields specify the fields selected (default: title,uid)
1014 * @return array
1015 * @deprecated since TYPO3 9, will be removed in TYPO3 10
1016 */
1017 public static function getListGroupNames($fields = 'title, uid')
1018 {
1019 GeneralUtility::logDeprecatedFunction();
1020 $beUser = static::getBackendUserAuthentication();
1021 $exQ = '';
1022 if (!$beUser->isAdmin()) {
1023 $exQ = ' AND uid IN (' . ($beUser->user['usergroup_cached_list'] ?: 0) . ')';
1024 }
1025 return self::getGroupNames($fields, $exQ);
1026 }
1027
1028 /**
1029 * Returns the array $usernames with the names of all users NOT IN $groupArray changed to the uid (hides the usernames!).
1030 * If $excludeBlindedFlag is set, then these records are unset from the array $usernames
1031 * 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
1032 *
1033 * @param array $usernames User names
1034 * @param array $groupArray Group names
1035 * @param bool $excludeBlindedFlag If $excludeBlindedFlag is set, then these records are unset from the array $usernames
1036 * @return array User names, blinded
1037 */
1038 public static function blindUserNames($usernames, $groupArray, $excludeBlindedFlag = false)
1039 {
1040 if (is_array($usernames) && is_array($groupArray)) {
1041 foreach ($usernames as $uid => $row) {
1042 $userN = $uid;
1043 $set = 0;
1044 if ($row['uid'] != static::getBackendUserAuthentication()->user['uid']) {
1045 foreach ($groupArray as $v) {
1046 if ($v && GeneralUtility::inList($row['usergroup_cached_list'], $v)) {
1047 $userN = $row['username'];
1048 $set = 1;
1049 }
1050 }
1051 } else {
1052 $userN = $row['username'];
1053 $set = 1;
1054 }
1055 $usernames[$uid]['username'] = $userN;
1056 if ($excludeBlindedFlag && !$set) {
1057 unset($usernames[$uid]);
1058 }
1059 }
1060 }
1061 return $usernames;
1062 }
1063
1064 /**
1065 * Corresponds to blindUserNames but works for groups instead
1066 *
1067 * @param array $groups Group names
1068 * @param array $groupArray Group names (reference)
1069 * @param bool $excludeBlindedFlag If $excludeBlindedFlag is set, then these records are unset from the array $usernames
1070 * @return array
1071 */
1072 public static function blindGroupNames($groups, $groupArray, $excludeBlindedFlag = false)
1073 {
1074 if (is_array($groups) && is_array($groupArray)) {
1075 foreach ($groups as $uid => $row) {
1076 $groupN = $uid;
1077 $set = 0;
1078 if (in_array($uid, $groupArray, false)) {
1079 $groupN = $row['title'];
1080 $set = 1;
1081 }
1082 $groups[$uid]['title'] = $groupN;
1083 if ($excludeBlindedFlag && !$set) {
1084 unset($groups[$uid]);
1085 }
1086 }
1087 }
1088 return $groups;
1089 }
1090
1091 /*******************************************
1092 *
1093 * Output related
1094 *
1095 *******************************************/
1096 /**
1097 * Returns the difference in days between input $tstamp and $EXEC_TIME
1098 *
1099 * @param int $tstamp Time stamp, seconds
1100 * @return int
1101 */
1102 public static function daysUntil($tstamp)
1103 {
1104 $delta_t = $tstamp - $GLOBALS['EXEC_TIME'];
1105 return ceil($delta_t / (3600 * 24));
1106 }
1107
1108 /**
1109 * Returns $tstamp formatted as "ddmmyy" (According to $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'])
1110 *
1111 * @param int $tstamp Time stamp, seconds
1112 * @return string Formatted time
1113 */
1114 public static function date($tstamp)
1115 {
1116 return date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'], (int)$tstamp);
1117 }
1118
1119 /**
1120 * Returns $tstamp formatted as "ddmmyy hhmm" (According to $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] AND $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'])
1121 *
1122 * @param int $value Time stamp, seconds
1123 * @return string Formatted time
1124 */
1125 public static function datetime($value)
1126 {
1127 return date(
1128 $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'],
1129 $value
1130 );
1131 }
1132
1133 /**
1134 * Returns $value (in seconds) formatted as hh:mm:ss
1135 * For instance $value = 3600 + 60*2 + 3 should return "01:02:03"
1136 *
1137 * @param int $value Time stamp, seconds
1138 * @param bool $withSeconds Output hh:mm:ss. If FALSE: hh:mm
1139 * @return string Formatted time
1140 */
1141 public static function time($value, $withSeconds = true)
1142 {
1143 return gmdate('H:i' . ($withSeconds ? ':s' : ''), (int)$value);
1144 }
1145
1146 /**
1147 * Returns the "age" in minutes / hours / days / years of the number of $seconds inputted.
1148 *
1149 * @param int $seconds Seconds could be the difference of a certain timestamp and time()
1150 * @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")
1151 * @return string Formatted time
1152 */
1153 public static function calcAge($seconds, $labels = ' min| hrs| days| yrs| min| hour| day| year')
1154 {
1155 $labelArr = explode('|', $labels);
1156 $absSeconds = abs($seconds);
1157 $sign = $seconds < 0 ? -1 : 1;
1158 if ($absSeconds < 3600) {
1159 $val = round($absSeconds / 60);
1160 $seconds = $sign * $val . ($val == 1 ? $labelArr[4] : $labelArr[0]);
1161 } elseif ($absSeconds < 24 * 3600) {
1162 $val = round($absSeconds / 3600);
1163 $seconds = $sign * $val . ($val == 1 ? $labelArr[5] : $labelArr[1]);
1164 } elseif ($absSeconds < 365 * 24 * 3600) {
1165 $val = round($absSeconds / (24 * 3600));
1166 $seconds = $sign * $val . ($val == 1 ? $labelArr[6] : $labelArr[2]);
1167 } else {
1168 $val = round($absSeconds / (365 * 24 * 3600));
1169 $seconds = $sign * $val . ($val == 1 ? $labelArr[7] : $labelArr[3]);
1170 }
1171 return $seconds;
1172 }
1173
1174 /**
1175 * Returns a formatted timestamp if $tstamp is set.
1176 * The date/datetime will be followed by the age in parenthesis.
1177 *
1178 * @param int $tstamp Time stamp, seconds
1179 * @param int $prefix 1/-1 depending on polarity of age.
1180 * @param string $date $date=="date" will yield "dd:mm:yy" formatting, otherwise "dd:mm:yy hh:mm
1181 * @return string
1182 */
1183 public static function dateTimeAge($tstamp, $prefix = 1, $date = '')
1184 {
1185 if (!$tstamp) {
1186 return '';
1187 }
1188 $label = static::getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.minutesHoursDaysYears');
1189 $age = ' (' . self::calcAge($prefix * ($GLOBALS['EXEC_TIME'] - $tstamp), $label) . ')';
1190 return ($date === 'date' ? self::date($tstamp) : self::datetime($tstamp)) . $age;
1191 }
1192
1193 /**
1194 * Resolves file references for a given record.
1195 *
1196 * @param string $tableName Name of the table of the record
1197 * @param string $fieldName Name of the field of the record
1198 * @param array $element Record data
1199 * @param NULL|int $workspaceId Workspace to fetch data for
1200 * @return NULL|\TYPO3\CMS\Core\Resource\FileReference[]
1201 */
1202 public static function resolveFileReferences($tableName, $fieldName, $element, $workspaceId = null)
1203 {
1204 if (empty($GLOBALS['TCA'][$tableName]['columns'][$fieldName]['config'])) {
1205 return null;
1206 }
1207 $configuration = $GLOBALS['TCA'][$tableName]['columns'][$fieldName]['config'];
1208 if (empty($configuration['type']) || $configuration['type'] !== 'inline'
1209 || empty($configuration['foreign_table']) || $configuration['foreign_table'] !== 'sys_file_reference'
1210 ) {
1211 return null;
1212 }
1213
1214 $fileReferences = [];
1215 /** @var $relationHandler RelationHandler */
1216 $relationHandler = GeneralUtility::makeInstance(RelationHandler::class);
1217 if ($workspaceId !== null) {
1218 $relationHandler->setWorkspaceId($workspaceId);
1219 }
1220 $relationHandler->start(
1221 $element[$fieldName],
1222 $configuration['foreign_table'],
1223 $configuration['MM'],
1224 $element['uid'],
1225 $tableName,
1226 $configuration
1227 );
1228 $relationHandler->processDeletePlaceholder();
1229 $referenceUids = $relationHandler->tableArray[$configuration['foreign_table']];
1230
1231 foreach ($referenceUids as $referenceUid) {
1232 try {
1233 $fileReference = ResourceFactory::getInstance()->getFileReferenceObject(
1234 $referenceUid,
1235 [],
1236 ($workspaceId === 0)
1237 );
1238 $fileReferences[$fileReference->getUid()] = $fileReference;
1239 } catch (\TYPO3\CMS\Core\Resource\Exception\FileDoesNotExistException $e) {
1240 /**
1241 * We just catch the exception here
1242 * Reasoning: There is nothing an editor or even admin could do
1243 */
1244 } catch (\InvalidArgumentException $e) {
1245 /**
1246 * The storage does not exist anymore
1247 * Log the exception message for admins as they maybe can restore the storage
1248 */
1249 $logMessage = $e->getMessage() . ' (table: "' . $tableName . '", fieldName: "' . $fieldName . '", referenceUid: ' . $referenceUid . ')';
1250 GeneralUtility::sysLog($logMessage, 'core', GeneralUtility::SYSLOG_SEVERITY_ERROR);
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 } else {
2243 return $l;
2244 }
2245 }
2246
2247 /**
2248 * 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.
2249 *
2250 * @param string $table Table name, present in TCA
2251 * @param string $fN Field name
2252 * @param string $fV Field value
2253 * @param int $fixed_lgd_chars The max amount of characters the value may occupy
2254 * @param int $uid Uid of the current record
2255 * @param bool $forceResult If BackendUtility::getRecordTitle is used to process the value, this parameter is forwarded.
2256 * @param int $pid Optional page uid is used to evaluate page TSConfig for the given field
2257 * @return string
2258 * @see getProcessedValue()
2259 */
2260 public static function getProcessedValueExtra(
2261 $table,
2262 $fN,
2263 $fV,
2264 $fixed_lgd_chars = 0,
2265 $uid = 0,
2266 $forceResult = true,
2267 $pid = 0
2268 ) {
2269 $fVnew = self::getProcessedValue($table, $fN, $fV, $fixed_lgd_chars, 1, 0, $uid, $forceResult, $pid);
2270 if (!isset($fVnew)) {
2271 if (is_array($GLOBALS['TCA'][$table])) {
2272 if ($fN == $GLOBALS['TCA'][$table]['ctrl']['tstamp'] || $fN == $GLOBALS['TCA'][$table]['ctrl']['crdate']) {
2273 $fVnew = self::datetime($fV);
2274 } elseif ($fN === 'pid') {
2275 // Fetches the path with no regard to the users permissions to select pages.
2276 $fVnew = self::getRecordPath($fV, '1=1', 20);
2277 } else {
2278 $fVnew = $fV;
2279 }
2280 }
2281 }
2282 return $fVnew;
2283 }
2284
2285 /**
2286 * Returns fields for a table, $table, which would typically be interesting to select
2287 * This includes uid, the fields defined for title, icon-field.
2288 * 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)
2289 *
2290 * @param string $table Table name, present in $GLOBALS['TCA']
2291 * @param string $prefix Table prefix
2292 * @param array $fields Preset fields (must include prefix if that is used)
2293 * @return string List of fields.
2294 */
2295 public static function getCommonSelectFields($table, $prefix = '', $fields = [])
2296 {
2297 $fields[] = $prefix . 'uid';
2298 if (isset($GLOBALS['TCA'][$table]['ctrl']['label']) && $GLOBALS['TCA'][$table]['ctrl']['label'] != '') {
2299 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['label'];
2300 }
2301 if ($GLOBALS['TCA'][$table]['ctrl']['label_alt']) {
2302 $secondFields = GeneralUtility::trimExplode(',', $GLOBALS['TCA'][$table]['ctrl']['label_alt'], true);
2303 foreach ($secondFields as $fieldN) {
2304 $fields[] = $prefix . $fieldN;
2305 }
2306 }
2307 if (static::isTableWorkspaceEnabled($table)) {
2308 $fields[] = $prefix . 't3ver_id';
2309 $fields[] = $prefix . 't3ver_state';
2310 $fields[] = $prefix . 't3ver_wsid';
2311 $fields[] = $prefix . 't3ver_count';
2312 }
2313 if ($GLOBALS['TCA'][$table]['ctrl']['selicon_field']) {
2314 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['selicon_field'];
2315 }
2316 if ($GLOBALS['TCA'][$table]['ctrl']['typeicon_column']) {
2317 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['typeicon_column'];
2318 }
2319 if (is_array($GLOBALS['TCA'][$table]['ctrl']['enablecolumns'])) {
2320 if ($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['disabled']) {
2321 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['disabled'];
2322 }
2323 if ($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['starttime']) {
2324 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['starttime'];
2325 }
2326 if ($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['endtime']) {
2327 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['endtime'];
2328 }
2329 if ($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['fe_group']) {
2330 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['fe_group'];
2331 }
2332 }
2333 return implode(',', array_unique($fields));
2334 }
2335
2336 /*******************************************
2337 *
2338 * Backend Modules API functions
2339 *
2340 *******************************************/
2341
2342 /**
2343 * Returns CSH help text (description), if configured for, as an array (title, description)
2344 *
2345 * @param string $table Table name
2346 * @param string $field Field name
2347 * @return array With keys 'description' (raw, as available in locallang), 'title' (optional), 'moreInfo'
2348 */
2349 public static function helpTextArray($table, $field)
2350 {
2351 if (!isset($GLOBALS['TCA_DESCR'][$table]['columns'])) {
2352 static::getLanguageService()->loadSingleTableDescription($table);
2353 }
2354 $output = [
2355 'description' => null,
2356 'title' => null,
2357 'moreInfo' => false
2358 ];
2359 if (is_array($GLOBALS['TCA_DESCR'][$table]) && is_array($GLOBALS['TCA_DESCR'][$table]['columns'][$field])) {
2360 $data = $GLOBALS['TCA_DESCR'][$table]['columns'][$field];
2361 // Add alternative title, if defined
2362 if ($data['alttitle']) {
2363 $output['title'] = $data['alttitle'];
2364 }
2365 // If we have more information to show and access to the cshmanual
2366 if (($data['image_descr'] || $data['seeAlso'] || $data['details'] || $data['syntax'])
2367 && static::getBackendUserAuthentication()->check('modules', 'help_CshmanualCshmanual')
2368 ) {
2369 $output['moreInfo'] = true;
2370 }
2371 // Add description
2372 if ($data['description']) {
2373 $output['description'] = $data['description'];
2374 }
2375 }
2376 return $output;
2377 }
2378
2379 /**
2380 * Returns CSH help text
2381 *
2382 * @param string $table Table name
2383 * @param string $field Field name
2384 * @return string HTML content for help text
2385 * @see cshItem()
2386 */
2387 public static function helpText($table, $field)
2388 {
2389 $helpTextArray = self::helpTextArray($table, $field);
2390 $output = '';
2391 $arrow = '';
2392 // Put header before the rest of the text
2393 if ($helpTextArray['title'] !== null) {
2394 $output .= '<h2>' . $helpTextArray['title'] . '</h2>';
2395 }
2396 // Add see also arrow if we have more info
2397 if ($helpTextArray['moreInfo']) {
2398 /** @var IconFactory $iconFactory */
2399 $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
2400 $arrow = $iconFactory->getIcon('actions-view-go-forward', Icon::SIZE_SMALL)->render();
2401 }
2402 // Wrap description and arrow in p tag
2403 if ($helpTextArray['description'] !== null || $arrow) {
2404 $output .= '<p class="t3-help-short">' . nl2br(htmlspecialchars($helpTextArray['description'])) . $arrow . '</p>';
2405 }
2406 return $output;
2407 }
2408
2409 /**
2410 * API function that wraps the text / html in help text, so if a user hovers over it
2411 * the help text will show up
2412 * This is the new help API function since TYPO3 4.5, and uses the new behaviour
2413 * (hover over text, no icon, no fulltext option, no option to disable the help)
2414 *
2415 * @param string $table The table name for which the help should be shown
2416 * @param string $field The field name for which the help should be shown
2417 * @param string $text The text which should be wrapped with the help text
2418 * @param array $overloadHelpText Array with text to overload help text
2419 * @return string the HTML code ready to render
2420 */
2421 public static function wrapInHelp($table, $field, $text = '', array $overloadHelpText = [])
2422 {
2423 // Initialize some variables
2424 $helpText = '';
2425 $abbrClassAdd = '';
2426 $hasHelpTextOverload = !empty($overloadHelpText);
2427 // Get the help text that should be shown on hover
2428 if (!$hasHelpTextOverload) {
2429 $helpText = self::helpText($table, $field);
2430 }
2431 // If there's a help text or some overload information, proceed with preparing an output
2432 // @todo: right now this is a hard dependency on csh manual, as the whole help system should be moved to
2433 // the extension. The core provides an API for adding help and rendering help, but the rendering
2434 // should be up to the extension itself
2435 if ((!empty($helpText) || $hasHelpTextOverload) && ExtensionManagementUtility::isLoaded('cshmanual')) {
2436 // If no text was given, just use the regular help icon
2437 if ($text == '') {
2438 /** @var IconFactory $iconFactory */
2439 $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
2440 $text = $iconFactory->getIcon('actions-system-help-open', Icon::SIZE_SMALL)->render();
2441 $abbrClassAdd = '-icon';
2442 }
2443 $text = '<abbr class="t3-help-teaser' . $abbrClassAdd . '">' . $text . '</abbr>';
2444 $wrappedText = '<span class="t3-help-link" href="#" data-table="' . $table . '" data-field="' . $field . '"';
2445 // The overload array may provide a title and a description
2446 // If either one is defined, add them to the "data" attributes
2447 if ($hasHelpTextOverload) {
2448 if (isset($overloadHelpText['title'])) {
2449 $wrappedText .= ' data-title="' . htmlspecialchars($overloadHelpText['title']) . '"';
2450 }
2451 if (isset($overloadHelpText['description'])) {
2452 $wrappedText .= ' data-description="' . htmlspecialchars($overloadHelpText['description']) . '"';
2453 }
2454 }
2455 $wrappedText .= '>' . $text . '</span>';
2456 return $wrappedText;
2457 }
2458 return $text;
2459 }
2460
2461 /**
2462 * API for getting CSH icons/text for use in backend modules.
2463 * TCA_DESCR will be loaded if it isn't already
2464 *
2465 * @param string $table Table name ('_MOD_'+module name)
2466 * @param string $field Field name (CSH locallang main key)
2467 * @param string $_ (unused)
2468 * @param string $wrap Wrap code for icon-mode, splitted by "|". Not used for full-text mode.
2469 * @return string HTML content for help text
2470 */
2471 public static function cshItem($table, $field, $_ = '', $wrap = '')
2472 {
2473 static::getLanguageService()->loadSingleTableDescription($table);
2474 if (is_array($GLOBALS['TCA_DESCR'][$table])
2475 && is_array($GLOBALS['TCA_DESCR'][$table]['columns'][$field])
2476 ) {
2477 // Creating short description
2478 $output = self::wrapInHelp($table, $field);
2479 if ($output && $wrap) {
2480 $wrParts = explode('|', $wrap);
2481 $output = $wrParts[0] . $output . $wrParts[1];
2482 }
2483 return $output;
2484 }
2485 return '';
2486 }
2487
2488 /**
2489 * 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.
2490 * REMEMBER to always htmlspecialchar() content in href-properties to ampersands get converted to entities (XHTML requirement and XSS precaution)
2491 *
2492 * @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.
2493 * @param string $_ (unused)
2494 * @param string $requestUri An optional returnUrl you can set - automatically set to REQUEST_URI.
2495 *
2496 * @return string
2497 */
2498 public static function editOnClick($params, $_ = '', $requestUri = '')
2499 {
2500 if ($requestUri == -1) {
2501 $returnUrl = 'T3_THIS_LOCATION';
2502 } else {
2503 $returnUrl = GeneralUtility::quoteJSvalue(rawurlencode($requestUri ?: GeneralUtility::getIndpEnv('REQUEST_URI')));
2504 }
2505 return 'window.location.href=' . GeneralUtility::quoteJSvalue(self::getModuleUrl('record_edit') . $params . '&returnUrl=') . '+' . $returnUrl . '; return false;';
2506 }
2507
2508 /**
2509 * Returns a JavaScript string for viewing the page id, $id
2510 * It will detect the correct domain name if needed and provide the link with the right back path.
2511 * Also it will re-use any window already open.
2512 *
2513 * @param int $pageUid Page UID
2514 * @param string $backPath Must point back to TYPO3_mainDir (where the site is assumed to be one level above)
2515 * @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)
2516 * @param string $anchorSection Optional anchor to the URL
2517 * @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!
2518 * @param string $additionalGetVars Additional GET variables.
2519 * @param bool $switchFocus If TRUE, then the preview window will gain the focus.
2520 * @return string
2521 */
2522 public static function viewOnClick(
2523 $pageUid,
2524 $backPath = '',
2525 $rootLine = null,
2526 $anchorSection = '',
2527 $alternativeUrl = '',
2528 $additionalGetVars = '',
2529 $switchFocus = true
2530 ) {
2531 $viewScript = '/index.php?id=';
2532 if ($alternativeUrl) {
2533 $viewScript = $alternativeUrl;
2534 }
2535
2536 if (
2537 isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['viewOnClickClass'])
2538 && is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['viewOnClickClass'])
2539 ) {
2540 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['viewOnClickClass'] as $className) {
2541 $hookObj = GeneralUtility::makeInstance($className);
2542 if (method_exists($hookObj, 'preProcess')) {
2543 $hookObj->preProcess(
2544 $pageUid,
2545 $backPath,
2546 $rootLine,
2547 $anchorSection,
2548 $viewScript,
2549 $additionalGetVars,
2550 $switchFocus
2551 );
2552 }
2553 }
2554 }
2555
2556 if ($alternativeUrl) {
2557 $previewUrl = $viewScript;
2558 } else {
2559 $permissionClause = $GLOBALS['BE_USER']->getPagePermsClause(Permission::PAGE_SHOW);
2560 $pageInfo = self::readPageAccess($pageUid, $permissionClause);
2561 $additionalGetVars .= self::ADMCMD_previewCmds($pageInfo);
2562 $previewUrl = self::createPreviewUrl($pageUid, $rootLine, $anchorSection, $additionalGetVars, $viewScript);
2563 }
2564
2565 if (
2566 isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['viewOnClickClass'])
2567 && is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['viewOnClickClass'])
2568 ) {
2569 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['viewOnClickClass'] as $className) {
2570 $hookObj = GeneralUtility::makeInstance($className);
2571 if (method_exists($hookObj, 'postProcess')) {
2572 $previewUrl = $hookObj->postProcess(
2573 $previewUrl,
2574 $pageUid,
2575 $rootLine,
2576 $anchorSection,
2577 $viewScript,
2578 $additionalGetVars,
2579 $switchFocus
2580 );
2581 }
2582 }
2583 }
2584
2585 $onclickCode = 'var previewWin = window.open(' . GeneralUtility::quoteJSvalue($previewUrl) . ',\'newTYPO3frontendWindow\');' . ($switchFocus ? 'previewWin.focus();' : '');
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,
2845 $elementName,
2846 $currentValue,
2847 $menuItems,
2848 $script = '',
2849 $addParams = ''
2850 ) {
2851 if (!is_array($menuItems) || count($menuItems) <= 1) {
2852 return '';
2853 }
2854 $scriptUrl = self::buildScriptUrl($mainParams, $addParams, $script);
2855 $options = [];
2856 foreach ($menuItems as $value => $label) {
2857 $options[] = '<option value="'
2858 . htmlspecialchars($value) . '"'
2859 . ((string)$currentValue === (string)$value ? ' selected="selected"' : '') . '>'
2860 . htmlspecialchars($label, ENT_COMPAT, 'UTF-8', false) . '</option>';
2861 }
2862 if (!empty($options)) {
2863 $onChange = 'jumpToUrl(' . GeneralUtility::quoteJSvalue($scriptUrl . '&' . $elementName . '=') . '+this.options[this.selectedIndex].value,this);';
2864 return '
2865 <div class="form-group">
2866 <!-- Function Menu of module -->
2867 <select class="form-control input-sm" name="' . htmlspecialchars($elementName) . '" onchange="' . htmlspecialchars($onChange) . '">
2868 ' . implode(LF, $options) . '
2869 </select>
2870 </div>
2871 ';
2872 }
2873 return '';
2874 }
2875
2876 /**
2877 * Checkbox function menu.
2878 * Works like ->getFuncMenu() but takes no $menuItem array since this is a simple checkbox.
2879 *
2880 * @param mixed $mainParams $id is the "&id=" parameter value to be sent to the module, but it can be also a parameter array which will be passed instead of the &id=...