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