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