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