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