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