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