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