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