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