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