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