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