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