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