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