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