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