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