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