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