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