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