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