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