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