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