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