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