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