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