2 /***************************************************************
5 * (c) 1999-2011 Kasper Skårhøj (kasperYYYY@typo3.com)
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.
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.
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.
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
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.
33 * Call ALL methods without making an object!
34 * Eg. to get a page-record 51 do this: 't3lib_BEfunc::getRecord('pages',51)'
36 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
40 final class t3lib_BEfunc
{
42 /*******************************************
44 * SQL-related, selecting records, searching
46 *******************************************/
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.
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"
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';
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']
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
79 public static function getRecord($table, $uid, $fields = '*', $where = '', $useDeleteClause = TRUE) {
80 if ($GLOBALS['TCA'][$table]) {
81 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
84 'uid=' . intval($uid) . ($useDeleteClause ? self
::deleteClause($table) : '') . $where
86 $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
87 $GLOBALS['TYPO3_DB']->sql_free_result($res);
95 * Like getRecord(), but overlays workspace version if any.
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
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);
111 if (is_array($row)) {
112 foreach (array_keys($row) as $key) {
113 if (!t3lib_div
::inList($fields, $key) && $key{0} !== '_') {
119 $row = self
::getRecord($table, $uid, $fields, $where, $useDeleteClause);
120 self
::workspaceOL($table, $row, -99, $unsetMovePointers);
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;
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
137 public static function getRecordRaw($table, $where = '', $fields = '*') {
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);
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
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)
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(
166 $theField . '=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($theValue, $theTable) .
167 ($useDeleteClause ? self
::deleteClause($theTable) . ' ' : '') .
168 self
::versioningPlaceholderClause($theTable) . ' ' .
169 $whereClause, // whereClauseMightContainGroupOrderBy
175 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
178 $GLOBALS['TYPO3_DB']->sql_free_result($res);
186 * Makes an backwards explode on the $str and returns an array with ($table, $uid).
187 * Example: tt_content_45 => array('tt_content', 45)
189 * @param string $str [tablename]_[uid] string to explode
192 public static function splitTable_Uid($str) {
193 list($uid, $table) = explode('_', strrev($str), 2);
194 return array(strrev($table), strrev($uid));
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.
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
206 public static function getSQLselectableList($in_list, $tablename, $default_tablename) {
208 if ((string) trim($in_list) != '') {
209 $tempItemArray = explode(',', trim($in_list));
210 foreach ($tempItemArray as $key => $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) {
222 return implode(',', $list);
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.
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
235 public static function BEenableFields($table, $inv = 0) {
236 $ctrl = $GLOBALS['TCA'][$table]['ctrl'];
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';
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'] . ')';
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'] . ')';
258 $outQ = ($inv ?
'(' . implode(' OR ', $invQuery) . ')' : implode(' AND ', $query));
260 return $outQ ?
' AND ' . $outQ : '';
264 * Fetches the localization for a given record.
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
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(
278 $tcaCtrl['transOrigPointerField'],
280 'AND ' . $tcaCtrl['languageField'] . '=' . intval($language) . ($andWhereClause ?
' ' . $andWhereClause : ''),
286 return $recordLocalization;
289 /*******************************************
291 * Page tree, TCA related
293 *******************************************/
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.
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!)
305 public static function BEgetRootLine($uid, $clause = '', $workspaceOL = FALSE) {
306 static $BEgetRootLine_cache = array();
310 $ident = $pid . '-' . $clause . '-' . $workspaceOL;
312 if (is_array($BEgetRootLine_cache[$ident])) {
313 $output = $BEgetRootLine_cache[$ident];
316 $theRowArray = array();
317 while ($uid != 0 && $loopCheck) {
319 $row = self
::getPageForRootline($uid, $clause, $workspaceOL);
320 if (is_array($row)) {
322 $theRowArray[] = $row;
328 $theRowArray[] = array('uid' => 0, 'title' => '');
330 $c = count($theRowArray);
332 foreach ($theRowArray as $val) {
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']
347 if (isset($val['_ORIG_pid'])) {
348 $output[$c]['_ORIG_pid'] = $val['_ORIG_pid'];
351 $BEgetRootLine_cache[$ident] = $output;
357 * Gets the cached page record for the rootline
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
365 protected static function getPageForRootline($uid, $clause, $workspaceOL) {
366 static $getPageForRootline_cache = array();
367 $ident = $uid . '-' . $clause . '-' . $workspaceOL;
369 if (is_array($getPageForRootline_cache[$ident])) {
370 $row = $getPageForRootline_cache[$ident];
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',
375 'uid=' . intval($uid) . ' ' .
376 self
::deleteClause('pages') . ' ' .
377 $clause // whereClauseMightContainGroupOrderBy
380 $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
383 self
::workspaceOL('pages', $row);
385 if (is_array($row)) {
386 self
::fixVersioningPid('pages', $row);
387 $getPageForRootline_cache[$ident] = $row;
390 $GLOBALS['TYPO3_DB']->sql_free_result($res);
396 * Opens the page tree to the specified page id
398 * @param integer $pid Page id.
399 * @param boolean $clearExpansion If set, then other open branches are closed.
402 public static function openPageTree($pid, $clearExpansion) {
404 // Get current expansion data:
405 if ($clearExpansion) {
406 $expandedPages = array();
408 $expandedPages = unserialize($GLOBALS['BE_USER']->uc
['browseTrees']['browsePages']);
412 $rL = self
::BEgetRootLine($pid);
414 // First, find out what mount index to use (if more than one DB mount exists):
416 $mountKeys = array_flip($GLOBALS['BE_USER']->returnWebmounts());
417 foreach ($rL as $rLDat) {
418 if (isset($mountKeys[$rLDat['uid']])) {
419 $mountIndex = $mountKeys[$rLDat['uid']];
424 // Traverse rootline and open paths:
425 foreach ($rL as $rLDat) {
426 $expandedPages[$mountIndex][$rLDat['uid']] = 1;
430 $GLOBALS['BE_USER']->uc
['browseTrees']['browsePages'] = serialize($expandedPages);
431 $GLOBALS['BE_USER']->writeUC();
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.
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.
445 public static function getRecordPath($uid, $clause, $titleLimit, $fullTitleLimit = 0) {
451 $output = $fullOutput = '/';
453 $clause = trim($clause);
454 if ($clause !== '' && substr($clause, 0, 3) !== 'AND') {
455 $clause = 'AND ' . $clause;
457 $data = self
::BEgetRootLine($uid, $clause);
459 foreach ($data as $record) {
460 if ($record['uid'] === 0) {
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;
469 if ($fullTitleLimit) {
470 return array($output, $fullOutput);
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
480 * @return array Array of arrays with excludeFields (fieldname, table:fieldname) from all TCA entries and from FlexForms (fieldname, table:extkey;sheetname;fieldname)
482 public static function getExcludeFields() {
484 $theExcludeArray = array();
485 $tc_keys = array_keys($GLOBALS['TCA']);
486 foreach ($tc_keys as $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
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']);
500 $theExcludeArray[] = array($Fname, $table . ':' . $field);
504 // All FlexForm fields
505 $flexFormArray = self
::getRegisteredFlexForms($table);
506 foreach ($flexFormArray as $tableField => $flexForms) {
507 // Prefix for field label, e.g. "Plugin Options:"
509 if (!empty($GLOBALS['TCA'][$table]['columns'][$tableField]['label'])) {
510 $labelPrefix = $GLOBALS['LANG']->sl($GLOBALS['TCA'][$table]['columns'][$tableField]['label']);
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'])) {
520 foreach ($sheet['ROOT']['el'] as $fieldName => $field) {
521 // Use only excludeable fields
522 if (empty($field['TCEforms']['exclude'])) {
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);
534 // Sort fields by label
535 usort($theExcludeArray, array(t3lib_TCEforms_Flexforms
, 'compareArraysByFirstValue'));
537 return $theExcludeArray;
541 * Returns an array with explicit Allow/Deny fields.
542 * Used for listing these field/value pairs in be_groups forms
544 * @return array Array with information from all of $GLOBALS['TCA']
546 public static function getExplicitAuthFieldValues() {
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'),
555 $allowDenyOptions = Array();
556 $tc_keys = array_keys($GLOBALS['TCA']);
557 foreach ($tc_keys as $table) {
560 t3lib_div
::loadTCA($table);
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']) {
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']);
575 foreach ($fCfg['items'] as $iVal) {
576 // Values '' is not controlled by this setting.
577 if (strcmp($iVal[1], '')) {
581 switch ((string) $fCfg['authMode']) {
582 case 'explicitAllow':
589 if (!strcmp($iVal[4], 'EXPL_ALLOW')) {
591 } elseif (!strcmp($iVal[4], 'EXPL_DENY')) {
599 $allowDenyOptions[$table . ':' . $field]['items'][$iVal[1]] = array($iMode, $GLOBALS['LANG']->sl($iVal[0]), $adLabel[$iMode]);
609 return $allowDenyOptions;
613 * Returns an array with system languages:
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.
620 * @return array Array with languages (title, uid, flagIcon)
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']
635 return $sysLanguages;
639 * Determines whether a table is localizable and has the languageField and transOrigPointerField set in $GLOBALS['TCA'].
641 * @param string $table The table to check
642 * @return boolean Whether a table is localizable
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']);
650 return $isLocalizable;
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.
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
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'];
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;
676 return $localizationMode;
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)
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.
688 public static function readPageAccess($id, $perms_clause) {
689 if ((string) $id != '') {
692 if ($GLOBALS['BE_USER']->isAdmin()) {
694 $pageinfo['_thePath'] = $path;
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);
713 * Returns the "types" configuration parsed into an array for the record, $rec, from table, $table
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.
720 public static function getTCAtypes($table, $rec, $useFieldNameAsKey = 0) {
721 t3lib_div
::loadTCA($table);
722 if ($GLOBALS['TCA'][$table]) {
725 $fieldValue = self
::getTCAtypeValue($table, $rec);
728 $typesConf = $GLOBALS['TCA'][$table]['types'][$fieldValue];
730 // Get fields list and traverse it
731 $fieldList = explode(',', $typesConf['showitem']);
732 $altFieldList = array();
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);
740 $fieldList[$k] = array(
741 'field' => $pFieldName,
742 'title' => $pAltTitle,
743 'palette' => $pPalette,
744 'spec' => $specConfParts,
747 if ($useFieldNameAsKey) {
748 $altFieldList[$fieldList[$k]['field']] = $fieldList[$k];
751 if ($useFieldNameAsKey) {
752 $fieldList = $altFieldList;
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)
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.
770 * @param string $table Table name present in TCA
771 * @param array $row Record from $table
772 * @return string Field value
775 public static function getTCAtypeValue($table, $row) {
779 t3lib_div
::loadTCA($table);
780 if ($GLOBALS['TCA'][$table]) {
781 $field = $GLOBALS['TCA'][$table]['ctrl']['type'];
783 if (strpos($field, ':') !== FALSE) {
784 list($pointerField, $foreignTableTypeField) = explode(':', $field);
786 // Get field value from database if field is not in the $row array
787 if (!isset($row[$pointerField])) {
788 $localRow = t3lib_BEfunc
::getRecord($table, $row['uid'], $pointerField);
789 $foreignUid = $localRow[$pointerField];
791 $foreignUid = $row[$pointerField];
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.
803 throw new RuntimeException('TCA foreign field pointer fields are only allowed to be used with group or select field types.', 1325862240);
806 $foreignRow = t3lib_BEfunc
::getRecord($foreignTable, $foreignUid, $foreignTableTypeField);
808 if ($foreignRow[$foreignTableTypeField]) {
809 $typeNum = $foreignRow[$foreignTableTypeField];
813 $typeNum = $row[$field];
815 // If that value is an empty string, set it to "0" (zero)
816 if (!strcmp($typeNum, '')) {
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;
825 // Force to string. Necessary for eg '-1' to be recognized as a type value.
826 $typeNum = (string)$typeNum;
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
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
840 public static function getSpecConfParts($str, $defaultExtras) {
842 // Add defaultExtras:
843 $specConfParts = t3lib_div
::trimExplode(':', $defaultExtras . ':' . $str, 1);
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)
854 $specConfParts[trim($v2)] = 1;
858 $specConfParts = array();
860 return $specConfParts;
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
867 * @param array $pArr Array of "[key] = [value]" strings to convert.
870 public static function getSpecConfParametersFromArray($pArr) {
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]);
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.
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()
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'];
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) {
912 // Up to two pointer fields can be specified in a comma separated list.
913 $pointerFields = t3lib_div
::trimExplode(',', $ds_pointerField);
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]];
927 $srcPointer = $row[$pointerFields[0]];
930 $srcPointer = isset($ds_array[$srcPointer]) ?
$srcPointer : 'default';
932 $srcPointer = 'default';
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));
941 $dataStructArray = 'The file "' . substr($ds_array[$srcPointer], 5) . '" in ds-array key "' . $srcPointer . '" was not found ("' . $file . '")';
944 $dataStructArray = t3lib_div
::xml2array($ds_array[$srcPointer]);
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];
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###
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!
958 $uidAcc = array(); // Used to avoid looping, if any should happen.
959 $subFieldPointer = $conf['ds_pointerField_searchParent_subField'];
960 while (!$srcPointer) {
962 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
963 'uid,' . $ds_pointerField . ',' . $ds_searchParentField . ($subFieldPointer ?
',' . $subFieldPointer : ''),
965 'uid=' . intval($newRecordPidValue ?
$newRecordPidValue : $rr[$ds_searchParentField]) . self
::deleteClause($table) ###NOTE_A###
967 $newRecordPidValue = 0;
968 $rr = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
969 $GLOBALS['TYPO3_DB']->sql_free_result($res);
971 // Break if no result from SQL db or if looping...
972 if (!is_array($rr) ||
isset($uidAcc[$rr['uid']])) {
975 $uidAcc[$rr['uid']] = 1;
978 self
::workspaceOL($table, $rr);
979 self
::fixVersioningPid($table, $rr, TRUE);
981 $srcPointer = ($subFieldPointer && $rr[$subFieldPointer]) ?
$rr[$subFieldPointer] : $rr[$ds_pointerField];
985 // If there is a srcPointer value:
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);
992 self
::workspaceOL($tName, $dataStructRec);
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]));
999 $dataStructArray = sprintf('File \'%s\' was not found', $dataStructRec[$fName]);
1002 // No file pointer, handle as being XML (default behaviour)
1003 $dataStructArray = t3lib_div
::xml2array($dataStructRec[$fName]);
1006 $dataStructArray = 'No tablename (' . $tName . ') or fieldname (' . $fName . ') was found an valid!';
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));
1014 $dataStructArray = 'The file "' . $srcPointer . '" was not found ("' . $file . '")';
1019 $dataStructArray = 'No source value in fieldname "' . $ds_pointerField . '"';
1022 $dataStructArray = 'No proper configuration!';
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);
1035 return $dataStructArray;
1039 * Returns all registered FlexForm definitions with title and fields
1041 * @param string $table The content table
1042 * @return array The data structures with speaking extension title
1043 * @see t3lib_BEfunc::getExcludeFields()
1045 public static function getRegisteredFlexForms($table = 'tt_content') {
1046 if (empty($table) ||
empty($GLOBALS['TCA'][$table]['columns'])) {
1050 $flexForms = array();
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();
1056 unset($fieldConf['config']['ds']['default']);
1058 // Get pointer fields
1059 $pointerFields = (!empty($fieldConf['config']['ds_pointerField']) ?
$fieldConf['config']['ds_pointerField'] : 'list_type,CType');
1060 $pointerFields = t3lib_div
::trimExplode(',', $pointerFields);
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];
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);
1077 $dataStruct = t3lib_div
::xml2array($dataStruct);
1078 if (!is_array($dataStruct)) {
1082 // Get flexform content
1083 $dataStruct = t3lib_div
::resolveAllSheetsInDS($dataStruct);
1084 if (empty($dataStruct['sheets']) ||
!is_array($dataStruct['sheets'])) {
1088 // Use DS pointer to get extension title from TCA
1090 $keyFields = t3lib_div
::trimExplode(',', $flexFormKey);
1091 foreach ($pointerFields as $pointerKey => $pointerName) {
1092 if (empty($keyFields[$pointerKey]) ||
$keyFields[$pointerKey] == '*' ||
$keyFields[$pointerKey] == 'list') {
1095 if (!empty($GLOBALS['TCA'][$table]['columns'][$pointerName]['config']['items'])) {
1096 $items = $GLOBALS['TCA'][$table]['columns'][$pointerName]['config']['items'];
1097 if (!is_array($items)) {
1100 foreach ($items as $itemConf) {
1101 if (!empty($itemConf[0]) && !empty($itemConf[1]) && $itemConf[1] == $keyFields[$pointerKey]) {
1102 $title = $itemConf[0];
1109 $flexForms[$tableField][$extIdent] = array(
1111 'ds' => $dataStruct,
1120 /*******************************************
1124 *******************************************/
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:
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!
1136 public static function storeHash($hash, $data, $ident) {
1137 $GLOBALS['typo3CacheManager']->getCache('cache_hash')->set(
1140 array('ident_' . $ident),
1141 0 // unlimited lifetime
1146 * Returns string value stored for the hash string in the cache "cache_hash"
1147 * Can be used to retrieved a cached value
1149 * IDENTICAL to the function by same name found in t3lib_page
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
1155 public static function getHash($hash, $expTime = 0) {
1156 $hashContent = NULL;
1157 $cacheEntry = $GLOBALS['typo3CacheManager']->getCache('cache_hash')->get($hash);
1159 $hashContent = $cacheEntry;
1161 return $hashContent;
1164 /*******************************************
1166 * TypoScript related
1168 *******************************************/
1171 * Returns the Page TSconfig for page with id, $id
1172 * Requires class "t3lib_TSparser"
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
1180 public static function getPagesTSconfig($id, $rootLine = '', $returnPartArray = 0) {
1182 if (!is_array($rootLine)) {
1183 $rootLine = self
::BEgetRootLine($id, '', TRUE);
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'];
1193 $TSdataArray = t3lib_TSparser
::checkIncludeLines_array($TSdataArray);
1194 if ($returnPartArray) {
1195 return $TSdataArray;
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);
1205 $TSconfig = $res['TSconfig'];
1208 $hash = md5('pageTS:' . $pageTS);
1209 $cachedContent = self
::getHash($hash);
1210 $TSconfig = array();
1211 if (isset($cachedContent)) {
1212 $TSconfig = unserialize($cachedContent);
1214 $parseObj = t3lib_div
::makeInstance('t3lib_TSparser');
1215 $parseObj->parse($pageTS);
1216 $TSconfig = $parseObj->setup
;
1217 self
::storeHash($hash, serialize($TSconfig), 'PAGES_TSconfig');
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);
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.
1234 * THIS DOES NOT CHECK ANY PERMISSIONS. SHOULD IT?
1235 * More documentation is needed.
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.]
1243 * @see implodeTSParams(), getPagesTSconfig()
1245 public static function updatePagesTSconfig($id, $pageTS, $TSconfPrefix, $impParams = '') {
1247 if (is_array($pageTS) && $id > 0) {
1248 if (!is_array($impParams)) {
1249 $impParams = self
::implodeTSParams(self
::getPagesTSconfig($id));
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);
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) {
1266 foreach ($TSlines as $ki => $kv) {
1267 if (substr($kv, 0, strlen($f) +
1) == $f . '=') {
1268 $TSlines[$ki] = $f . '=' . $v;
1274 $TSlines = array_reverse($TSlines);
1275 $TSlines[] = $f . '=' . $v;
1276 $TSlines = array_reverse($TSlines);
1279 $TSlines = array_reverse($TSlines);
1281 // Store those changes
1282 $TSconf = implode(LF
, $TSlines);
1284 $GLOBALS['TYPO3_DB']->exec_UPDATEquery('pages', 'uid=' . intval($id), array('TSconfig' => $TSconf));
1290 * Implodes a multi dimensional TypoScript array, $p, into a one-dimentional array (return value)
1292 * @param array $p TypoScript structure
1293 * @param string $k Prefix string
1294 * @return array Imploded TypoScript objectstring/values
1296 public static function implodeTSParams($p, $k = '') {
1297 $implodeParams = array();
1299 foreach ($p as $kb => $val) {
1300 if (is_array($val)) {
1301 $implodeParams = array_merge($implodeParams, self
::implodeTSParams($val, $k . $kb));
1303 $implodeParams[$k . $kb] = $val;
1307 return $implodeParams;
1310 /*******************************************
1312 * Users / Groups related
1314 *******************************************/
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
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
1324 public static function getUserNames($fields = 'username,usergroup,usergroup_cached_list,uid', $where = '') {
1325 $be_user_Array = array();
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;
1331 $GLOBALS['TYPO3_DB']->sql_free_result($res);
1333 return $be_user_Array;
1337 * Returns an array with be_groups records (title, uid) of all groups NOT DELETED sorted by their title
1339 * @param string $fields Field list
1340 * @param string $where WHERE clause
1343 public static function getGroupNames($fields = 'title,uid', $where = '') {
1344 $be_group_Array = Array();
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;
1350 $GLOBALS['TYPO3_DB']->sql_free_result($res);
1352 return $be_group_Array;
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.
1359 * @param string $fields Field list; $fields specify the fields selected (default: title,uid)
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) . ')';
1367 return self
::getGroupNames($fields, $exQ);
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
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
1380 public static function blindUserNames($usernames, $groupArray, $excludeBlindedFlag = 0) {
1381 if (is_array($usernames) && is_array($groupArray)) {
1382 foreach ($usernames as $uid => $row) {
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'];
1393 $userN = $row['username'];
1396 $usernames[$uid]['username'] = $userN;
1397 if ($excludeBlindedFlag && !$set) {
1398 unset($usernames[$uid]);
1406 * Corresponds to blindUserNames but works for groups instead
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
1413 public static function blindGroupNames($groups, $groupArray, $excludeBlindedFlag = 0) {
1414 if (is_array($groups) && is_array($groupArray)) {
1415 foreach ($groups as $uid => $row) {
1418 if (t3lib_div
::inArray($groupArray, $uid)) {
1419 $groupN = $row['title'];
1422 $groups[$uid]['title'] = $groupN;
1423 if ($excludeBlindedFlag && !$set) {
1424 unset($groups[$uid]);
1431 /*******************************************
1435 *******************************************/
1438 * Returns the difference in days between input $tstamp and $EXEC_TIME
1440 * @param integer $tstamp Time stamp, seconds
1443 public static function daysUntil($tstamp) {
1444 $delta_t = $tstamp - $GLOBALS['EXEC_TIME'];
1445 return ceil($delta_t / (3600 * 24));
1449 * Returns $tstamp formatted as "ddmmyy" (According to $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'])
1451 * @param integer $tstamp Time stamp, seconds
1452 * @return string Formatted time
1454 public static function date($tstamp) {
1455 return date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'], (int) $tstamp);
1459 * Returns $tstamp formatted as "ddmmyy hhmm" (According to $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] AND $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'])
1461 * @param integer $value Time stamp, seconds
1462 * @return string Formatted time
1464 public static function datetime($value) {
1465 return date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'], $value);
1469 * Returns $value (in seconds) formatted as hh:mm:ss
1470 * For instance $value = 3600 + 60*2 + 3 should return "01:02:03"
1472 * @param integer $value Time stamp, seconds
1473 * @param boolean $withSeconds Output hh:mm:ss. If FALSE: hh:mm
1474 * @return string Formatted time
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);
1482 $l .= ':' . sprintf('%02d', $sec);
1488 * Returns the "age" in minutes / hours / days / years of the number of $seconds inputted.
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
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]);
1508 $val = round($absSeconds / (365 * 24 * 3600));
1509 $seconds = ($sign * $val) . ($val == 1 ?
$labelArr[7] : $labelArr[3]);
1515 * Returns a formatted timestamp if $tstamp is set.
1516 * The date/datetime will be followed by the age in parenthesis.
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"
1523 public static function dateTimeAge($tstamp, $prefix = 1, $date = '') {
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')) . ')'
1531 * Returns alt="" and title="" attributes with the value of $content.
1533 * @param string $content Value for 'alt' and 'title' attributes (will be htmlspecialchars()'ed before output)
1536 public static function titleAltAttrib($content) {
1538 $out .= ' alt="' . htmlspecialchars($content) . '"';
1539 $out .= ' title="' . htmlspecialchars($content) . '"';
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.
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.
1560 public static function thumbCode($row, $table, $field, $backPath, $thumbScript = '', $uploaddir = NULL, $abs = 0, $tparams = '', $size = '', $linkInfoPopup = TRUE) {
1562 t3lib_div
::loadTCA($table);
1563 $tcaConfig = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
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])) {
1577 if ($tcaConfig['type'] === 'inline') {
1578 $referenceUids = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
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')
1588 foreach ($referenceUids as $referenceUid) {
1589 $fileReferenceObject = t3lib_file_Factory
::getInstance()->getFileReferenceObject($referenceUid['uid']);
1590 $fileObject = $fileReferenceObject->getOriginalFile();
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()) . '" />';
1602 $imgTag = t3lib_iconWorks
::getSpriteIconForFile(
1603 strtolower($fileObject->getExtension()),
1604 array('title' => $fileObject->getName())
1608 if ($linkInfoPopup) {
1609 $onClick = 'top.launchView(\'_FILE\',\'' . $fileObject->getUid() . '\',\'' . $backPath . '\'); return false;';
1610 $thumbData .= '<a href="#" onclick="' . htmlspecialchars($onClick) . '">' . $imgTag . '</a> ';
1612 $thumbData .= $imgTag;
1616 // Regular file references (as it only uses old syntax for thumbcode)
1618 // Find uploaddir automatically
1619 if (is_null($uploaddir)) {
1620 $uploaddir = $GLOBALS['TCA'][$table]['columns'][$field]['config']['uploadfolder'];
1622 $uploaddir = rtrim($uploaddir, '/');
1625 $thumbs = t3lib_div
::trimExplode(',', $row[$field], TRUE);
1628 foreach ($thumbs as $theFile) {
1630 $fileName = trim($uploaddir . '/' . $theFile, '/');
1631 $fileObject = t3lib_file_Factory
::getInstance()->retrieveFileOrFolderObject($fileName);
1633 $fileExtension = $fileObject->getExtension();
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);
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
1649 $thumbData .= $flashMessage->render();
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> ';
1658 $thumbData .= $image;
1662 $fileIcon = t3lib_iconWorks
::getSpriteIconForFile(
1664 array('title' => $fileObject->getName())
1667 if ($linkInfoPopup) {
1668 $onClick = 'top.launchView(\'_FILE\', \'' . $fileName . '\',\'\',\'' . $backPath . '\'); return false;';
1669 $thumbData .= '<a href="#" onclick="' . htmlspecialchars($onClick) . '">' . $fileIcon . '</a> ';
1671 $thumbData .= $fileIcon;
1682 * Returns single image tag to thumbnail using a thumbnail script (like thumbs.php)
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
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);
1696 $url = $thumbScript . '?' . $params;
1697 $th = '<img src="' . htmlspecialchars($url) . '" title="' . trim(basename($theFile)) . '"' . ($tparams ?
" " . $tparams : "") . ' alt="" />';
1702 * Returns title-attribute information for a page-record informing about id, alias, doktype, hidden, starttime, endtime, fe_group etc.
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
1709 public static function titleAttribForPages($row, $perms_clause = '', $includeAttrib = 1) {
1711 $parts[] = 'id=' . $row['uid'];
1712 if ($row['alias']) {
1713 $parts[] = $GLOBALS['LANG']->sL($GLOBALS['TCA']['pages']['columns']['alias']['label']) . ' ' . $row['alias'];
1715 if ($row['pid'] < 0) {
1716 $parts[] = 'v#1.' . $row['t3ver_id'];
1719 switch ($row['t3ver_state']) {
1721 $parts[] = 'PLH WSID#' . $row['t3ver_wsid'];
1724 $parts[] = 'Deleted element!';
1727 $parts[] = 'NEW LOCATION (PLH) WSID#' . $row['t3ver_wsid'];
1730 $parts[] = 'OLD LOCATION (PNT) WSID#' . $row['t3ver_wsid'];
1733 $parts[] = 'New element!';
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);
1743 $row['shortcut'] = intval($row['shortcut']);
1744 $lRec = self
::getRecordWSOL('pages', $row['shortcut'], 'title');
1745 $label = $lRec['title'] . ' (id=' . $row['shortcut'] . ')';
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']));
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);
1756 $lRec = self
::getRecordWSOL('pages', intval($row['mount_pid']), 'title');
1757 $label = $lRec['title'];
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']);
1764 if ($row['nav_hide']) {
1765 $parts[] = rtrim($GLOBALS['LANG']->sL($GLOBALS['TCA']['pages']['columns']['nav_hide']['label']), ':');
1767 if ($row['hidden']) {
1768 $parts[] = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.hidden');
1770 if ($row['starttime']) {
1771 $parts[] = $GLOBALS['LANG']->sL($GLOBALS['TCA']['pages']['columns']['starttime']['label']) . ' ' . self
::dateTimeAge($row['starttime'], -1, 'date');
1773 if ($row['endtime']) {
1774 $parts[] = $GLOBALS['LANG']->sL($GLOBALS['TCA']['pages']['columns']['endtime']['label']) . ' ' . self
::dateTimeAge($row['endtime'], -1, 'date');
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));
1782 $lRec = self
::getRecordWSOL('fe_groups', $fe_group, 'title');
1783 $fe_groups[] = $lRec['title'];
1786 $label = implode(', ', $fe_groups);
1787 $parts[] = $GLOBALS['LANG']->sL($GLOBALS['TCA']['pages']['columns']['fe_group']['label']) . ' ' . $label;
1789 $out = htmlspecialchars(implode(' - ', $parts));
1790 return $includeAttrib ?
'title="' . $out . '"' : $out;
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.
1798 * @param array $row Table row; $row is a row from the table, $table
1799 * @param string $table Table name
1802 public static function getRecordIconAltText($row, $table = 'pages') {
1803 if ($table == 'pages') {
1804 $out = self
::titleAttribForPages($row, '', 0);
1806 $ctrl = $GLOBALS['TCA'][$table]['ctrl']['enablecolumns'];
1809 $out = 'id=' . $row['uid'];
1810 if ($table == 'pages' && $row['alias']) {
1811 $out .= ' / ' . $row['alias'];
1813 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS'] && $row['pid'] < 0) {
1814 $out .= ' - v#1.' . $row['t3ver_id'];
1816 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
1817 switch ($row['t3ver_state']) {
1819 $out .= ' - PLH WSID#' . $row['t3ver_wsid'];
1822 $out .= ' - Deleted element!';
1825 $out .= ' - NEW LOCATION (PLH) WSID#' . $row['t3ver_wsid'];
1828 $out .= ' - OLD LOCATION (PNT) WSID#' . $row['t3ver_wsid'];
1831 $out .= ' - New element!';
1837 if ($ctrl['disabled']) {
1838 $out .= ($row[$ctrl['disabled']] ?
' - ' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.hidden') : '');
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') . ')';
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') . ')';
1853 return htmlspecialchars($out);
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
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
1864 public static function getLabelFromItemlist($table, $col, $key) {
1865 // Load full TCA for $table
1866 t3lib_div
::loadTCA($table);
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)) {
1881 * Splits the given key with commas and returns the list of all the localized items labels, separated by a comma.
1882 * NOTE: this does not take itemsProcFunc into account
1884 * @param string $table Table name, present in TCA
1885 * @param string $column Field name
1886 * @param string $key Key or comma-separated list of keys.
1887 * @return string Comma-separated list of localized labels
1889 public static function getLabelsFromItemsList($table, $column, $key) {
1891 $values = t3lib_div
::trimExplode(',', $key, TRUE);
1892 if (count($values) > 0) {
1893 // Load full TCA for $table
1894 t3lib_div
::loadTCA($table);
1895 // Check if there is an "items" array
1896 if (is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'][$column]) && is_array($GLOBALS['TCA'][$table]['columns'][$column]['config']['items'])) {
1897 // Loop on all selected values
1898 foreach ($values as $aValue) {
1899 foreach ($GLOBALS['TCA'][$table]['columns'][$column]['config']['items'] as $itemConfiguration) {
1900 // Loop on all available items
1901 // Keep matches and move on to next value
1902 if ($aValue == $itemConfiguration[1]) {
1903 $labels[] = $GLOBALS['LANG']->sL($itemConfiguration[0]);
1911 return implode(', ', $labels);
1915 * Returns the label-value for fieldname $col in table, $table
1916 * 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>'
1918 * @param string $table Table name, present in $GLOBALS['TCA']
1919 * @param string $col Field name
1920 * @param string $printAllWrap Wrap value - set function description
1923 public static function getItemLabel($table, $col, $printAllWrap = '') {
1924 // Load full TCA for $table
1925 t3lib_div
::loadTCA($table);
1926 // Check if column exists
1927 if (is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'][$col])) {
1928 return $GLOBALS['TCA'][$table]['columns'][$col]['label'];
1930 if ($printAllWrap) {
1931 $parts = explode('|', $printAllWrap);
1932 return $parts[0] . $col . $parts[1];
1937 * Returns the "title"-value in record, $row, from table, $table
1938 * The field(s) from which the value is taken is determined by the "ctrl"-entries 'label', 'label_alt' and 'label_alt_force'
1940 * @param string $table Table name, present in TCA
1941 * @param array $row Row from table
1942 * @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
1943 * @param boolean $forceResult If set, the function always returns an output. If no value is found for the title, '[No title]' is returned (localized).
1946 public static function getRecordTitle($table, $row, $prep = FALSE, $forceResult = TRUE) {
1947 if (is_array($GLOBALS['TCA'][$table])) {
1949 // If configured, call userFunc
1950 if ($GLOBALS['TCA'][$table]['ctrl']['label_userFunc']) {
1951 $params['table'] = $table;
1952 $params['row'] = $row;
1953 $params['title'] = '';
1954 // Create NULL-reference
1956 t3lib_div
::callUserFunction($GLOBALS['TCA'][$table]['ctrl']['label_userFunc'], $params, $null);
1957 $t = $params['title'];
1960 // No userFunc: Build label
1961 $t = self
::getProcessedValue($table, $GLOBALS['TCA'][$table]['ctrl']['label'], $row[$GLOBALS['TCA'][$table]['ctrl']['label']], 0, 0, FALSE, $row['uid'], $forceResult);
1962 if ($GLOBALS['TCA'][$table]['ctrl']['label_alt'] && ($GLOBALS['TCA'][$table]['ctrl']['label_alt_force'] ||
!strcmp($t, ''))) {
1963 $altFields = t3lib_div
::trimExplode(',', $GLOBALS['TCA'][$table]['ctrl']['label_alt'], 1);
1968 foreach ($altFields as $fN) {
1969 $t = trim(strip_tags($row[$fN]));
1970 if (strcmp($t, '')) {
1971 $t = self
::getProcessedValue($table, $fN, $t, 0, 0, FALSE, $row['uid']);
1972 if (!$GLOBALS['TCA'][$table]['ctrl']['label_alt_force']) {
1978 if ($GLOBALS['TCA'][$table]['ctrl']['label_alt_force']) {
1979 $t = implode(', ', $tA);
1984 // If the current result is empty, set it to '[No title]' (localized) and prepare for output if requested
1985 if ($prep ||
$forceResult) {
1987 $t = self
::getRecordTitlePrep($t);
1989 if (!strcmp(trim($t), '')) {
1990 $t = self
::getNoRecordTitle($prep);
1999 * Crops a title string to a limited lenght and if it really was cropped, wrap it in a <span title="...">|</span>,
2000 * which offers a tooltip with the original title when moving mouse over it.
2002 * @param string $title The title string to be cropped
2003 * @param integer $titleLength Crop title after this length - if not set, BE_USER->uc['titleLen'] is used
2004 * @return string The processed title string, wrapped in <span title="...">|</span> if cropped
2006 public static function getRecordTitlePrep($title, $titleLength = 0) {
2007 // If $titleLength is not a valid positive integer, use BE_USER->uc['titleLen']:
2008 if (!$titleLength ||
!t3lib_utility_Math
::canBeInterpretedAsInteger($titleLength) ||
$titleLength < 0) {
2009 $titleLength = $GLOBALS['BE_USER']->uc
['titleLen'];
2011 $titleOrig = htmlspecialchars($title);
2012 $title = htmlspecialchars(t3lib_div
::fixed_lgd_cs($title, $titleLength));
2013 // If title was cropped, offer a tooltip:
2014 if ($titleOrig != $title) {
2015 $title = '<span title="' . $titleOrig . '">' . $title . '</span>';
2021 * Get a localized [No title] string, wrapped in <em>|</em> if $prep is TRUE.
2023 * @param boolean $prep Wrap result in <em>|</em>
2024 * @return string Localized [No title] string
2026 public static function getNoRecordTitle($prep = FALSE) {
2027 $noTitle = '[' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.no_title', 1) . ']';
2029 $noTitle = '<em>' . $noTitle . '</em>';
2035 * Returns a human readable output of a value from a record
2036 * 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.
2037 * $table/$col is tablename and fieldname
2038 * REMEMBER to pass the output through htmlspecialchars() if you output it to the browser! (To protect it from XSS attacks and be XHTML compliant)
2040 * @param string $table Table name, present in TCA
2041 * @param string $col Field name, present in TCA
2042 * @param string $value The value of that field from a selected record
2043 * @param integer $fixed_lgd_chars The max amount of characters the value may occupy
2044 * @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")
2045 * @param boolean $noRecordLookup If set, no records will be looked up, UIDs are just shown.
2046 * @param integer $uid Uid of the current record
2047 * @param boolean $forceResult If t3lib_BEfunc::getRecordTitle is used to process the value, this parameter is forwarded.
2050 public static function getProcessedValue($table, $col, $value, $fixed_lgd_chars = 0, $defaultPassthrough = 0, $noRecordLookup = FALSE, $uid = 0, $forceResult = TRUE) {
2051 if ($col == 'uid') {
2052 // No need to load TCA as uid is not in TCA-array
2055 // Load full TCA for $table
2056 t3lib_div
::loadTCA($table);
2057 // Check if table and field is configured:
2058 if (is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'][$col])) {
2059 // Depending on the fields configuration, make a meaningful output value.
2060 $theColConf = $GLOBALS['TCA'][$table]['columns'][$col]['config'];
2063 *HOOK: pre-processing the human readable output from a record
2065 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['preProcessValue'])) {
2066 // Create NULL-reference
2068 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['preProcessValue'] as $_funcRef) {
2069 t3lib_div
::callUserFunction($_funcRef, $theColConf, $null);
2074 switch ((string) $theColConf['type']) {
2076 $l = self
::getLabelFromItemlist($table, $col, $value);
2077 $l = $GLOBALS['LANG']->sL($l);
2080 if ($theColConf['MM']) {
2082 // Display the title of MM related records in lists
2083 if ($noRecordLookup) {
2084 $MMfield = $theColConf['foreign_table'] . '.uid';
2086 $MMfields = array($theColConf['foreign_table'] . '.' . $GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label']);
2087 foreach (t3lib_div
::trimExplode(',', $GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label_alt'], 1) as $f) {
2088 $MMfields[] = $theColConf['foreign_table'] . '.' . $f;
2090 $MMfield = join(',', $MMfields);
2093 /** @var $dbGroup t3lib_loadDBGroup */
2094 $dbGroup = t3lib_div
::makeInstance('t3lib_loadDBGroup');
2095 $dbGroup->start($value, $theColConf['foreign_table'], $theColConf['MM'], $uid, $table, $theColConf);
2096 $selectUids = $dbGroup->tableArray
[$theColConf['foreign_table']];
2098 if (is_array($selectUids) && count($selectUids) > 0) {
2099 $MMres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
2101 $theColConf['foreign_table'],
2102 'uid IN (' . implode(',', $selectUids) . ')' . self
::deleteClause($theColConf['foreign_table'])
2104 while ($MMrow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($MMres)) {
2105 $mmlA[] = ($noRecordLookup ?
$MMrow['uid'] : self
::getRecordTitle($theColConf['foreign_table'], $MMrow, FALSE, $forceResult));
2107 $GLOBALS['TYPO3_DB']->sql_free_result($MMres);
2109 if (is_array($mmlA)) {
2110 $l = implode('; ', $mmlA);
2121 $l = self
::getLabelsFromItemsList($table, $col, $value);
2123 if ($theColConf['foreign_table'] && !$l && $GLOBALS['TCA'][$theColConf['foreign_table']]) {
2124 if ($noRecordLookup) {
2127 $rParts = t3lib_div
::trimExplode(',', $value, 1);
2129 foreach ($rParts as $rVal) {
2130 $rVal = intval($rVal);
2132 $r = self
::getRecordWSOL($theColConf['foreign_table'], $rVal);
2134 $r = self
::getRecordWSOL($theColConf['neg_foreign_table'], -$rVal);
2137 $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);
2139 $lA[] = $rVal ?
'[' . $rVal . '!]' : '';
2142 $l = implode(', ', $lA);
2148 $l = implode(', ', t3lib_div
::trimExplode(',', $value, 1));
2151 if (!is_array($theColConf['items']) ||
count($theColConf['items']) == 1) {
2152 $l = $value ?
$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:yes') : $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:no');
2155 foreach ($theColConf['items'] as $key => $val) {
2156 if ($value & pow(2, $key)) {
2157 $lA[] = $GLOBALS['LANG']->sL($val[0]);
2160 $l = implode(', ', $lA);
2164 // Hide value 0 for dates, but show it for everything else
2165 if (isset($value)) {
2166 if (t3lib_div
::inList($theColConf['eval'], 'date')) {
2167 if (!empty($value)) {
2168 $l = self
::date($value) .
2170 ($GLOBALS['EXEC_TIME'] - $value > 0 ?
'-' : '') .
2171 self
::calcAge(abs($GLOBALS['EXEC_TIME'] - $value), $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears')) .
2174 } elseif (t3lib_div
::inList($theColConf['eval'], 'time')) {
2175 if (!empty($value)) {
2176 $l = self
::time($value, FALSE);
2178 } elseif (t3lib_div
::inList($theColConf['eval'], 'timesec')) {
2179 if (!empty($value)) {
2180 $l = self
::time($value);
2182 } elseif (t3lib_div
::inList($theColConf['eval'], 'datetime')) {
2183 if (!empty($value)) {
2184 $l = self
::datetime($value);
2192 $l = strip_tags($value);
2195 if ($defaultPassthrough) {
2197 } elseif ($theColConf['MM']) {
2200 $l = t3lib_div
::fixed_lgd_cs(strip_tags($value), 200);
2205 // If this field is a password field, then hide the password by changing it to a random number of asterisk (*)
2206 if (stristr($theColConf['eval'], 'password')) {
2208 $randomNumber = rand(5, 12);
2209 for ($i = 0; $i < $randomNumber; $i++
) {
2215 *HOOK: post-processing the human readable output from a record
2217 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['postProcessValue'])) {
2218 // Create NULL-reference
2220 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['postProcessValue'] as $_funcRef) {
2223 'colConf' => $theColConf
2225 $l = t3lib_div
::callUserFunction($_funcRef, $params, $null);
2229 if ($fixed_lgd_chars) {
2230 return t3lib_div
::fixed_lgd_cs($l, $fixed_lgd_chars);
2238 * 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.
2240 * @param string $table Table name, present in TCA
2241 * @param string $fN Field name
2242 * @param string $fV Field value
2243 * @param integer $fixed_lgd_chars The max amount of characters the value may occupy
2244 * @param integer $uid Uid of the current record
2245 * @param boolean $forceResult If t3lib_BEfunc::getRecordTitle is used to process the value, this parameter is forwarded.
2247 * @see getProcessedValue()
2249 public static function getProcessedValueExtra($table, $fN, $fV, $fixed_lgd_chars = 0, $uid = 0, $forceResult = TRUE) {
2250 $fVnew = self
::getProcessedValue($table, $fN, $fV, $fixed_lgd_chars, 1, 0, $uid, $forceResult);
2251 if (!isset($fVnew)) {
2252 if (is_array($GLOBALS['TCA'][$table])) {
2253 if ($fN == $GLOBALS['TCA'][$table]['ctrl']['tstamp'] ||
$fN == $GLOBALS['TCA'][$table]['ctrl']['crdate']) {
2254 $fVnew = self
::datetime($fV);
2255 } elseif ($fN == 'pid') {
2256 // Fetches the path with no regard to the users permissions to select pages.
2257 $fVnew = self
::getRecordPath($fV, '1=1', 20);
2267 * Returns file icon name (from $FILEICONS) for the fileextension $ext
2269 * @param string $ext File extension, lowercase
2270 * @return string File icon filename
2272 public static function getFileIcon($ext) {
2273 return $GLOBALS['FILEICONS'][$ext] ?
$GLOBALS['FILEICONS'][$ext] : $GLOBALS['FILEICONS']['default'];
2277 * Returns fields for a table, $table, which would typically be interesting to select
2278 * This includes uid, the fields defined for title, icon-field.
2279 * 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)
2281 * @param string $table Table name, present in $GLOBALS['TCA']
2282 * @param string $prefix Table prefix
2283 * @param array $fields Preset fields (must include prefix if that is used)
2284 * @return string List of fields.
2286 public static function getCommonSelectFields($table, $prefix = '', $fields = array()) {
2287 $fields[] = $prefix . 'uid';
2288 if (isset($GLOBALS['TCA'][$table]['ctrl']['label']) && $GLOBALS['TCA'][$table]['ctrl']['label'] != '') {
2289 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['label'];
2292 if ($GLOBALS['TCA'][$table]['ctrl']['label_alt']) {
2293 $secondFields = t3lib_div
::trimExplode(',', $GLOBALS['TCA'][$table]['ctrl']['label_alt'], 1);
2294 foreach ($secondFields as $fieldN) {
2295 $fields[] = $prefix . $fieldN;
2298 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
2299 $fields[] = $prefix . 't3ver_id';
2300 $fields[] = $prefix . 't3ver_state';
2301 $fields[] = $prefix . 't3ver_wsid';
2302 $fields[] = $prefix . 't3ver_count';
2305 if ($GLOBALS['TCA'][$table]['ctrl']['selicon_field']) {
2306 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['selicon_field'];
2308 if ($GLOBALS['TCA'][$table]['ctrl']['typeicon_column']) {
2309 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['typeicon_column'];
2312 if (is_array($GLOBALS['TCA'][$table]['ctrl']['enablecolumns'])) {
2313 if ($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['disabled']) {
2314 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['disabled'];
2316 if ($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['starttime']) {
2317 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['starttime'];
2319 if ($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['endtime']) {
2320 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['endtime'];
2322 if ($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['fe_group']) {
2323 $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['fe_group'];
2327 return implode(',', array_unique($fields));
2331 * Makes a form for configuration of some values based on configuration found in the array $configArray,
2332 * with default values from $defaults and a data-prefix $dataPrefix
2333 * <form>-tags must be supplied separately
2334 * Needs more documentation and examples, in particular syntax for configuration array. See Inside TYPO3.
2335 * That's were you can expect to find example, if anywhere.
2337 * @param array $configArray Field configuration code.
2338 * @param array $defaults Defaults
2339 * @param string $dataPrefix Prefix for formfields
2340 * @return string HTML for a form.
2342 public static function makeConfigForm($configArray, $defaults, $dataPrefix) {
2343 $params = $defaults;
2344 if (is_array($configArray)) {
2346 foreach ($configArray as $fname => $config) {
2347 if (is_array($config)) {
2348 $lines[$fname] = '<strong>' . htmlspecialchars($config[1]) . '</strong><br />';
2349 $lines[$fname] .= $config[2] . '<br />';
2350 switch ($config[0]) {
2353 $formEl = '<input type="text" name="' . $dataPrefix . '[' . $fname . ']" value="' . $params[$fname] . '"' . $GLOBALS['TBE_TEMPLATE']->formWidth($config[0] == 'short' ?
24 : 48) . ' />';
2356 $formEl = '<input type="hidden" name="' . $dataPrefix . '[' . $fname . ']" value="0" /><input type="checkbox" name="' . $dataPrefix . '[' . $fname . ']" value="1"' . ($params[$fname] ?
' checked="checked"' : '') . ' />';
2363 foreach ($config[3] as $k => $v) {
2364 $opt[] = '<option value="' . htmlspecialchars($k) . '"' . ($params[$fname] == $k ?
' selected="selected"' : '') . '>' . htmlspecialchars($v) . '</option>';
2366 $formEl = '<select name="' . $dataPrefix . '[' . $fname . ']">' . implode('', $opt) . '</select>';
2372 $lines[$fname] .= $formEl;
2373 $lines[$fname] .= '<br /><br />';
2375 $lines[$fname] = '<hr />';
2377 $lines[$fname] .= '<strong>' . strtoupper(htmlspecialchars($config)) . '</strong><br />';
2380 $lines[$fname] .= '<br />';
2385 $out = implode('', $lines);
2386 $out .= '<input type="submit" name="submit" value="Update configuration" />';
2390 /*******************************************
2392 * Backend Modules API functions
2394 *******************************************/
2397 * Returns help-text icon if configured for.
2398 * TCA_DESCR must be loaded prior to this function and $GLOBALS['BE_USER'] must
2399 * have 'edit_showFieldHelp' set to 'icon', otherwise nothing is returned
2401 * Please note: since TYPO3 4.5 the UX team decided to not use CSH in its former way,
2402 * but to wrap the given text (where before the help icon was, and you could hover over it)
2403 * Please also note that since TYPO3 4.5 the option to enable help (none, icon only, full text)
2404 * was completely removed.
2406 * @param string $table Table name
2407 * @param string $field Field name
2408 * @param string $BACK_PATH Back path
2409 * @param boolean $force Force display of icon no matter BE_USER setting for help
2410 * @return string HTML content for a help icon/text
2412 public static function helpTextIcon($table, $field, $BACK_PATH, $force = 0) {
2413 if (is_array($GLOBALS['TCA_DESCR'][$table]) && is_array($GLOBALS['TCA_DESCR'][$table]['columns'][$field]) && (isset($GLOBALS['BE_USER']->uc
['edit_showFieldHelp']) ||
$force)) {
2414 return self
::wrapInHelp($table, $field);
2419 * Returns CSH help text (description), if configured for, as an array (title, description)
2421 * @param string $table Table name
2422 * @param string $field Field name
2423 * @return array With keys 'description' (raw, as available in locallang), 'title' (optional), 'moreInfo'
2425 public static function helpTextArray($table, $field) {
2426 if (!isset($GLOBALS['TCA_DESCR'][$table]['columns'])) {
2427 $GLOBALS['LANG']->loadSingleTableDescription($table);
2430 'description' => NULL,
2432 'moreInfo' => FALSE,
2434 if (is_array($GLOBALS['TCA_DESCR'][$table]) && is_array($GLOBALS['TCA_DESCR'][$table]['columns'][$field])) {
2435 $data = $GLOBALS['TCA_DESCR'][$table]['columns'][$field];
2437 // Add alternative title, if defined
2438 if ($data['alttitle']) {
2439 $output['title'] = $data['alttitle'];
2442 // If we have more information to show
2443 if ($data['image_descr'] ||
$data['seeAlso'] ||
$data['details'] ||
$data['syntax']) {
2444 $output['moreInfo'] = TRUE;
2448 if ($data['description']) {
2449 $output['description'] = $data['description'];
2456 * Returns CSH help text (description), if configured for.
2457 * $GLOBALS['TCA_DESCR'] must be loaded prior to this function and $GLOBALS['BE_USER'] must have "edit_showFieldHelp" set to "text",
2458 * otherwise nothing is returned.
2460 * @param string $table Table name
2461 * @param string $field Field name
2462 * @return string HTML content for help text
2464 public static function helpText($table, $field) {
2465 $helpTextArray = self
::helpTextArray($table, $field);
2470 // Put header before the rest of the text
2471 if ($helpTextArray['title'] !== NULL) {
2472 $output .= '<h2 class="t3-row-header">' . $helpTextArray['title'] . '</h2>';
2474 // Add see also arrow if we have more info
2475 if ($helpTextArray['moreInfo']) {
2476 $arrow = t3lib_iconWorks
::getSpriteIcon('actions-view-go-forward');
2478 // Wrap description and arrow in p tag
2479 if ($helpTextArray['description'] !== NULL ||
$arrow) {
2480 $output .= '<p class="t3-help-short">' . nl2br(htmlspecialchars($helpTextArray['description'])) . $arrow . '</p>';
2487 * API function that wraps the text / html in help text, so if a user hovers over it
2488 * the help text will show up
2489 * This is the new help API function since TYPO3 4.5, and uses the new behaviour
2490 * (hover over text, no icon, no fulltext option, no option to disable the help)
2492 * @param string $table The table name for which the help should be shown
2493 * @param string $field The field name for which the help should be shown
2494 * @param string $text The text which should be wrapped with the help text
2495 * @param array $overloadHelpText Array with text to overload help text
2496 * @return string the HTML code ready to render
2498 public static function wrapInHelp($table, $field, $text = '', array $overloadHelpText = array()) {
2499 // Initialize some variables
2502 $wrappedText = $text;
2503 $hasHelpTextOverload = count($overloadHelpText) > 0;
2505 // Get the help text that should be shown on hover
2506 if (!$hasHelpTextOverload) {
2507 $helpText = self
::helpText($table, $field);
2510 // If there's a help text or some overload information, proceed with preparing an output
2511 if (!empty($helpText) ||
$hasHelpTextOverload) {
2512 // If no text was given, just use the regular help icon
2514 $text = t3lib_iconWorks
::getSpriteIcon('actions-system-help-open');
2515 $abbrClassAdd = '-icon';
2517 $text = '<abbr class="t3-help-teaser' . $abbrClassAdd . '">' . $text . '</abbr>';
2518 $wrappedText = '<span class="t3-help-link" href="#" data-table="' . $table . '" data-field="' . $field . '"';
2519 // The overload array may provide a title and a description
2520 // If either one is defined, add them to the "data" attributes
2521 if ($hasHelpTextOverload) {
2522 if (isset($overloadHelpText['title'])) {
2523 $wrappedText .= ' data-title="' . htmlspecialchars($overloadHelpText['title']) . '"';
2525 if (isset($overloadHelpText['description'])) {
2526 $wrappedText .= ' data-description="' . htmlspecialchars($overloadHelpText['description']) . '"';
2529 $wrappedText .= '>' . $text . '</span>';
2532 return $wrappedText;
2537 * API for getting CSH icons/text for use in backend modules.
2538 * TCA_DESCR will be loaded if it isn't already
2540 * @param string $table Table name ('_MOD_'+module name)
2541 * @param string $field Field name (CSH locallang main key)
2542 * @param string $BACK_PATH Back path
2543 * @param string $wrap Wrap code for icon-mode, splitted by "|". Not used for full-text mode.
2544 * @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.
2545 * @param string $styleAttrib Additional style-attribute content for wrapping table (full text mode only)
2546 * @return string HTML content for help text
2547 * @see helpText(), helpTextIcon()
2549 public static function cshItem($table, $field, $BACK_PATH, $wrap = '', $onlyIconMode = FALSE, $styleAttrib = '') {
2550 if ($GLOBALS['BE_USER']->uc
['edit_showFieldHelp']) {
2551 $GLOBALS['LANG']->loadSingleTableDescription($table);
2553 if (is_array($GLOBALS['TCA_DESCR'][$table])) {
2554 // Creating CSH icon and short description:
2555 $fullText = self
::helpText($table, $field);
2556 $icon = self
::helpTextIcon($table, $field, $BACK_PATH);
2558 if ($fullText && !$onlyIconMode && $GLOBALS['BE_USER']->uc
['edit_showFieldHelp'] == 'text') {
2560 // Additional styles?
2561 $params = $styleAttrib ?
' style="' . $styleAttrib . '"' : '';
2563 // Compile table with CSH information:
2564 $fullText = '<table border="0" cellpadding="0" cellspacing="0" class="typo3-csh-inline"' . $params . '>
2566 <td valign="top" width="14"><div class="t3-row-header">' . $icon . '</div></td>
2567 <td valign="top">' . $fullText . '</td>
2571 $output = $fullText;
2575 if ($output && $wrap) {
2576 $wrParts = explode('|', $wrap);
2577 $output = $wrParts[0] . $output . $wrParts[1];
2587 * 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.
2588 * REMEMBER to always htmlspecialchar() content in href-properties to ampersands get converted to entities (XHTML requirement and XSS precaution)
2590 * @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.
2591 * @param string $backPath Must point back to the TYPO3_mainDir directory (where alt_doc.php is)
2592 * @param string $requestUri An optional returnUrl you can set - automatically set to REQUEST_URI.
2594 * @see template::issueCommand()
2596 public static function editOnClick($params, $backPath = '', $requestUri = '') {
2597 $retUrl = 'returnUrl=' . ($requestUri == -1 ?
"'+T3_THIS_LOCATION+'" : rawurlencode($requestUri ?
$requestUri : t3lib_div
::getIndpEnv('REQUEST_URI')));
2598 return "window.location.href='" . $backPath . "alt_doc.php?" . $retUrl . $params . "'; return false;";
2602 * Returns a JavaScript string for viewing the page id, $id
2603 * It will detect the correct domain name if needed and provide the link with the right back path.
2604 * Also it will re-use any window already open.
2606 * @param integer $pageUid Page id
2607 * @param string $backPath Must point back to TYPO3_mainDir (where the site is assumed to be one level above)
2608 * @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)
2609 * @param string $anchorSection Optional anchor to the URL
2610 * @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!
2611 * @param string $additionalGetVars Additional GET variables.
2612 * @param boolean $switchFocus If TRUE, then the preview window will gain the focus.
2615 public static function viewOnClick($pageUid, $backPath = '', $rootLine = '', $anchorSection = '', $alternativeUrl = '', $additionalGetVars = '', $switchFocus = TRUE) {
2616 $viewScript = '/index.php?id=';
2617 if ($alternativeUrl) {
2618 $viewScript = $alternativeUrl;
2621 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['viewOnClickClass'])
2622 && is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['viewOnClickClass'])) {
2623 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['viewOnClickClass'] as $funcRef) {
2624 $hookObj = t3lib_div
::getUserObj($funcRef);
2625 if (method_exists($hookObj, 'preProcess')) {
2626 $hookObj->preProcess($pageUid, $backPath, $rootLine, $anchorSection, $viewScript, $additionalGetVars, $switchFocus);
2631 // Look if a fixed preview language should be added:
2632 $viewLanguageOrder = $GLOBALS['BE_USER']->getTSConfigVal('options.view.languageOrder');
2633 if (strlen($viewLanguageOrder)) {
2636 // Find allowed languages (if none, all are allowed!)
2637 if (!$GLOBALS['BE_USER']->user
['admin'] &&
2638 strlen($GLOBALS['BE_USER']->groupData
['allowed_languages'])) {
2639 $allowedLanguages = array_flip(explode(',', $GLOBALS['BE_USER']->groupData
['allowed_languages']));
2642 // Traverse the view order, match first occurence:
2643 $languageOrder = t3lib_div
::intExplode(',', $viewLanguageOrder);
2644 foreach ($languageOrder as $langUid) {
2645 if (is_array($allowedLanguages) && count($allowedLanguages)) {
2647 if (isset($allowedLanguages[$langUid])) {
2648 $suffix = '&L=' . $langUid;
2652 // All allowed since no lang. are listed.
2653 $suffix = '&L=' . $langUid;
2658 $additionalGetVars .= $suffix;
2661 // Check a mount point needs to be previewed
2662 $sys_page = t3lib_div
::makeInstance('t3lib_pageSelect');
2663 $sys_page->init(FALSE);
2664 $mountPointInfo = $sys_page->getMountPointInfo($pageUid);
2665 if ($mountPointInfo && $mountPointInfo['overlay']) {
2666 $pageUid = $mountPointInfo['mount_pid'];
2667 $additionalGetVars .= '&MP=' . $mountPointInfo['MPvar'];
2670 $viewDomain = self
::getViewDomain($pageUid, $rootLine);
2671 $previewUrl = $viewDomain . $viewScript . $pageUid . $additionalGetVars . $anchorSection;
2672 $onclickCode = "var previewWin = window.open('" . $previewUrl . "','newTYPO3frontendWindow');" . ($switchFocus ?
'previewWin.focus();' : '');
2673 return $onclickCode;
2677 * Builds the frontend view domain for a given page ID with a given root
2680 * @param integer $pageId The page ID to use, must be > 0
2681 * @param array $rootLine The root line structure to use
2683 * @return string The full domain including the protocol http:// or https://, but without the trailing '/'
2685 * @author Michael Klapper <michael.klapper@aoemedia.de>
2687 public static function getViewDomain($pageId, $rootLine = NULL) {
2688 $domain = rtrim(t3lib_div
::getIndpEnv('TYPO3_SITE_URL'), '/');
2690 if (!is_array($rootLine)) {
2691 $rootLine = self
::BEgetRootLine($pageId);
2694 // Checks alternate domains
2695 if (count($rootLine) > 0) {
2696 $urlParts = parse_url($domain);
2698 /** @var t3lib_pageSelect $sysPage */
2699 $sysPage = t3lib_div
::makeInstance('t3lib_pageSelect');
2701 $page = (array)$sysPage->getPage($pageId);
2703 if ($page['url_scheme'] == t3lib_utility_Http
::SCHEME_HTTPS ||
($page['url_scheme'] == 0 && t3lib_div
::getIndpEnv('TYPO3_SSL'))) {
2704 $protocol = 'https';
2707 $domainName = self
::firstDomainRecord($rootLine);
2710 $domain = $domainName;
2712 $domainRecord = self
::getDomainStartPage($urlParts['host'], $urlParts['path']);
2713 $domain = $domainRecord['domainName'];
2717 $domain = $protocol . '://' . $domain;
2719 $domain = rtrim(t3lib_div
::getIndpEnv('TYPO3_SITE_URL'), '/');
2727 * Returns the merged User/Page TSconfig for page id, $id.
2728 * Please read details about module programming elsewhere!
2730 * @param integer $id Page uid
2731 * @param string $TSref An object string which determines the path of the TSconfig to return.
2734 public static function getModTSconfig($id, $TSref) {
2735 $pageTS_modOptions = $GLOBALS['BE_USER']->getTSConfig($TSref, self
::getPagesTSconfig($id));
2736 $BE_USER_modOptions = $GLOBALS['BE_USER']->getTSConfig($TSref);
2737 $modTSconfig = t3lib_div
::array_merge_recursive_overrule($pageTS_modOptions, $BE_USER_modOptions);
2738 return $modTSconfig;
2742 * Returns a selector box "function menu" for a module
2743 * Requires the JS function jumpToUrl() to be available
2744 * See Inside TYPO3 for details about how to use / make Function menus
2746 * @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=...
2747 * @param string $elementName The form elements name, probably something like "SET[...]"
2748 * @param string $currentValue The value to be selected currently.
2749 * @param array $menuItems An array with the menu items for the selector box
2750 * @param string $script The script to send the &id to, if empty it's automatically found
2751 * @param string $addParams Additional parameters to pass to the script.
2752 * @return string HTML code for selector box
2754 public static function getFuncMenu($mainParams, $elementName, $currentValue, $menuItems, $script = '', $addparams = '') {
2755 if (is_array($menuItems)) {
2756 if (!is_array($mainParams)) {
2757 $mainParams = array('id' => $mainParams);
2759 $mainParams = t3lib_div
::implodeArrayForUrl('', $mainParams);
2762 $script = basename(PATH_thisScript
);
2763 $mainParams .= (t3lib_div
::_GET('M') ?
'&M=' . rawurlencode(t3lib_div
::_GET('M')) : '');
2767 foreach ($menuItems as $value => $label) {
2768 $options[] = '<option value="' . htmlspecialchars($value) . '"' . (!strcmp($currentValue, $value) ?
' selected="selected"' : '') . '>' .
2769 t3lib_div
::deHSCentities(htmlspecialchars($label)) .
2772 if (count($options)) {
2773 $onChange = 'jumpToUrl(\'' . $script . '?' . $mainParams . $addparams . '&' . $elementName . '=\'+this.options[this.selectedIndex].value,this);';
2776 <!-- Function Menu of module -->
2777 <select name="' . $elementName . '" onchange="' . htmlspecialchars($onChange) . '">
2787 * Checkbox function menu.
2788 * Works like ->getFuncMenu() but takes no $menuItem array since this is a simple checkbox.
2790 * @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=...
2791 * @param string $elementName The form elements name, probably something like "SET[...]"
2792 * @param string $currentValue The value to be selected currently.
2793 * @param string $script The script to send the &id to, if empty it's automatically found
2794 * @param string $addParams Additional parameters to pass to the script.
2795 * @param string $tagParams Additional attributes for the checkbox input tag
2796 * @return string HTML code for checkbox
2797 * @see getFuncMenu()
2799 public static function getFuncCheck($mainParams, $elementName, $currentValue, $script = '', $addparams = '', $tagParams = '') {
2800 if (!is_array($mainParams)) {
2801 $mainParams = array('id' => $mainParams);
2803 $mainParams = t3lib_div
::implodeArrayForUrl('', $mainParams);
2806 $script = basename(PATH_thisScript
);
2807 $mainParams .= (t3lib_div
::_GET('M') ?
'&M=' . rawurlencode(t3lib_div
::_GET('M')) : '');
2810 $onClick = 'jumpToUrl(\'' . $script . '?' . $mainParams . $addparams . '&' . $elementName . '=\'+(this.checked?1:0),this);';
2811 return '<input type="checkbox" class="checkbox" name="' . $elementName . '"' . ($currentValue ?
' checked="checked"' : '') . ' onclick="' . htmlspecialchars($onClick) . '"' . ($tagParams ?
' ' . $tagParams : '') . ' />';
2815 * Input field function menu
2816 * Works like ->getFuncMenu() / ->getFuncCheck() but displays a input field instead which updates the script "onchange"
2818 * @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=...
2819 * @param string $elementName The form elements name, probably something like "SET[...]"
2820 * @param string $currentValue The value to be selected currently.
2821 * @param integer $size Relative size of input field, max is 48
2822 * @param string $script The script to send the &id to, if empty it's automatically found
2823 * @param string $addParams Additional parameters to pass to the script.
2824 * @return string HTML code for input text field.
2825 * @see getFuncMenu()
2827 public static function getFuncInput($mainParams, $elementName, $currentValue, $size = 10, $script = "", $addparams = "") {
2828 if (!is_array($mainParams)) {
2829 $mainParams = array('id' => $mainParams);
2831 $mainParams = t3lib_div
::implodeArrayForUrl('', $mainParams);
2834 $script = basename(PATH_thisScript
);
2835 $mainParams .= (t3lib_div
::_GET('M') ?
'&M=' . rawurlencode(t3lib_div
::_GET('M')) : '');
2838 $onChange = 'jumpToUrl(\'' . $script . '?' . $mainParams . $addparams . '&' . $elementName . '=\'+escape(this.value),this);';
2839 return '<input type="text"' . $GLOBALS['TBE_TEMPLATE']->formWidth($size) . ' name="' . $elementName . '" value="' . htmlspecialchars($currentValue) . '" onchange="' . htmlspecialchars($onChange) . '" />';
2843 * Removes menu items from $itemArray if they are configured to be removed by TSconfig for the module ($modTSconfig)
2844 * See Inside TYPO3 about how to program modules and use this API.
2846 * @param array $modTSconfig Module TS config array
2847 * @param array $itemArray Array of items from which to remove items.
2848 * @param string $TSref $TSref points to the "object string" in $modTSconfig
2849 * @return array The modified $itemArray is returned.
2851 public static function unsetMenuItems($modTSconfig, $itemArray, $TSref) {
2852 // Getting TS-config options for this module for the Backend User:
2853 $conf = $GLOBALS['BE_USER']->getTSConfig($TSref, $modTSconfig);
2854 if (is_array($conf['properties'])) {
2855 foreach ($conf['properties'] as $key => $val) {
2857 unset($itemArray[$key]);