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