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