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