[TASK] Introduce DeprecationUtility and move methods
[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\Messaging\FlashMessage;
27 use TYPO3\CMS\Core\Resource\AbstractFile;
28 use TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException;
29 use TYPO3\CMS\Core\Resource\File;
30 use TYPO3\CMS\Core\Resource\ProcessedFile;
31 use TYPO3\CMS\Core\Resource\ResourceFactory;
32 use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser;
33 use TYPO3\CMS\Core\Utility\ArrayUtility;
34 use TYPO3\CMS\Core\Utility\DeprecationUtility;
35 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
36 use TYPO3\CMS\Core\Utility\GeneralUtility;
37 use TYPO3\CMS\Core\Utility\HttpUtility;
38 use TYPO3\CMS\Core\Utility\MathUtility;
39 use TYPO3\CMS\Core\Utility\PathUtility;
40 use TYPO3\CMS\Core\Utility\StringUtility;
41 use TYPO3\CMS\Core\Versioning\VersionState;
42 use TYPO3\CMS\Frontend\Page\PageRepository;
43 use TYPO3\CMS\Lang\LanguageService;
44
45 /**
46 * Standard functions available for the TYPO3 backend.
47 * You are encouraged to use this class in your own applications (Backend Modules)
48 * Don't instantiate - call functions with "\TYPO3\CMS\Backend\Utility\BackendUtility::" prefixed the function name.
49 *
50 * Call ALL methods without making an object!
51 * Eg. to get a page-record 51 do this: '\TYPO3\CMS\Backend\Utility\BackendUtility::getRecord('pages',51)'
52 */
53 class BackendUtility
54 {
55 /**
56 * Cache the TCA configuration of tables with their types during runtime
57 *
58 * @var array
59 * @see self::getTCAtypes()
60 */
61 protected static $tcaTableTypeConfigurationCache = array();
62
63 /*******************************************
64 *
65 * SQL-related, selecting records, searching
66 *
67 *******************************************/
68 /**
69 * Returns the WHERE clause " AND NOT [tablename].[deleted-field]" if a deleted-field
70 * is configured in $GLOBALS['TCA'] for the tablename, $table
71 * This function should ALWAYS be called in the backend for selection on tables which
72 * are configured in $GLOBALS['TCA'] since it will ensure consistent selection of records,
73 * even if they are marked deleted (in which case the system must always treat them as non-existent!)
74 * In the frontend a function, ->enableFields(), is known to filter hidden-field, start- and endtime
75 * and fe_groups as well. But that is a job of the frontend, not the backend. If you need filtering
76 * on those fields as well in the backend you can use ->BEenableFields() though.
77 *
78 * @param string $table Table name present in $GLOBALS['TCA']
79 * @param string $tableAlias Table alias if any
80 * @return string WHERE clause for filtering out deleted records, eg " AND tablename.deleted=0
81 */
82 public static function deleteClause($table, $tableAlias = '')
83 {
84 if (!empty($GLOBALS['TCA'][$table]['ctrl']['delete'])) {
85 return ' AND ' . ($tableAlias ?: $table) . '.' . $GLOBALS['TCA'][$table]['ctrl']['delete'] . '=0';
86 } else {
87 return '';
88 }
89 }
90
91 /**
92 * Gets record with uid = $uid from $table
93 * You can set $field to a list of fields (default is '*')
94 * Additional WHERE clauses can be added by $where (fx. ' AND blabla = 1')
95 * Will automatically check if records has been deleted and if so, not return anything.
96 * $table must be found in $GLOBALS['TCA']
97 *
98 * @param string $table Table name present in $GLOBALS['TCA']
99 * @param int $uid UID of record
100 * @param string $fields List of fields to select
101 * @param string $where Additional WHERE clause, eg. " AND blablabla = 0
102 * @param bool $useDeleteClause Use the deleteClause to check if a record is deleted (default TRUE)
103 * @return array|NULL Returns the row if found, otherwise NULL
104 */
105 public static function getRecord($table, $uid, $fields = '*', $where = '', $useDeleteClause = true)
106 {
107 // Ensure we have a valid uid (not 0 and not NEWxxxx) and a valid TCA
108 if ((int)$uid && !empty($GLOBALS['TCA'][$table])) {
109 $where = 'uid=' . (int)$uid . ($useDeleteClause ? self::deleteClause($table) : '') . $where;
110 $row = static::getDatabaseConnection()->exec_SELECTgetSingleRow($fields, $table, $where);
111 if ($row) {
112 return $row;
113 }
114 }
115 return null;
116 }
117
118 /**
119 * Like getRecord(), but overlays workspace version if any.
120 *
121 * @param string $table Table name present in $GLOBALS['TCA']
122 * @param int $uid UID of record
123 * @param string $fields List of fields to select
124 * @param string $where Additional WHERE clause, eg. " AND blablabla = 0
125 * @param bool $useDeleteClause Use the deleteClause to check if a record is deleted (default TRUE)
126 * @param bool $unsetMovePointers If TRUE the function does not return a "pointer" row for moved records in a workspace
127 * @return array Returns the row if found, otherwise nothing
128 */
129 public static function getRecordWSOL($table, $uid, $fields = '*', $where = '', $useDeleteClause = true, $unsetMovePointers = false)
130 {
131 if ($fields !== '*') {
132 $internalFields = GeneralUtility::uniqueList($fields . ',uid,pid');
133 $row = self::getRecord($table, $uid, $internalFields, $where, $useDeleteClause);
134 self::workspaceOL($table, $row, -99, $unsetMovePointers);
135 if (is_array($row)) {
136 foreach ($row as $key => $_) {
137 if (!GeneralUtility::inList($fields, $key) && $key[0] !== '_') {
138 unset($row[$key]);
139 }
140 }
141 }
142 } else {
143 $row = self::getRecord($table, $uid, $fields, $where, $useDeleteClause);
144 self::workspaceOL($table, $row, -99, $unsetMovePointers);
145 }
146 return $row;
147 }
148
149 /**
150 * Returns the first record found from $table with $where as WHERE clause
151 * This function does NOT check if a record has the deleted flag set.
152 * $table does NOT need to be configured in $GLOBALS['TCA']
153 * The query used is simply this:
154 * $query = 'SELECT ' . $fields . ' FROM ' . $table . ' WHERE ' . $where;
155 *
156 * @param string $table Table name (not necessarily in TCA)
157 * @param string $where WHERE clause
158 * @param string $fields $fields is a list of fields to select, default is '*'
159 * @return array|bool First row found, if any, FALSE otherwise
160 */
161 public static function getRecordRaw($table, $where = '', $fields = '*')
162 {
163 $row = false;
164 $db = static::getDatabaseConnection();
165 if (false !== ($res = $db->exec_SELECTquery($fields, $table, $where, '', '', '1'))) {
166 $row = $db->sql_fetch_assoc($res);
167 $db->sql_free_result($res);
168 }
169 return $row;
170 }
171
172 /**
173 * Returns records from table, $theTable, where a field ($theField) equals the value, $theValue
174 * The records are returned in an array
175 * If no records were selected, the function returns nothing
176 *
177 * @param string $theTable Table name present in $GLOBALS['TCA']
178 * @param string $theField Field to select on
179 * @param string $theValue Value that $theField must match
180 * @param string $whereClause Optional additional WHERE clauses put in the end of the query. DO NOT PUT IN GROUP BY, ORDER BY or LIMIT!
181 * @param string $groupBy Optional GROUP BY field(s), if none, supply blank string.
182 * @param string $orderBy Optional ORDER BY field(s), if none, supply blank string.
183 * @param string $limit Optional LIMIT value ([begin,]max), if none, supply blank string.
184 * @param bool $useDeleteClause Use the deleteClause to check if a record is deleted (default TRUE)
185 * @return mixed Multidimensional array with selected records (if any is selected)
186 */
187 public static function getRecordsByField($theTable, $theField, $theValue, $whereClause = '', $groupBy = '', $orderBy = '', $limit = '', $useDeleteClause = true)
188 {
189 if (is_array($GLOBALS['TCA'][$theTable])) {
190 $db = static::getDatabaseConnection();
191 $res = $db->exec_SELECTquery(
192 '*',
193 $theTable,
194 $theField . '=' . $db->fullQuoteStr($theValue, $theTable) .
195 ($useDeleteClause ? self::deleteClause($theTable) . ' ' : '') .
196 self::versioningPlaceholderClause($theTable) . ' ' .
197 $whereClause,
198 $groupBy,
199 $orderBy,
200 $limit
201 );
202 $rows = array();
203 while ($row = $db->sql_fetch_assoc($res)) {
204 $rows[] = $row;
205 }
206 $db->sql_free_result($res);
207 if (!empty($rows)) {
208 return $rows;
209 }
210 }
211 return null;
212 }
213
214 /**
215 * Makes an backwards explode on the $str and returns an array with ($table, $uid).
216 * Example: tt_content_45 => array('tt_content', 45)
217 *
218 * @param string $str [tablename]_[uid] string to explode
219 * @return array
220 */
221 public static function splitTable_Uid($str)
222 {
223 list($uid, $table) = explode('_', strrev($str), 2);
224 return array(strrev($table), strrev($uid));
225 }
226
227 /**
228 * Returns a list of pure ints based on $in_list being a list of records with table-names prepended.
229 * 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.
230 *
231 * @param string $in_list Input list
232 * @param string $tablename Table name from which ids is returned
233 * @param string $default_tablename $default_tablename denotes what table the number '45' is from (if nothing is prepended on the value)
234 * @return string List of ids
235 * @deprecated since TYPO3 CMS 8, will be removed in TYPO3 CMS 9.
236 */
237 public static function getSQLselectableList($in_list, $tablename, $default_tablename)
238 {
239 DeprecationUtility::logFunction();
240 $list = array();
241 if ((string)trim($in_list) != '') {
242 $tempItemArray = explode(',', trim($in_list));
243 foreach ($tempItemArray as $key => $val) {
244 $val = strrev($val);
245 $parts = explode('_', $val, 2);
246 if ((string)trim($parts[0]) != '') {
247 $theID = (int)strrev($parts[0]);
248 $theTable = trim($parts[1]) ? strrev(trim($parts[1])) : $default_tablename;
249 if ($theTable == $tablename) {
250 $list[] = $theID;
251 }
252 }
253 }
254 }
255 return implode(',', $list);
256 }
257
258 /**
259 * Backend implementation of enableFields()
260 * Notice that "fe_groups" is not selected for - only disabled, starttime and endtime.
261 * Notice that deleted-fields are NOT filtered - you must ALSO call deleteClause in addition.
262 * $GLOBALS["SIM_ACCESS_TIME"] is used for date.
263 *
264 * @param string $table The table from which to return enableFields WHERE clause. Table name must have a 'ctrl' section in $GLOBALS['TCA'].
265 * @param bool $inv Means that the query will select all records NOT VISIBLE records (inverted selection)
266 * @return string WHERE clause part
267 */
268 public static function BEenableFields($table, $inv = false)
269 {
270 $ctrl = $GLOBALS['TCA'][$table]['ctrl'];
271 $query = array();
272 $invQuery = array();
273 if (is_array($ctrl)) {
274 if (is_array($ctrl['enablecolumns'])) {
275 if ($ctrl['enablecolumns']['disabled']) {
276 $field = $table . '.' . $ctrl['enablecolumns']['disabled'];
277 $query[] = $field . '=0';
278 $invQuery[] = $field . '<>0';
279 }
280 if ($ctrl['enablecolumns']['starttime']) {
281 $field = $table . '.' . $ctrl['enablecolumns']['starttime'];
282 $query[] = '(' . $field . '<=' . $GLOBALS['SIM_ACCESS_TIME'] . ')';
283 $invQuery[] = '(' . $field . '<>0 AND ' . $field . '>' . $GLOBALS['SIM_ACCESS_TIME'] . ')';
284 }
285 if ($ctrl['enablecolumns']['endtime']) {
286 $field = $table . '.' . $ctrl['enablecolumns']['endtime'];
287 $query[] = '(' . $field . '=0 OR ' . $field . '>' . $GLOBALS['SIM_ACCESS_TIME'] . ')';
288 $invQuery[] = '(' . $field . '<>0 AND ' . $field . '<=' . $GLOBALS['SIM_ACCESS_TIME'] . ')';
289 }
290 }
291 }
292 $outQ = $inv ? '(' . implode(' OR ', $invQuery) . ')' : implode(' AND ', $query);
293 return $outQ ? ' AND ' . $outQ : '';
294 }
295
296 /**
297 * Fetches the localization for a given record.
298 *
299 * @param string $table Table name present in $GLOBALS['TCA']
300 * @param int $uid The uid of the record
301 * @param int $language The uid of the language record in sys_language
302 * @param string $andWhereClause Optional additional WHERE clause (default: '')
303 * @return mixed Multidimensional array with selected records; if none exist, FALSE is returned
304 */
305 public static function getRecordLocalization($table, $uid, $language, $andWhereClause = '')
306 {
307 $recordLocalization = false;
308
309 // Check if translations are stored in other table
310 if (isset($GLOBALS['TCA'][$table]['ctrl']['transForeignTable'])) {
311 $table = $GLOBALS['TCA'][$table]['ctrl']['transForeignTable'];
312 }
313
314 if (self::isTableLocalizable($table)) {
315 $tcaCtrl = $GLOBALS['TCA'][$table]['ctrl'];
316 $recordLocalization = self::getRecordsByField($table, $tcaCtrl['transOrigPointerField'], $uid, 'AND ' . $tcaCtrl['languageField'] . '=' . (int)$language . ($andWhereClause ? ' ' . $andWhereClause : ''), '', '', '1');
317 }
318 return $recordLocalization;
319 }
320
321 /*******************************************
322 *
323 * Page tree, TCA related
324 *
325 *******************************************/
326 /**
327 * 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.
328 * By default deleted pages are filtered.
329 * 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.
330 *
331 * @param int $uid Page id for which to create the root line.
332 * @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.
333 * @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!
334 * @return array Root line array, all the way to the page tree root (or as far as $clause allows!)
335 */
336 public static function BEgetRootLine($uid, $clause = '', $workspaceOL = false)
337 {
338 static $BEgetRootLine_cache = array();
339 $output = array();
340 $pid = $uid;
341 $ident = $pid . '-' . $clause . '-' . $workspaceOL;
342 if (is_array($BEgetRootLine_cache[$ident])) {
343 $output = $BEgetRootLine_cache[$ident];
344 } else {
345 $loopCheck = 100;
346 $theRowArray = array();
347 while ($uid != 0 && $loopCheck) {
348 $loopCheck--;
349 $row = self::getPageForRootline($uid, $clause, $workspaceOL);
350 if (is_array($row)) {
351 $uid = $row['pid'];
352 $theRowArray[] = $row;
353 } else {
354 break;
355 }
356 }
357 if ($uid == 0) {
358 $theRowArray[] = array('uid' => 0, 'title' => '');
359 }
360 $c = count($theRowArray);
361 foreach ($theRowArray as $val) {
362 $c--;
363 $output[$c] = array(
364 'uid' => $val['uid'],
365 'pid' => $val['pid'],
366 'title' => $val['title'],
367 'doktype' => $val['doktype'],
368 'tsconfig_includes' => $val['tsconfig_includes'],
369 'TSconfig' => $val['TSconfig'],
370 'is_siteroot' => $val['is_siteroot'],
371 't3ver_oid' => $val['t3ver_oid'],
372 't3ver_wsid' => $val['t3ver_wsid'],
373 't3ver_state' => $val['t3ver_state'],
374 't3ver_stage' => $val['t3ver_stage'],
375 'backend_layout_next_level' => $val['backend_layout_next_level']
376 );
377 if (isset($val['_ORIG_pid'])) {
378 $output[$c]['_ORIG_pid'] = $val['_ORIG_pid'];
379 }
380 }
381 $BEgetRootLine_cache[$ident] = $output;
382 }
383 return $output;
384 }
385
386 /**
387 * Gets the cached page record for the rootline
388 *
389 * @param int $uid Page id for which to create the root line.
390 * @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.
391 * @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!
392 * @return array Cached page record for the rootline
393 * @see BEgetRootLine
394 */
395 protected static function getPageForRootline($uid, $clause, $workspaceOL)
396 {
397 static $getPageForRootline_cache = array();
398 $ident = $uid . '-' . $clause . '-' . $workspaceOL;
399 if (is_array($getPageForRootline_cache[$ident])) {
400 $row = $getPageForRootline_cache[$ident];
401 } else {
402 $db = static::getDatabaseConnection();
403 $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);
404 $row = $db->sql_fetch_assoc($res);
405 if ($row) {
406 $newLocation = false;
407 if ($workspaceOL) {
408 self::workspaceOL('pages', $row);
409 $newLocation = self::getMovePlaceholder('pages', $row['uid'], 'pid');
410 }
411 if (is_array($row)) {
412 if ($newLocation !== false) {
413 $row['pid'] = $newLocation['pid'];
414 } else {
415 self::fixVersioningPid('pages', $row);
416 }
417 $getPageForRootline_cache[$ident] = $row;
418 }
419 }
420 $db->sql_free_result($res);
421 }
422 return $row;
423 }
424
425 /**
426 * Opens the page tree to the specified page id
427 *
428 * @param int $pid Page id.
429 * @param bool $clearExpansion If set, then other open branches are closed.
430 * @return void
431 */
432 public static function openPageTree($pid, $clearExpansion)
433 {
434 $beUser = static::getBackendUserAuthentication();
435 // Get current expansion data:
436 if ($clearExpansion) {
437 $expandedPages = array();
438 } else {
439 $expandedPages = unserialize($beUser->uc['browseTrees']['browsePages']);
440 }
441 // Get rootline:
442 $rL = self::BEgetRootLine($pid);
443 // First, find out what mount index to use (if more than one DB mount exists):
444 $mountIndex = 0;
445 $mountKeys = array_flip($beUser->returnWebmounts());
446 foreach ($rL as $rLDat) {
447 if (isset($mountKeys[$rLDat['uid']])) {
448 $mountIndex = $mountKeys[$rLDat['uid']];
449 break;
450 }
451 }
452 // Traverse rootline and open paths:
453 foreach ($rL as $rLDat) {
454 $expandedPages[$mountIndex][$rLDat['uid']] = 1;
455 }
456 // Write back:
457 $beUser->uc['browseTrees']['browsePages'] = serialize($expandedPages);
458 $beUser->writeUC();
459 }
460
461 /**
462 * Returns the path (visually) of a page $uid, fx. "/First page/Second page/Another subpage"
463 * Each part of the path will be limited to $titleLimit characters
464 * Deleted pages are filtered out.
465 *
466 * @param int $uid Page uid for which to create record path
467 * @param string $clause Clause is additional where clauses, eg.
468 * @param int $titleLimit Title limit
469 * @param int $fullTitleLimit Title limit of Full title (typ. set to 1000 or so)
470 * @return mixed Path of record (string) OR array with short/long title if $fullTitleLimit is set.
471 */
472 public static function getRecordPath($uid, $clause, $titleLimit, $fullTitleLimit = 0)
473 {
474 if (!$titleLimit) {
475 $titleLimit = 1000;
476 }
477 $output = $fullOutput = '/';
478 $clause = trim($clause);
479 if ($clause !== '' && substr($clause, 0, 3) !== 'AND') {
480 $clause = 'AND ' . $clause;
481 }
482 $data = self::BEgetRootLine($uid, $clause);
483 foreach ($data as $record) {
484 if ($record['uid'] === 0) {
485 continue;
486 }
487 $output = '/' . GeneralUtility::fixed_lgd_cs(strip_tags($record['title']), $titleLimit) . $output;
488 if ($fullTitleLimit) {
489 $fullOutput = '/' . GeneralUtility::fixed_lgd_cs(strip_tags($record['title']), $fullTitleLimit) . $fullOutput;
490 }
491 }
492 if ($fullTitleLimit) {
493 return array($output, $fullOutput);
494 } else {
495 return $output;
496 }
497 }
498
499 /**
500 * Gets the original translation pointer table.
501 * For e.g. pages_language_overlay this would be pages.
502 *
503 * @param string $table Name of the table
504 * @return string Pointer table (if any)
505 */
506 public static function getOriginalTranslationTable($table)
507 {
508 if (!empty($GLOBALS['TCA'][$table]['ctrl']['transOrigPointerTable'])) {
509 $table = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerTable'];
510 }
511
512 return $table;
513 }
514
515 /**
516 * Determines whether a table is localizable and has the languageField and transOrigPointerField set in $GLOBALS['TCA'].
517 *
518 * @param string $table The table to check
519 * @return bool Whether a table is localizable
520 */
521 public static function isTableLocalizable($table)
522 {
523 $isLocalizable = false;
524 if (isset($GLOBALS['TCA'][$table]['ctrl']) && is_array($GLOBALS['TCA'][$table]['ctrl'])) {
525 $tcaCtrl = $GLOBALS['TCA'][$table]['ctrl'];
526 $isLocalizable = isset($tcaCtrl['languageField']) && $tcaCtrl['languageField'] && isset($tcaCtrl['transOrigPointerField']) && $tcaCtrl['transOrigPointerField'];
527 }
528 return $isLocalizable;
529 }
530
531 /**
532 * Returns the value of the property localizationMode in the given $config array ($GLOBALS['TCA'][<table>]['columns'][<field>]['config']).
533 * If the table is prepared for localization and no localizationMode is set, 'select' is returned by default.
534 * If the table is not prepared for localization or not defined at all in $GLOBALS['TCA'], FALSE is returned.
535 *
536 * @param string $table The name of the table to lookup in TCA
537 * @param mixed $fieldOrConfig The fieldname (string) or the configuration of the field to check (array)
538 * @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
539 */
540 public static function getInlineLocalizationMode($table, $fieldOrConfig)
541 {
542 $localizationMode = false;
543 $config = null;
544 if (is_array($fieldOrConfig) && !empty($fieldOrConfig)) {
545 $config = $fieldOrConfig;
546 } elseif (is_string($fieldOrConfig) && isset($GLOBALS['TCA'][$table]['columns'][$fieldOrConfig]['config'])) {
547 $config = $GLOBALS['TCA'][$table]['columns'][$fieldOrConfig]['config'];
548 }
549 if (is_array($config) && isset($config['type']) && $config['type'] === 'inline' && self::isTableLocalizable($table)) {
550 $localizationMode = isset($config['behaviour']['localizationMode']) && $config['behaviour']['localizationMode']
551 ? $config['behaviour']['localizationMode']
552 : 'select';
553 // The mode 'select' is not possible when child table is not localizable at all:
554 if ($localizationMode === 'select' && !self::isTableLocalizable($config['foreign_table'])) {
555 $localizationMode = false;
556 }
557 }
558 return $localizationMode;
559 }
560
561 /**
562 * 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.
563 * If $id is zero a pseudo root-page with "_thePath" set is returned IF the current BE_USER is admin.
564 * In any case ->isInWebMount must return TRUE for the user (regardless of $perms_clause)
565 *
566 * @param int $id Page uid for which to check read-access
567 * @param string $perms_clause This is typically a value generated with static::getBackendUserAuthentication()->getPagePermsClause(1);
568 * @return array Returns page record if OK, otherwise FALSE.
569 */
570 public static function readPageAccess($id, $perms_clause)
571 {
572 if ((string)$id !== '') {
573 $id = (int)$id;
574 if (!$id) {
575 if (static::getBackendUserAuthentication()->isAdmin()) {
576 $path = '/';
577 $pageinfo['_thePath'] = $path;
578 return $pageinfo;
579 }
580 } else {
581 $pageinfo = self::getRecord('pages', $id, '*', $perms_clause ? ' AND ' . $perms_clause : '');
582 if ($pageinfo['uid'] && static::getBackendUserAuthentication()->isInWebMount($id, $perms_clause)) {
583 self::workspaceOL('pages', $pageinfo);
584 if (is_array($pageinfo)) {
585 self::fixVersioningPid('pages', $pageinfo);
586 list($pageinfo['_thePath'], $pageinfo['_thePathFull']) = self::getRecordPath((int)$pageinfo['uid'], $perms_clause, 15, 1000);
587 return $pageinfo;
588 }
589 }
590 }
591 }
592 return false;
593 }
594
595 /**
596 * Returns the "types" configuration parsed into an array for the record, $rec, from table, $table
597 *
598 * @param string $table Table name (present in TCA)
599 * @param array $rec Record from $table
600 * @param bool $useFieldNameAsKey If $useFieldNameAsKey is set, then the fieldname is associative keys in the return array, otherwise just numeric keys.
601 * @return array|NULL
602 */
603 public static function getTCAtypes($table, $rec, $useFieldNameAsKey = false)
604 {
605 if ($GLOBALS['TCA'][$table]) {
606 // Get type value:
607 $fieldValue = self::getTCAtypeValue($table, $rec);
608 $cacheIdentifier = $table . '-type-' . $fieldValue . '-fnk-' . $useFieldNameAsKey;
609
610 // Fetch from first-level-cache if available
611 if (isset(self::$tcaTableTypeConfigurationCache[$cacheIdentifier])) {
612 return self::$tcaTableTypeConfigurationCache[$cacheIdentifier];
613 }
614
615 // Get typesConf
616 $typesConf = $GLOBALS['TCA'][$table]['types'][$fieldValue];
617 // Get fields list and traverse it
618 $fieldList = explode(',', $typesConf['showitem']);
619
620 // Add subtype fields e.g. for a valid RTE transformation
621 // The RTE runs the DB -> RTE transformation only, if the RTE field is part of the getTCAtypes array
622 if (isset($typesConf['subtype_value_field'])) {
623 $subType = $rec[$typesConf['subtype_value_field']];
624 if (isset($typesConf['subtypes_addlist'][$subType])) {
625 $subFields = GeneralUtility::trimExplode(',', $typesConf['subtypes_addlist'][$subType], true);
626 $fieldList = array_merge($fieldList, $subFields);
627 }
628 }
629
630 $altFieldList = array();
631 // Traverse fields in types config and parse the configuration into a nice array:
632 foreach ($fieldList as $k => $v) {
633 list($pFieldName, $pAltTitle, $pPalette) = GeneralUtility::trimExplode(';', $v);
634 $defaultExtras = '';
635 if (!empty($typesConf['columnsOverrides'][$pFieldName]['defaultExtras'])) {
636 // Use defaultExtras from columnsOverrides if given
637 $defaultExtras = $typesConf['columnsOverrides'][$pFieldName]['defaultExtras'];
638 } elseif (!empty($GLOBALS['TCA'][$table]['columns'][$pFieldName]['defaultExtras'])) {
639 // Use defaultExtras from columns if given
640 $defaultExtras = $GLOBALS['TCA'][$table]['columns'][$pFieldName]['defaultExtras'];
641 }
642 $specConfParts = self::getSpecConfParts($defaultExtras);
643 $fieldList[$k] = array(
644 'field' => $pFieldName,
645 'title' => $pAltTitle,
646 'palette' => $pPalette,
647 'spec' => $specConfParts,
648 'origString' => $v
649 );
650 if ($useFieldNameAsKey) {
651 $altFieldList[$fieldList[$k]['field']] = $fieldList[$k];
652 }
653 }
654 if ($useFieldNameAsKey) {
655 $fieldList = $altFieldList;
656 }
657
658 // Add to first-level-cache
659 self::$tcaTableTypeConfigurationCache[$cacheIdentifier] = $fieldList;
660
661 // Return array:
662 return $fieldList;
663 }
664 return null;
665 }
666
667 /**
668 * Returns the "type" value of $rec from $table which can be used to look up the correct "types" rendering section in $GLOBALS['TCA']
669 * If no "type" field is configured in the "ctrl"-section of the $GLOBALS['TCA'] for the table, zero is used.
670 * 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)
671 *
672 * Note: This method is very similar to the type determination of FormDataProvider/DatabaseRecordTypeValue,
673 * however, it has two differences:
674 * 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).
675 * 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"
676 * and "group" field values are stored, which makes different processing of the "foreign pointer field" type field variant necessary.
677 *
678 * @param string $table Table name present in TCA
679 * @param array $row Record from $table
680 * @throws \RuntimeException
681 * @return string Field value
682 * @see getTCAtypes()
683 */
684 public static function getTCAtypeValue($table, $row)
685 {
686 $typeNum = 0;
687 if ($GLOBALS['TCA'][$table]) {
688 $field = $GLOBALS['TCA'][$table]['ctrl']['type'];
689 if (strpos($field, ':') !== false) {
690 list($pointerField, $foreignTableTypeField) = explode(':', $field);
691 // Get field value from database if field is not in the $row array
692 if (!isset($row[$pointerField])) {
693 $localRow = self::getRecord($table, $row['uid'], $pointerField);
694 $foreignUid = $localRow[$pointerField];
695 } else {
696 $foreignUid = $row[$pointerField];
697 }
698 if ($foreignUid) {
699 $fieldConfig = $GLOBALS['TCA'][$table]['columns'][$pointerField]['config'];
700 $relationType = $fieldConfig['type'];
701 if ($relationType === 'select') {
702 $foreignTable = $fieldConfig['foreign_table'];
703 } elseif ($relationType === 'group') {
704 $allowedTables = explode(',', $fieldConfig['allowed']);
705 $foreignTable = $allowedTables[0];
706 } else {
707 throw new \RuntimeException('TCA foreign field pointer fields are only allowed to be used with group or select field types.', 1325862240);
708 }
709 $foreignRow = self::getRecord($foreignTable, $foreignUid, $foreignTableTypeField);
710 if ($foreignRow[$foreignTableTypeField]) {
711 $typeNum = $foreignRow[$foreignTableTypeField];
712 }
713 }
714 } else {
715 $typeNum = $row[$field];
716 }
717 // If that value is an empty string, set it to "0" (zero)
718 if (empty($typeNum)) {
719 $typeNum = 0;
720 }
721 }
722 // If current typeNum doesn't exist, set it to 0 (or to 1 for historical reasons, if 0 doesn't exist)
723 if (!$GLOBALS['TCA'][$table]['types'][$typeNum]) {
724 $typeNum = $GLOBALS['TCA'][$table]['types']['0'] ? 0 : 1;
725 }
726 // Force to string. Necessary for eg '-1' to be recognized as a type value.
727 $typeNum = (string)$typeNum;
728 return $typeNum;
729 }
730
731 /**
732 * Parses "defaultExtras" of $GLOBALS['TCA'] columns config section to an array.
733 * Elements are split by ":" and within those parts, parameters are split by "|".
734 *
735 * See unit tests for details.
736 *
737 * @param string $defaultExtrasString "defaultExtras" string from columns config
738 * @return array
739 */
740 public static function getSpecConfParts($defaultExtrasString)
741 {
742 $specConfParts = GeneralUtility::trimExplode(':', $defaultExtrasString, true);
743 $reg = array();
744 if (!empty($specConfParts)) {
745 foreach ($specConfParts as $k2 => $v2) {
746 unset($specConfParts[$k2]);
747 if (preg_match('/(.*)\\[(.*)\\]/', $v2, $reg)) {
748 $specConfParts[trim($reg[1])] = array(
749 'parameters' => GeneralUtility::trimExplode('|', $reg[2], true)
750 );
751 } else {
752 $specConfParts[trim($v2)] = 1;
753 }
754 }
755 } else {
756 $specConfParts = array();
757 }
758 return $specConfParts;
759 }
760
761 /**
762 * Takes an array of "[key] = [value]" strings and returns an array with the keys set as keys pointing to the value.
763 * Better see it in action! Find example in Inside TYPO3
764 *
765 * @param array $pArr Array of "[key] = [value]" strings to convert.
766 * @return array
767 */
768 public static function getSpecConfParametersFromArray($pArr)
769 {
770 $out = array();
771 if (is_array($pArr)) {
772 foreach ($pArr as $k => $v) {
773 $parts = explode('=', $v, 2);
774 if (count($parts) === 2) {
775 $out[trim($parts[0])] = trim($parts[1]);
776 } else {
777 $out[$k] = $v;
778 }
779 }
780 }
781 return $out;
782 }
783
784 /**
785 * Finds the Data Structure for a FlexForm field
786 *
787 * NOTE ON data structures for deleted records: This function may fail to deliver the data structure
788 * for a record for a few reasons:
789 * a) The data structure could be deleted (either with deleted-flagged or hard-deleted),
790 * b) the data structure is fetched using the ds_pointerField_searchParent in which case any
791 * deleted record on the route to the final location of the DS will make it fail.
792 * In theory, we can solve the problem in the case where records that are deleted-flagged keeps us
793 * from finding the DS - this is done at the markers ###NOTE_A### where we make sure to also select deleted records.
794 * However, we generally want the DS lookup to fail for deleted records since for the working website we expect a
795 * deleted-flagged record to be as inaccessible as one that is completely deleted from the DB. Any way we look
796 * at it, this may lead to integrity problems of the reference index and even lost files if attached.
797 * However, that is not really important considering that a single change to a data structure can instantly
798 * invalidate large amounts of the reference index which we do accept as a cost for the flexform features.
799 * Other than requiring a reference index update, deletion of/changes in data structure or the failure to look
800 * them up when completely deleting records may lead to lost files in the uploads/ folders since those are now
801 * without a proper reference.
802 *
803 * @param array $conf Field config array
804 * @param array $row Record data
805 * @param string $table The table name
806 * @param string $fieldName Optional fieldname passed to hook object
807 * @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.
808 * @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)
809 * @return mixed If array, the data structure was found and returned as an array. Otherwise (string) it is an error message.
810 * @todo: All those nasty details should be covered with tests, also it is very unfortunate the final $srcPointer is not exposed
811 */
812 public static function getFlexFormDS($conf, $row, $table, $fieldName = '', $WSOL = true, $newRecordPidValue = 0)
813 {
814 // Get pointer field etc from TCA-config:
815 $ds_pointerField = $conf['ds_pointerField'];
816 $ds_array = $conf['ds'];
817 $ds_tableField = $conf['ds_tableField'];
818 $ds_searchParentField = $conf['ds_pointerField_searchParent'];
819 // If there is a data source array, that takes precedence
820 if (is_array($ds_array)) {
821 // If a pointer field is set, take the value from that field in the $row array and use as key.
822 if ($ds_pointerField) {
823 // Up to two pointer fields can be specified in a comma separated list.
824 $pointerFields = GeneralUtility::trimExplode(',', $ds_pointerField);
825 // 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.
826 if (count($pointerFields) === 2) {
827 if ($ds_array[$row[$pointerFields[0]] . ',' . $row[$pointerFields[1]]]) {
828 // Check if we have a DS for the combination of both pointer fields values
829 $srcPointer = $row[$pointerFields[0]] . ',' . $row[$pointerFields[1]];
830 } elseif ($ds_array[$row[$pointerFields[1]] . ',*']) {
831 // Check if we have a DS for the value of the first pointer field suffixed with ",*"
832 $srcPointer = $row[$pointerFields[1]] . ',*';
833 } elseif ($ds_array['*,' . $row[$pointerFields[1]]]) {
834 // Check if we have a DS for the value of the second pointer field prefixed with "*,"
835 $srcPointer = '*,' . $row[$pointerFields[1]];
836 } elseif ($ds_array[$row[$pointerFields[0]]]) {
837 // Check if we have a DS for just the value of the first pointer field (mainly for backwards compatibility)
838 $srcPointer = $row[$pointerFields[0]];
839 } else {
840 $srcPointer = null;
841 }
842 } else {
843 $srcPointer = $row[$pointerFields[0]];
844 }
845 $srcPointer = $srcPointer !== null && isset($ds_array[$srcPointer]) ? $srcPointer : 'default';
846 } else {
847 $srcPointer = 'default';
848 }
849 // 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.
850 if (substr($ds_array[$srcPointer], 0, 5) == 'FILE:') {
851 $file = GeneralUtility::getFileAbsFileName(substr($ds_array[$srcPointer], 5));
852 if ($file && @is_file($file)) {
853 $dataStructArray = GeneralUtility::xml2array(GeneralUtility::getUrl($file));
854 } else {
855 $dataStructArray = 'The file "' . substr($ds_array[$srcPointer], 5) . '" in ds-array key "' . $srcPointer . '" was not found ("' . $file . '")';
856 }
857 } else {
858 $dataStructArray = GeneralUtility::xml2array($ds_array[$srcPointer]);
859 }
860 } elseif ($ds_pointerField) {
861 // If pointer field AND possibly a table/field is set:
862 // Value of field pointed to:
863 $srcPointer = $row[$ds_pointerField];
864 // Searching recursively back if 'ds_pointerField_searchParent' is defined (typ. a page rootline, or maybe a tree-table):
865 if ($ds_searchParentField && !$srcPointer) {
866 $rr = self::getRecord($table, $row['uid'], 'uid,' . $ds_searchParentField);
867 // Get the "pid" field - we cannot know that it is in the input record! ###NOTE_A###
868 if ($WSOL) {
869 self::workspaceOL($table, $rr);
870 self::fixVersioningPid($table, $rr, true);
871 }
872 $db = static::getDatabaseConnection();
873 $uidAcc = array();
874 // Used to avoid looping, if any should happen.
875 $subFieldPointer = $conf['ds_pointerField_searchParent_subField'];
876 while (!$srcPointer) {
877 $res = $db->exec_SELECTquery('uid,' . $ds_pointerField . ',' . $ds_searchParentField . ($subFieldPointer ? ',' . $subFieldPointer : ''), $table, 'uid=' . (int)($newRecordPidValue ?: $rr[$ds_searchParentField]) . self::deleteClause($table));
878 $newRecordPidValue = 0;
879 $rr = $db->sql_fetch_assoc($res);
880 $db->sql_free_result($res);
881 // Break if no result from SQL db or if looping...
882 if (!is_array($rr) || isset($uidAcc[$rr['uid']])) {
883 break;
884 }
885 $uidAcc[$rr['uid']] = 1;
886 if ($WSOL) {
887 self::workspaceOL($table, $rr);
888 self::fixVersioningPid($table, $rr, true);
889 }
890 $srcPointer = $subFieldPointer && $rr[$subFieldPointer] ? $rr[$subFieldPointer] : $rr[$ds_pointerField];
891 }
892 }
893 // If there is a srcPointer value:
894 if ($srcPointer) {
895 if (MathUtility::canBeInterpretedAsInteger($srcPointer)) {
896 // If integer, then its a record we will look up:
897 list($tName, $fName) = explode(':', $ds_tableField, 2);
898 if ($tName && $fName && is_array($GLOBALS['TCA'][$tName])) {
899 $dataStructRec = self::getRecord($tName, $srcPointer);
900 if ($WSOL) {
901 self::workspaceOL($tName, $dataStructRec);
902 }
903 if (strpos($dataStructRec[$fName], '<') === false) {
904 if (is_file(PATH_site . $dataStructRec[$fName])) {
905 // The value is a pointer to a file
906 $dataStructArray = GeneralUtility::xml2array(GeneralUtility::getUrl(PATH_site . $dataStructRec[$fName]));
907 } else {
908 $dataStructArray = sprintf('File \'%s\' was not found', $dataStructRec[$fName]);
909 }
910 } else {
911 // No file pointer, handle as being XML (default behaviour)
912 $dataStructArray = GeneralUtility::xml2array($dataStructRec[$fName]);
913 }
914 } else {
915 $dataStructArray = 'No tablename (' . $tName . ') or fieldname (' . $fName . ') was found an valid!';
916 }
917 } else {
918 // Otherwise expect it to be a file:
919 $file = GeneralUtility::getFileAbsFileName($srcPointer);
920 if ($file && @is_file($file)) {
921 $dataStructArray = GeneralUtility::xml2array(GeneralUtility::getUrl($file));
922 } else {
923 // Error message.
924 $dataStructArray = 'The file "' . $srcPointer . '" was not found ("' . $file . '")';
925 }
926 }
927 } else {
928 // Error message.
929 $dataStructArray = 'No source value in fieldname "' . $ds_pointerField . '"';
930 }
931 } else {
932 $dataStructArray = 'No proper configuration!';
933 }
934 // Hook for post-processing the Flexform DS. Introduces the possibility to configure Flexforms via TSConfig
935 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['getFlexFormDSClass'])) {
936 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['getFlexFormDSClass'] as $classRef) {
937 $hookObj = GeneralUtility::getUserObj($classRef);
938 if (method_exists($hookObj, 'getFlexFormDS_postProcessDS')) {
939 $hookObj->getFlexFormDS_postProcessDS($dataStructArray, $conf, $row, $table, $fieldName);
940 }
941 }
942 }
943 return $dataStructArray;
944 }
945
946 /*******************************************
947 *
948 * Caching related
949 *
950 *******************************************/
951 /**
952 * Stores $data in the 'cache_hash' cache with the hash key, $hash
953 * and visual/symbolic identification, $ident
954 *
955 * IDENTICAL to the function by same name found in \TYPO3\CMS\Frontend\Page\PageRepository
956 *
957 * @param string $hash 32 bit hash string (eg. a md5 hash of a serialized array identifying the data being stored)
958 * @param mixed $data The data to store
959 * @param string $ident $ident is just a textual identification in order to inform about the content!
960 * @return void
961 */
962 public static function storeHash($hash, $data, $ident)
963 {
964 /** @var CacheManager $cacheManager */
965 $cacheManager = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Cache\CacheManager::class);
966 $cacheManager->getCache('cache_hash')->set($hash, $data, array('ident_' . $ident), 0);
967 }
968
969 /**
970 * Returns data stored for the hash string in the cache "cache_hash"
971 * Can be used to retrieved a cached value, array or object
972 *
973 * IDENTICAL to the function by same name found in \TYPO3\CMS\Frontend\Page\PageRepository
974 *
975 * @param string $hash The hash-string which was used to store the data value
976 * @return mixed The "data" from the cache
977 */
978 public static function getHash($hash)
979 {
980 /** @var CacheManager $cacheManager */
981 $cacheManager = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Cache\CacheManager::class);
982 $cacheEntry = $cacheManager->getCache('cache_hash')->get($hash);
983 $hashContent = null;
984 if ($cacheEntry) {
985 $hashContent = $cacheEntry;
986 }
987 return $hashContent;
988 }
989
990 /*******************************************
991 *
992 * TypoScript related
993 *
994 *******************************************/
995 /**
996 * Returns the Page TSconfig for page with id, $id
997 *
998 * @param int $id Page uid for which to create Page TSconfig
999 * @param array $rootLine If $rootLine is an array, that is used as rootline, otherwise rootline is just calculated
1000 * @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.
1001 * @return array Page TSconfig
1002 * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser
1003 */
1004 public static function getPagesTSconfig($id, $rootLine = null, $returnPartArray = false)
1005 {
1006 static $pagesTSconfig_cacheReference = array();
1007 static $combinedTSconfig_cache = array();
1008
1009 $id = (int)$id;
1010 if ($returnPartArray === false
1011 && $rootLine === null
1012 && isset($pagesTSconfig_cacheReference[$id])
1013 ) {
1014 return $combinedTSconfig_cache[$pagesTSconfig_cacheReference[$id]];
1015 } else {
1016 $TSconfig = array();
1017 if (!is_array($rootLine)) {
1018 $useCacheForCurrentPageId = true;
1019 $rootLine = self::BEgetRootLine($id, '', true);
1020 } else {
1021 $useCacheForCurrentPageId = false;
1022 }
1023
1024 // Order correctly
1025 ksort($rootLine);
1026 $TSdataArray = array();
1027 // Setting default configuration
1028 $TSdataArray['defaultPageTSconfig'] = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPageTSconfig'];
1029 foreach ($rootLine as $k => $v) {
1030 if (trim($v['tsconfig_includes'])) {
1031 $includeTsConfigFileList = GeneralUtility::trimExplode(',', $v['tsconfig_includes'], true);
1032 // Traversing list
1033 foreach ($includeTsConfigFileList as $key => $includeTsConfigFile) {
1034 if (StringUtility::beginsWith($includeTsConfigFile, 'EXT:')) {
1035 list($includeTsConfigFileExtensionKey, $includeTsConfigFilename) = explode(
1036 '/',
1037 substr($includeTsConfigFile, 4),
1038 2
1039 );
1040 if (
1041 (string)$includeTsConfigFileExtensionKey !== ''
1042 && ExtensionManagementUtility::isLoaded($includeTsConfigFileExtensionKey)
1043 && (string)$includeTsConfigFilename !== ''
1044 ) {
1045 $includeTsConfigFileAndPath = ExtensionManagementUtility::extPath($includeTsConfigFileExtensionKey) .
1046 $includeTsConfigFilename;
1047 if (file_exists($includeTsConfigFileAndPath)) {
1048 $TSdataArray['uid_' . $v['uid'] . '_static_' . $key] = GeneralUtility::getUrl($includeTsConfigFileAndPath);
1049 }
1050 }
1051 }
1052 }
1053 }
1054 $TSdataArray['uid_' . $v['uid']] = $v['TSconfig'];
1055 }
1056 $TSdataArray = static::emitGetPagesTSconfigPreIncludeSignal($TSdataArray, $id, $rootLine, $returnPartArray);
1057 $TSdataArray = TypoScriptParser::checkIncludeLines_array($TSdataArray);
1058 if ($returnPartArray) {
1059 return $TSdataArray;
1060 }
1061 // Parsing the page TS-Config
1062 $pageTS = implode(LF . '[GLOBAL]' . LF, $TSdataArray);
1063 /* @var $parseObj \TYPO3\CMS\Backend\Configuration\TsConfigParser */
1064 $parseObj = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Configuration\TsConfigParser::class);
1065 $res = $parseObj->parseTSconfig($pageTS, 'PAGES', $id, $rootLine);
1066 if ($res) {
1067 $TSconfig = $res['TSconfig'];
1068 }
1069 $cacheHash = $res['hash'];
1070 // Get User TSconfig overlay
1071 $userTSconfig = static::getBackendUserAuthentication()->userTS['page.'];
1072 if (is_array($userTSconfig)) {
1073 ArrayUtility::mergeRecursiveWithOverrule($TSconfig, $userTSconfig);
1074 $cacheHash .= '_user' . $GLOBALS['BE_USER']->user['uid'];
1075 }
1076
1077 if ($useCacheForCurrentPageId) {
1078 if (!isset($combinedTSconfig_cache[$cacheHash])) {
1079 $combinedTSconfig_cache[$cacheHash] = $TSconfig;
1080 }
1081 $pagesTSconfig_cacheReference[$id] = $cacheHash;
1082 }
1083 }
1084 return $TSconfig;
1085 }
1086
1087 /*******************************************
1088 *
1089 * Users / Groups related
1090 *
1091 *******************************************/
1092 /**
1093 * Returns an array with be_users records of all user NOT DELETED sorted by their username
1094 * Keys in the array is the be_users uid
1095 *
1096 * @param string $fields Optional $fields list (default: username,usergroup,usergroup_cached_list,uid) can be used to set the selected fields
1097 * @param string $where Optional $where clause (fx. "AND username='pete'") can be used to limit query
1098 * @return array
1099 */
1100 public static function getUserNames($fields = 'username,usergroup,usergroup_cached_list,uid', $where = '')
1101 {
1102 return self::getRecordsSortedByTitle(
1103 GeneralUtility::trimExplode(',', $fields, true),
1104 'be_users',
1105 'username',
1106 'AND pid=0 ' . $where
1107 );
1108 }
1109
1110 /**
1111 * Returns an array with be_groups records (title, uid) of all groups NOT DELETED sorted by their title
1112 *
1113 * @param string $fields Field list
1114 * @param string $where WHERE clause
1115 * @return array
1116 */
1117 public static function getGroupNames($fields = 'title,uid', $where = '')
1118 {
1119 return self::getRecordsSortedByTitle(
1120 GeneralUtility::trimExplode(',', $fields, true),
1121 'be_groups',
1122 'title',
1123 'AND pid=0 ' . $where
1124 );
1125 }
1126
1127 /**
1128 * Returns an array of all non-deleted records of a table sorted by a given title field.
1129 * The value of the title field will be replaced by the return value
1130 * of self::getRecordTitle() before the sorting is performed.
1131 *
1132 * @param array $fields Fields to select
1133 * @param string $table Table name
1134 * @param string $titleField Field that will contain the record title
1135 * @param string $where Additional where clause
1136 * @return array Array of sorted records
1137 */
1138 protected static function getRecordsSortedByTitle(array $fields, $table, $titleField, $where = '')
1139 {
1140 $fieldsIndex = array_flip($fields);
1141 // Make sure the titleField is amongst the fields when getting sorted
1142 $fieldsIndex[$titleField] = 1;
1143
1144 $result = array();
1145 $db = static::getDatabaseConnection();
1146 $res = $db->exec_SELECTquery('*', $table, '1=1 ' . $where . self::deleteClause($table));
1147 while ($record = $db->sql_fetch_assoc($res)) {
1148 // store the uid, because it might be unset if it's not among the requested $fields
1149 $recordId = $record['uid'];
1150 $record[$titleField] = self::getRecordTitle($table, $record);
1151
1152 // include only the requested fields in the result
1153 $result[$recordId] = array_intersect_key($record, $fieldsIndex);
1154 }
1155 $db->sql_free_result($res);
1156
1157 // sort records by $sortField. This is not done in the query because the title might have been overwritten by
1158 // self::getRecordTitle();
1159 return ArrayUtility::sortArraysByKey($result, $titleField);
1160 }
1161
1162 /**
1163 * Returns an array with be_groups records (like ->getGroupNames) but:
1164 * - 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.
1165 *
1166 * @param string $fields Field list; $fields specify the fields selected (default: title,uid)
1167 * @return array
1168 */
1169 public static function getListGroupNames($fields = 'title, uid')
1170 {
1171 $beUser = static::getBackendUserAuthentication();
1172 $exQ = ' AND hide_in_lists=0';
1173 if (!$beUser->isAdmin()) {
1174 $exQ .= ' AND uid IN (' . ($beUser->user['usergroup_cached_list'] ?: 0) . ')';
1175 }
1176 return self::getGroupNames($fields, $exQ);
1177 }
1178
1179 /**
1180 * Returns the array $usernames with the names of all users NOT IN $groupArray changed to the uid (hides the usernames!).
1181 * If $excludeBlindedFlag is set, then these records are unset from the array $usernames
1182 * 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
1183 *
1184 * @param array $usernames User names
1185 * @param array $groupArray Group names
1186 * @param bool $excludeBlindedFlag If $excludeBlindedFlag is set, then these records are unset from the array $usernames
1187 * @return array User names, blinded
1188 */
1189 public static function blindUserNames($usernames, $groupArray, $excludeBlindedFlag = false)
1190 {
1191 if (is_array($usernames) && is_array($groupArray)) {
1192 foreach ($usernames as $uid => $row) {
1193 $userN = $uid;
1194 $set = 0;
1195 if ($row['uid'] != static::getBackendUserAuthentication()->user['uid']) {
1196 foreach ($groupArray as $v) {
1197 if ($v && GeneralUtility::inList($row['usergroup_cached_list'], $v)) {
1198 $userN = $row['username'];
1199 $set = 1;
1200 }
1201 }
1202 } else {
1203 $userN = $row['username'];
1204 $set = 1;
1205 }
1206 $usernames[$uid]['username'] = $userN;
1207 if ($excludeBlindedFlag && !$set) {
1208 unset($usernames[$uid]);
1209 }
1210 }
1211 }
1212 return $usernames;
1213 }
1214
1215 /**
1216 * Corresponds to blindUserNames but works for groups instead
1217 *
1218 * @param array $groups Group names
1219 * @param array $groupArray Group names (reference)
1220 * @param bool $excludeBlindedFlag If $excludeBlindedFlag is set, then these records are unset from the array $usernames
1221 * @return array
1222 */
1223 public static function blindGroupNames($groups, $groupArray, $excludeBlindedFlag = false)
1224 {
1225 if (is_array($groups) && is_array($groupArray)) {
1226 foreach ($groups as $uid => $row) {
1227 $groupN = $uid;
1228 $set = 0;
1229 if (ArrayUtility::inArray($groupArray, $uid)) {
1230 $groupN = $row['title'];
1231 $set = 1;
1232 }
1233 $groups[$uid]['title'] = $groupN;
1234 if ($excludeBlindedFlag && !$set) {
1235 unset($groups[$uid]);
1236 }
1237 }
1238 }
1239 return $groups;
1240 }
1241
1242 /*******************************************
1243 *
1244 * Output related
1245 *
1246 *******************************************/
1247 /**
1248 * Returns the difference in days between input $tstamp and $EXEC_TIME
1249 *
1250 * @param int $tstamp Time stamp, seconds
1251 * @return int
1252 */
1253 public static function daysUntil($tstamp)
1254 {
1255 $delta_t = $tstamp - $GLOBALS['EXEC_TIME'];
1256 return ceil($delta_t / (3600 * 24));
1257 }
1258
1259 /**
1260 * Returns $tstamp formatted as "ddmmyy" (According to $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'])
1261 *
1262 * @param int $tstamp Time stamp, seconds
1263 * @return string Formatted time
1264 */
1265 public static function date($tstamp)
1266 {
1267 return date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'], (int)$tstamp);
1268 }
1269
1270 /**
1271 * Returns $tstamp formatted as "ddmmyy hhmm" (According to $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] AND $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'])
1272 *
1273 * @param int $value Time stamp, seconds
1274 * @return string Formatted time
1275 */
1276 public static function datetime($value)
1277 {
1278 return date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'], $value);
1279 }
1280
1281 /**
1282 * Returns $value (in seconds) formatted as hh:mm:ss
1283 * For instance $value = 3600 + 60*2 + 3 should return "01:02:03"
1284 *
1285 * @param int $value Time stamp, seconds
1286 * @param bool $withSeconds Output hh:mm:ss. If FALSE: hh:mm
1287 * @return string Formatted time
1288 */
1289 public static function time($value, $withSeconds = true)
1290 {
1291 $hh = floor($value / 3600);
1292 $min = floor(($value - $hh * 3600) / 60);
1293 $sec = $value - $hh * 3600 - $min * 60;
1294 $l = sprintf('%02d', $hh) . ':' . sprintf('%02d', $min);
1295 if ($withSeconds) {
1296 $l .= ':' . sprintf('%02d', $sec);
1297 }
1298 return $l;
1299 }
1300
1301 /**
1302 * Returns the "age" in minutes / hours / days / years of the number of $seconds inputted.
1303 *
1304 * @param int $seconds Seconds could be the difference of a certain timestamp and time()
1305 * @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")
1306 * @return string Formatted time
1307 */
1308 public static function calcAge($seconds, $labels = ' min| hrs| days| yrs| min| hour| day| year')
1309 {
1310 $labelArr = explode('|', $labels);
1311 $absSeconds = abs($seconds);
1312 $sign = $seconds < 0 ? -1 : 1;
1313 if ($absSeconds < 3600) {
1314 $val = round($absSeconds / 60);
1315 $seconds = $sign * $val . ($val == 1 ? $labelArr[4] : $labelArr[0]);
1316 } elseif ($absSeconds < 24 * 3600) {
1317 $val = round($absSeconds / 3600);
1318 $seconds = $sign * $val . ($val == 1 ? $labelArr[5] : $labelArr[1]);
1319 } elseif ($absSeconds < 365 * 24 * 3600) {
1320 $val = round($absSeconds / (24 * 3600));
1321 $seconds = $sign * $val . ($val == 1 ? $labelArr[6] : $labelArr[2]);
1322 } else {
1323 $val = round($absSeconds / (365 * 24 * 3600));
1324 $seconds = $sign * $val . ($val == 1 ? $labelArr[7] : $labelArr[3]);
1325 }
1326 return $seconds;
1327 }
1328
1329 /**
1330 * Returns a formatted timestamp if $tstamp is set.
1331 * The date/datetime will be followed by the age in parenthesis.
1332 *
1333 * @param int $tstamp Time stamp, seconds
1334 * @param int $prefix 1/-1 depending on polarity of age.
1335 * @param string $date $date=="date" will yield "dd:mm:yy" formatting, otherwise "dd:mm:yy hh:mm
1336 * @return string
1337 */
1338 public static function dateTimeAge($tstamp, $prefix = 1, $date = '')
1339 {
1340 if (!$tstamp) {
1341 return '';
1342 }
1343 $label = static::getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:labels.minutesHoursDaysYears');
1344 $age = ' (' . self::calcAge($prefix * ($GLOBALS['EXEC_TIME'] - $tstamp), $label) . ')';
1345 return $date === 'date' ? self::date($tstamp) : self::datetime($tstamp) . $age;
1346 }
1347
1348 /**
1349 * Returns alt="" and title="" attributes with the value of $content.
1350 *
1351 * @param string $content Value for 'alt' and 'title' attributes (will be htmlspecialchars()'ed before output)
1352 * @return string
1353 * @deprecated since TYPO3 CMS 8, will be removed in TYPO3 CMS 9.
1354 */
1355 public static function titleAltAttrib($content)
1356 {
1357 DeprecationUtility::logFunction();
1358 $out = '';
1359 $out .= ' alt="' . htmlspecialchars($content) . '"';
1360 $out .= ' title="' . htmlspecialchars($content) . '"';
1361 return $out;
1362 }
1363
1364 /**
1365 * Resolves file references for a given record.
1366 *
1367 * @param string $tableName Name of the table of the record
1368 * @param string $fieldName Name of the field of the record
1369 * @param array $element Record data
1370 * @param NULL|int $workspaceId Workspace to fetch data for
1371 * @return NULL|\TYPO3\CMS\Core\Resource\FileReference[]
1372 */
1373 public static function resolveFileReferences($tableName, $fieldName, $element, $workspaceId = null)
1374 {
1375 if (empty($GLOBALS['TCA'][$tableName]['columns'][$fieldName]['config'])) {
1376 return null;
1377 }
1378 $configuration = $GLOBALS['TCA'][$tableName]['columns'][$fieldName]['config'];
1379 if (empty($configuration['type']) || $configuration['type'] !== 'inline'
1380 || empty($configuration['foreign_table']) || $configuration['foreign_table'] !== 'sys_file_reference') {
1381 return null;
1382 }
1383
1384 $fileReferences = array();
1385 /** @var $relationHandler RelationHandler */
1386 $relationHandler = GeneralUtility::makeInstance(RelationHandler::class);
1387 if ($workspaceId !== null) {
1388 $relationHandler->setWorkspaceId($workspaceId);
1389 }
1390 $relationHandler->start($element[$fieldName], $configuration['foreign_table'], $configuration['MM'], $element['uid'], $tableName, $configuration);
1391 $relationHandler->processDeletePlaceholder();
1392 $referenceUids = $relationHandler->tableArray[$configuration['foreign_table']];
1393
1394 foreach ($referenceUids as $referenceUid) {
1395 try {
1396 $fileReference = ResourceFactory::getInstance()->getFileReferenceObject($referenceUid, array(), ($workspaceId === 0));
1397 $fileReferences[$fileReference->getUid()] = $fileReference;
1398 } catch (\TYPO3\CMS\Core\Resource\Exception\FileDoesNotExistException $e) {
1399 /**
1400 * We just catch the exception here
1401 * Reasoning: There is nothing an editor or even admin could do
1402 */
1403 } catch (\InvalidArgumentException $e) {
1404 /**
1405 * The storage does not exist anymore
1406 * Log the exception message for admins as they maybe can restore the storage
1407 */
1408 $logMessage = $e->getMessage() . ' (table: "' . $tableName . '", fieldName: "' . $fieldName . '", referenceUid: ' . $referenceUid . ')';
1409 GeneralUtility::sysLog($logMessage, 'core', GeneralUtility::SYSLOG_SEVERITY_ERROR);
1410 }
1411 }
1412
1413 return $fileReferences;
1414 }
1415
1416 /**
1417 * 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
1418 * All $GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'] extension are made to thumbnails + ttf file (renders font-example)
1419 * Thumbsnails are linked to the show_item.php script which will display further details.
1420 *
1421 * @param array $row Row is the database row from the table, $table.
1422 * @param string $table Table name for $row (present in TCA)
1423 * @param string $field Field is pointing to the list of image files
1424 * @param string $backPath Back path prefix for image tag src="" field
1425 * @param string $thumbScript UNUSED since FAL
1426 * @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!)
1427 * @param int $abs UNUSED
1428 * @param string $tparams Optional: $tparams is additional attributes for the image tags
1429 * @param int|string $size Optional: $size is [w]x[h] of the thumbnail. 64 is default.
1430 * @param bool $linkInfoPopup Whether to wrap with a link opening the info popup
1431 * @return string Thumbnail image tag.
1432 */
1433 public static function thumbCode($row, $table, $field, $backPath = '', $thumbScript = '', $uploaddir = null, $abs = 0, $tparams = '', $size = '', $linkInfoPopup = true)
1434 {
1435 // Check and parse the size parameter
1436 $size = trim($size);
1437 $sizeParts = array(64, 64);
1438 if ($size) {
1439 $sizeParts = explode('x', $size . 'x' . $size);
1440 }
1441 $thumbData = '';
1442 $fileReferences = static::resolveFileReferences($table, $field, $row);
1443 // FAL references
1444 $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
1445 if ($fileReferences !== null) {
1446 foreach ($fileReferences as $fileReferenceObject) {
1447 $fileObject = $fileReferenceObject->getOriginalFile();
1448
1449 if ($fileObject->isMissing()) {
1450 $flashMessage = \TYPO3\CMS\Core\Resource\Utility\BackendUtility::getFlashMessageForMissingFile($fileObject);
1451 $thumbData .= $flashMessage->render();
1452 continue;
1453 }
1454
1455 // Preview web image or media elements
1456 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())) {
1457 $processedImage = $fileObject->process(ProcessedFile::CONTEXT_IMAGECROPSCALEMASK, array(
1458 'width' => $sizeParts[0],
1459 'height' => $sizeParts[1] . 'c',
1460 'crop' => $fileReferenceObject->getProperty('crop')
1461 ));
1462 $imageUrl = $processedImage->getPublicUrl(true);
1463 $imgTag = '<img src="' . $imageUrl . '" ' .
1464 'width="' . $processedImage->getProperty('width') . '" ' .
1465 'height="' . $processedImage->getProperty('height') . '" ' .
1466 'alt="' . htmlspecialchars($fileReferenceObject->getName()) . '" />';
1467 } else {
1468 // Icon
1469 $imgTag = '<span title="' . htmlspecialchars($fileObject->getName()) . '">' . $iconFactory->getIconForResource($fileObject, Icon::SIZE_SMALL)->render() . '</span>';
1470 }
1471 if ($linkInfoPopup) {
1472 $onClick = 'top.launchView(\'_FILE\',\'' . (int)$fileObject->getUid() . '\',' . GeneralUtility::quoteJSvalue($backPath) . '); return false;';
1473 $thumbData .= '<a href="#" onclick="' . htmlspecialchars($onClick) . '">' . $imgTag . '</a> ';
1474 } else {
1475 $thumbData .= $imgTag;
1476 }
1477 }
1478 } else {
1479 // Find uploaddir automatically
1480 if (is_null($uploaddir)) {
1481 $uploaddir = $GLOBALS['TCA'][$table]['columns'][$field]['config']['uploadfolder'];
1482 }
1483 $uploaddir = rtrim($uploaddir, '/');
1484 // Traverse files:
1485 $thumbs = GeneralUtility::trimExplode(',', $row[$field], true);
1486 $thumbData = '';
1487 foreach ($thumbs as $theFile) {
1488 if ($theFile) {
1489 $fileName = trim($uploaddir . '/' . $theFile, '/');
1490 try {
1491 /** @var File $fileObject */
1492 $fileObject = ResourceFactory::getInstance()->retrieveFileOrFolderObject($fileName);
1493 // Skip the resource if it's not of type AbstractFile. One case where this can happen if the
1494 // storage has been externally modified and the field value now points to a folder
1495 // instead of a file.
1496 if (!$fileObject instanceof AbstractFile) {
1497 continue;
1498 }
1499 if ($fileObject->isMissing()) {
1500 $flashMessage = \TYPO3\CMS\Core\Resource\Utility\BackendUtility::getFlashMessageForMissingFile($fileObject);
1501 $thumbData .= $flashMessage->render();
1502 continue;
1503 }
1504 } catch (ResourceDoesNotExistException $exception) {
1505 /** @var FlashMessage $flashMessage */
1506 $flashMessage = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Messaging\FlashMessage::class,
1507 htmlspecialchars($exception->getMessage()),
1508 static::getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:warning.file_missing', true),
1509 FlashMessage::ERROR
1510 );
1511 $thumbData .= $flashMessage->render();
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) . ',\'\',' . GeneralUtility::quoteJSvalue($backPath) . ');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) . ',\'\',' . GeneralUtility::quoteJSvalue($backPath) . '); 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 DeprecationUtility::logFunction();
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
2452 if ($data['image_descr'] || $data['seeAlso'] || $data['details'] || $data['syntax']) {
2453 $output['moreInfo'] = true;
2454 }
2455 // Add description
2456 if ($data['description']) {
2457 $output['description'] = $data['description'];
2458 }
2459 }
2460 return $output;
2461 }
2462
2463 /**
2464 * Returns CSH help text
2465 *
2466 * @param string $table Table name
2467 * @param string $field Field name
2468 * @return string HTML content for help text
2469 * @see cshItem()
2470 */
2471 public static function helpText($table, $field)
2472 {
2473 $helpTextArray = self::helpTextArray($table, $field);
2474 $output = '';
2475 $arrow = '';
2476 // Put header before the rest of the text
2477 if ($helpTextArray['title'] !== null) {
2478 $output .= '<h2 class="t3-row-header">' . $helpTextArray['title'] . '</h2>';
2479 }
2480 // Add see also arrow if we have more info
2481 if ($helpTextArray['moreInfo']) {
2482 /** @var IconFactory $iconFactory */
2483 $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
2484 $arrow = $iconFactory->getIcon('actions-view-go-forward', Icon::SIZE_SMALL)->render();
2485 }
2486 // Wrap description and arrow in p tag
2487 if ($helpTextArray['description'] !== null || $arrow) {
2488 $output .= '<p class="t3-help-short">' . nl2br(htmlspecialchars($helpTextArray['description'])) . $arrow . '</p>';
2489 }
2490 return $output;
2491 }
2492
2493 /**
2494 * API function that wraps the text / html in help text, so if a user hovers over it
2495 * the help text will show up
2496 * This is the new help API function since TYPO3 4.5, and uses the new behaviour
2497 * (hover over text, no icon, no fulltext option, no option to disable the help)
2498 *
2499 * @param string $table The table name for which the help should be shown
2500 * @param string $field The field name for which the help should be shown
2501 * @param string $text The text which should be wrapped with the help text
2502 * @param array $overloadHelpText Array with text to overload help text
2503 * @return string the HTML code ready to render
2504 */
2505 public static function wrapInHelp($table, $field, $text = '', array $overloadHelpText = array())
2506 {
2507 if (!ExtensionManagementUtility::isLoaded('context_help')) {
2508 return $text;
2509 }
2510
2511 // Initialize some variables
2512 $helpText = '';
2513 $abbrClassAdd = '';
2514 $wrappedText = $text;
2515 $hasHelpTextOverload = !empty($overloadHelpText);
2516 // Get the help text that should be shown on hover
2517 if (!$hasHelpTextOverload) {
2518 $helpText = self::helpText($table, $field);
2519 }
2520 // If there's a help text or some overload information, proceed with preparing an output
2521 // @todo: right now this is a hard dependency on csh manual, as the whole help system should be moved to
2522 // the extension. The core provides an API for adding help and rendering help, but the rendering
2523 // should be up to the extension itself
2524 if ((!empty($helpText) || $hasHelpTextOverload) && ExtensionManagementUtility::isLoaded('cshmanual')) {
2525 // If no text was given, just use the regular help icon
2526 if ($text == '') {
2527 /** @var IconFactory $iconFactory */
2528 $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
2529 $text = $iconFactory->getIcon('actions-system-help-open', Icon::SIZE_SMALL)->render();
2530 $abbrClassAdd = '-icon';
2531 }
2532 $text = '<abbr class="t3-help-teaser' . $abbrClassAdd . '">' . $text . '</abbr>';
2533 $wrappedText = '<span class="t3-help-link" href="#" data-table="' . $table . '" data-field="' . $field . '"';
2534 // The overload array may provide a title and a description
2535 // If either one is defined, add them to the "data" attributes
2536 if ($hasHelpTextOverload) {
2537 if (isset($overloadHelpText['title'])) {
2538 $wrappedText .= ' data-title="' . htmlspecialchars($overloadHelpText['title']) . '"';
2539 }
2540 if (isset($overloadHelpText['description'])) {
2541 $wrappedText .= ' data-description="' . htmlspecialchars($overloadHelpText['description']) . '"';
2542 }
2543 }
2544 $wrappedText .= '>' . $text . '</span>';
2545 return $wrappedText;
2546 }
2547 return $text;
2548 }
2549
2550 /**
2551 * API for getting CSH icons/text for use in backend modules.
2552 * TCA_DESCR will be loaded if it isn't already
2553 *
2554 * @param string $table Table name ('_MOD_'+module name)
2555 * @param string $field Field name (CSH locallang main key)
2556 * @param string $_ (unused)
2557 * @param string $wrap Wrap code for icon-mode, splitted by "|". Not used for full-text mode.
2558 * @return string HTML content for help text
2559 */
2560 public static function cshItem($table, $field, $_ = '', $wrap = '')
2561 {
2562 static::getLanguageService()->loadSingleTableDescription($table);
2563 if (is_array($GLOBALS['TCA_DESCR'][$table])
2564 && is_array($GLOBALS['TCA_DESCR'][$table]['columns'][$field])) {
2565 // Creating short description
2566 $output = self::wrapInHelp($table, $field);
2567 if ($output && $wrap) {
2568 $wrParts = explode('|', $wrap);
2569 $output = $wrParts[0] . $output . $wrParts[1];
2570 }
2571 return $output;
2572 }
2573 return '';
2574 }
2575
2576 /**
2577 * 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.
2578 * REMEMBER to always htmlspecialchar() content in href-properties to ampersands get converted to entities (XHTML requirement and XSS precaution)
2579 *
2580 * @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.
2581 * @param string $_ (unused)
2582 * @param string $requestUri An optional returnUrl you can set - automatically set to REQUEST_URI.
2583 *
2584 * @return string
2585 */
2586 public static function editOnClick($params, $_ = '', $requestUri = '')
2587 {
2588 if ($requestUri == -1) {
2589 $returnUrl = 'T3_THIS_LOCATION';
2590 } else {
2591 $returnUrl = GeneralUtility::quoteJSvalue(rawurlencode($requestUri ?: GeneralUtility::getIndpEnv('REQUEST_URI')));
2592 }
2593 return 'window.location.href=' . GeneralUtility::quoteJSvalue(self::getModuleUrl('record_edit') . $params . '&returnUrl=') . '+' . $returnUrl . '; return false;';
2594 }
2595
2596 /**
2597 * Returns a JavaScript string for viewing the page id, $id
2598 * It will detect the correct domain name if needed and provide the link with the right back path.
2599 * Also it will re-use any window already open.
2600 *
2601 * @param int $pageUid Page UID
2602 * @param string $backPath Must point back to TYPO3_mainDir (where the site is assumed to be one level above)
2603 * @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)
2604 * @param string $anchorSection Optional anchor to the URL
2605 * @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!
2606 * @param string $additionalGetVars Additional GET variables.
2607 * @param bool $switchFocus If TRUE, then the preview window will gain the focus.
2608 * @return string
2609 */
2610 public static function viewOnClick($pageUid, $backPath = '', $rootLine = null, $anchorSection = '', $alternativeUrl = '', $additionalGetVars = '', $switchFocus = true)
2611 {
2612 $viewScript = '/index.php?id=';
2613 if ($alternativeUrl) {
2614 $viewScript = $alternativeUrl;
2615 }
2616
2617 if (
2618 isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['viewOnClickClass'])
2619 && is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['viewOnClickClass'])
2620 ) {
2621 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['viewOnClickClass'] as $funcRef) {
2622 $hookObj = GeneralUtility::getUserObj($funcRef);
2623 if (method_exists($hookObj, 'preProcess')) {
2624 $hookObj->preProcess($pageUid, $backPath, $rootLine, $anchorSection, $viewScript, $additionalGetVars, $switchFocus);
2625 }
2626 }
2627 }
2628
2629 if ($alternativeUrl) {
2630 $previewUrl = $viewScript;
2631 } else {
2632 $previewUrl = self::createPreviewUrl($pageUid, $rootLine, $anchorSection, $additionalGetVars, $viewScript);
2633 }
2634
2635 if (
2636 isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['viewOnClickClass'])
2637 && is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['viewOnClickClass'])
2638 ) {
2639 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['viewOnClickClass'] as $className) {
2640 $hookObj = GeneralUtility::makeInstance($className);
2641 if (method_exists($hookObj, 'postProcess')) {
2642 $previewUrl = $hookObj->postProcess($previewUrl, $pageUid, $backPath, $rootLine, $anchorSection, $viewScript, $additionalGetVars, $switchFocus);
2643 }
2644 }
2645 }
2646
2647 $onclickCode = 'var previewWin = window.open(' . GeneralUtility::quoteJSvalue($previewUrl) . ',\'newTYPO3frontendWindow\');' . ($switchFocus ? 'previewWin.focus();' : '');
2648 return $onclickCode;
2649 }
2650
2651 /**
2652 * Makes click menu link (context sensitive menu)
2653 *
2654 * Returns $str wrapped in a link which will activate the context sensitive
2655 * menu for the record ($table/$uid) or file ($table = file)
2656 * The link will load the top frame with the parameter "&item" which is the table, uid
2657 * and listFrame arguments imploded by "|": rawurlencode($table.'|'.$uid.'|'.$listFr)
2658 *
2659 * @param string $content String to be wrapped in link, typ. image tag.
2660 * @param string $table Table name/File path. If the icon is for a database
2661 * record, enter the tablename from $GLOBALS['TCA']. If a file then enter
2662 * the absolute filepath
2663 * @param int $uid If icon is for database record this is the UID for the
2664 * record from $table
2665 * @param bool $listFrame Tells the top frame script that the link is coming
2666 * from a "list" frame which means a frame from within the backend content frame.
2667 * @param string $addParams Additional GET parameters for the link to the
2668 * ClickMenu AJAX request
2669 * @param string $enDisItems Enable / Disable click menu items.
2670 * Example: "+new,view" will display ONLY these two items (and any spacers
2671 * in between), "new,view" will display all BUT these two items.
2672 * @param bool $returnTagParameters If set, will return only the onclick
2673 * JavaScript, not the whole link.
2674 *
2675 * @return string The link wrapped input string.
2676 */
2677 public static function wrapClickMenuOnIcon(
2678 $content,
2679 $table,
2680 $uid = 0,
2681 $listFrame = true,
2682 $addParams = '',
2683 $enDisItems = '',
2684 $returnTagParameters = false
2685 ) {
2686 $tagParameters = array(
2687 'class' => 't3-js-clickmenutrigger',
2688 'data-table' => $table,
2689 'data-uid' => (int)$uid !== 0 ? (int)$uid : '',
2690 'data-listframe' => $listFrame,
2691 'data-iteminfo' => str_replace('+', '%2B', $enDisItems),
2692 'data-parameters' => $addParams,
2693 );
2694
2695 if ($returnTagParameters) {
2696 return $tagParameters;
2697 }
2698 return '<a href="#" ' . GeneralUtility::implodeAttributes($tagParameters, true) . '>' . $content . '</a>';
2699 }
2700
2701 /**
2702 * Returns a URL with a command to TYPO3 Datahandler
2703 *
2704 * @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
2705 * @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
2706 * @return string URL to BackendUtility::getModuleUrl('tce_db') + parameters
2707 */
2708 public static function getLinkToDataHandlerAction($parameters, $redirectUrl = '')
2709 {
2710 $urlParameters = [
2711 'prErr' => 1,
2712 'uPT' => 1,
2713 'vC' => static::getBackendUserAuthentication()->veriCode()
2714 ];