2 namespace TYPO3\CMS\Backend\Utility
;
5 * This file is part of the TYPO3 CMS project.
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.
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
14 * The TYPO3 project - inspiring people to share!
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
;
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.
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)'
56 * Cache the TCA configuration of tables with their types during runtime
59 * @see self::getTCAtypes()
61 protected static $tcaTableTypeConfigurationCache = array();
63 /*******************************************
65 * SQL-related, selecting records, searching
67 *******************************************/
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.
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
82 public static function deleteClause($table, $tableAlias = '')
84 if ($GLOBALS['TCA'][$table]['ctrl']['delete']) {
85 return ' AND ' . ($tableAlias ?
: $table) . '.' . $GLOBALS['TCA'][$table]['ctrl']['delete'] . '=0';
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']
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
105 public static function getRecord($table, $uid, $fields = '*', $where = '', $useDeleteClause = true
)
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);
119 * Like getRecord(), but overlays workspace version if any.
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
129 public static function getRecordWSOL($table, $uid, $fields = '*', $where = '', $useDeleteClause = true
, $unsetMovePointers = false
)
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] !== '_') {
143 $row = self
::getRecord($table, $uid, $fields, $where, $useDeleteClause);
144 self
::workspaceOL($table, $row, -99, $unsetMovePointers);
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;
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
161 public static function getRecordRaw($table, $where = '', $fields = '*')
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);
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
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)
187 public static function getRecordsByField($theTable, $theField, $theValue, $whereClause = '', $groupBy = '', $orderBy = '', $limit = '', $useDeleteClause = true
)
189 if (is_array($GLOBALS['TCA'][$theTable])) {
190 $db = static::getDatabaseConnection();
191 $res = $db->exec_SELECTquery(
194 $theField . '=' . $db->fullQuoteStr($theValue, $theTable) .
195 ($useDeleteClause ? self
::deleteClause($theTable) . ' ' : '') .
196 self
::versioningPlaceholderClause($theTable) . ' ' .
203 while ($row = $db->sql_fetch_assoc($res)) {
206 $db->sql_free_result($res);
215 * Makes an backwards explode on the $str and returns an array with ($table, $uid).
216 * Example: tt_content_45 => array('tt_content', 45)
218 * @param string $str [tablename]_[uid] string to explode
221 public static function splitTable_Uid($str)
223 list($uid, $table) = explode('_', strrev($str), 2);
224 return array(strrev($table), strrev($uid));
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.
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
236 public static function getSQLselectableList($in_list, $tablename, $default_tablename)
239 if ((string)trim($in_list) != '') {
240 $tempItemArray = explode(',', trim($in_list));
241 foreach ($tempItemArray as $key => $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) {
253 return implode(',', $list);
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.
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
266 public static function BEenableFields($table, $inv = false
)
268 $ctrl = $GLOBALS['TCA'][$table]['ctrl'];
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';
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'] . ')';
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'] . ')';
290 $outQ = $inv ?
'(' . implode(' OR ', $invQuery) . ')' : implode(' AND ', $query);
291 return $outQ ?
' AND ' . $outQ : '';
295 * Fetches the localization for a given record.
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
303 public static function getRecordLocalization($table, $uid, $language, $andWhereClause = '')
305 $recordLocalization = false
;
307 // Check if translations are stored in other table
308 if (isset($GLOBALS['TCA'][$table]['ctrl']['transForeignTable'])) {
309 $table = $GLOBALS['TCA'][$table]['ctrl']['transForeignTable'];
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');
316 return $recordLocalization;
319 /*******************************************
321 * Page tree, TCA related
323 *******************************************/
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.
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!)
334 public static function BEgetRootLine($uid, $clause = '', $workspaceOL = false
)
336 static $BEgetRootLine_cache = array();
339 $ident = $pid . '-' . $clause . '-' . $workspaceOL;
340 if (is_array($BEgetRootLine_cache[$ident])) {
341 $output = $BEgetRootLine_cache[$ident];
344 $theRowArray = array();
345 while ($uid != 0 && $loopCheck) {
347 $row = self
::getPageForRootline($uid, $clause, $workspaceOL);
348 if (is_array($row)) {
350 $theRowArray[] = $row;
356 $theRowArray[] = array('uid' => 0, 'title' => '');
358 $c = count($theRowArray);
359 foreach ($theRowArray as $val) {
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']
375 if (isset($val['_ORIG_pid'])) {
376 $output[$c]['_ORIG_pid'] = $val['_ORIG_pid'];
379 $BEgetRootLine_cache[$ident] = $output;
385 * Gets the cached page record for the rootline
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
393 protected static function getPageForRootline($uid, $clause, $workspaceOL)
395 static $getPageForRootline_cache = array();
396 $ident = $uid . '-' . $clause . '-' . $workspaceOL;
397 if (is_array($getPageForRootline_cache[$ident])) {
398 $row = $getPageForRootline_cache[$ident];
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);
404 $newLocation = false
;
406 self
::workspaceOL('pages', $row);
407 $newLocation = self
::getMovePlaceholder('pages', $row['uid'], 'pid');
409 if (is_array($row)) {
410 if ($newLocation !== false
) {
411 $row['pid'] = $newLocation['pid'];
413 self
::fixVersioningPid('pages', $row);
415 $getPageForRootline_cache[$ident] = $row;
418 $db->sql_free_result($res);
424 * Opens the page tree to the specified page id
426 * @param int $pid Page id.
427 * @param bool $clearExpansion If set, then other open branches are closed.
430 public static function openPageTree($pid, $clearExpansion)
432 $beUser = static::getBackendUserAuthentication();
433 // Get current expansion data:
434 if ($clearExpansion) {
435 $expandedPages = array();
437 $expandedPages = unserialize($beUser->uc
['browseTrees']['browsePages']);
440 $rL = self
::BEgetRootLine($pid);
441 // First, find out what mount index to use (if more than one DB mount exists):
443 $mountKeys = array_flip($beUser->returnWebmounts());
444 foreach ($rL as $rLDat) {
445 if (isset($mountKeys[$rLDat['uid']])) {
446 $mountIndex = $mountKeys[$rLDat['uid']];
450 // Traverse rootline and open paths:
451 foreach ($rL as $rLDat) {
452 $expandedPages[$mountIndex][$rLDat['uid']] = 1;
455 $beUser->uc
['browseTrees']['browsePages'] = serialize($expandedPages);
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.
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.
470 public static function getRecordPath($uid, $clause, $titleLimit, $fullTitleLimit = 0)
475 $output = $fullOutput = '/';
476 $clause = trim($clause);
477 if ($clause !== '' && substr($clause, 0, 3) !== 'AND') {
478 $clause = 'AND ' . $clause;
480 $data = self
::BEgetRootLine($uid, $clause);
481 foreach ($data as $record) {
482 if ($record['uid'] === 0) {
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;
490 if ($fullTitleLimit) {
491 return array($output, $fullOutput);
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
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
504 public static function getExcludeFields()
506 GeneralUtility
::logDeprecatedFunction();
507 $finalExcludeArray = array();
509 // Fetch translations for table names
510 $tableToTranslation = array();
511 $lang = static::getLanguageService();
513 foreach ($GLOBALS['TCA'] as $table => $conf) {
514 $tableToTranslation[$table] = $lang->sl($conf['ctrl']['title']);
516 // Sort by translations
517 asort($tableToTranslation);
518 foreach ($tableToTranslation as $table => $translatedTable) {
519 $excludeArrayTable = array();
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']))
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']);
531 $excludeArrayTable[] = array($translatedTable . ': ' . $translatedField, $table . ':' . $field);
535 // All FlexForm fields
536 $flexFormArray = static::getRegisteredFlexForms($table);
537 foreach ($flexFormArray as $tableField => $flexForms) {
538 // Prefix for field label, e.g. "Plugin Options:"
540 if (!empty($GLOBALS['TCA'][$table]['columns'][$tableField]['label'])) {
541 $labelPrefix = $lang->sl($GLOBALS['TCA'][$table]['columns'][$tableField]['label']);
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'])) {
551 foreach ($sheet['ROOT']['el'] as $fieldName => $field) {
552 // Use only fields that have exclude flag set
553 if (empty($field['TCEforms']['exclude'])) {
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);
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);
573 $finalExcludeArray = array_merge($finalExcludeArray, $excludeArrayTable);
577 return $finalExcludeArray;
581 * Returns an array with explicit Allow/Deny fields.
582 * Used for listing these field/value pairs in be_groups forms
584 * @return array Array with information from all of $GLOBALS['TCA']
585 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
587 public static function getExplicitAuthFieldValues()
589 GeneralUtility
::logDeprecatedFunction();
591 $lang = static::getLanguageService();
593 'ALLOW' => $lang->sl('LLL:EXT:lang/locallang_core.xlf:labels.allow'),
594 'DENY' => $lang->sl('LLL:EXT:lang/locallang_core.xlf:labels.deny')
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']) {
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']);
611 foreach ($fCfg['items'] as $iVal) {
612 // Values '' is not controlled by this setting.
613 if ((string)$iVal[1] !== '') {
616 switch ((string)$fCfg['authMode']) {
617 case 'explicitAllow':
624 if ($iVal[4] === 'EXPL_ALLOW') {
626 } elseif ($iVal[4] === 'EXPL_DENY') {
633 $allowDenyOptions[$table . ':' . $field]['items'][$iVal[1]] = array($iMode, $lang->sl($iVal[0]), $adLabel[$iMode]);
642 return $allowDenyOptions;
646 * Returns an array with system languages:
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.
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
655 public static function getSystemLanguages()
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']
671 return $sysLanguages;
675 * Gets the original translation pointer table.
676 * For e.g. pages_language_overlay this would be pages.
678 * @param string $table Name of the table
679 * @return string Pointer table (if any)
681 public static function getOriginalTranslationTable($table)
683 if (!empty($GLOBALS['TCA'][$table]['ctrl']['transOrigPointerTable'])) {
684 $table = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerTable'];
691 * Determines whether a table is localizable and has the languageField and transOrigPointerField set in $GLOBALS['TCA'].
693 * @param string $table The table to check
694 * @return bool Whether a table is localizable
696 public static function isTableLocalizable($table)
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'];
703 return $isLocalizable;
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.
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
715 public static function getInlineLocalizationMode($table, $fieldOrConfig)
717 $localizationMode = false
;
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'];
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']
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
;
733 return $localizationMode;
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)
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.
745 public static function readPageAccess($id, $perms_clause)
747 if ((string)$id !== '') {
750 if (static::getBackendUserAuthentication()->isAdmin()) {
752 $pageinfo['_thePath'] = $path;
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);
771 * Returns the "types" configuration parsed into an array for the record, $rec, from table, $table
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.
778 public static function getTCAtypes($table, $rec, $useFieldNameAsKey = false
)
780 if ($GLOBALS['TCA'][$table]) {
782 $fieldValue = self
::getTCAtypeValue($table, $rec);
783 $cacheIdentifier = $table . '-type-' . $fieldValue . '-fnk-' . $useFieldNameAsKey;
785 // Fetch from first-level-cache if available
786 if (isset(self
::$tcaTableTypeConfigurationCache[$cacheIdentifier])) {
787 return self
::$tcaTableTypeConfigurationCache[$cacheIdentifier];
791 $typesConf = $GLOBALS['TCA'][$table]['types'][$fieldValue];
792 // Get fields list and traverse it
793 $fieldList = explode(',', $typesConf['showitem']);
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);
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);
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'];
817 $specConfParts = self
::getSpecConfParts($defaultExtras);
818 $fieldList[$k] = array(
819 'field' => $pFieldName,
820 'title' => $pAltTitle,
821 'palette' => $pPalette,
822 'spec' => $specConfParts,
825 if ($useFieldNameAsKey) {
826 $altFieldList[$fieldList[$k]['field']] = $fieldList[$k];
829 if ($useFieldNameAsKey) {
830 $fieldList = $altFieldList;
833 // Add to first-level-cache
834 self
::$tcaTableTypeConfigurationCache[$cacheIdentifier] = $fieldList;
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)
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.
853 * @param string $table Table name present in TCA
854 * @param array $row Record from $table
855 * @throws \RuntimeException
856 * @return string Field value
859 public static function getTCAtypeValue($table, $row)
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];
871 $foreignUid = $row[$pointerField];
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];
882 throw new \
RuntimeException('TCA foreign field pointer fields are only allowed to be used with group or select field types.', 1325862240);
884 $foreignRow = self
::getRecord($foreignTable, $foreignUid, $foreignTableTypeField);
885 if ($foreignRow[$foreignTableTypeField]) {
886 $typeNum = $foreignRow[$foreignTableTypeField];
890 $typeNum = $row[$field];
892 // If that value is an empty string, set it to "0" (zero)
893 if (empty($typeNum)) {
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;
901 // Force to string. Necessary for eg '-1' to be recognized as a type value.
902 $typeNum = (string)$typeNum;
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 "|".
910 * See unit tests for details.
912 * @param string $defaultExtrasString "defaultExtras" string from columns config
913 * @param string $_ @deprecated since TYPO3 CMS 7, will be removed with TYPO3 CMS 8
916 public static function getSpecConfParts($defaultExtrasString, $_ = '')
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;
923 $specConfParts = GeneralUtility
::trimExplode(':', $defaultExtrasString, true
);
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
)
933 $specConfParts[trim($v2)] = 1;
937 $specConfParts = array();
939 return $specConfParts;
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
946 * @param array $pArr Array of "[key] = [value]" strings to convert.
949 public static function getSpecConfParametersFromArray($pArr)
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]);
966 * Finds the Data Structure for a FlexForm field
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.
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
993 public static function getFlexFormDS($conf, $row, $table, $fieldName = '', $WSOL = true
, $newRecordPidValue = 0)
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]];
1024 $srcPointer = $row[$pointerFields[0]];
1026 $srcPointer = $srcPointer !== null
&& isset($ds_array[$srcPointer]) ?
$srcPointer : 'default';
1028 $srcPointer = 'default';
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));
1036 $dataStructArray = 'The file "' . substr($ds_array[$srcPointer], 5) . '" in ds-array key "' . $srcPointer . '" was not found ("' . $file . '")';
1039 $dataStructArray = GeneralUtility
::xml2array($ds_array[$srcPointer]);
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###
1050 self
::workspaceOL($table, $rr);
1051 self
::fixVersioningPid($table, $rr, true
);
1053 $db = static::getDatabaseConnection();
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']])) {
1066 $uidAcc[$rr['uid']] = 1;
1068 self
::workspaceOL($table, $rr);
1069 self
::fixVersioningPid($table, $rr, true
);
1071 $srcPointer = $subFieldPointer && $rr[$subFieldPointer] ?
$rr[$subFieldPointer] : $rr[$ds_pointerField];
1074 // If there is a srcPointer value:
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);
1082 self
::workspaceOL($tName, $dataStructRec);
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]));
1089 $dataStructArray = sprintf('File \'%s\' was not found', $dataStructRec[$fName]);
1092 // No file pointer, handle as being XML (default behaviour)
1093 $dataStructArray = GeneralUtility
::xml2array($dataStructRec[$fName]);
1096 $dataStructArray = 'No tablename (' . $tName . ') or fieldname (' . $fName . ') was found an valid!';
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));
1105 $dataStructArray = 'The file "' . $srcPointer . '" was not found ("' . $file . '")';
1110 $dataStructArray = 'No source value in fieldname "' . $ds_pointerField . '"';
1113 $dataStructArray = 'No proper configuration!';
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);
1124 return $dataStructArray;
1128 * Returns all registered FlexForm definitions with title and fields
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
1135 public static function getRegisteredFlexForms($table = 'tt_content')
1137 GeneralUtility
::logDeprecatedFunction();
1138 if (empty($table) ||
empty($GLOBALS['TCA'][$table]['columns'])) {
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);
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];
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);
1163 $dataStruct = GeneralUtility
::xml2array($dataStruct);
1164 if (!is_array($dataStruct)) {
1168 // Get flexform content
1169 $dataStruct = GeneralUtility
::resolveAllSheetsInDS($dataStruct);
1170 if (empty($dataStruct['sheets']) ||
!is_array($dataStruct['sheets'])) {
1173 // Use DS pointer to get extension title from TCA
1175 $keyFields = GeneralUtility
::trimExplode(',', $flexFormKey);
1176 foreach ($pointerFields as $pointerKey => $pointerName) {
1177 if (empty($keyFields[$pointerKey]) ||
$keyFields[$pointerKey] == '*' ||
$keyFields[$pointerKey] == 'list') {
1180 if (!empty($GLOBALS['TCA'][$table]['columns'][$pointerName]['config']['items'])) {
1181 $items = $GLOBALS['TCA'][$table]['columns'][$pointerName]['config']['items'];
1182 if (!is_array($items)) {
1185 foreach ($items as $itemConf) {
1186 if (!empty($itemConf[0]) && !empty($itemConf[1]) && $itemConf[1] == $keyFields[$pointerKey]) {
1187 $title = $itemConf[0];
1193 $flexForms[$tableField][$extIdent] = array(
1203 /*******************************************
1207 *******************************************/
1209 * Stores $data in the 'cache_hash' cache with the hash key, $hash
1210 * and visual/symbolic identification, $ident
1212 * IDENTICAL to the function by same name found in \TYPO3\CMS\Frontend\Page\PageRepository
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!
1219 public static function storeHash($hash, $data, $ident)
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);
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
1230 * IDENTICAL to the function by same name found in \TYPO3\CMS\Frontend\Page\PageRepository
1232 * @param string $hash The hash-string which was used to store the data value
1233 * @return mixed The "data" from the cache
1235 public static function getHash($hash)
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
;
1242 $hashContent = $cacheEntry;
1244 return $hashContent;
1247 /*******************************************
1249 * TypoScript related
1251 *******************************************/
1253 * Returns the Page TSconfig for page with id, $id
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
1261 public static function getPagesTSconfig($id, $rootLine = null
, $returnPartArray = false
)
1263 static $pagesTSconfig_cacheReference = array();
1264 static $combinedTSconfig_cache = array();
1267 if ($returnPartArray === false
1268 && $rootLine === null
1269 && isset($pagesTSconfig_cacheReference[$id])
1271 return $combinedTSconfig_cache[$pagesTSconfig_cacheReference[$id]];
1273 $TSconfig = array();
1274 if (!is_array($rootLine)) {
1275 $useCacheForCurrentPageId = true
;
1276 $rootLine = self
::BEgetRootLine($id, '', true
);
1278 $useCacheForCurrentPageId = false
;
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
);
1290 foreach ($includeTsConfigFileList as $key => $includeTsConfigFile) {
1291 if (StringUtility
::beginsWith($includeTsConfigFile, 'EXT:')) {
1292 list($includeTsConfigFileExtensionKey, $includeTsConfigFilename) = explode(
1294 substr($includeTsConfigFile, 4),
1298 (string)$includeTsConfigFileExtensionKey !== ''
1299 && ExtensionManagementUtility
::isLoaded($includeTsConfigFileExtensionKey)
1300 && (string)$includeTsConfigFilename !== ''
1302 $includeTsConfigFileAndPath = ExtensionManagementUtility
::extPath($includeTsConfigFileExtensionKey) .
1303 $includeTsConfigFilename;
1304 if (file_exists($includeTsConfigFileAndPath)) {
1305 $TSdataArray['uid_' . $v['uid'] . '_static_' . $key] = GeneralUtility
::getUrl($includeTsConfigFileAndPath);
1311 $TSdataArray['uid_' . $v['uid']] = $v['TSconfig'];
1313 $TSdataArray = static::emitGetPagesTSconfigPreIncludeSignal($TSdataArray, $id, $rootLine, $returnPartArray);
1314 $TSdataArray = TypoScriptParser
::checkIncludeLines_array($TSdataArray);
1315 if ($returnPartArray) {
1316 return $TSdataArray;
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);
1324 $TSconfig = $res['TSconfig'];
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'];
1334 if ($useCacheForCurrentPageId) {
1335 if (!isset($combinedTSconfig_cache[$cacheHash])) {
1336 $combinedTSconfig_cache[$cacheHash] = $TSconfig;
1338 $pagesTSconfig_cacheReference[$id] = $cacheHash;
1345 * Implodes a multi dimensional TypoScript array, $p, into a one-dimensional array (return value)
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
1352 public static function implodeTSParams($p, $k = '')
1354 GeneralUtility
::logDeprecatedFunction();
1355 $implodeParams = array();
1357 foreach ($p as $kb => $val) {
1358 if (is_array($val)) {
1359 $implodeParams = array_merge($implodeParams, self
::implodeTSParams($val, $k . $kb));
1361 $implodeParams[$k . $kb] = $val;
1365 return $implodeParams;
1368 /*******************************************
1370 * Users / Groups related
1372 *******************************************/
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
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
1381 public static function getUserNames($fields = 'username,usergroup,usergroup_cached_list,uid', $where = '')
1383 return self
::getRecordsSortedByTitle(
1384 GeneralUtility
::trimExplode(',', $fields, true
),
1387 'AND pid=0 ' . $where
1392 * Returns an array with be_groups records (title, uid) of all groups NOT DELETED sorted by their title
1394 * @param string $fields Field list
1395 * @param string $where WHERE clause
1398 public static function getGroupNames($fields = 'title,uid', $where = '')
1400 return self
::getRecordsSortedByTitle(
1401 GeneralUtility
::trimExplode(',', $fields, true
),
1404 'AND pid=0 ' . $where
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.
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
1419 protected static function getRecordsSortedByTitle(array $fields, $table, $titleField, $where = '')
1421 $fieldsIndex = array_flip($fields);
1422 // Make sure the titleField is amongst the fields when getting sorted
1423 $fieldsIndex[$titleField] = 1;
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);
1433 // include only the requested fields in the result
1434 $result[$recordId] = array_intersect_key($record, $fieldsIndex);
1436 $db->sql_free_result($res);
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);
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.
1447 * @param string $fields Field list; $fields specify the fields selected (default: title,uid)
1450 public static function getListGroupNames($fields = 'title, uid')
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) . ')';
1457 return self
::getGroupNames($fields, $exQ);
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
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
1470 public static function blindUserNames($usernames, $groupArray, $excludeBlindedFlag = false
)
1472 if (is_array($usernames) && is_array($groupArray)) {
1473 foreach ($usernames as $uid => $row) {
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'];
1484 $userN = $row['username'];
1487 $usernames[$uid]['username'] = $userN;
1488 if ($excludeBlindedFlag && !$set) {
1489 unset($usernames[$uid]);
1497 * Corresponds to blindUserNames but works for groups instead
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
1504 public static function blindGroupNames($groups, $groupArray, $excludeBlindedFlag = false
)
1506 if (is_array($groups) && is_array($groupArray)) {
1507 foreach ($groups as $uid => $row) {
1510 if (ArrayUtility
::inArray($groupArray, $uid)) {
1511 $groupN = $row['title'];
1514 $groups[$uid]['title'] = $groupN;
1515 if ($excludeBlindedFlag && !$set) {
1516 unset($groups[$uid]);
1523 /*******************************************
1527 *******************************************/
1529 * Returns the difference in days between input $tstamp and $EXEC_TIME
1531 * @param int $tstamp Time stamp, seconds
1534 public static function daysUntil($tstamp)
1536 $delta_t = $tstamp - $GLOBALS['EXEC_TIME'];
1537 return ceil($delta_t / (3600 * 24));
1541 * Returns $tstamp formatted as "ddmmyy" (According to $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'])
1543 * @param int $tstamp Time stamp, seconds
1544 * @return string Formatted time
1546 public static function date($tstamp)
1548 return date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'], (int)$tstamp);
1552 * Returns $tstamp formatted as "ddmmyy hhmm" (According to $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] AND $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'])
1554 * @param int $value Time stamp, seconds
1555 * @return string Formatted time
1557 public static function datetime($value)
1559 return date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'], $value);
1563 * Returns $value (in seconds) formatted as hh:mm:ss
1564 * For instance $value = 3600 + 60*2 + 3 should return "01:02:03"
1566 * @param int $value Time stamp, seconds
1567 * @param bool $withSeconds Output hh:mm:ss. If FALSE: hh:mm
1568 * @return string Formatted time
1570 public static function time($value, $withSeconds = true
)
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);
1577 $l .= ':' . sprintf('%02d', $sec);
1583 * Returns the "age" in minutes / hours / days / years of the number of $seconds inputted.
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
1589 public static function calcAge($seconds, $labels = ' min| hrs| days| yrs| min| hour| day| year')
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]);
1604 $val = round($absSeconds / (365 * 24 * 3600));
1605 $seconds = $sign * $val . ($val == 1 ?
$labelArr[7] : $labelArr[3]);
1611 * Returns a formatted timestamp if $tstamp is set.
1612 * The date/datetime will be followed by the age in parenthesis.
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
1619 public static function dateTimeAge($tstamp, $prefix = 1, $date = '')
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;
1630 * Returns alt="" and title="" attributes with the value of $content.
1632 * @param string $content Value for 'alt' and 'title' attributes (will be htmlspecialchars()'ed before output)
1635 public static function titleAltAttrib($content)
1638 $out .= ' alt="' . htmlspecialchars($content) . '"';
1639 $out .= ' title="' . htmlspecialchars($content) . '"';
1644 * Resolves file references for a given record.
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[]
1652 public static function resolveFileReferences($tableName, $fieldName, $element, $workspaceId = null
)
1654 if (empty($GLOBALS['TCA'][$tableName]['columns'][$fieldName]['config'])) {
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') {
1663 $fileReferences = array();
1664 /** @var $relationHandler RelationHandler */
1665 $relationHandler = GeneralUtility
::makeInstance(RelationHandler
::class);
1666 if ($workspaceId !== null
) {
1667 $relationHandler->setWorkspaceId($workspaceId);
1669 $relationHandler->start($element[$fieldName], $configuration['foreign_table'], $configuration['MM'], $element['uid'], $tableName, $configuration);
1670 $relationHandler->processDeletePlaceholder();
1671 $referenceUids = $relationHandler->tableArray
[$configuration['foreign_table']];
1673 foreach ($referenceUids as $referenceUid) {
1675 $fileReference = ResourceFactory
::getInstance()->getFileReferenceObject($referenceUid, array(), ($workspaceId === 0));
1676 $fileReferences[$fileReference->getUid()] = $fileReference;
1677 } catch (\TYPO3\CMS\Core\Resource\Exception\FileDoesNotExistException
$e) {
1679 * We just catch the exception here
1680 * Reasoning: There is nothing an editor or even admin could do
1682 } catch (\InvalidArgumentException
$e) {
1684 * The storage does not exist anymore
1685 * Log the exception message for admins as they maybe can restore the storage
1687 $logMessage = $e->getMessage() . ' (table: "' . $tableName . '", fieldName: "' . $fieldName . '", referenceUid: ' . $referenceUid . ')';
1688 GeneralUtility
::sysLog($logMessage, 'core', GeneralUtility
::SYSLOG_SEVERITY_ERROR
);
1692 return $fileReferences;
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.
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.
1712 public static function thumbCode($row, $table, $field, $backPath = '', $thumbScript = '', $uploaddir = null
, $abs = 0, $tparams = '', $size = '', $linkInfoPopup = true
)
1714 // Check and parse the size parameter
1715 $size = trim($size);
1716 $sizeParts = array(64, 64);
1718 $sizeParts = explode('x', $size . 'x' . $size);
1721 $fileReferences = static::resolveFileReferences($table, $field, $row);
1723 $iconFactory = GeneralUtility
::makeInstance(IconFactory
::class);
1724 if ($fileReferences !== null
) {
1725 foreach ($fileReferences as $fileReferenceObject) {
1726 $fileObject = $fileReferenceObject->getOriginalFile();
1728 if ($fileObject->isMissing()) {
1729 $flashMessage = \TYPO3\CMS\Core\Resource\Utility\BackendUtility
::getFlashMessageForMissingFile($fileObject);
1730 $thumbData .= $flashMessage->render();
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')
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()) . '" />';
1748 $imgTag = '<span title="' . htmlspecialchars($fileObject->getName()) . '">' . $iconFactory->getIconForResource($fileObject, Icon
::SIZE_SMALL
)->render() . '</span>';
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> ';
1754 $thumbData .= $imgTag;
1758 // Find uploaddir automatically
1759 if (is_null($uploaddir)) {
1760 $uploaddir = $GLOBALS['TCA'][$table]['columns'][$field]['config']['uploadfolder'];
1762 $uploaddir = rtrim($uploaddir, '/');
1764 $thumbs = GeneralUtility
::trimExplode(',', $row[$field], true
);
1766 foreach ($thumbs as $theFile) {
1768 $fileName = trim($uploaddir . '/' . $theFile, '/');
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();
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
),
1784 $thumbData .= $flashMessage->render();
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> ';
1799 $thumbData .= $image;
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> ';
1808 $thumbData .= $fileIcon;
1818 * Returns single image tag to thumbnail using a thumbnail script (like thumbs.php)
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
1827 public static function getThumbNail($thumbScript, $theFile, $tparams = '', $size = '')
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="" />';
1841 * Returns title-attribute information for a page-record informing about id, alias, doktype, hidden, starttime, endtime, fe_group etc.
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
1848 public static function titleAttribForPages($row, $perms_clause = '', $includeAttrib = true
)
1850 $lang = static::getLanguageService();
1852 $parts[] = 'id=' . $row['uid'];
1853 if ($row['alias']) {
1854 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['alias']['label']) . ' ' . $row['alias'];
1856 if ($row['pid'] < 0) {
1857 $parts[] = 'v#1.' . $row['t3ver_id'];
1859 switch (VersionState
::cast($row['t3ver_state'])) {
1860 case new VersionState(VersionState
::NEW_PLACEHOLDER
):
1861 $parts[] = 'PLH WSID#' . $row['t3ver_wsid'];
1863 case new VersionState(VersionState
::DELETE_PLACEHOLDER
):
1864 $parts[] = 'Deleted element!';
1866 case new VersionState(VersionState
::MOVE_PLACEHOLDER
):
1867 $parts[] = 'NEW LOCATION (PLH) WSID#' . $row['t3ver_wsid'];
1869 case new VersionState(VersionState
::MOVE_POINTER
):
1870 $parts[] = 'OLD LOCATION (PNT) WSID#' . $row['t3ver_wsid'];
1872 case new VersionState(VersionState
::NEW_PLACEHOLDER_VERSION
):
1873 $parts[] = 'New element!';
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);
1882 $row['shortcut'] = (int)$row['shortcut'];
1883 $lRec = self
::getRecordWSOL('pages', $row['shortcut'], 'title');
1884 $label = $lRec['title'] . ' (id=' . $row['shortcut'] . ')';
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']));
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);
1894 $lRec = self
::getRecordWSOL('pages', (int)$row['mount_pid'], 'title');
1895 $label = $lRec['title'] . ' (id=' . $row['mount_pid'] . ')';
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']);
1902 if ($row['nav_hide']) {
1903 $parts[] = rtrim($lang->sL($GLOBALS['TCA']['pages']['columns']['nav_hide']['label']), ':');
1905 if ($row['hidden']) {
1906 $parts[] = $lang->sL('LLL:EXT:lang/locallang_core.xlf:labels.hidden');
1908 if ($row['starttime']) {
1909 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['starttime']['label']) . ' ' . self
::dateTimeAge($row['starttime'], -1, 'date');
1911 if ($row['endtime']) {
1912 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['endtime']['label']) . ' ' . self
::dateTimeAge($row['endtime'], -1, 'date');
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));
1920 $lRec = self
::getRecordWSOL('fe_groups', $fe_group, 'title');
1921 $fe_groups[] = $lRec['title'];
1924 $label = implode(', ', $fe_groups);
1925 $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['fe_group']['label']) . ' ' . $label;
1927 $out = htmlspecialchars(implode(' - ', $parts));
1928 return $includeAttrib ?
'title="' . $out . '"' : $out;
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.
1936 * @param array $row Table row; $row is a row from the table, $table
1937 * @param string $table Table name
1940 public static function getRecordIconAltText($row, $table = 'pages')
1942 if ($table == 'pages') {
1943 $out = self
::titleAttribForPages($row, '', 0);
1945 $out = !empty(trim($GLOBALS['TCA'][$table]['ctrl']['descriptionColumn'])) ?
$row[$GLOBALS['TCA'][$table]['ctrl']['descriptionColumn']] . ' ' : '';
1946 $ctrl = $GLOBALS['TCA'][$table]['ctrl']['enablecolumns'];
1948 $out .= '(id=' . $row['uid'] . ')';
1949 if ($table == 'pages' && $row['alias']) {
1950 $out .= ' / ' . $row['alias'];
1952 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS'] && $row['pid'] < 0) {
1953 $out .= ' - v#1.' . $row['t3ver_id'];
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'];
1960 case new VersionState(VersionState
::DELETE_PLACEHOLDER
):
1961 $out .= ' - Deleted element!';
1963 case new VersionState(VersionState
::MOVE_PLACEHOLDER
):
1964 $out .= ' - NEW LOCATION (PLH) WSID#' . $row['t3ver_wsid'];
1966 case new VersionState(VersionState
::MOVE_POINTER
):
1967 $out .= ' - OLD LOCATION (PNT) WSID#' . $row['t3ver_wsid'];
1969 case new VersionState(VersionState
::NEW_PLACEHOLDER_VERSION
):
1970 $out .= ' - New element!';
1975 $lang = static::getLanguageService();
1976 if ($ctrl['disabled']) {
1977 $out .= $row[$ctrl['disabled']] ?
' - ' . $lang->sL('LLL:EXT:lang/locallang_core.xlf:labels.hidden') : '';
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') . ')';
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') . ')';
1988 return htmlspecialchars($out);
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
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
1999 public static function getLabelFromItemlist($table, $col, $key)
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) {
2015 * Return the label of a field by additionally checking TsConfig values
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
2023 public static function getLabelFromItemListMerged($pageId, $table, $column, $key)
2025 $pageTsConfig = static::getPagesTSconfig($pageId);
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];
2034 if (empty($label)) {
2035 $tcaValue = self
::getLabelFromItemlist($table, $column, $key);
2036 if (!empty($tcaValue)) {
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
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
2053 public static function getLabelsFromItemsList($table, $column, $keyList, array $columnTsConfig = array())
2055 // Check if there is an "items" array
2057 !isset($GLOBALS['TCA'][$table]['columns'][$column]['config']['items'])
2058 ||
!is_array($GLOBALS['TCA'][$table]['columns'][$column]['config']['items'])
2064 $keys = GeneralUtility
::trimExplode(',', $keyList, true
);
2066 // Loop on all selected values
2067 foreach ($keys as $key) {
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];
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;
2087 if ($label !== null
) {
2088 $labels[] = static::getLanguageService()->sL($label);
2091 return implode(', ', $labels);
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>'
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
2103 public static function getItemLabel($table, $col, $printAllWrap = '')
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'];
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];
2119 * Replace field values in given row with values from the original language
2120 * if l10n_mode TCA settings require to do so.
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
2126 protected static function replaceL10nModeFields($table, array $row)
2128 $originalUidField = isset($GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'])
2129 ?
$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']
2131 if (empty($row[$originalUidField])) {
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']
2141 if ($l10n_mode === 'exclude' ||
($l10n_mode === 'mergeIfNotBlank' && trim($row[$field]) === '')) {
2142 $row[$field] = $originalRow[$field];
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'
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).
2158 public static function getRecordTitle($table, $row, $prep = false
, $forceResult = true
)
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();
2169 // Create NULL-reference
2171 GeneralUtility
::callUserFunction($GLOBALS['TCA'][$table]['ctrl']['label_userFunc'], $params, $null);
2172 $recordTitle = $params['title'];
2174 if (is_array($row)) {
2175 $row = self
::replaceL10nModeFields($table, $row);
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
);
2183 if (!empty($recordTitle)) {
2184 $tA[] = $recordTitle;
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']) {
2193 $tA[] = $recordTitle;
2196 if ($GLOBALS['TCA'][$table]['ctrl']['label_alt_force']) {
2197 $recordTitle = implode(', ', $tA);
2201 // If the current result is empty, set it to '[No title]' (localized) and prepare for output if requested
2202 if ($prep ||
$forceResult) {
2204 $recordTitle = self
::getRecordTitlePrep($recordTitle);
2206 if (trim($recordTitle) === '') {
2207 $recordTitle = self
::getNoRecordTitle($prep);
2212 return $recordTitle;
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.
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
2223 public static function getRecordTitlePrep($title, $titleLength = 0)
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'];
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>';
2239 * Get a localized [No title] string, wrapped in <em>|</em> if $prep is TRUE.
2241 * @param bool $prep Wrap result in <em>|</em>
2242 * @return string Localized [No title] string
2244 public static function getNoRecordTitle($prep = false
)
2246 $noTitle = '[' . static::getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:labels.no_title', true
) . ']';
2248 $noTitle = '<em>' . $noTitle . '</em>';
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)
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
2271 public static function getProcessedValue($table, $col, $value, $fixed_lgd_chars = 0, $defaultPassthrough = false
, $noRecordLookup = false
, $uid = 0, $forceResult = true
, $pid = 0)
2273 if ($col === 'uid') {
2274 // uid is not in TCA-array
2277 // Check if table and field is configured
2278 if (!is_array($GLOBALS['TCA'][$table]) ||
!is_array($GLOBALS['TCA'][$table]['columns'][$col])) {
2281 // Depending on the fields configuration, make a meaningful output value.
2282 $theColConf = $GLOBALS['TCA'][$table]['columns'][$col]['config'];
2284 *HOOK: pre-processing the human readable output from a record
2286 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['preProcessValue'])) {
2287 // Create NULL-reference
2289 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['preProcessValue'] as $_funcRef) {
2290 GeneralUtility
::callUserFunction($_funcRef, $theColConf, $null);
2294 $db = static::getDatabaseConnection();
2295 $lang = static::getLanguageService();
2296 switch ((string)$theColConf['type']) {
2298 $l = self
::getLabelFromItemlist($table, $col, $value);
2303 if ($theColConf['MM']) {
2305 // Display the title of MM related records in lists
2306 if ($noRecordLookup) {
2307 $MMfield = $theColConf['foreign_table'] . '.uid';
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;
2313 $MMfield = join(',', $MMfields);
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']));
2322 while ($MMrow = $db->sql_fetch_assoc($MMres)) {
2323 // Keep sorting of $selectUids
2324 $mmlA[array_search($MMrow['uid'], $selectUids)] = $noRecordLookup ?
2326 static::getRecordTitle($theColConf['foreign_table'], $MMrow, false
, $forceResult);
2328 $db->sql_free_result($MMres);
2329 if (!empty($mmlA)) {
2331 $l = implode('; ', $mmlA);
2342 $columnTsConfig = array();
2344 $pageTsConfig = self
::getPagesTSconfig($pid);
2345 if (isset($pageTsConfig['TCEFORM.'][$table . '.'][$col . '.']) && is_array($pageTsConfig['TCEFORM.'][$table . '.'][$col . '.'])) {
2346 $columnTsConfig = $pageTsConfig['TCEFORM.'][$table . '.'][$col . '.'];
2349 $l = self
::getLabelsFromItemsList($table, $col, $value, $columnTsConfig);
2350 if ($theColConf['foreign_table'] && !$l && $GLOBALS['TCA'][$theColConf['foreign_table']]) {
2351 if ($noRecordLookup) {
2355 if ($uid && isset($theColConf['foreign_field']) && $theColConf['foreign_field'] !== '') {
2357 if (!empty($theColConf['foreign_table_field'])) {
2358 $whereClause .= ' AND ' . $theColConf['foreign_table_field'] . ' = ' . static::getDatabaseConnection()->fullQuoteStr($table, $theColConf['foreign_table']);
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']);
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'];
2372 if (empty($rParts)) {
2373 $rParts = GeneralUtility
::trimExplode(',', $value, true
);
2376 foreach ($rParts as $rVal) {
2378 $r = self
::getRecordWSOL($theColConf['foreign_table'], $rVal);
2380 $lA[] = $lang->sL($theColConf['foreign_table_prefix']) . self
::getRecordTitle($theColConf['foreign_table'], $r, false
, $forceResult);
2382 $lA[] = $rVal ?
'[' . $rVal . '!]' : '';
2385 $l = implode(', ', $lA);
2388 if (empty($l) && !empty($value)) {
2389 // Use plain database value when label is empty
2395 // resolve the titles for DB records
2396 if ($theColConf['internal_type'] === 'db') {
2397 if ($theColConf['MM']) {
2399 // Display the title of MM related records in lists
2400 if ($noRecordLookup) {
2401 $MMfield = $theColConf['foreign_table'] . '.uid';
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) {
2408 $MMfields[] = $theColConf['foreign_table'] . '.' . $f;
2411 $MMfield = join(',', $MMfields);
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(
2420 $theColConf['foreign_table'],
2421 'uid IN (' . implode(',', $selectUids) . ')' . static::deleteClause($theColConf['foreign_table'])
2424 while ($MMrow = $db->sql_fetch_assoc($MMres)) {
2425 // Keep sorting of $selectUids
2426 $mmlA[array_search($MMrow['uid'], $selectUids)] = $noRecordLookup
2428 : static::getRecordTitle($theColConf['foreign_table'], $MMrow, false
, $forceResult);
2430 $db->sql_free_result($MMres);
2431 if (!empty($mmlA)) {
2433 $l = implode('; ', $mmlA);
2444 $finalValues = array();
2445 $relationTableName = $theColConf['allowed'];
2446 $explodedValues = GeneralUtility
::trimExplode(',', $value, true
);
2448 foreach ($explodedValues as $explodedValue) {
2449 if (MathUtility
::canBeInterpretedAsInteger($explodedValue)) {
2450 $relationTableNameForField = $relationTableName;
2452 list($relationTableNameForField, $explodedValue) = self
::splitTable_Uid($explodedValue);
2455 $relationRecord = static::getRecordWSOL($relationTableNameForField, $explodedValue);
2456 $finalValues[] = static::getRecordTitle($relationTableNameForField, $relationRecord);
2458 $l = implode(', ', $finalValues);
2461 $l = implode(', ', GeneralUtility
::trimExplode(',', $value, true
));
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');
2469 foreach ($theColConf['items'] as $key => $val) {
2470 if ($value & pow(2, $key)) {
2471 $lA[] = $lang->sL($val[0]);
2474 $l = implode(', ', $lA);
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;
2487 if (!empty($value)) {
2489 $dateColumnConfiguration = $GLOBALS['TCA'][$table]['columns'][$col]['config'];
2490 $ageDisplayKey = 'disableAgeDisplay';
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')) . ')';
2499 $l = self
::date($value) . $ageSuffix;
2501 } elseif (GeneralUtility
::inList($theColConf['eval'], 'time')) {
2502 if (!empty($value)) {
2503 $l = self
::time($value, false
);
2505 } elseif (GeneralUtility
::inList($theColConf['eval'], 'timesec')) {
2506 if (!empty($value)) {
2507 $l = self
::time($value);
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;
2516 if (!empty($value)) {
2517 $l = self
::datetime($value);
2525 $l = strip_tags($value);
2528 if ($defaultPassthrough) {
2530 } elseif ($theColConf['MM']) {
2533 $l = GeneralUtility
::fixed_lgd_cs(strip_tags($value), 200);
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')) {
2539 $randomNumber = rand(5, 12);
2540 for ($i = 0; $i < $randomNumber; $i++
) {
2545 *HOOK: post-processing the human readable output from a record
2547 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['postProcessValue'])) {
2548 // Create NULL-reference
2550 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['postProcessValue'] as $_funcRef) {
2553 'colConf' => $theColConf
2555 $l = GeneralUtility
::callUserFunction($_funcRef, $params, $null);
2558 if ($fixed_lgd_chars) {
2559 return GeneralUtility
::fixed_lgd_cs($l, $fixed_lgd_chars);
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.
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
2576 * @see getProcessedValue()
2578 public static function getProcessedValueExtra($table, $fN, $fV, $fixed_lgd_chars = 0, $uid = 0, $forceResult = true
, $pid = 0)
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);
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)
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.
2606 public static function getCommonSelectFields($table, $prefix = '', $fields = array())
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'];
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;
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';
2624 if ($GLOBALS['TCA'][$table]['ctrl']['selicon_field']) {
2625 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['selicon_field'];
2627 if ($GLOBALS['TCA'][$table]['ctrl']['typeicon_column']) {
2628 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['typeicon_column'];
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'];
2634 if ($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['starttime']) {
2635 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['starttime'];
2637 if ($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['endtime']) {
2638 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['endtime'];
2640 if ($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['fe_group']) {
2641 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['fe_group'];
2644 return implode(',', array_unique($fields));
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.
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.
2659 public static function makeConfigForm($configArray, $defaults, $dataPrefix)
2661 $params = $defaults;
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]) {
2672 $formEl = '<input type="text" name="' . $dataPrefix . '[' . $fname . ']" value="' . $params[$fname] . '"' . static::getDocumentTemplate()->formWidth(($config[0] == 'short' ?
24 : 48)) . ' />';
2675 $formEl = '<input type="hidden" name="' . $dataPrefix . '[' . $fname . ']" value="0" /><input type="checkbox" name="' . $dataPrefix . '[' . $fname . ']" value="1"' . ($params[$fname] ?
' checked="checked"' : '') . ' />';
2682 foreach ($config[3] as $k => $v) {
2683 $opt[] = '<option value="' . htmlspecialchars($k) . '"' . ($params[$fname] == $k ?
' selected="selected"' : '') . '>' . htmlspecialchars($v) . '</option>';
2685 $formEl = '<select name="' . $dataPrefix . '[' . $fname . ']">' . implode('', $opt) . '</select>';
2688 $formEl = '<strong>Should not happen. Bug in config.</strong>';
2690 $lines[$fname] .= $formEl;
2691 $lines[$fname] .= '<br /><br />';
2693 $lines[$fname] = '<hr />';
2695 $lines[$fname] .= '<strong>' . strtoupper(htmlspecialchars($config)) . '</strong><br />';
2698 $lines[$fname] .= '<br />';
2703 $out = implode('', $lines);
2704 $out .= '<input class="btn btn-default" type="submit" name="submit" value="Update configuration" />';
2708 /*******************************************
2710 * Backend Modules API functions
2712 *******************************************/
2714 * Returns help-text icon if configured for.
2715 * TCA_DESCR must be loaded prior to this function
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.
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
2729 public static function helpTextIcon($table, $field, $_ = '', $force = false