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