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