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