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