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