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