[BUGFIX] BackendUtility::dateTimeAge must return correct values
[Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Classes / Utility / BackendUtility.php
1 <?php
2 namespace TYPO3\CMS\Backend\Utility;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Backend\Configuration\TranslationConfigurationProvider;
18 use TYPO3\CMS\Backend\Routing\UriBuilder;
19 use TYPO3\CMS\Backend\Template\DocumentTemplate;
20 use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
21 use TYPO3\CMS\Core\Cache\CacheManager;
22 use TYPO3\CMS\Core\Database\DatabaseConnection;
23 use TYPO3\CMS\Core\Database\PreparedStatement;
24 use TYPO3\CMS\Core\Database\RelationHandler;
25 use TYPO3\CMS\Core\FormProtection\FormProtectionFactory;
26 use TYPO3\CMS\Core\Imaging\Icon;
27 use TYPO3\CMS\Core\Imaging\IconFactory;
28 use TYPO3\CMS\Core\Messaging\FlashMessage;
29 use TYPO3\CMS\Core\Resource\AbstractFile;
30 use TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException;
31 use TYPO3\CMS\Core\Resource\File;
32 use TYPO3\CMS\Core\Resource\ProcessedFile;
33 use TYPO3\CMS\Core\Resource\ResourceFactory;
34 use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser;
35 use TYPO3\CMS\Core\Utility\ArrayUtility;
36 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
37 use TYPO3\CMS\Core\Utility\GeneralUtility;
38 use TYPO3\CMS\Core\Utility\HttpUtility;
39 use TYPO3\CMS\Core\Utility\MathUtility;
40 use TYPO3\CMS\Core\Utility\PathUtility;
41 use TYPO3\CMS\Core\Utility\StringUtility;
42 use TYPO3\CMS\Core\Versioning\VersionState;
43 use TYPO3\CMS\Frontend\Page\PageRepository;
44 use TYPO3\CMS\Lang\LanguageService;
45
46 /**
47 * Standard functions available for the TYPO3 backend.
48 * You are encouraged to use this class in your own applications (Backend Modules)
49 * Don't instantiate - call functions with "\TYPO3\CMS\Backend\Utility\BackendUtility::" prefixed the function name.
50 *
51 * Call ALL methods without making an object!
52 * Eg. to get a page-record 51 do this: '\TYPO3\CMS\Backend\Utility\BackendUtility::getRecord('pages',51)'
53 */
54 class BackendUtility
55 {
56 /**
57 * Cache the TCA configuration of tables with their types during runtime
58 *
59 * @var array
60 * @see self::getTCAtypes()
61 */
62 protected static $tcaTableTypeConfigurationCache = array();
63
64 /*******************************************
65 *
66 * SQL-related, selecting records, searching
67 *
68 *******************************************/
69 /**
70 * Returns the WHERE clause " AND NOT [tablename].[deleted-field]" if a deleted-field
71 * is configured in $GLOBALS['TCA'] for the tablename, $table
72 * This function should ALWAYS be called in the backend for selection on tables which
73 * are configured in $GLOBALS['TCA'] since it will ensure consistent selection of records,
74 * even if they are marked deleted (in which case the system must always treat them as non-existent!)
75 * In the frontend a function, ->enableFields(), is known to filter hidden-field, start- and endtime
76 * and fe_groups as well. But that is a job of the frontend, not the backend. If you need filtering
77 * on those fields as well in the backend you can use ->BEenableFields() though.
78 *
79 * @param string $table Table name present in $GLOBALS['TCA']
80 * @param string $tableAlias Table alias if any
81 * @return string WHERE clause for filtering out deleted records, eg " AND tablename.deleted=0
82 */
83 public static function deleteClause($table, $tableAlias = '')
84 {
85 if (!empty($GLOBALS['TCA'][$table]['ctrl']['delete'])) {
86 return ' AND ' . ($tableAlias ?: $table) . '.' . $GLOBALS['TCA'][$table]['ctrl']['delete'] . '=0';
87 } else {
88 return '';
89 }
90 }
91
92 /**
93 * Gets record with uid = $uid from $table
94 * You can set $field to a list of fields (default is '*')
95 * Additional WHERE clauses can be added by $where (fx. ' AND blabla = 1')
96 * Will automatically check if records has been deleted and if so, not return anything.
97 * $table must be found in $GLOBALS['TCA']
98 *
99 * @param string $table Table name present in $GLOBALS['TCA']
100 * @param int $uid UID of record
101 * @param string $fields List of fields to select
102 * @param string $where Additional WHERE clause, eg. " AND blablabla = 0
103 * @param bool $useDeleteClause Use the deleteClause to check if a record is deleted (default TRUE)
104 * @return array|NULL Returns the row if found, otherwise NULL
105 */
106 public static function getRecord($table, $uid, $fields = '*', $where = '', $useDeleteClause = true)
107 {
108 // Ensure we have a valid uid (not 0 and not NEWxxxx) and a valid TCA
109 if ((int)$uid && !empty($GLOBALS['TCA'][$table])) {
110 $where = 'uid=' . (int)$uid . ($useDeleteClause ? self::deleteClause($table) : '') . $where;
111 $row = static::getDatabaseConnection()->exec_SELECTgetSingleRow($fields, $table, $where);
112 if ($row) {
113 return $row;
114 }
115 }
116 return null;
117 }
118
119 /**
120 * Like getRecord(), but overlays workspace version if any.
121 *
122 * @param string $table Table name present in $GLOBALS['TCA']
123 * @param int $uid UID of record
124 * @param string $fields List of fields to select
125 * @param string $where Additional WHERE clause, eg. " AND blablabla = 0
126 * @param bool $useDeleteClause Use the deleteClause to check if a record is deleted (default TRUE)
127 * @param bool $unsetMovePointers If TRUE the function does not return a "pointer" row for moved records in a workspace
128 * @return array Returns the row if found, otherwise nothing
129 */
130 public static function getRecordWSOL($table, $uid, $fields = '*', $where = '', $useDeleteClause = true, $unsetMovePointers = false)
131 {
132 if ($fields !== '*') {
133 $internalFields = GeneralUtility::uniqueList($fields . ',uid,pid');
134 $row = self::getRecord($table, $uid, $internalFields, $where, $useDeleteClause);
135 self::workspaceOL($table, $row, -99, $unsetMovePointers);
136 if (is_array($row)) {
137 foreach ($row as $key => $_) {
138 if (!GeneralUtility::inList($fields, $key) && $key[0] !== '_') {
139 unset($row[$key]);
140 }
141 }
142 }
143 } else {
144 $row = self::getRecord($table, $uid, $fields, $where, $useDeleteClause);
145 self::workspaceOL($table, $row, -99, $unsetMovePointers);
146 }
147 return $row;
148 }
149
150 /**
151 * Returns the first record found from $table with $where as WHERE clause
152 * This function does NOT check if a record has the deleted flag set.
153 * $table does NOT need to be configured in $GLOBALS['TCA']
154 * The query used is simply this:
155 * $query = 'SELECT ' . $fields . ' FROM ' . $table . ' WHERE ' . $where;
156 *
157 * @param string $table Table name (not necessarily in TCA)
158 * @param string $where WHERE clause
159 * @param string $fields $fields is a list of fields to select, default is '*'
160 * @return array|bool First row found, if any, FALSE otherwise
161 */
162 public static function getRecordRaw($table, $where = '', $fields = '*')
163 {
164 $row = false;
165 $db = static::getDatabaseConnection();
166 if (false !== ($res = $db->exec_SELECTquery($fields, $table, $where, '', '', '1'))) {
167 $row = $db->sql_fetch_assoc($res);
168 $db->sql_free_result($res);
169 }
170 return $row;
171 }
172
173 /**
174 * Returns records from table, $theTable, where a field ($theField) equals the value, $theValue
175 * The records are returned in an array
176 * If no records were selected, the function returns nothing
177 *
178 * @param string $theTable Table name present in $GLOBALS['TCA']
179 * @param string $theField Field to select on
180 * @param string $theValue Value that $theField must match
181 * @param string $whereClause Optional additional WHERE clauses put in the end of the query. DO NOT PUT IN GROUP BY, ORDER BY or LIMIT!
182 * @param string $groupBy Optional GROUP BY field(s), if none, supply blank string.
183 * @param string $orderBy Optional ORDER BY field(s), if none, supply blank string.
184 * @param string $limit Optional LIMIT value ([begin,]max), if none, supply blank string.
185 * @param bool $useDeleteClause Use the deleteClause to check if a record is deleted (default TRUE)
186 * @return mixed Multidimensional array with selected records (if any is selected)
187 */
188 public static function getRecordsByField($theTable, $theField, $theValue, $whereClause = '', $groupBy = '', $orderBy = '', $limit = '', $useDeleteClause = true)
189 {
190 if (is_array($GLOBALS['TCA'][$theTable])) {
191 $db = static::getDatabaseConnection();
192 $res = $db->exec_SELECTquery(
193 '*',
194 $theTable,
195 $theField . '=' . $db->fullQuoteStr($theValue, $theTable) .
196 ($useDeleteClause ? self::deleteClause($theTable) . ' ' : '') .
197 self::versioningPlaceholderClause($theTable) . ' ' .
198 $whereClause,
199 $groupBy,
200 $orderBy,
201 $limit
202 );
203 $rows = array();
204 while ($row = $db->sql_fetch_assoc($res)) {
205 $rows[] = $row;
206 }
207 $db->sql_free_result($res);
208 if (!empty($rows)) {
209 return $rows;
210 }
211 }
212 return null;
213 }
214
215 /**
216 * Makes an backwards explode on the $str and returns an array with ($table, $uid).
217 * Example: tt_content_45 => array('tt_content', 45)
218 *
219 * @param string $str [tablename]_[uid] string to explode
220 * @return array
221 */
222 public static function splitTable_Uid($str)
223 {
224 list($uid, $table) = explode('_', strrev($str), 2);
225 return array(strrev($table), strrev($uid));
226 }
227
228 /**
229 * Returns a list of pure ints based on $in_list being a list of records with table-names prepended.
230 * Ex: $in_list = "pages_4,tt_content_12,45" would result in a return value of "4,45" if $tablename is "pages" and $default_tablename is 'pages' as well.
231 *
232 * @param string $in_list Input list
233 * @param string $tablename Table name from which ids is returned
234 * @param string $default_tablename $default_tablename denotes what table the number '45' is from (if nothing is prepended on the value)
235 * @return string List of ids
236 */
237 public static function getSQLselectableList($in_list, $tablename, $default_tablename)
238 {
239 $list = array();
240 if ((string)trim($in_list) != '') {
241 $tempItemArray = explode(',', trim($in_list));
242 foreach ($tempItemArray as $key => $val) {
243 $val = strrev($val);
244 $parts = explode('_', $val, 2);
245 if ((string)trim($parts[0]) != '') {
246 $theID = (int)strrev($parts[0]);
247 $theTable = trim($parts[1]) ? strrev(trim($parts[1])) : $default_tablename;
248 if ($theTable == $tablename) {
249 $list[] = $theID;
250 }
251 }
252 }
253 }
254 return implode(',', $list);
255 }
256
257 /**
258 * Backend implementation of enableFields()
259 * Notice that "fe_groups" is not selected for - only disabled, starttime and endtime.
260 * Notice that deleted-fields are NOT filtered - you must ALSO call deleteClause in addition.
261 * $GLOBALS["SIM_ACCESS_TIME"] is used for date.
262 *
263 * @param string $table The table from which to return enableFields WHERE clause. Table name must have a 'ctrl' section in $GLOBALS['TCA'].
264 * @param bool $inv Means that the query will select all records NOT VISIBLE records (inverted selection)
265 * @return string WHERE clause part
266 */
267 public static function BEenableFields($table, $inv = false)
268 {
269 $ctrl = $GLOBALS['TCA'][$table]['ctrl'];
270 $query = array();
271 $invQuery = array();
272 if (is_array($ctrl)) {
273 if (is_array($ctrl['enablecolumns'])) {
274 if ($ctrl['enablecolumns']['disabled']) {
275 $field = $table . '.' . $ctrl['enablecolumns']['disabled'];
276 $query[] = $field . '=0';
277 $invQuery[] = $field . '<>0';
278 }
279 if ($ctrl['enablecolumns']['starttime']) {
280 $field = $table . '.' . $ctrl['enablecolumns']['starttime'];
281 $query[] = '(' . $field . '<=' . $GLOBALS['SIM_ACCESS_TIME'] . ')';
282 $invQuery[] = '(' . $field . '<>0 AND ' . $field . '>' . $GLOBALS['SIM_ACCESS_TIME'] . ')';
283 }
284 if ($ctrl['enablecolumns']['endtime']) {
285 $field = $table . '.' . $ctrl['enablecolumns']['endtime'];
286 $query[] = '(' . $field . '=0 OR ' . $field . '>' . $GLOBALS['SIM_ACCESS_TIME'] . ')';
287 $invQuery[] = '(' . $field . '<>0 AND ' . $field . '<=' . $GLOBALS['SIM_ACCESS_TIME'] . ')';
288 }
289 }
290 }
291 $outQ = $inv ? '(' . implode(' OR ', $invQuery) . ')' : implode(' AND ', $query);
292 return $outQ ? ' AND ' . $outQ : '';
293 }
294
295 /**
296 * Fetches the localization for a given record.
297 *
298 * @param string $table Table name present in $GLOBALS['TCA']
299 * @param int $uid The uid of the record
300 * @param int $language The uid of the language record in sys_language
301 * @param string $andWhereClause Optional additional WHERE clause (default: '')
302 * @return mixed Multidimensional array with selected records; if none exist, FALSE is returned
303 */
304 public static function getRecordLocalization($table, $uid, $language, $andWhereClause = '')
305 {
306 $recordLocalization = false;
307
308 // Check if translations are stored in other table
309 if (isset($GLOBALS['TCA'][$table]['ctrl']['transForeignTable'])) {
310 $table = $GLOBALS['TCA'][$table]['ctrl']['transForeignTable'];
311 }
312
313 if (self::isTableLocalizable($table)) {
314 $tcaCtrl = $GLOBALS['TCA'][$table]['ctrl'];
315 $recordLocalization = self::getRecordsByField($table, $tcaCtrl['transOrigPointerField'], $uid, 'AND ' . $tcaCtrl['languageField'] . '=' . (int)$language . ($andWhereClause ? ' ' . $andWhereClause : ''), '', '', '1');
316 }
317 return $recordLocalization;
318 }
319
320 /*******************************************
321 *
322 * Page tree, TCA related
323 *
324 *******************************************/
325 /**
326 * Returns what is called the 'RootLine'. That is an array with information about the page records from a page id ($uid) and back to the root.
327 * By default deleted pages are filtered.
328 * This RootLine will follow the tree all the way to the root. This is opposite to another kind of root line known from the frontend where the rootline stops when a root-template is found.
329 *
330 * @param int $uid Page id for which to create the root line.
331 * @param string $clause Clause can be used to select other criteria. It would typically be where-clauses that stops the process if we meet a page, the user has no reading access to.
332 * @param bool $workspaceOL If TRUE, version overlay is applied. This must be requested specifically because it is usually only wanted when the rootline is used for visual output while for permission checking you want the raw thing!
333 * @return array Root line array, all the way to the page tree root (or as far as $clause allows!)
334 */
335 public static function BEgetRootLine($uid, $clause = '', $workspaceOL = false)
336 {
337 static $BEgetRootLine_cache = array();
338 $output = array();
339 $pid = $uid;
340 $ident = $pid . '-' . $clause . '-' . $workspaceOL;
341 if (is_array($BEgetRootLine_cache[$ident])) {
342 $output = $BEgetRootLine_cache[$ident];
343 } else {
344 $loopCheck = 100;
345 $theRowArray = array();
346 while ($uid != 0 && $loopCheck) {
347 $loopCheck--;
348 $row = self::getPageForRootline($uid, $clause, $workspaceOL);
349 if (is_array($row)) {
350 $uid = $row['pid'];
351 $theRowArray[] = $row;
352 } else {
353 break;
354 }
355 }
356 if ($uid == 0) {
357 $theRowArray[] = array('uid' => 0, 'title' => '');
358 }
359 $c = count($theRowArray);
360 foreach ($theRowArray as $val) {
361 $c--;
362 $output[$c] = array(
363 'uid' => $val['uid'],
364 'pid' => $val['pid'],
365 'title' => $val['title'],
366 'doktype' => $val['doktype'],
367 'tsconfig_includes' => $val['tsconfig_includes'],
368 'TSconfig' => $val['TSconfig'],
369 'is_siteroot' => $val['is_siteroot'],
370 't3ver_oid' => $val['t3ver_oid'],
371 't3ver_wsid' => $val['t3ver_wsid'],
372 't3ver_state' => $val['t3ver_state'],
373 't3ver_stage' => $val['t3ver_stage'],
374 'backend_layout_next_level' => $val['backend_layout_next_level']
375 );
376 if (isset($val['_ORIG_pid'])) {
377 $output[$c]['_ORIG_pid'] = $val['_ORIG_pid'];
378 }
379 }
380 $BEgetRootLine_cache[$ident] = $output;
381 }
382 return $output;
383 }
384
385 /**
386 * Gets the cached page record for the rootline
387 *
388 * @param int $uid Page id for which to create the root line.
389 * @param string $clause Clause can be used to select other criteria. It would typically be where-clauses that stops the process if we meet a page, the user has no reading access to.
390 * @param bool $workspaceOL If TRUE, version overlay is applied. This must be requested specifically because it is usually only wanted when the rootline is used for visual output while for permission checking you want the raw thing!
391 * @return array Cached page record for the rootline
392 * @see BEgetRootLine
393 */
394 protected static function getPageForRootline($uid, $clause, $workspaceOL)
395 {
396 static $getPageForRootline_cache = array();
397 $ident = $uid . '-' . $clause . '-' . $workspaceOL;
398 if (is_array($getPageForRootline_cache[$ident])) {
399 $row = $getPageForRootline_cache[$ident];
400 } else {
401 $db = static::getDatabaseConnection();
402 $res = $db->exec_SELECTquery('pid,uid,title,doktype,tsconfig_includes,TSconfig,is_siteroot,t3ver_oid,t3ver_wsid,t3ver_state,t3ver_stage,backend_layout_next_level', 'pages', 'uid=' . (int)$uid . ' ' . self::deleteClause('pages') . ' ' . $clause);
403 $row = $db->sql_fetch_assoc($res);
404 if ($row) {
405 $newLocation = false;
406 if ($workspaceOL) {
407 self::workspaceOL('pages', $row);
408 $newLocation = self::getMovePlaceholder('pages', $row['uid'], 'pid');
409 }
410 if (is_array($row)) {
411 if ($newLocation !== false) {
412 $row['pid'] = $newLocation['pid'];
413 } else {
414 self::fixVersioningPid('pages', $row);
415 }
416 $getPageForRootline_cache[$ident] = $row;
417 }
418 }
419 $db->sql_free_result($res);
420 }
421 return $row;
422 }
423
424 /**
425 * Opens the page tree to the specified page id
426 *
427 * @param int $pid Page id.
428 * @param bool $clearExpansion If set, then other open branches are closed.
429 * @return void
430 */
431 public static function openPageTree($pid, $clearExpansion)
432 {
433 $beUser = static::getBackendUserAuthentication();
434 // Get current expansion data:
435 if ($clearExpansion) {
436 $expandedPages = array();
437 } else {
438 $expandedPages = unserialize($beUser->uc['browseTrees']['browsePages']);
439 }
440 // Get rootline:
441 $rL = self::BEgetRootLine($pid);
442 // First, find out what mount index to use (if more than one DB mount exists):
443 $mountIndex = 0;
444 $mountKeys = array_flip($beUser->returnWebmounts());
445 foreach ($rL as $rLDat) {
446 if (isset($mountKeys[$rLDat['uid']])) {
447 $mountIndex = $mountKeys[$rLDat['uid']];
448 break;
449 }
450 }
451 // Traverse rootline and open paths:
452 foreach ($rL as $rLDat) {
453 $expandedPages[$mountIndex][$rLDat['uid']] = 1;
454 }
455 // Write back:
456 $beUser->uc['browseTrees']['browsePages'] = serialize($expandedPages);
457 $beUser->writeUC();
458 }
459
460 /**
461 * Returns the path (visually) of a page $uid, fx. "/First page/Second page/Another subpage"
462 * Each part of the path will be limited to $titleLimit characters
463 * Deleted pages are filtered out.
464 *
465 * @param int $uid Page uid for which to create record path
466 * @param string $clause Clause is additional where clauses, eg.
467 * @param int $titleLimit Title limit
468 * @param int $fullTitleLimit Title limit of Full title (typ. set to 1000 or so)
469 * @return mixed Path of record (string) OR array with short/long title if $fullTitleLimit is set.
470 */
471 public static function getRecordPath($uid, $clause, $titleLimit, $fullTitleLimit = 0)
472 {
473 if (!$titleLimit) {
474 $titleLimit = 1000;
475 }
476 $output = $fullOutput = '/';
477 $clause = trim($clause);
478 if ($clause !== '' && substr($clause, 0, 3) !== 'AND') {
479 $clause = 'AND ' . $clause;
480 }
481 $data = self::BEgetRootLine($uid, $clause);
482 foreach ($data as $record) {
483 if ($record['uid'] === 0) {
484 continue;
485 }
486 $output = '/' . GeneralUtility::fixed_lgd_cs(strip_tags($record['title']), $titleLimit) . $output;
487 if ($fullTitleLimit) {
488 $fullOutput = '/' . GeneralUtility::fixed_lgd_cs(strip_tags($record['title']), $fullTitleLimit) . $fullOutput;
489 }
490 }
491 if ($fullTitleLimit) {
492 return array($output, $fullOutput);
493 } else {
494 return $output;
495 }
496 }
497
498 /**
499 * 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 // Do not show previews of hidden references
1728 if ($fileReferenceObject->getProperty('hidden')) {
1729 continue;
1730 }
1731 $fileObject = $fileReferenceObject->getOriginalFile();
1732
1733 if ($fileObject->isMissing()) {
1734 $thumbData .= '<span class="label label-danger">'
1735 . htmlspecialchars(static::getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:warning.file_missing'))
1736 . '</span>&nbsp;' . htmlspecialchars($fileObject->getName()) . '<br />';
1737 continue;
1738 }
1739
1740 // Preview web image or media elements
1741 if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['thumbnails'] && GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'] . ',' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['mediafile_ext'], $fileReferenceObject->getExtension())) {
1742 $processedImage = $fileObject->process(ProcessedFile::CONTEXT_IMAGECROPSCALEMASK, array(
1743 'width' => $sizeParts[0],
1744 'height' => $sizeParts[1] . 'c',
1745 'crop' => $fileReferenceObject->getProperty('crop')
1746 ));
1747 $imageUrl = $processedImage->getPublicUrl(true);
1748 $imgTag = '<img src="' . $imageUrl . '" ' .
1749 'width="' . $processedImage->getProperty('width') . '" ' .
1750 'height="' . $processedImage->getProperty('height') . '" ' .
1751 'alt="' . htmlspecialchars($fileReferenceObject->getName()) . '" />';
1752 } else {
1753 // Icon
1754 $imgTag = '<span title="' . htmlspecialchars($fileObject->getName()) . '">' . $iconFactory->getIconForResource($fileObject, Icon::SIZE_SMALL)->render() . '</span>';
1755 }
1756 if ($linkInfoPopup) {
1757 $onClick = 'top.launchView(\'_FILE\',\'' . (int)$fileObject->getUid() . '\',' . GeneralUtility::quoteJSvalue($backPath) . '); return false;';
1758 $thumbData .= '<a href="#" onclick="' . htmlspecialchars($onClick) . '">' . $imgTag . '</a> ';
1759 } else {
1760 $thumbData .= $imgTag;
1761 }
1762 }
1763 } else {
1764 // Find uploaddir automatically
1765 if (is_null($uploaddir)) {
1766 $uploaddir = $GLOBALS['TCA'][$table]['columns'][$field]['config']['uploadfolder'];
1767 }
1768 $uploaddir = rtrim($uploaddir, '/');
1769 // Traverse files:
1770 $thumbs = GeneralUtility::trimExplode(',', $row[$field], true);
1771 $thumbData = '';
1772 foreach ($thumbs as $theFile) {
1773 if ($theFile) {
1774 $fileName = trim($uploaddir . '/' . $theFile, '/');
1775 try {
1776 /** @var File $fileObject */
1777 $fileObject = ResourceFactory::getInstance()->retrieveFileOrFolderObject($fileName);
1778 // Skip the resource if it's not of type AbstractFile. One case where this can happen if the
1779 // storage has been externally modified and the field value now points to a folder
1780 // instead of a file.
1781 if (!$fileObject instanceof AbstractFile) {
1782 continue;
1783 }
1784 if ($fileObject->isMissing()) {
1785 $thumbData .= '<span class="label label-danger">'
1786 . htmlspecialchars(static::getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:warning.file_missing'))
1787 . '</span>&nbsp;' . htmlspecialchars($fileObject->getName()) . '<br />';
1788 continue;
1789 }
1790 } catch (ResourceDoesNotExistException $exception) {
1791 $thumbData .= '<span class="label label-danger">'
1792 . htmlspecialchars(static::getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:warning.file_missing'))
1793 . '</span>&nbsp;' . htmlspecialchars($fileName) . '<br />';
1794 continue;
1795 }
1796
1797 $fileExtension = $fileObject->getExtension();
1798 if ($fileExtension == 'ttf' || GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'], $fileExtension)) {
1799 $imageUrl = $fileObject->process(ProcessedFile::CONTEXT_IMAGEPREVIEW, array(
1800 'width' => $sizeParts[0],
1801 'height' => $sizeParts[1]
1802 ))->getPublicUrl(true);
1803 $image = '<img src="' . htmlspecialchars($imageUrl) . '" hspace="2" border="0" title="' . htmlspecialchars($fileObject->getName()) . '"' . $tparams . ' alt="" />';
1804 if ($linkInfoPopup) {
1805 $onClick = 'top.launchView(\'_FILE\', ' . GeneralUtility::quoteJSvalue($fileName) . ',\'\',' . GeneralUtility::quoteJSvalue($backPath) . ');return false;';
1806 $thumbData .= '<a href="#" onclick="' . htmlspecialchars($onClick) . '">' . $image . '</a> ';
1807 } else {
1808 $thumbData .= $image;
1809 }
1810 } else {
1811 // Gets the icon
1812 $fileIcon = '<span title="' . htmlspecialchars($fileObject->getName()) . '">' . $iconFactory->getIconForResource($fileObject, Icon::SIZE_SMALL)->render() . '</span>';
1813 if ($linkInfoPopup) {
1814 $onClick = 'top.launchView(\'_FILE\', ' . GeneralUtility::quoteJSvalue($fileName) . ',\'\',' . GeneralUtility::quoteJSvalue($backPath) . '); return false;';
1815 $thumbData .= '<a href="#" onclick="' . htmlspecialchars($onClick) . '">' . $fileIcon . '</a> ';
1816 } else {
1817 $thumbData .= $fileIcon;
1818 }
1819 }
1820 }
1821 }
1822 }
1823 return $thumbData;
1824 }
1825
1826 /**
1827 * Returns single image tag to thumbnail using a thumbnail script (like thumbs.php)
1828 *
1829 * @param string $thumbScript Must point to "thumbs.php" relative to the script position
1830 * @param string $theFile Must be the proper reference to the file that thumbs.php should show
1831 * @param string $tparams The additional attributes for the image tag
1832 * @param string $size The size of the thumbnail send along to thumbs.php
1833 * @return string Image tag
1834 * @deprecated since TYPO3 CMS 7, will be removed with TYPO3 CMS 8, use the corresponding Resource objects and Processing functionality
1835 */
1836 public static function getThumbNail($thumbScript, $theFile, $tparams = '', $size = '')
1837 {
1838 GeneralUtility::logDeprecatedFunction();
1839 $size = trim($size);
1840 $check = basename($theFile) . ':' . filemtime($theFile) . ':' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
1841 $params = '&file=' . rawurlencode($theFile);
1842 $params .= $size ? '&size=' . $size : '';
1843 $params .= '&md5sum=' . md5($check);
1844 $url = $thumbScript . '?' . $params;
1845 $th = '<img src="' . htmlspecialchars($url) . '" title="' . trim(basename($theFile)) . '"' . ($tparams ? ' ' . $tparams : '') . ' alt="" />';
1846 return $th;
1847 }
1848
1849 /**
1850 * Returns title-attribute information for a page-record informing about id, alias, doktype, hidden, starttime, endtime, fe_group etc.
1851 *
1852 * @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)
1853 * @param string $perms_clause This is used to get the record path of the shortcut page, if any (and doktype==4)
1854 * @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
1855 * @return string
1856 */
1857 public static function titleAttribForPages($row, $perms_clause = '', $includeAttrib = true)
1858 {
1859 $lang = static::getLanguageService();
1860 $parts = array();
1861 $parts[] = 'id=' . $row['uid'];
1862 if ($row['alias']) {
1863 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['alias']['label']) . ' ' . $row['alias'];
1864 }
1865 if ($row['pid'] < 0) {
1866 $parts[] = 'v#1.' . $row['t3ver_id'];
1867 }
1868 switch (VersionState::cast($row['t3ver_state'])) {
1869 case new VersionState(VersionState::NEW_PLACEHOLDER):
1870 $parts[] = 'PLH WSID#' . $row['t3ver_wsid'];
1871 break;
1872 case new VersionState(VersionState::DELETE_PLACEHOLDER):
1873 $parts[] = 'Deleted element!';
1874 break;
1875 case new VersionState(VersionState::MOVE_PLACEHOLDER):
1876 $parts[] = 'NEW LOCATION (PLH) WSID#' . $row['t3ver_wsid'];
1877 break;
1878 case new VersionState(VersionState::MOVE_POINTER):
1879 $parts[] = 'OLD LOCATION (PNT) WSID#' . $row['t3ver_wsid'];
1880 break;
1881 case new VersionState(VersionState::NEW_PLACEHOLDER_VERSION):
1882 $parts[] = 'New element!';
1883 break;
1884 }
1885 if ($row['doktype'] == PageRepository::DOKTYPE_LINK) {
1886 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['url']['label']) . ' ' . $row['url'];
1887 } elseif ($row['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
1888 if ($perms_clause) {
1889 $label = self::getRecordPath((int)$row['shortcut'], $perms_clause, 20);
1890 } else {
1891 $row['shortcut'] = (int)$row['shortcut'];
1892 $lRec = self::getRecordWSOL('pages', $row['shortcut'], 'title');
1893 $label = $lRec['title'] . ' (id=' . $row['shortcut'] . ')';
1894 }
1895 if ($row['shortcut_mode'] != PageRepository::SHORTCUT_MODE_NONE) {
1896 $label .= ', ' . $lang->sL($GLOBALS['TCA']['pages']['columns']['shortcut_mode']['label']) . ' ' . $lang->sL(self::getLabelFromItemlist('pages', 'shortcut_mode', $row['shortcut_mode']));
1897 }
1898 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['shortcut']['label']) . ' ' . $label;
1899 } elseif ($row['doktype'] == PageRepository::DOKTYPE_MOUNTPOINT) {
1900 if ($perms_clause) {
1901 $label = self::getRecordPath((int)$row['mount_pid'], $perms_clause, 20);
1902 } else {
1903 $lRec = self::getRecordWSOL('pages', (int)$row['mount_pid'], 'title');
1904 $label = $lRec['title'] . ' (id=' . $row['mount_pid'] . ')';
1905 }
1906 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['mount_pid']['label']) . ' ' . $label;
1907 if ($row['mount_pid_ol']) {
1908 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['mount_pid_ol']['label']);
1909 }
1910 }
1911 if ($row['nav_hide']) {
1912 $parts[] = rtrim($lang->sL($GLOBALS['TCA']['pages']['columns']['nav_hide']['label']), ':');
1913 }
1914 if ($row['hidden']) {
1915 $parts[] = $lang->sL('LLL:EXT:lang/locallang_core.xlf:labels.hidden');
1916 }
1917 if ($row['starttime']) {
1918 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['starttime']['label']) . ' ' . self::dateTimeAge($row['starttime'], -1, 'date');
1919 }
1920 if ($row['endtime']) {
1921 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['endtime']['label']) . ' ' . self::dateTimeAge($row['endtime'], -1, 'date');
1922 }
1923 if ($row['fe_group']) {
1924 $fe_groups = array();
1925 foreach (GeneralUtility::intExplode(',', $row['fe_group']) as $fe_group) {
1926 if ($fe_group < 0) {
1927 $fe_groups[] = $lang->sL(self::getLabelFromItemlist('pages', 'fe_group', $fe_group));
1928 } else {
1929 $lRec = self::getRecordWSOL('fe_groups', $fe_group, 'title');
1930 $fe_groups[] = $lRec['title'];
1931 }
1932 }
1933 $label = implode(', ', $fe_groups);
1934 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['fe_group']['label']) . ' ' . $label;
1935 }
1936 $out = htmlspecialchars(implode(' - ', $parts));
1937 return $includeAttrib ? 'title="' . $out . '"' : $out;
1938 }
1939
1940 /**
1941 * Returns the combined markup for Bootstraps tooltips
1942 *
1943 * @param array $row
1944 * @param string $table
1945 * @return string
1946 */
1947 public static function getRecordToolTip(array $row, $table = 'pages')
1948 {
1949 $toolTipText = self::getRecordIconAltText($row, $table);
1950 $toolTipCode = 'data-toggle="tooltip" data-title=" ' . str_replace(' - ', '<br>', $toolTipText) . '" data-html="true" data-placement="right"';
1951 return $toolTipCode;
1952 }
1953
1954 /**
1955 * Returns title-attribute information for ANY record (from a table defined in TCA of course)
1956 * 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.
1957 * "pages" table can be used as well and will return the result of ->titleAttribForPages() for that page.
1958 *
1959 * @param array $row Table row; $row is a row from the table, $table
1960 * @param string $table Table name
1961 * @return string
1962 */
1963 public static function getRecordIconAltText($row, $table = 'pages')
1964 {
1965 if ($table == 'pages') {
1966 $out = self::titleAttribForPages($row, '', 0);
1967 } else {
1968 $out = !empty(trim($GLOBALS['TCA'][$table]['ctrl']['descriptionColumn'])) ? $row[$GLOBALS['TCA'][$table]['ctrl']['descriptionColumn']] . ' ' : '';
1969 $ctrl = $GLOBALS['TCA'][$table]['ctrl']['enablecolumns'];
1970 // Uid is added
1971 $out .= 'id=' . $row['uid'];
1972 if ($table == 'pages' && $row['alias']) {
1973 $out .= ' / ' . $row['alias'];
1974 }
1975 if (static::isTableWorkspaceEnabled($table) && $row['pid'] < 0) {
1976 $out .= ' - v#1.' . $row['t3ver_id'];
1977 }
1978 if (static::isTableWorkspaceEnabled($table)) {
1979 switch (VersionState::cast($row['t3ver_state'])) {
1980 case new VersionState(VersionState::NEW_PLACEHOLDER):
1981 $out .= ' - PLH WSID#' . $row['t3ver_wsid'];
1982 break;
1983 case new VersionState(VersionState::DELETE_PLACEHOLDER):
1984 $out .= ' - Deleted element!';
1985 break;
1986 case new VersionState(VersionState::MOVE_PLACEHOLDER):
1987 $out .= ' - NEW LOCATION (PLH) WSID#' . $row['t3ver_wsid'];
1988 break;
1989 case new VersionState(VersionState::MOVE_POINTER):
1990 $out .= ' - OLD LOCATION (PNT) WSID#' . $row['t3ver_wsid'];
1991 break;
1992 case new VersionState(VersionState::NEW_PLACEHOLDER_VERSION):
1993 $out .= ' - New element!';
1994 break;
1995 }
1996 }
1997 // Hidden
1998 $lang = static::getLanguageService();
1999 if ($ctrl['disabled']) {
2000 $out .= $row[$ctrl['disabled']] ? ' - ' . $lang->sL('LLL:EXT:lang/locallang_core.xlf:labels.hidden') : '';
2001 }
2002 if ($ctrl['starttime']) {
2003 if ($row[$ctrl['starttime']] > $GLOBALS['EXEC_TIME']) {
2004 $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') . ')';
2005 }
2006 }
2007 if ($row[$ctrl['endtime']]) {
2008 $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') . ')';
2009 }
2010 }
2011 return htmlspecialchars($out);
2012 }
2013
2014 /**
2015 * Returns the label of the first found entry in an "items" array from $GLOBALS['TCA'] (tablename = $table/fieldname = $col) where the value is $key
2016 *
2017 * @param string $table Table name, present in $GLOBALS['TCA']
2018 * @param string $col Field name, present in $GLOBALS['TCA']
2019 * @param string $key items-array value to match
2020 * @return string Label for item entry
2021 */
2022 public static function getLabelFromItemlist($table, $col, $key)
2023 {
2024 // Check, if there is an "items" array:
2025 if (is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'][$col]) && is_array($GLOBALS['TCA'][$table]['columns'][$col]['config']['items'])) {
2026 // Traverse the items-array...
2027 foreach ($GLOBALS['TCA'][$table]['columns'][$col]['config']['items'] as $v) {
2028 // ... and return the first found label where the value was equal to $key
2029 if ((string)$v[1] === (string)$key) {
2030 return $v[0];
2031 }
2032 }
2033 }
2034 return '';
2035 }
2036
2037 /**
2038 * Return the label of a field by additionally checking TsConfig values
2039 *
2040 * @param int $pageId Page id
2041 * @param string $table Table name
2042 * @param string $column Field Name
2043 * @param string $key item value
2044 * @return string Label for item entry
2045 */
2046 public static function getLabelFromItemListMerged($pageId, $table, $column, $key)
2047 {
2048 $pageTsConfig = static::getPagesTSconfig($pageId);
2049 $label = '';
2050 if (is_array($pageTsConfig['TCEFORM.']) && is_array($pageTsConfig['TCEFORM.'][$table . '.']) && is_array($pageTsConfig['TCEFORM.'][$table . '.'][$column . '.'])) {
2051 if (is_array($pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['addItems.']) && isset($pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['addItems.'][$key])) {
2052 $label = $pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['addItems.'][$key];
2053 } elseif (is_array($pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['altLabels.']) && isset($pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['altLabels.'][$key])) {
2054 $label = $pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['altLabels.'][$key];
2055 }
2056 }
2057 if (empty($label)) {
2058 $tcaValue = self::getLabelFromItemlist($table, $column, $key);
2059 if (!empty($tcaValue)) {
2060 $label = $tcaValue;
2061 }
2062 }
2063 return $label;
2064 }
2065
2066 /**
2067 * Splits the given key with commas and returns the list of all the localized items labels, separated by a comma.
2068 * NOTE: this does not take itemsProcFunc into account
2069 *
2070 * @param string $table Table name, present in TCA
2071 * @param string $column Field name
2072 * @param string $keyList Key or comma-separated list of keys.
2073 * @param array $columnTsConfig page TSConfig for $column (TCEMAIN.<table>.<column>)
2074 * @return string Comma-separated list of localized labels
2075 */
2076 public static function getLabelsFromItemsList($table, $column, $keyList, array $columnTsConfig = array())
2077 {
2078 // Check if there is an "items" array
2079 if (
2080 !isset($GLOBALS['TCA'][$table]['columns'][$column]['config']['items'])
2081 || !is_array($GLOBALS['TCA'][$table]['columns'][$column]['config']['items'])
2082 || $keyList === ''
2083 ) {
2084 return '';
2085 }
2086
2087 $keys = GeneralUtility::trimExplode(',', $keyList, true);
2088 $labels = array();
2089 // Loop on all selected values
2090 foreach ($keys as $key) {
2091 $label = null;
2092 if ($columnTsConfig) {
2093 // Check if label has been defined or redefined via pageTsConfig
2094 if (isset($columnTsConfig['addItems.'][$key])) {
2095 $label = $columnTsConfig['addItems.'][$key];
2096 } elseif (isset($columnTsConfig['altLabels.'][$key])) {
2097 $label = $columnTsConfig['altLabels.'][$key];
2098 }
2099 }
2100 if ($label === null) {
2101 // Otherwise lookup the label in TCA items list
2102 foreach ($GLOBALS['TCA'][$table]['columns'][$column]['config']['items'] as $itemConfiguration) {
2103 list($currentLabel, $currentKey) = $itemConfiguration;
2104 if ((string)$key === (string)$currentKey) {
2105 $label = $currentLabel;
2106 break;
2107 }
2108 }
2109 }
2110 if ($label !== null) {
2111 $labels[] = static::getLanguageService()->sL($label);
2112 }
2113 }
2114 return implode(', ', $labels);
2115 }
2116
2117 /**
2118 * Returns the label-value for fieldname $col in table, $table
2119 * 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>'
2120 *
2121 * @param string $table Table name, present in $GLOBALS['TCA']
2122 * @param string $col Field name
2123 * @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.
2124 * @return string or NULL if $col is not found in the TCA table
2125 */
2126 public static function getItemLabel($table, $col, $printAllWrap = '')
2127 {
2128 // Check if column exists
2129 if (is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'][$col])) {
2130 return $GLOBALS['TCA'][$table]['columns'][$col]['label'];
2131 }
2132 if ($printAllWrap) {
2133 GeneralUtility::deprecationLog('The third parameter of getItemLabel() is deprecated with TYPO3 CMS 6.2 and will be removed two versions later.');
2134 $parts = explode('|', $printAllWrap);
2135 return $parts[0] . $col . $parts[1];
2136 }
2137
2138 return null;
2139 }
2140
2141 /**
2142 * Replace field values in given row with values from the original language
2143 * if l10n_mode TCA settings require to do so.
2144 *
2145 * @param string $table Table name
2146 * @param array $row Row to fill with original language values
2147 * @return array Row with values from the original language
2148 */
2149 protected static function replaceL10nModeFields($table, array $row)
2150 {
2151 $originalUidField = isset($GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'])
2152 ? $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']
2153 : '';
2154 if (empty($row[$originalUidField])) {
2155 return $row;
2156 }
2157
2158 $originalTable = self::getOriginalTranslationTable($table);
2159 $originalRow = self::getRecord($originalTable, $row[$originalUidField]);
2160 foreach ($row as $field => $_) {
2161 $l10n_mode = isset($GLOBALS['TCA'][$originalTable]['columns'][$field]['l10n_mode'])
2162 ? $GLOBALS['TCA'][$originalTable]['columns'][$field]['l10n_mode']
2163 : '';
2164 if ($l10n_mode === 'exclude' || ($l10n_mode === 'mergeIfNotBlank' && trim($row[$field]) === '')) {
2165 $row[$field] = $originalRow[$field];
2166 }
2167 }
2168 return $row;
2169 }
2170
2171 /**
2172 * Returns the "title"-value in record, $row, from table, $table
2173 * The field(s) from which the value is taken is determined by the "ctrl"-entries 'label', 'label_alt' and 'label_alt_force'
2174 *
2175 * @param string $table Table name, present in TCA
2176 * @param array $row Row from table
2177 * @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
2178 * @param bool $forceResult If set, the function always returns an output. If no value is found for the title, '[No title]' is returned (localized).
2179 * @return string
2180 */
2181 public static function getRecordTitle($table, $row, $prep = false, $forceResult = true)
2182 {
2183 $recordTitle = '';
2184 if (is_array($GLOBALS['TCA'][$table])) {
2185 // If configured, call userFunc
2186 if ($GLOBALS['TCA'][$table]['ctrl']['label_userFunc']) {
2187 $params['table'] = $table;
2188 $params['row'] = $row;
2189 $params['title'] = '';
2190 $params['options'] = isset($GLOBALS['TCA'][$table]['ctrl']['label_userFunc_options']) ? $GLOBALS['TCA'][$table]['ctrl']['label_userFunc_options'] : array();
2191
2192 // Create NULL-reference
2193 $null = null;
2194 GeneralUtility::callUserFunction($GLOBALS['TCA'][$table]['ctrl']['label_userFunc'], $params, $null);
2195 $recordTitle = $params['title'];
2196 } else {
2197 if (is_array($row)) {
2198 $row = self::replaceL10nModeFields($table, $row);
2199 }
2200
2201 // No userFunc: Build label
2202 $recordTitle = self::getProcessedValue($table, $GLOBALS['TCA'][$table]['ctrl']['label'], $row[$GLOBALS['TCA'][$table]['ctrl']['label']], 0, 0, false, $row['uid'], $forceResult);
2203 if ($GLOBALS['TCA'][$table]['ctrl']['label_alt'] && ($GLOBALS['TCA'][$table]['ctrl']['label_alt_force'] || (string)$recordTitle === '')) {
2204 $altFields = GeneralUtility::trimExplode(',', $GLOBALS['TCA'][$table]['ctrl']['label_alt'], true);
2205 $tA = array();
2206 if (!empty($recordTitle)) {
2207 $tA[] = $recordTitle;
2208 }
2209 foreach ($altFields as $fN) {
2210 $recordTitle = trim(strip_tags($row[$fN]));
2211 if ((string)$recordTitle !== '') {
2212 $recordTitle = self::getProcessedValue($table, $fN, $recordTitle, 0, 0, false, $row['uid']);
2213 if (!$GLOBALS['TCA'][$table]['ctrl']['label_alt_force']) {
2214 break;
2215 }
2216 $tA[] = $recordTitle;
2217 }
2218 }
2219 if ($GLOBALS['TCA'][$table]['ctrl']['label_alt_force']) {
2220 $recordTitle = implode(', ', $tA);
2221 }
2222 }
2223 }
2224 // If the current result is empty, set it to '[No title]' (localized) and prepare for output if requested
2225 if ($prep || $forceResult) {
2226 if ($prep) {
2227 $recordTitle = self::getRecordTitlePrep($recordTitle);
2228 }
2229 if (trim($recordTitle) === '') {
2230 $recordTitle = self::getNoRecordTitle($prep);
2231 }
2232 }
2233 }
2234
2235 return $recordTitle;
2236 }
2237
2238 /**
2239 * Crops a title string to a limited length and if it really was cropped, wrap it in a <span title="...">|</span>,
2240 * which offers a tooltip with the original title when moving mouse over it.
2241 *
2242 * @param string $title The title string to be cropped
2243 * @param int $titleLength Crop title after this length - if not set, BE_USER->uc['titleLen'] is used
2244 * @return string The processed title string, wrapped in <span title="...">|</span> if cropped
2245 */
2246 public static function getRecordTitlePrep($title, $titleLength = 0)
2247 {
2248 // If $titleLength is not a valid positive integer, use BE_USER->uc['titleLen']:
2249 if (!$titleLength || !MathUtility::canBeInterpretedAsInteger($titleLength) || $titleLength < 0) {
2250 $titleLength = static::getBackendUserAuthentication()->uc['titleLen'];
2251 }
2252 $titleOrig = htmlspecialchars($title);
2253 $title = htmlspecialchars(GeneralUtility::fixed_lgd_cs($title, $titleLength));
2254 // If title was cropped, offer a tooltip:
2255 if ($titleOrig != $title) {
2256 $title = '<span title="' . $titleOrig . '">' . $title . '</span>';
2257 }
2258 return $title;
2259 }
2260
2261 /**
2262 * Get a localized [No title] string, wrapped in <em>|</em> if $prep is TRUE.
2263 *
2264 * @param bool $prep Wrap result in <em>|</em>
2265 * @return string Localized [No title] string
2266 */
2267 public static function getNoRecordTitle($prep = false)
2268 {
2269 $noTitle = '[' . static::getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:labels.no_title', true) . ']';
2270 if ($prep) {
2271 $noTitle = '<em>' . $noTitle . '</em>';
2272 }
2273 return $noTitle;
2274 }
2275
2276 /**
2277 * Returns a human readable output of a value from a record
2278 * 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.
2279 * $table/$col is tablename and fieldname
2280 * REMEMBER to pass the output through htmlspecialchars() if you output it to the browser! (To protect it from XSS attacks and be XHTML compliant)
2281 *
2282 * @param string $table Table name, present in TCA
2283 * @param string $col Field name, present in TCA
2284 * @param string $value The value of that field from a selected record
2285 * @param int $fixed_lgd_chars The max amount of characters the value may occupy
2286 * @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")
2287 * @param bool $noRecordLookup If set, no records will be looked up, UIDs are just shown.
2288 * @param int $uid Uid of the current record
2289 * @param bool $forceResult If BackendUtility::getRecordTitle is used to process the value, this parameter is forwarded.
2290 * @param int $pid Optional page uid is used to evaluate page TSConfig for the given field
2291 * @throws \InvalidArgumentException
2292 * @return string|NULL
2293 */
2294 public static function getProcessedValue($table, $col, $value, $fixed_lgd_chars = 0, $defaultPassthrough = false, $noRecordLookup = false, $uid = 0, $forceResult = true, $pid = 0)
2295 {
2296 if ($col === 'uid') {
2297 // uid is not in TCA-array
2298 return $value;
2299 }
2300 // Check if table and field is configured
2301 if (!is_array($GLOBALS['TCA'][$table]) || !is_array($GLOBALS['TCA'][$table]['columns'][$col])) {
2302 return null;
2303 }
2304 // Depending on the fields configuration, make a meaningful output value.
2305 $theColConf = $GLOBALS['TCA'][$table]['columns'][$col]['config'];
2306 /*****************
2307 *HOOK: pre-processing the human readable output from a record
2308 ****************/
2309 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['preProcessValue'])) {
2310 // Create NULL-reference
2311 $null = null;
2312 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['preProcessValue'] as $_funcRef) {
2313 GeneralUtility::callUserFunction($_funcRef, $theColConf, $null);
2314 }
2315 }
2316 $l = '';
2317 $db = static::getDatabaseConnection();
2318 $lang = static::getLanguageService();
2319 switch ((string)$theColConf['type']) {
2320 case 'radio':
2321 $l = self::getLabelFromItemlist($table, $col, $value);
2322 $l = $lang->sL($l);
2323 break;
2324 case 'inline':
2325 case 'select':
2326 if ($theColConf['MM']) {
2327 if ($uid) {
2328 // Display the title of MM related records in lists
2329 if ($noRecordLookup) {
2330 $MMfield = $theColConf['foreign_table'] . '.uid';
2331 } else {
2332 $MMfields = array($theColConf['foreign_table'] . '.' . $GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label']);
2333 foreach (GeneralUtility::trimExplode(',', $GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label_alt'], true) as $f) {
2334 $MMfields[] = $theColConf['foreign_table'] . '.' . $f;
2335 }
2336 $MMfield = join(',', $MMfields);
2337 }
2338 /** @var $dbGroup RelationHandler */
2339 $dbGroup = GeneralUtility::makeInstance(RelationHandler::class);
2340 $dbGroup->start($value, $theColConf['foreign_table'], $theColConf['MM'], $uid, $table, $theColConf);
2341 $selectUids = $dbGroup->tableArray[$theColConf['foreign_table']];
2342 if (is_array($selectUids) && !empty($selectUids)) {
2343 $MMres = $db->exec_SELECTquery('uid, ' . $MMfield, $theColConf['foreign_table'], 'uid IN (' . implode(',', $selectUids) . ')' . self::deleteClause($theColConf['foreign_table']));
2344 $mmlA = array();
2345 while ($MMrow = $db->sql_fetch_assoc($MMres)) {
2346 // Keep sorting of $selectUids
2347 $mmlA[array_search($MMrow['uid'], $selectUids)] = $noRecordLookup ?
2348 $MMrow['uid'] :
2349 static::getRecordTitle($theColConf['foreign_table'], $MMrow, false, $forceResult);
2350 }
2351 $db->sql_free_result($MMres);
2352 if (!empty($mmlA)) {
2353 ksort($mmlA);
2354 $l = implode('; ', $mmlA);
2355 } else {
2356 $l = 'N/A';
2357 }
2358 } else {
2359 $l = 'N/A';
2360 }
2361 } else {
2362 $l = 'N/A';
2363 }
2364 } else {
2365 $columnTsConfig = array();
2366 if ($pid) {
2367 $pageTsConfig = self::getPagesTSconfig($pid);
2368 if (isset($pageTsConfig['TCEFORM.'][$table . '.'][$col . '.']) && is_array($pageTsConfig['TCEFORM.'][$table . '.'][$col . '.'])) {
2369 $columnTsConfig = $pageTsConfig['TCEFORM.'][$table . '.'][$col . '.'];
2370 }
2371 }
2372 $l = self::getLabelsFromItemsList($table, $col, $value, $columnTsConfig);
2373 if ($theColConf['foreign_table'] && !$l && $GLOBALS['TCA'][$theColConf['foreign_table']]) {
2374 if ($noRecordLookup) {
2375 $l = $value;
2376 } else {
2377 $rParts = array();
2378 if ($uid && isset($theColConf['foreign_field']) && $theColConf['foreign_field'] !== '') {
2379 $whereClause = '';
2380 if (!empty($theColConf['foreign_table_field'])) {
2381 $whereClause .= ' AND ' . $theColConf['foreign_table_field'] . ' = ' . static::getDatabaseConnection()->fullQuoteStr($table, $theColConf['foreign_table']);
2382 }
2383 // Add additional where clause if foreign_match_fields are defined
2384 $foreignMatchFields = is_array($theColConf['foreign_match_fields']) ? $theColConf['foreign_match_fields'] : array();
2385 foreach ($foreignMatchFields as $matchField => $matchValue) {
2386 $whereClause .= ' AND ' . $matchField . '=' . static::getDatabaseConnection()->fullQuoteStr($matchValue, $theColConf['foreign_table']);
2387 }
2388 $records = self::getRecordsByField($theColConf['foreign_table'], $theColConf['foreign_field'], $uid, $whereClause);
2389 if (!empty($records)) {
2390 foreach ($records as $record) {
2391 $rParts[] = $record['uid'];
2392 }
2393 }
2394 }
2395 if (empty($rParts)) {
2396 $rParts = GeneralUtility::trimExplode(',', $value, true);
2397 }
2398 $lA = array();
2399 foreach ($rParts as $rVal) {
2400 $rVal = (int)$rVal;
2401 $r = self::getRecordWSOL($theColConf['foreign_table'], $rVal);
2402 if (is_array($r)) {
2403 $lA[] = $lang->sL($theColConf['foreign_table_prefix']) . self::getRecordTitle($theColConf['foreign_table'], $r, false, $forceResult);
2404 } else {
2405 $lA[] = $rVal ? '[' . $rVal . '!]' : '';
2406 }
2407 }
2408 $l = implode(', ', $lA);
2409 }
2410 }
2411 if (empty($l) && !empty($value)) {
2412 // Use plain database value when label is empty
2413 $l = $value;
2414 }
2415 }
2416 break;
2417 case 'group':
2418 // resolve the titles for DB records
2419 if ($theColConf['internal_type'] === 'db') {
2420 if ($theColConf['MM']) {
2421 if ($uid) {
2422 // Display the title of MM related records in lists
2423 if ($noRecordLookup) {
2424 $MMfield = $theColConf['foreign_table'] . '.uid';
2425 } else {
2426 $MMfields = array($theColConf['foreign_table'] . '.' . $GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label']);
2427 $altLabelFields = explode(',', $GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label_alt']);
2428 foreach ($altLabelFields as $f) {
2429 $f = trim($f);
2430 if ($f !== '') {
2431 $MMfields[] = $theColConf['foreign_table'] . '.' . $f;
2432 }
2433 }
2434 $MMfield = join(',', $MMfields);
2435 }
2436 /** @var $dbGroup RelationHandler */
2437 $dbGroup = GeneralUtility::makeInstance(RelationHandler::class);
2438 $dbGroup->start($value, $theColConf['foreign_table'], $theColConf['MM'], $uid, $table, $theColConf);
2439 $selectUids = $dbGroup->tableArray[$theColConf['foreign_table']];
2440 if (!empty($selectUids) && is_array($selectUids)) {
2441 $MMres = $db->exec_SELECTquery(
2442 'uid, ' . $MMfield,
2443 $theColConf['foreign_table'],
2444 'uid IN (' . implode(',', $selectUids) . ')' . static::deleteClause($theColConf['foreign_table'])
2445 );
2446 $mmlA = array();
2447 while ($MMrow = $db->sql_fetch_assoc($MMres)) {
2448 // Keep sorting of $selectUids
2449 $mmlA[array_search($MMrow['uid'], $selectUids)] = $noRecordLookup
2450 ? $MMrow['uid']
2451 : static::getRecordTitle($theColConf['foreign_table'], $MMrow, false, $forceResult);
2452 }
2453 $db->sql_free_result($MMres);
2454 if (!empty($mmlA)) {
2455 ksort($mmlA);
2456 $l = implode('; ', $mmlA);
2457 } else {
2458 $l = 'N/A';
2459 }
2460 } else {
2461 $l = 'N/A';
2462 }
2463 } else {
2464 $l = 'N/A';
2465 }
2466 } else {
2467 $finalValues = array();
2468 $relationTableName = $theColConf['allowed'];
2469 $explodedValues = GeneralUtility::trimExplode(',', $value, true);
2470
2471 foreach ($explodedValues as $explodedValue) {
2472 if (MathUtility::canBeInterpretedAsInteger($explodedValue)) {
2473 $relationTableNameForField = $relationTableName;
2474 } else {
2475 list($relationTableNameForField, $explodedValue) = self::splitTable_Uid($explodedValue);
2476 }
2477
2478 $relationRecord = static::getRecordWSOL($relationTableNameForField, $explodedValue);
2479 $finalValues[] = static::getRecordTitle($relationTableNameForField, $relationRecord);
2480 }
2481 $l = implode(', ', $finalValues);
2482 }
2483 } else {
2484 $l = implode(', ', GeneralUtility::trimExplode(',', $value, true));
2485 }
2486 break;
2487 case 'check':
2488 if (!is_array($theColConf['items']) || count($theColConf['items']) === 1) {
2489 $l = $value ? $lang->sL('LLL:EXT:lang/locallang_common.xlf:yes') : $lang->sL('LLL:EXT:lang/locallang_common.xlf:no');
2490 } else {
2491 $lA = array();
2492 foreach ($theColConf['items'] as $key => $val) {
2493 if ($value & pow(2, $key)) {
2494 $lA[] = $lang->sL($val[0]);
2495 }
2496 }
2497 $l = implode(', ', $lA);
2498 }
2499 break;
2500 case 'input':
2501 // Hide value 0 for dates, but show it for everything else
2502 if (isset($value)) {
2503 if (GeneralUtility::inList($theColConf['eval'], 'date')) {
2504 // Handle native date field
2505 if (isset($theColConf['dbType']) && $theColConf['dbType'] === 'date') {
2506 $dateTimeFormats = $db->getDateTimeFormats($table);
2507 $emptyValue = $dateTimeFormats['date']['empty'];
2508 $value = $value !== $emptyValue ? strtotime($value) : 0;
2509 }
2510 if (!empty($value)) {
2511 $ageSuffix = '';
2512 $dateColumnConfiguration = $GLOBALS['TCA'][$table]['columns'][$col]['config'];
2513 $ageDisplayKey = 'disableAgeDisplay';
2514
2515 // generate age suffix as long as not explicitly suppressed
2516 if (!isset($dateColumnConfiguration[$ageDisplayKey])
2517 // non typesafe comparison on intention
2518 || $dateColumnConfiguration[$ageDisplayKey] == false) {
2519 $ageSuffix = ' (' . ($GLOBALS['EXEC_TIME'] - $value > 0 ? '-' : '') . self::calcAge(abs(($GLOBALS['EXEC_TIME'] - $value)), $lang->sL('LLL:EXT:lang/locallang_core.xlf:labels.minutesHoursDaysYears')) . ')';
2520 }
2521
2522 $l = self::date($value) . $ageSuffix;
2523 }
2524 } elseif (GeneralUtility::inList($theColConf['eval'], 'time')) {
2525 if (!empty($value)) {
2526 $l = self::time($value, false);
2527 }
2528 } elseif (GeneralUtility::inList($theColConf['eval'], 'timesec')) {
2529 if (!empty($value)) {
2530 $l = self::time($value);
2531 }
2532 } elseif (GeneralUtility::inList($theColConf['eval'], 'datetime')) {
2533 // Handle native date/time field
2534 if (isset($theColConf['dbType']) && $theColConf['dbType'] === 'datetime') {
2535 $dateTimeFormats = $db->getDateTimeFormats($table);
2536 $emptyValue = $dateTimeFormats['datetime']['empty'];
2537 $value = $value !== $emptyValue ? strtotime($value) : 0;
2538 }
2539 if (!empty($value)) {
2540 $l = self::datetime($value);
2541 }
2542 } else {
2543 $l = $value;
2544 }
2545 }
2546 break;
2547 case 'flex':
2548 $l = strip_tags($value);
2549 break;
2550 default:
2551 if ($defaultPassthrough) {
2552 $l = $value;
2553 } elseif ($theColConf['MM']) {
2554 $l = 'N/A';
2555 } elseif ($value) {
2556 $l = GeneralUtility::fixed_lgd_cs(strip_tags($value), 200);
2557 }
2558 }
2559 // If this field is a password field, then hide the password by changing it to a random number of asterisk (*)
2560 if (stristr($theColConf['eval'], 'password')) {
2561 $l = '';
2562 $randomNumber = rand(5, 12);
2563 for ($i = 0; $i < $randomNumber; $i++) {
2564 $l .= '*';
2565 }
2566 }
2567 /*****************
2568 *HOOK: post-processing the human readable output from a record
2569 ****************/
2570 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['postProcessValue'])) {
2571 // Create NULL-reference
2572 $null = null;
2573 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['postProcessValue'] as $_funcRef) {
2574 $params = array(
2575 'value' => $l,
2576 'colConf' => $theColConf
2577 );
2578 $l = GeneralUtility::callUserFunction($_funcRef, $params, $null);
2579 }
2580 }
2581 if ($fixed_lgd_chars) {
2582 return GeneralUtility::fixed_lgd_cs($l, $fixed_lgd_chars);
2583 } else {
2584 return $l;
2585 }
2586 }
2587
2588 /**
2589 * 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.
2590 *
2591 * @param string $table Table name, present in TCA
2592 * @param string $fN Field name
2593 * @param string $fV Field value
2594 * @param int $fixed_lgd_chars The max amount of characters the value may occupy
2595 * @param int $uid Uid of the current record
2596 * @param bool $forceResult If BackendUtility::getRecordTitle is used to process the value, this parameter is forwarded.
2597 * @param int $pid Optional page uid is used to evaluate page TSConfig for the given field
2598 * @return string
2599 * @see getProcessedValue()
2600 */
2601 public static function getProcessedValueExtra($table, $fN, $fV, $fixed_lgd_chars = 0, $uid = 0, $forceResult = true, $pid = 0)
2602 {
2603 $fVnew = self::getProcessedValue($table, $fN, $fV, $fixed_lgd_chars, 1, 0, $uid, $forceResult, $pid);
2604 if (!isset($fVnew)) {
2605 if (is_array($GLOBALS['TCA'][$table])) {
2606 if ($fN == $GLOBALS['TCA'][$table]['ctrl']['tstamp'] || $fN == $GLOBALS['TCA'][$table]['ctrl']['crdate']) {
2607 $fVnew = self::datetime($fV);
2608 } elseif ($fN == 'pid') {
2609 // Fetches the path with no regard to the users permissions to select pages.
2610 $fVnew = self::getRecordPath($fV, '1=1', 20);
2611 } else {
2612 $fVnew = $fV;
2613 }
2614 }
2615 }
2616 return $fVnew;
2617 }
2618
2619 /**
2620 * Returns fields for a table, $table, which would typically be interesting to select
2621 * This includes uid, the fields defined for title, icon-field.
2622 * 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)
2623 *
2624 * @param string $table Table name, present in $GLOBALS['TCA']
2625 * @param string $prefix Table prefix
2626 * @param array $fields Preset fields (must include prefix if that is used)
2627 * @return string List of fields.
2628 */
2629 public static function getCommonSelectFields($table, $prefix = '', $fields = array())
2630 {
2631 $fields[] = $prefix . 'uid';
2632 if (isset($GLOBALS['TCA'][$table]['ctrl']['label']) && $GLOBALS['TCA'][$table]['ctrl']['label'] != '') {
2633 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['label'];
2634 }
2635 if ($GLOBALS['TCA'][$table]['ctrl']['label_alt']) {
2636 $secondFields = GeneralUtility::trimExplode(',', $GLOBALS['TCA'][$table]['ctrl']['label_alt'], true);
2637 foreach ($secondFields as $fieldN) {
2638 $fields[] = $prefix . $fieldN;
2639 }
2640 }
2641 if (static::isTableWorkspaceEnabled($table)) {
2642 $fields[] = $prefix . 't3ver_id';
2643 $fields[] = $prefix . 't3ver_state';
2644 $fields[] = $prefix . 't3ver_wsid';
2645 $fields[] = $prefix . 't3ver_count';
2646 }
2647 if ($GLOBALS['TCA'][$table]['ctrl']['selicon_field']) {
2648 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['selicon_field'];
2649 }
2650 if ($GLOBALS['TCA'][$table]['ctrl']['typeicon_column']) {
2651 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['typeicon_column'];
2652 }
2653 if (is_array($GLOBALS['TCA'][$table]['ctrl']['enablecolumns'])) {
2654 if ($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['disabled']) {
2655 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['disabled'];
2656 }
2657 if ($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['starttime']) {
2658 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['starttime'];
2659 }
2660 if ($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['endtime']) {
2661 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['endtime'];
2662 }
2663 if ($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['fe_group']) {
2664 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['fe_group'];
2665 }
2666 }
2667 return implode(',', array_unique($fields));
2668 }
2669
2670 /**
2671 * Makes a form for configuration of some values based on configuration found in the array $configArray,
2672 * with default values from $defaults and a data-prefix $dataPrefix
2673 * <form>-tags must be supplied separately
2674 * Needs more documentation and examples, in particular syntax for configuration array. See Inside TYPO3.
2675 * That's were you can expect to find example, if anywhere.
2676 *
2677 * @param array $configArray Field configuration code.
2678 * @param array $defaults Defaults
2679 * @param string $dataPrefix Prefix for formfields
2680 * @return string HTML for a form.
2681 */
2682 public static function makeConfigForm($configArray, $defaults, $dataPrefix)
2683 {
2684 $params = $defaults;
2685 $lines = array();
2686 if (is_array($configArray)) {
2687 foreach ($configArray as $fname => $config) {
2688 if (is_array($config)) {
2689 $lines[$fname] = '<strong>' . htmlspecialchars($config[1]) . '</strong><br />';
2690 $lines[$fname] .= $config[2] . '<br />';
2691 switch ($config[0]) {
2692 case 'string':
2693
2694 case 'short':
2695 $formEl = '<input type="text" name="' . $dataPrefix . '[' . $fname . ']" value="' . $params[$fname] . '"' . static::getDocumentTemplate()->formWidth(($config[0] == 'short' ? 24 : 48)) . ' />';
2696 break;
2697 case 'check':
2698 $formEl = '<input type="hidden" name="' . $dataPrefix . '[' . $fname . ']" value="0" /><input type="checkbox" name="' . $dataPrefix . '[' . $fname . ']" value="1"' . ($params[$fname] ? ' checked="checked"' : '') . ' />';
2699 break;
2700 case 'comment':
2701 $formEl = '';
2702 break;
2703 case 'select':
2704 $opt = array();
2705 foreach ($config[3] as $k => $v) {
2706 $opt[] = '<option value="' . htmlspecialchars($k) . '"' . ($params[$fname] == $k ? ' selected="selected"' : '') . '>' . htmlspecialchars($v) . '</option>';
2707 }
2708 $formEl = '<select name="' . $dataPrefix . '[' . $fname . ']">' . implode('', $opt) . '</select>';
2709 break;
2710 default:
2711 $formEl = '<strong>Should not happen. Bug in config.</strong>';
2712 }
2713 $lines[$fname] .= $formEl;
2714 $lines[$fname] .= '<br /><br />';
2715 } else {
2716 $lines[$fname] = '<hr />';
2717 if ($config) {
2718 $lines[$fname] .= '<strong>' . strtoupper(htmlspecialchars($config)) . '</strong><br />';
2719 }
2720 if ($config) {
2721 $lines[$fname] .= '<br />';
2722 }
2723 }
2724 }