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