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