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