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