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