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