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