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