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