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