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