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