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