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