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