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