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