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