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