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