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