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