* When using frontend editing with pop-up window the save-and-view button will not...
[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) {
946
947 // Get pointer field etc from TCA-config:
948 $ds_pointerField = $conf['ds_pointerField'];
949 $ds_array = $conf['ds'];
950 $ds_tableField = $conf['ds_tableField'];
951 $ds_searchParentField = $conf['ds_pointerField_searchParent'];
952
953 // Find source value:
954 $dataStructArray='';
955 if (is_array($ds_array)) { // If there is a data source array, that takes precedence
956 // If a pointer field is set, take the value from that field in the $row array and use as key.
957 if ($ds_pointerField) {
958 $srcPointer = $row[$ds_pointerField];
959 $srcPointer = isset($ds_array[$srcPointer]) ? $srcPointer : 'default';
960 } else $srcPointer='default';
961
962 // 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.
963 if (substr($ds_array[$srcPointer],0,5)=='FILE:') {
964 $file = t3lib_div::getFileAbsFileName(substr($ds_array[$srcPointer],5));
965 if ($file && @is_file($file)) {
966 $dataStructArray = t3lib_div::xml2array(t3lib_div::getUrl($file));
967 } else $dataStructArray = 'The file "'.substr($dsSrc,5).'" in ds-array key "'.$srcPointer.'" was not found ("'.$file.'")'; // Error message.
968 } else {
969 $dataStructArray = t3lib_div::xml2array($ds_array[$srcPointer]);
970 }
971
972 } elseif ($ds_pointerField) { // If pointer field AND possibly a table/field is set:
973 // Value of field pointed to:
974 $srcPointer = $row[$ds_pointerField];
975
976 // Searching recursively back if 'ds_pointerField_searchParent' is defined (typ. a page rootline, or maybe a tree-table):
977 if ($ds_searchParentField && !$srcPointer) {
978 $rr = t3lib_BEfunc::getRecord($table,$row['uid'],'uid,'.$ds_searchParentField); // Get the "pid" field - we cannot know that it is in the input record!
979 t3lib_BEfunc::fixVersioningPid($table,$rr);
980 $uidAcc=array(); // Used to avoid looping, if any should happen.
981 $subFieldPointer = $conf['ds_pointerField_searchParent_subField'];
982 while(!$srcPointer) {
983 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
984 'uid,'.$ds_pointerField.','.$ds_searchParentField.($subFieldPointer?','.$subFieldPointer:''),
985 $table,
986 'uid='.intval($rr[$ds_searchParentField]).t3lib_BEfunc::deleteClause($table)
987 );
988 $rr = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
989
990 // break if no result from SQL db or if looping...
991 if (!is_array($rr) || isset($uidAcc[$rr['uid']])) break;
992 $uidAcc[$rr['uid']]=1;
993
994 t3lib_BEfunc::fixVersioningPid($table,$rr);
995 $srcPointer = ($subFieldPointer && $rr[$subFieldPointer]) ? $rr[$subFieldPointer] : $rr[$ds_pointerField];
996 }
997 }
998
999 // If there is a srcPointer value:
1000 if ($srcPointer) {
1001 if (t3lib_div::testInt($srcPointer)) { // If integer, then its a record we will look up:
1002 list($tName,$fName) = explode(':',$ds_tableField,2);
1003 if ($tName && $fName && is_array($GLOBALS['TCA'][$tName])) {
1004 $dataStructRec = t3lib_BEfunc::getRecord($tName, $srcPointer);
1005 $dataStructArray = t3lib_div::xml2array($dataStructRec[$fName]);
1006 } else $dataStructArray = 'No tablename ('.$tName.') or fieldname ('.$fName.') was found an valid!';
1007 } else { // Otherwise expect it to be a file:
1008 $file = t3lib_div::getFileAbsFileName($srcPointer);
1009 if ($file && @is_file($file)) {
1010 $dataStructArray = t3lib_div::xml2array(t3lib_div::getUrl($file));
1011 } else $dataStructArray='The file "'.$srcPointer.'" was not found ("'.$file.'")'; // Error message.
1012 }
1013 } else $dataStructArray='No source value in fieldname "'.$ds_pointerField.'"'; // Error message.
1014 } else $dataStructArray='No proper configuration!';
1015 return $dataStructArray;
1016 }
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035 /*******************************************
1036 *
1037 * Caching related
1038 *
1039 *******************************************/
1040
1041 /**
1042 * Stores the string value $data in the 'cache_hash' table with the hash key, $hash, and visual/symbolic identification, $ident
1043 * IDENTICAL to the function by same name found in t3lib_page:
1044 * Usage: 2
1045 *
1046 * @param string Hash key, 32 bytes hex
1047 * @param string $data must be serialized before function call
1048 * @param string Visual/symbolic identification (informational only)
1049 * @return void
1050 */
1051 function storeHash($hash,$data,$ident) {
1052 $insertFields = array(
1053 'hash' => $hash,
1054 'content' => $data,
1055 'ident' => $ident,
1056 'tstamp' => time()
1057 );
1058 $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_hash', 'hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($hash, 'cache_hash'));
1059 $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_hash', $insertFields);
1060 }
1061
1062 /**
1063 * Retrieves the string content stored with hash key, $hash, in cache_hash
1064 * IDENTICAL to the function by same name found in t3lib_page:
1065 * Usage: 2
1066 *
1067 * @param string Hash key, 32 bytes hex
1068 * @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.
1069 * @return string
1070 */
1071 function getHash($hash,$expTime) {
1072 // if expTime is not set, the hash will never expire
1073 $expTime = intval($expTime);
1074 if ($expTime) {
1075 $whereAdd = ' AND tstamp > '.(time()-$expTime);
1076 }
1077 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('content', 'cache_hash', 'hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($hash, 'cache_hash').$whereAdd);
1078 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1079 return $row['content'];
1080 }
1081 }
1082
1083
1084
1085
1086
1087
1088
1089
1090 /*******************************************
1091 *
1092 * TypoScript related
1093 *
1094 *******************************************/
1095
1096 /**
1097 * Returns the Page TSconfig for page with id, $id
1098 * Requires class "t3lib_TSparser"
1099 * Usage: 26 (spec. in ext info_pagetsconfig)
1100 *
1101 * @param integer Page uid for which to create Page TSconfig
1102 * @param array If $rootLine is an array, that is used as rootline, otherwise rootline is just calculated
1103 * @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.
1104 * @return array Page TSconfig
1105 * @see t3lib_TSparser
1106 */
1107 function getPagesTSconfig($id,$rootLine='',$returnPartArray=0) {
1108 $id=intval($id);
1109 if (!is_array($rootLine)) {
1110 $rootLine = t3lib_BEfunc::BEgetRootLine($id,'');
1111 }
1112 ksort($rootLine); // Order correctly, changed 030102
1113 reset($rootLine);
1114 $TSdataArray = array();
1115 $TSdataArray['defaultPageTSconfig']=$GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPageTSconfig']; // Setting default configuration:
1116 while(list($k,$v)=each($rootLine)) {
1117 $TSdataArray['uid_'.$v['uid']]=$v['TSconfig'];
1118 }
1119 $TSdataArray = t3lib_TSparser::checkIncludeLines_array($TSdataArray);
1120 if ($returnPartArray) {
1121 return $TSdataArray;
1122 }
1123
1124 // Parsing the user TS (or getting from cache)
1125 $userTS = implode($TSdataArray,chr(10).'[GLOBAL]'.chr(10));
1126 $hash = md5('pageTS:'.$userTS);
1127 $cachedContent = t3lib_BEfunc::getHash($hash,0);
1128 $TSconfig = array();
1129 if (isset($cachedContent)) {
1130 $TSconfig = unserialize($cachedContent);
1131 } else {
1132 $parseObj = t3lib_div::makeInstance('t3lib_TSparser');
1133 $parseObj->parse($userTS);
1134 $TSconfig = $parseObj->setup;
1135 t3lib_BEfunc::storeHash($hash,serialize($TSconfig),'PAGES_TSconfig');
1136 }
1137 return $TSconfig;
1138 }
1139
1140 /**
1141 * Updates Page TSconfig for a page with $id
1142 * 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.
1143 * $impParams can be supplied as already known Page TSconfig, otherwise it's calculated.
1144 *
1145 * THIS DOES NOT CHECK ANY PERMISSIONS. SHOULD IT?
1146 * More documentation is needed.
1147 *
1148 * Usage: 1 (ext. direct_mail)
1149 *
1150 * @param integer Page id
1151 * @param array Page TS array to write
1152 * @param string Prefix for object paths
1153 * @param array [Description needed.]
1154 * @return void
1155 * @internal
1156 * @see implodeTSParams(), getPagesTSconfig()
1157 */
1158 function updatePagesTSconfig($id,$pageTS,$TSconfPrefix,$impParams='') {
1159 $id=intval($id);
1160 if (is_array($pageTS) && $id>0) {
1161 if (!is_array($impParams)) {
1162 $impParams =t3lib_BEfunc::implodeTSParams(t3lib_BEfunc::getPagesTSconfig($id));
1163 }
1164 reset($pageTS);
1165 $set=array();
1166 while(list($f,$v)=each($pageTS)) {
1167 $f = $TSconfPrefix.$f;
1168 if ((!isset($impParams[$f])&&trim($v)) || strcmp(trim($impParams[$f]),trim($v))) {
1169 $set[$f]=trim($v);
1170 }
1171 }
1172 if (count($set)) {
1173 // Get page record and TS config lines
1174 $pRec = t3lib_befunc::getRecord('pages',$id);
1175 $TSlines = explode(chr(10),$pRec['TSconfig']);
1176 $TSlines = array_reverse($TSlines);
1177 // Reset the set of changes.
1178 reset($set);
1179 while(list($f,$v)=each($set)) {
1180 reset($TSlines);
1181 $inserted=0;
1182 while(list($ki,$kv)=each($TSlines)) {
1183 if (substr($kv,0,strlen($f)+1)==$f.'=') {
1184 $TSlines[$ki]=$f.'='.$v;
1185 $inserted=1;
1186 break;
1187 }
1188 }
1189 if (!$inserted) {
1190 $TSlines = array_reverse($TSlines);
1191 $TSlines[]=$f.'='.$v;
1192 $TSlines = array_reverse($TSlines);
1193 }
1194 }
1195 $TSlines = array_reverse($TSlines);
1196
1197 // store those changes
1198 $TSconf = implode(chr(10),$TSlines);
1199
1200 $GLOBALS['TYPO3_DB']->exec_UPDATEquery('pages', 'uid='.intval($id), array('TSconfig' => $TSconf));
1201 }
1202 }
1203 }
1204
1205 /**
1206 * Implodes a multi dimensional TypoScript array, $p, into a one-dimentional array (return value)
1207 * Usage: 3
1208 *
1209 * @param array TypoScript structure
1210 * @param string Prefix string
1211 * @return array Imploded TypoScript objectstring/values
1212 */
1213 function implodeTSParams($p,$k='') {
1214 $implodeParams=array();
1215 if (is_array($p)) {
1216 reset($p);
1217 while(list($kb,$val)=each($p)) {
1218 if (is_array($val)) {
1219 $implodeParams = array_merge($implodeParams,t3lib_BEfunc::implodeTSParams($val,$k.$kb));
1220 } else {
1221 $implodeParams[$k.$kb]=$val;
1222 }
1223 }
1224 }
1225 return $implodeParams;
1226 }
1227
1228
1229
1230
1231
1232
1233
1234
1235 /*******************************************
1236 *
1237 * Users / Groups related
1238 *
1239 *******************************************/
1240
1241 /**
1242 * Returns an array with be_users records of all user NOT DELETED sorted by their username
1243 * Keys in the array is the be_users uid
1244 * Usage: 14 (spec. ext. "beuser" and module "web_perm")
1245 *
1246 * @param string Optional $fields list (default: username,usergroup,usergroup_cached_list,uid) can be used to set the selected fields
1247 * @param string Optional $where clause (fx. "AND username='pete'") can be used to limit query
1248 * @return array
1249 */
1250 function getUserNames($fields='username,usergroup,usergroup_cached_list,uid',$where='') {
1251 $be_user_Array=Array();
1252
1253 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fields, 'be_users', 'pid=0 '.$where.t3lib_BEfunc::deleteClause('be_users'), '', 'username');
1254 while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1255 $be_user_Array[$row['uid']]=$row;
1256 }
1257 return $be_user_Array;
1258 }
1259
1260 /**
1261 * Returns an array with be_groups records (title, uid) of all groups NOT DELETED sorted by their title
1262 * Usage: 8 (spec. ext. "beuser" and module "web_perm")
1263 *
1264 * @param string Field list
1265 * @param string WHERE clause
1266 * @return array
1267 */
1268 function getGroupNames($fields='title,uid', $where='') {
1269 $be_group_Array = Array();
1270 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fields, 'be_groups', 'pid=0 '.$where.t3lib_BEfunc::deleteClause('be_groups'), '', 'title');
1271 while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1272 $be_group_Array[$row['uid']] = $row;
1273 }
1274 return $be_group_Array;
1275 }
1276
1277 /**
1278 * Returns an array with be_groups records (like ->getGroupNames) but:
1279 * - 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.
1280 * Usage: 2 (module "web_perm" and ext. taskcenter)
1281 *
1282 * @param string Field list; $fields specify the fields selected (default: title,uid)
1283 * @return array
1284 */
1285 function getListGroupNames($fields='title,uid') {
1286 $exQ=' AND hide_in_lists=0';
1287 if (!$GLOBALS['BE_USER']->isAdmin()) {
1288 $exQ.=' AND uid IN ('.($GLOBALS['BE_USER']->user['usergroup_cached_list']?$GLOBALS['BE_USER']->user['usergroup_cached_list']:0).')';
1289 }
1290 return t3lib_BEfunc::getGroupNames($fields,$exQ);
1291 }
1292
1293 /**
1294 * Returns the array $usernames with the names of all users NOT IN $groupArray changed to the uid (hides the usernames!).
1295 * If $excludeBlindedFlag is set, then these records are unset from the array $usernames
1296 * Takes $usernames (array made by t3lib_BEfunc::getUserNames()) and a $groupArray (array with the groups a certain user is member of) as input
1297 * Usage: 8
1298 *
1299 * @param array User names
1300 * @param array Group names
1301 * @param boolean If $excludeBlindedFlag is set, then these records are unset from the array $usernames
1302 * @return array User names, blinded
1303 */
1304 function blindUserNames($usernames,$groupArray,$excludeBlindedFlag=0) {
1305 if (is_array($usernames) && is_array($groupArray)) {
1306 while(list($uid,$row)=each($usernames)) {
1307 $userN=$uid;
1308 $set=0;
1309 if ($row['uid']!=$GLOBALS['BE_USER']->user['uid']) {
1310 reset($groupArray);
1311 while(list(,$v)=each($groupArray)) {
1312 if ($v && t3lib_div::inList($row['usergroup_cached_list'],$v)) {
1313 $userN = $row['username'];
1314 $set=1;
1315 }
1316 }
1317 } else {
1318 $userN = $row['username'];
1319 $set=1;
1320 }
1321 $usernames[$uid]['username']=$userN;
1322 if ($excludeBlindedFlag && !$set) {unset($usernames[$uid]);}
1323 }
1324 }
1325 return $usernames;
1326 }
1327
1328 /**
1329 * Corresponds to blindUserNames but works for groups instead
1330 * Usage: 2 (module web_perm)
1331 *
1332 * @param array Group names
1333 * @param array Group names (reference)
1334 * @param boolean If $excludeBlindedFlag is set, then these records are unset from the array $usernames
1335 * @return array
1336 */
1337 function blindGroupNames($groups,$groupArray,$excludeBlindedFlag=0) {
1338 if (is_array($groups) && is_array($groupArray)) {
1339 while(list($uid,$row)=each($groups)) {
1340 $groupN=$uid;
1341 $set=0;
1342 if (t3lib_div::inArray($groupArray,$uid)) {
1343 $groupN=$row['title'];
1344 $set=1;
1345 }
1346 $groups[$uid]['title']=$groupN;
1347 if ($excludeBlindedFlag && !$set) {unset($groups[$uid]);}
1348 }
1349 }
1350 return $groups;
1351 }
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365 /*******************************************
1366 *
1367 * Output related
1368 *
1369 *******************************************/
1370
1371 /**
1372 * Returns the difference in days between input $tstamp and $EXEC_TIME
1373 * Usage: 2 (class t3lib_BEfunc)
1374 *
1375 * @param integer Time stamp, seconds
1376 * @return integer
1377 */
1378 function daysUntil($tstamp) {
1379 $delta_t = $tstamp-$GLOBALS['EXEC_TIME'];
1380 return ceil($delta_t/(3600*24));
1381 }
1382
1383 /**
1384 * Returns $tstamp formatted as "ddmmyy" (According to $TYPO3_CONF_VARS['SYS']['ddmmyy'])
1385 * Usage: 11
1386 *
1387 * @param integer Time stamp, seconds
1388 * @return string Formatted time
1389 */
1390 function date($tstamp) {
1391 return date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'],$tstamp);
1392 }
1393
1394 /**
1395 * Returns $tstamp formatted as "ddmmyy hhmm" (According to $TYPO3_CONF_VARS['SYS']['ddmmyy'] AND $TYPO3_CONF_VARS['SYS']['hhmm'])
1396 * Usage: 28
1397 *
1398 * @param integer Time stamp, seconds
1399 * @return string Formatted time
1400 */
1401 function datetime($value) {
1402 return date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'].' '.$GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'], $value);
1403 }
1404
1405 /**
1406 * Returns $value (in seconds) formatted as hh:mm:ss
1407 * For instance $value = 3600 + 60*2 + 3 should return "01:02:03"
1408 * Usage: 1 (class t3lib_BEfunc)
1409 *
1410 * @param integer Time stamp, seconds
1411 * @return string Formatted time
1412 */
1413 function time($value) {
1414 $hh = floor($value/3600);
1415 $min = floor(($value-$hh*3600)/60);
1416 $sec = $value-$hh*3600-$min*60;
1417 $l = sprintf('%02d',$hh).':'.sprintf('%02d',$min).':'.sprintf('%02d',$sec);
1418 return $l;
1419 }
1420
1421 /**
1422 * Returns the "age" in minutes / hours / days / years of the number of $seconds inputted.
1423 * Usage: 15
1424 *
1425 * @param integer $seconds could be the difference of a certain timestamp and time()
1426 * @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")
1427 * @return string Formatted time
1428 */
1429 function calcAge($seconds,$labels = 'min|hrs|days|yrs') {
1430 $labelArr = explode('|',$labels);
1431 $prefix='';
1432 if ($seconds<0) {$prefix='-'; $seconds=abs($seconds);}
1433 if ($seconds<3600) {
1434 $seconds = round ($seconds/60).' '.trim($labelArr[0]);
1435 } elseif ($seconds<24*3600) {
1436 $seconds = round ($seconds/3600).' '.trim($labelArr[1]);
1437 } elseif ($seconds<365*24*3600) {
1438 $seconds = round ($seconds/(24*3600)).' '.trim($labelArr[2]);
1439 } else {
1440 $seconds = round ($seconds/(365*24*3600)).' '.trim($labelArr[3]);
1441 }
1442 return $prefix.$seconds;
1443 }
1444
1445 /**
1446 * Returns a formatted timestamp if $tstamp is set.
1447 * The date/datetime will be followed by the age in parenthesis.
1448 * Usage: 3
1449 *
1450 * @param integer Time stamp, seconds
1451 * @param integer 1/-1 depending on polarity of age.
1452 * @param string $date=="date" will yield "dd:mm:yy" formatting, otherwise "dd:mm:yy hh:mm"
1453 * @return string
1454 */
1455 function dateTimeAge($tstamp,$prefix=1,$date='') {
1456 return $tstamp ?
1457 ($date=='date' ? t3lib_BEfunc::date($tstamp) : t3lib_BEfunc::datetime($tstamp)).
1458 ' ('.t3lib_BEfunc::calcAge($prefix*(time()-$tstamp),$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears')).')' : '';
1459 }
1460
1461 /**
1462 * Returns either title='' or alt='' attribute. This depends on the client browser and whether it supports title='' or not (which is the default)
1463 * If no $content is given only the attribute name is returned.
1464 * The returned attribute with content will have a leading space char.
1465 * Warning: Be careful to submit empty $content var - that will return just the attribute name!
1466 * Usage: 0
1467 *
1468 * @param string String to set as title-attribute. If no $content is given only the attribute name is returned.
1469 * @param boolean If $hsc is set, then content of the attribute is htmlspecialchar()'ed (which is good for XHTML and other reasons...)
1470 * @return string
1471 * @depreciated The idea made sense with older browsers, but now all browsers should support the "title" attribute - so just hardcode the title attribute instead!
1472 */
1473 function titleAttrib($content='',$hsc=0) {
1474 global $CLIENT;
1475 $attrib= ($CLIENT['BROWSER']=='net'&&$CLIENT['VERSION']<5)||$CLIENT['BROWSER']=='konqu' ? 'alt' : 'title';
1476 return strcmp($content,'')?' '.$attrib.'="'.($hsc?htmlspecialchars($content):$content).'"' : $attrib;
1477 }
1478
1479 /**
1480 * Returns alt="" and title="" attributes with the value of $content.
1481 * Usage: 7
1482 *
1483 * @param string Value for 'alt' and 'title' attributes (will be htmlspecialchars()'ed before output)
1484 * @return string
1485 */
1486 function titleAltAttrib($content) {
1487 $out='';
1488 $out.=' alt="'.htmlspecialchars($content).'"';
1489 $out.=' title="'.htmlspecialchars($content).'"';
1490 return $out;
1491 }
1492
1493 /**
1494 * 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
1495 * All $TYPO3_CONF_VARS['GFX']['imagefile_ext'] extension are made to thumbnails + ttf file (renders font-example)
1496 * Thumbsnails are linked to the show_item.php script which will display further details.
1497 * Usage: 7
1498 *
1499 * @param array $row is the database row from the table, $table.
1500 * @param string Table name for $row (present in TCA)
1501 * @param string $field is pointing to the field with the list of image files
1502 * @param string Back path prefix for image tag src="" field
1503 * @param string Optional: $thumbScript os by default 'thumbs.php' if you don't set it otherwise
1504 * @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!)
1505 * @param boolean If set, uploaddir is NOT prepended with "../"
1506 * @param string Optional: $tparams is additional attributes for the image tags
1507 * @param integer Optional: $size is [w]x[h] of the thumbnail. 56 is default.
1508 * @return string Thumbnail image tag.
1509 */
1510 function thumbCode($row,$table,$field,$backPath,$thumbScript='',$uploaddir=NULL,$abs=0,$tparams='',$size='') {
1511 global $TCA;
1512 // Load table.
1513 t3lib_div::loadTCA($table);
1514
1515 // Find uploaddir automatically
1516 $uploaddir = (is_null($uploaddir)) ? $TCA[$table]['columns'][$field]['config']['uploadfolder'] : $uploaddir;
1517 $uploaddir = preg_replace('#/$#','',$uploaddir);
1518
1519 // Set thumbs-script:
1520 if (!$GLOBALS['TYPO3_CONF_VARS']['GFX']['thumbnails']) {
1521 $thumbScript='gfx/notfound_thumb.gif';
1522 } elseif(!$thumbScript) {
1523 $thumbScript='thumbs.php';
1524 }
1525 // Check and parse the size parameter
1526 $sizeParts=array();
1527 if ($size = trim($size)) {
1528 $sizeParts = explode('x', $size.'x'.$size);
1529 if(!intval($sizeParts[0])) $size='';
1530 }
1531
1532 // Traverse files:
1533 $thumbs = explode(',', $row[$field]);
1534 $thumbData='';
1535 while(list(,$theFile)=each($thumbs)) {
1536 if (trim($theFile)) {
1537 $fI = t3lib_div::split_fileref($theFile);
1538 $ext = $fI['fileext'];
1539 // New 190201 start
1540 $max=0;
1541 if (t3lib_div::inList('gif,jpg,png',$ext)) {
1542 $imgInfo=@getimagesize(PATH_site.$uploaddir.'/'.$theFile);
1543 if (is_array($imgInfo)) {$max = max($imgInfo[0],$imgInfo[1]);}
1544 }
1545 // use the original image if it's size fits to the thumbnail size
1546 if ($max && $max<=(count($sizeParts)&&max($sizeParts)?max($sizeParts):56)) {
1547 $url = $uploaddir.'/'.trim($theFile);
1548 $theFile = '../'.$url;
1549 $onClick='top.launchView(\''.$theFile.'\',\'\',\''.$backPath.'\');return false;';
1550 $thumbData.='<a href="#" onclick="'.htmlspecialchars($onClick).'"><img src="../'.$backPath.$url.'" '.$imgInfo[3].' hspace="2" border="0" title="'.trim($url).'"'.$tparams.' alt="" /></a> ';
1551 // New 190201 stop
1552 } elseif ($ext=='ttf' || t3lib_div::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'],$ext)) {
1553 $theFile = ($abs?'':'../').($uploaddir?$uploaddir.'/':'').trim($theFile);
1554 $params = '&file='.rawurlencode($theFile);
1555 $params .= $size?'&size='.$size:'';
1556 $url = $thumbScript.'?&dummy='.$GLOBALS['EXEC_TIME'].$params;
1557 $onClick='top.launchView(\''.$theFile.'\',\'\',\''.$backPath.'\');return false;';
1558 $thumbData.='<a href="#" onclick="'.htmlspecialchars($onClick).'"><img src="'.htmlspecialchars($backPath.$url).'" hspace="2" border="0" title="'.trim($theFile).'"'.$tparams.' alt="" /></a> ';
1559 } else {
1560 $icon = t3lib_BEfunc::getFileIcon($ext);
1561 $url = 'gfx/fileicons/'.$icon;
1562 $thumbData.='<img src="'.$backPath.$url.'" hspace="2" border="0" title="'.trim($theFile).'"'.$tparams.' alt="" /> ';
1563 }
1564 }
1565 }
1566 return $thumbData;
1567 }
1568
1569 /**
1570 * Returns single image tag to thumbnail using a thumbnail script (like thumbs.php)
1571 * Usage: 3
1572 *
1573 * @param string $thumbScript must point to "thumbs.php" relative to the script position
1574 * @param string $theFile must be the proper reference to the file thumbs.php should show
1575 * @param string $tparams are additional attributes for the image tag
1576 * @param integer $size is the size of the thumbnail send along to "thumbs.php"
1577 * @return string Image tag
1578 */
1579 function getThumbNail($thumbScript,$theFile,$tparams='',$size='') {
1580 $params = '&file='.rawurlencode($theFile);
1581 $params .= trim($size)?'&size='.trim($size):'';
1582 $url = $thumbScript.'?&dummy='.$GLOBALS['EXEC_TIME'].$params;
1583 $th='<img src="'.htmlspecialchars($url).'" title="'.trim(basename($theFile)).'"'.($tparams?" ".$tparams:"").' alt="" />';
1584 return $th;
1585 }
1586
1587 /**
1588 * Returns title-attribute information for a page-record informing about id, alias, doktype, hidden, starttime, endtime, fe_group etc.
1589 * Usage: 8
1590 *
1591 * @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)
1592 * @param string $perms_clause is used to get the record path of the shortcut page, if any (and doktype==4)
1593 * @param boolean If $includeAttrib is set, then the 'title=""' attribute is wrapped about the return value, which is in any case htmlspecialchar()'ed already
1594 * @return string
1595 */
1596 function titleAttribForPages($row,$perms_clause='',$includeAttrib=1) {
1597 global $TCA,$LANG;
1598 $parts=array();
1599 $parts[] = 'id='.$row['uid'];
1600 if ($row['alias']) $parts[]=$LANG->sL($TCA['pages']['columns']['alias']['label']).' '.$row['alias'];
1601 if ($row['t3ver_id']) $parts[] = 'v#'.$row['t3ver_id'];
1602 if ($row['doktype']=='3') {
1603 $parts[]=$LANG->sL($TCA['pages']['columns']['url']['label']).' '.$row['url'];
1604 } elseif ($row['doktype']=='4') {
1605 if ($perms_clause) {
1606 $label = t3lib_BEfunc::getRecordPath(intval($row['shortcut']),$perms_clause,20);
1607 } else {
1608 $lRec = t3lib_BEfunc::getRecord('pages',intval($row['shortcut']),'title');
1609 $label = $lRec['title'];
1610 }
1611 if ($row['shortcut_mode']>0) {
1612 $label.=', '.$LANG->sL($TCA['pages']['columns']['shortcut_mode']['label']).' '.
1613 $LANG->sL(t3lib_BEfunc::getLabelFromItemlist('pages','shortcut_mode',$row['shortcut_mode']));
1614 }
1615 $parts[]=$LANG->sL($TCA['pages']['columns']['shortcut']['label']).' '.$label;
1616 } elseif ($row['doktype']=='7') {
1617 if ($perms_clause) {
1618 $label = t3lib_BEfunc::getRecordPath(intval($row['mount_pid']),$perms_clause,20);
1619 } else {
1620 $lRec = t3lib_BEfunc::getRecord('pages',intval($row['mount_pid']),'title');
1621 $label = $lRec['title'];
1622 }
1623 $parts[]=$LANG->sL($TCA['pages']['columns']['mount_pid']['label']).' '.$label;
1624 if ($row['mount_pid_ol']) {
1625 $parts[] = $LANG->sL($TCA['pages']['columns']['mount_pid_ol']['label']);
1626 }
1627 }
1628 if ($row['nav_hide']) $parts[] = ereg_replace(':$','',$LANG->sL($TCA['pages']['columns']['nav_hide']['label']));
1629 if ($row['hidden']) $parts[] = $LANG->sL('LLL:EXT:lang/locallang_core.php:labels.hidden');
1630 if ($row['starttime']) $parts[] = $LANG->sL($TCA['pages']['columns']['starttime']['label']).' '.t3lib_BEfunc::dateTimeAge($row['starttime'],-1,'date');
1631 if ($row['endtime']) $parts[] = $LANG->sL($TCA['pages']['columns']['endtime']['label']).' '.t3lib_BEfunc::dateTimeAge($row['endtime'],-1,'date');
1632 if ($row['fe_group']) {
1633 if ($row['fe_group']<0) {
1634 $label = $LANG->sL(t3lib_BEfunc::getLabelFromItemlist('pages','fe_group',$row['fe_group']));
1635 } else {
1636 $lRec = t3lib_BEfunc::getRecord('fe_groups',$row['fe_group'],'title');
1637 $label = $lRec['title'];
1638 }
1639 $parts[] = $LANG->sL($TCA['pages']['columns']['fe_group']['label']).' '.$label;
1640 }
1641 $out = htmlspecialchars(implode(' - ',$parts));
1642 return $includeAttrib ? 'title="'.$out.'"' : $out;
1643 }
1644
1645 /**
1646 * Returns title-attribute information for ANY record (from a table defined in TCA of course)
1647 * 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.
1648 * "pages" table can be used as well and will return the result of ->titleAttribForPages() for that page.
1649 * Usage: 10
1650 *
1651 * @param array Table row; $row is a row from the table, $table
1652 * @param string Table name
1653 * @return string
1654 */
1655 function getRecordIconAltText($row,$table='pages') {
1656 if ($table=='pages') {
1657 $out = t3lib_BEfunc::titleAttribForPages($row,'',0);
1658 } else {
1659 $ctrl = $GLOBALS['TCA'][$table]['ctrl']['enablecolumns'];
1660
1661 $out='id='.$row['uid']; // Uid is added
1662 if ($table=='pages' && $row['alias']) {
1663 $out.=' / '.$row['alias'];
1664 }
1665 if ($GLOBALS['TCA'][$table]['ctrl']['versioning'] && $row['t3ver_id']) {
1666 $out.=' - v#'.$row['t3ver_id'];
1667 }
1668 if ($ctrl['disabled']) { // Hidden ...
1669 $out.=($row[$ctrl['disabled']]?' - '.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.hidden'):'');
1670 }
1671 if ($ctrl['starttime']) {
1672 if ($row[$ctrl['starttime']] > $GLOBALS['EXEC_TIME']) {
1673 $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').')';
1674 }
1675 }
1676 if ($row[$ctrl['endtime']]) {
1677 $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').')';
1678 }
1679 }
1680 return htmlspecialchars($out);
1681 }
1682
1683 /**
1684 * Returns the label of the first found entry in an "items" array from $TCA (tablename=$table/fieldname=$col) where the value is $key
1685 * Usage: 9
1686 *
1687 * @param string Table name, present in $TCA
1688 * @param string Field name, present in $TCA
1689 * @param string items-array value to match
1690 * @return string Label for item entry
1691 */
1692 function getLabelFromItemlist($table,$col,$key) {
1693 global $TCA;
1694 // Load full TCA for $table
1695 t3lib_div::loadTCA($table);
1696
1697 // Check, if there is an "items" array:
1698 if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$col]) && is_array($TCA[$table]['columns'][$col]['config']['items'])) {
1699 // Traverse the items-array...
1700 reset($TCA[$table]['columns'][$col]['config']['items']);
1701 while(list($k,$v)=each($TCA[$table]['columns'][$col]['config']['items'])) {
1702 // ... and return the first found label where the value was equal to $key
1703 if (!strcmp($v[1],$key)) return $v[0];
1704 }
1705 }
1706 }
1707
1708 /**
1709 * Returns the label-value for fieldname $col in table, $table
1710 * 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>'
1711 * Usage: 17
1712 *
1713 * @param string Table name, present in $TCA
1714 * @param string Field name
1715 * @param string Wrap value - set function description
1716 * @return string
1717 */
1718 function getItemLabel($table,$col,$printAllWrap='') {
1719 global $TCA;
1720 // Load full TCA for $table
1721 t3lib_div::loadTCA($table);
1722 // Check if column exists
1723 if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$col])) {
1724 // Re
1725 return $TCA[$table]['columns'][$col]['label'];
1726 }
1727 if ($printAllWrap) {
1728 $parts = explode('|',$printAllWrap);
1729 return $parts[0].$col.$parts[1];
1730 }
1731 }
1732
1733 /**
1734 * Returns the "title"-value in record, $row, from table, $table
1735 * The field(s) from which the value is taken is determined by the "ctrl"-entries 'label', 'label_alt' and 'label_alt_force'
1736 * Usage: 26
1737 *
1738 * @param string Table name, present in TCA
1739 * @param array Row from table
1740 * @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
1741 * @return string
1742 */
1743 function getRecordTitle($table,$row,$prep=0) {
1744 global $TCA;
1745 if (is_array($TCA[$table])) {
1746 $t = $row[$TCA[$table]['ctrl']['label']];
1747 if ($TCA[$table]['ctrl']['label_alt'] && ($TCA[$table]['ctrl']['label_alt_force'] || !strcmp($t,''))) {
1748 $altFields=t3lib_div::trimExplode(',',$TCA[$table]['ctrl']['label_alt'],1);
1749 $tA=array();
1750 $tA[]=$t;
1751 while(list(,$fN)=each($altFields)) {
1752 $t = $tA[] = trim(strip_tags($row[$fN]));
1753 if (strcmp($t,'') && !$TCA[$table]['ctrl']['label_alt_force']) break;
1754 }
1755 if ($TCA[$table]['ctrl']['label_alt_force']) $t=implode(', ',$tA);
1756 }
1757 if ($prep) {
1758 $t = htmlspecialchars(t3lib_div::fixed_lgd_cs($t,$GLOBALS['BE_USER']->uc['titleLen']));
1759 if (!strcmp(trim($t),'')) $t='<em>['.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.no_title',1).']</em>';
1760 }
1761 return $t;
1762 }
1763 }
1764
1765 /**
1766 * Returns a human readable output of a value from a record
1767 * 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.
1768 * $table/$col is tablename and fieldname
1769 * REMEMBER to pass the output through htmlspecialchars() if you output it to the browser! (To protect it from XSS attacks and be XHTML compliant)
1770 * Usage: 24
1771 *
1772 * @param string Table name, present in TCA
1773 * @param string Field name, present in TCA
1774 * @param string $value is the value of that field from a selected record
1775 * @param integer $fixed_lgd_chars is the max amount of characters the value may occupy
1776 * @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")
1777 * @param boolean If set, no records will be looked up, UIDs are just shown.
1778 * @param integer uid of the current record
1779 * @return string
1780 */
1781 function getProcessedValue($table,$col,$value,$fixed_lgd_chars=0,$defaultPassthrough=0,$noRecordLookup=FALSE,$uid=0) {
1782 global $TCA;
1783 // Load full TCA for $table
1784 t3lib_div::loadTCA($table);
1785 // Check if table and field is configured:
1786 if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$col])) {
1787 // Depending on the fields configuration, make a meaningful output value.
1788 $theColConf = $TCA[$table]['columns'][$col]['config'];
1789 $l='';
1790 switch((string)$theColConf['type']) {
1791 case 'radio':
1792 $l=t3lib_BEfunc::getLabelFromItemlist($table,$col,$value);
1793 break;
1794 case 'select':
1795 if ($theColConf['MM']) {
1796 // Display the title of MM related records in lists
1797 $MMres = $GLOBALS['TYPO3_DB']->exec_SELECT_mm_query(
1798 $theColConf['foreign_table'].'.'.$TCA[$theColConf['foreign_table']]['ctrl']['label'],
1799 $table,
1800 $theColConf['MM'],
1801 $theColConf['foreign_table'],
1802 'AND '.$table.'.uid ='.intval($uid).t3lib_BEfunc::deleteClause($theColConf['foreign_table'])
1803 );
1804 if ($MMres) {
1805 while($MMrow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($MMres)) {
1806 $mmlA[] = $MMrow[$TCA[$theColConf['foreign_table']]['ctrl']['label']];
1807 }
1808 if (is_array($mmlA)) {
1809 $l=implode(', ',$mmlA);
1810 } else {
1811 $l = '';
1812 }
1813 } else {
1814 $l = 'n/A';
1815 }
1816 } else {
1817 $l = t3lib_BEfunc::getLabelFromItemlist($table,$col,$value);
1818 $l = $GLOBALS['LANG']->sL($l);
1819 if ($theColConf['foreign_table'] && !$l && $TCA[$theColConf['foreign_table']]) {
1820 if ($noRecordLookup) {
1821 $l = $value;
1822 } else {
1823 $rParts = t3lib_div::trimExplode(',',$value,1);
1824 reset($rParts);
1825 $lA = array();
1826 while(list(,$rVal)=each($rParts)) {
1827 $rVal = intval($rVal);
1828 if ($rVal>0) {
1829 $r=t3lib_BEfunc::getRecord($theColConf['foreign_table'],$rVal);
1830 } else {
1831 $r=t3lib_BEfunc::getRecord($theColConf['neg_foreign_table'],-$rVal);
1832 }
1833 if (is_array($r)) {
1834 $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);
1835 } else {
1836 $lA[]=$rVal?'['.$rVal.'!]':'';
1837 }
1838 }
1839 $l = implode(',',$lA);
1840 }
1841 }
1842 }
1843 break;
1844 case 'check':
1845 if (!is_array($theColConf['items']) || count($theColConf['items'])==1) {
1846 $l = $value ? 'Yes' : '';
1847 } else {
1848 reset($theColConf['items']);
1849 $lA=Array();
1850 while(list($key,$val)=each($theColConf['items'])) {
1851 if ($value & pow(2,$key)) {$lA[]=$GLOBALS['LANG']->sL($val[0]);}
1852 }
1853 $l = implode($lA,', ');
1854 }
1855 break;
1856 case 'input':
1857 if ($value) {
1858 if (t3lib_div::inList($theColConf['eval'],'date')) {
1859 $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')).')';
1860 } elseif (t3lib_div::inList($theColConf['eval'],'time')) {
1861 $l = t3lib_BEfunc::time($value);
1862 } elseif (t3lib_div::inList($theColConf['eval'],'datetime')) {
1863 $l = t3lib_BEfunc::datetime($value);
1864 } else {
1865 $l = $value;
1866 }
1867 }
1868 break;
1869 default:
1870 if ($defaultPassthrough) {
1871 $l=$value;
1872 } elseif ($theColConf['MM']) {
1873 $l='N/A';
1874 } elseif ($value) {
1875 $l=t3lib_div::fixed_lgd_cs(strip_tags($value),200);
1876 }
1877 break;
1878 }
1879 if ($fixed_lgd_chars) {
1880 return t3lib_div::fixed_lgd_cs($l,$fixed_lgd_chars);
1881 } else {
1882 return $l;
1883 }
1884 }
1885 }
1886
1887 /**
1888 * 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.
1889 * Usage: 2
1890 *
1891 * @param string Table name, present in TCA
1892 * @param string Field name
1893 * @param string Field value
1894 * @param integer $fixed_lgd_chars is the max amount of characters the value may occupy
1895 * @param integer uid of the current record
1896 * @return string
1897 * @see getProcessedValue()
1898 */
1899 function getProcessedValueExtra($table,$fN,$fV,$fixed_lgd_chars=0,$uid=0) {
1900 global $TCA;
1901 $fVnew = t3lib_BEfunc::getProcessedValue($table,$fN,$fV,$fixed_lgd_chars,0,0,$uid);
1902 if (!isset($fVnew)) {
1903 if (is_array($TCA[$table])) {
1904 if ($fN==$TCA[$table]['ctrl']['tstamp'] || $fN==$TCA[$table]['ctrl']['crdate']) {
1905 $fVnew = t3lib_BEfunc::datetime($fV);
1906 } elseif ($fN=='pid'){
1907 $fVnew = t3lib_BEfunc::getRecordPath($fV,'1=1',20); // Fetches the path with no regard to the users permissions to select pages.
1908 } else {
1909 $fVnew = $fV;
1910 }
1911 }
1912 }
1913 return $fVnew;
1914 }
1915
1916 /**
1917 * Returns file icon name (from $FILEICONS) for the fileextension $ext
1918 * Usage: 10
1919 *
1920 * @param string File extension, lowercase
1921 * @return string File icon filename
1922 */
1923 function getFileIcon($ext) {
1924 return $GLOBALS['FILEICONS'][$ext] ? $GLOBALS['FILEICONS'][$ext] : $GLOBALS['FILEICONS']['default'];
1925 }
1926
1927 /**
1928 * Returns fields for a table, $table, which would typically be interesting to select
1929 * This includes uid, the fields defined for title, icon-field.
1930 * 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)
1931 * Usage: 3
1932 *
1933 * @param string Table name, present in TCA
1934 * @param string Table prefix
1935 * @return string List of fields.
1936 */
1937 function getCommonSelectFields($table,$prefix) {
1938 global $TCA;
1939 $fields = array();
1940 $fields[] = $prefix.'uid';
1941 $fields[] = $prefix.$TCA[$table]['ctrl']['label'];
1942
1943 if ($TCA[$table]['ctrl']['label_alt']) {
1944 $secondFields = t3lib_div::trimExplode(',',$TCA[$table]['ctrl']['label_alt'],1);
1945 foreach($secondFields as $fieldN) {
1946 $fields[] = $prefix.$fieldN;
1947 }
1948 }
1949 if ($TCA[$table]['ctrl']['versioning']) {
1950 $fields[] = $prefix.'t3ver_id';
1951 }
1952
1953 if ($TCA[$table]['ctrl']['selicon_field']) $fields[] = $prefix.$TCA[$table]['ctrl']['selicon_field'];
1954 if ($TCA[$table]['ctrl']['typeicon_column']) $fields[] = $prefix.$TCA[$table]['ctrl']['typeicon_column'];
1955
1956 if (is_array($TCA[$table]['ctrl']['enablecolumns'])) {
1957 if ($TCA[$table]['ctrl']['enablecolumns']['disabled']) $fields[] = $prefix.$TCA[$table]['ctrl']['enablecolumns']['disabled'];
1958 if ($TCA[$table]['ctrl']['enablecolumns']['starttime']) $fields[] = $prefix.$TCA[$table]['ctrl']['enablecolumns']['starttime'];
1959 if ($TCA[$table]['ctrl']['enablecolumns']['endtime']) $fields[] = $prefix.$TCA[$table]['ctrl']['enablecolumns']['endtime'];
1960 if ($TCA[$table]['ctrl']['enablecolumns']['fe_group']) $fields[] = $prefix.$TCA[$table]['ctrl']['enablecolumns']['fe_group'];
1961 }
1962
1963 return implode(',',array_unique($fields));
1964 }
1965
1966 /**
1967 * 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
1968 * <form>-tags must be supplied separately
1969 * 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.
1970 * Usage: 1 (ext. direct_mail)
1971 *
1972 * @param array Field configuration code.
1973 * @param array Defaults
1974 * @param string Prefix for formfields
1975 * @return string HTML for a form.
1976 */
1977 function makeConfigForm($configArray,$defaults,$dataPrefix) {
1978 $params = $defaults;
1979 if (is_array($configArray)) {
1980 reset($configArray);
1981 $lines=array();
1982 while(list($fname,$config)=each($configArray)) {
1983 if (is_array($config)) {
1984 $lines[$fname]='<strong>'.htmlspecialchars($config[1]).'</strong><br />';
1985 $lines[$fname].=$config[2].'<br />';
1986 switch($config[0]) {
1987 case 'string':
1988 case 'short':
1989 $formEl = '<input type="text" name="'.$dataPrefix.'['.$fname.']" value="'.$params[$fname].'"'.$GLOBALS['TBE_TEMPLATE']->formWidth($config[0]=='short'?24:48).' />';
1990 break;
1991 case 'check':
1992 $formEl = '<input type="hidden" name="'.$dataPrefix.'['.$fname.']" value="0" /><input type="checkbox" name="'.$dataPrefix.'['.$fname.']" value="1"'.($params[$fname]?' checked="checked"':'').' />';
1993 break;
1994 case 'comment':
1995 $formEl = '';
1996 break;
1997 case 'select':
1998 reset($config[3]);
1999 $opt=array();
2000 while(list($k,$v)=each($config[3])) {
2001 $opt[]='<option value="'.htmlspecialchars($k).'"'.($params[$fname]==$k?' selected="selected"':'').'>'.htmlspecialchars($v).'</option>';
2002 }
2003 $formEl = '<select name="'.$dataPrefix.'['.$fname.']">'.implode('',$opt).'</select>';
2004 break;
2005 default:
2006 debug($config);
2007 break;
2008 }
2009 $lines[$fname].=$formEl;
2010 $lines[$fname].='<br /><br />';
2011 } else {
2012 $lines[$fname]='<hr />';
2013 if ($config) $lines[$fname].='<strong>'.strtoupper(htmlspecialchars($config)).'</strong><br />';
2014 if ($config) $lines[$fname].='<br />';
2015 }
2016 }
2017 }
2018 $out = implode('',$lines);
2019 $out.='<input type="submit" name="submit" value="Update configuration" />';
2020 return $out;
2021 }
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035 /*******************************************
2036 *
2037 * Backend Modules API functions
2038 *
2039 *******************************************/
2040
2041 /**
2042 * Returns help-text icon if configured for.
2043 * TCA_DESCR must be loaded prior to this function and $BE_USER must have 'edit_showFieldHelp' set to 'icon', otherwise nothing is returned
2044 * Usage: 6
2045 *
2046 * @param string Table name
2047 * @param string Field name
2048 * @param string Back path
2049 * @param boolean Force display of icon nomatter BE_USER setting for help
2050 * @return string HTML content for a help icon/text
2051 */
2052 function helpTextIcon($table,$field,$BACK_PATH,$force=0) {
2053 global $TCA_DESCR,$BE_USER;
2054 if (is_array($TCA_DESCR[$table]) && is_array($TCA_DESCR[$table]['columns'][$field]) && ($BE_USER->uc['edit_showFieldHelp']=='icon' || $force)) {
2055 $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;';
2056 return '<a href="#" onclick="'.htmlspecialchars($onClick).'">'.
2057 '<img'.t3lib_iconWorks::skinImg($BACK_PATH,'gfx/helpbubble.gif','width="14" height="14"').' hspace="2" border="0" class="typo3-csh-icon" alt="" />'.
2058 '</a>';
2059 }
2060 }
2061
2062 /**
2063 * Returns CSH help text (description), if configured for.
2064 * TCA_DESCR must be loaded prior to this function and $BE_USER must have "edit_showFieldHelp" set to "text", otherwise nothing is returned
2065 * Will automatically call t3lib_BEfunc::helpTextIcon() to get the icon for the text.
2066 * Usage: 4
2067 *
2068 * @param string Table name
2069 * @param string Field name
2070 * @param string Back path
2071 * @param string Additional style-attribute content for wrapping table
2072 * @return string HTML content for help text
2073 */
2074 function helpText($table,$field,$BACK_PATH,$styleAttrib='') {
2075 global $TCA_DESCR,$BE_USER;
2076 if (is_array($TCA_DESCR[$table]) && is_array($TCA_DESCR[$table]['columns'][$field]) && $BE_USER->uc['edit_showFieldHelp']=='text') {
2077 $fDat = $TCA_DESCR[$table]['columns'][$field];
2078
2079 // Get Icon:
2080 $editIcon = t3lib_BEfunc::helpTextIcon(
2081 $table,
2082 $field,
2083 $BACK_PATH,
2084 TRUE
2085 );
2086 // Add title?
2087 $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;';
2088 $text =
2089 ($fDat['alttitle'] ? '<h4><a href="#" onclick="'.htmlspecialchars($onClick).'">'.$fDat['alttitle'].'</a></h4>' : '').
2090 $fDat['description'];
2091
2092 // More information to get?
2093 if ($fDat['image_descr'] || $fDat['seeAlso'] || $fDat['details'] || $fDat['syntax']) { // || $fDat['image'];
2094 $text.=' <a href="#" onclick="'.htmlspecialchars($onClick).'">'.
2095 '<img'.t3lib_iconWorks::skinImg($BACK_PATH,'gfx/rel_db.gif','width="13" height="12"').' class="absmiddle typo3-csh-more" alt="" />'.
2096 '</a>';
2097 }
2098
2099 // Additional styles?
2100 $params = $styleAttrib ? ' style="'.$styleAttrib.'"' : '';
2101
2102 // Compile table with CSH information:
2103 return '<table border="0" cellpadding="2" cellspacing="0" class="typo3-csh-inline"'.$params.'>
2104 <tr>
2105 <td valign="top" width="14">'.$editIcon.'</td>
2106 <td valign="top">'.$text.'</td>
2107 </tr>
2108 </table>';
2109 }
2110 }
2111
2112 /**
2113 * API for getting CSH icons/text for use in backend modules.
2114 * TCA_DESCR will be loaded if it isn't already
2115 * Usage: ?
2116 *
2117 * @param string Table name ('_MOD_'+module name)
2118 * @param string Field name (CSH locallang main key)
2119 * @param string Back path
2120 * @param string Wrap code for icon-mode, splitted by "|". Not used for full-text mode.
2121 * @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.
2122 * @param string Additional style-attribute content for wrapping table (full text mode only)
2123 * @return string HTML content for help text
2124 * @see helpText(), helpTextIcon()
2125 */
2126 function cshItem($table,$field,$BACK_PATH,$wrap='',$onlyIconMode=FALSE, $styleAttrib='') {
2127 global $TCA_DESCR, $LANG, $BE_USER;
2128 if ($BE_USER->uc['edit_showFieldHelp']) {
2129 $LANG->loadSingleTableDescription($table);
2130
2131 if (is_array($TCA_DESCR[$table])) {
2132 // Creating CSH icon and short description:
2133 $fullText = t3lib_BEfunc::helpText($table,$field,$BACK_PATH,$styleAttrib);
2134 $icon = t3lib_BEfunc::helpTextIcon($table,$field,$BACK_PATH,$onlyIconMode);
2135
2136 if ($fullText && !$onlyIconMode) {
2137 $output = $fullText;
2138 } else {
2139 #$output = '<span style="position:absolute; filter: alpha(opacity=50); -moz-opacity: 0.50;">'.$icon.'</span>';
2140 $output = $icon;
2141
2142 if ($output && $wrap) {
2143 $wrParts = explode('|',$wrap);
2144 $output = $wrParts[0].$output.$wrParts[1];
2145 }
2146 }
2147
2148 return $output;
2149 }
2150 }
2151 }
2152
2153 /**
2154 * 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.
2155 * REMEMBER to always htmlspecialchar() content in href-properties to ampersands get converted to entities (XHTML requirement and XSS precaution)
2156 * Usage: 35
2157 *
2158 * @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.
2159 * @param string $backPath must point back to the TYPO3_mainDir directory (where alt_doc.php is)
2160 * @param string $requestUri is an optional returnUrl you can set - automatically set to REQUEST_URI.
2161 * @return string
2162 * @see template::issueCommand()
2163 */
2164 function editOnClick($params,$backPath='',$requestUri='') {
2165 $retUrl = 'returnUrl='.($requestUri==-1?"'+T3_THIS_LOCATION+'":rawurlencode($requestUri?$requestUri:t3lib_div::getIndpEnv('REQUEST_URI')));
2166 return "document.location='".$backPath."alt_doc.php?".$retUrl.$params."'; return false;";
2167 }
2168
2169 /**
2170 * Returns a JavaScript string for viewing the page id, $id
2171 * 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.
2172 * Usage: 8
2173 *
2174 * @param integer $id is page id
2175 * @param string $backpath must point back to TYPO3_mainDir (where the site is assumed to be one level above)
2176 * @param array If root line is supplied the function will look for the first found domain record and use that URL instead (if found)
2177 * @param string $anchor is optional anchor to the URL
2178 * @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!
2179 * @param string Additional GET variables.
2180 * @param boolean If true, then the preview window will gain the focus.
2181 * @return string
2182 */
2183 function viewOnClick($id,$backPath='',$rootLine='',$anchor='',$altUrl='',$addGetVars='',$switchFocus=TRUE) {
2184 if ($altUrl) {
2185 $url = $altUrl;
2186 } else {
2187 if ($rootLine) {
2188 $parts = parse_url(t3lib_div::getIndpEnv('TYPO3_SITE_URL'));
2189 if (t3lib_BEfunc::getDomainStartPage($parts['host'],$parts['path'])) {
2190 $preUrl_temp = t3lib_BEfunc::firstDomainRecord($rootLine);
2191 }
2192 }
2193 $preUrl = $preUrl_temp ? (t3lib_div::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://').$preUrl_temp : $backPath.'..';
2194 $url = $preUrl.'/index.php?id='.$id.$addGetVars.$anchor;
2195 }
2196
2197 return "previewWin=window.open('".$url."','newTypo3FrontendWindow','status=1,menubar=1,resizable=1,location=1,scrollbars=1,toolbar=1');".
2198 ($switchFocus ? 'previewWin.focus();' : '');
2199 }
2200
2201 /**
2202 * Returns the merged User/Page TSconfig for page id, $id.
2203 * Please read details about module programming elsewhere!
2204 * Usage: 15
2205 *
2206 * @param integer Page uid
2207 * @param string $TSref is an object string which determines the path of the TSconfig to return.
2208 * @return array
2209 */
2210 function getModTSconfig($id,$TSref) {
2211 $pageTS_modOptions = $GLOBALS['BE_USER']->getTSConfig($TSref,t3lib_BEfunc::getPagesTSconfig($id));
2212 $BE_USER_modOptions = $GLOBALS['BE_USER']->getTSConfig($TSref);
2213 $modTSconfig = t3lib_div::array_merge_recursive_overrule($pageTS_modOptions,$BE_USER_modOptions);
2214 return $modTSconfig;
2215 }
2216
2217 /**
2218 * Returns a selector box "function menu" for a module
2219 * Requires the JS function jumpToUrl() to be available
2220 * See Inside TYPO3 for details about how to use / make Function menus
2221 * Usage: 50
2222 *
2223 * @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=...
2224 * @param string $elementName it the form elements name, probably something like "SET[...]"
2225 * @param string $currentValue is the value to be selected currently.
2226 * @param array $menuItems is an array with the menu items for the selector box
2227 * @param string $script is the script to send the &id to, if empty it's automatically found
2228 * @param string $addParams is additional parameters to pass to the script.
2229 * @return string HTML code for selector box
2230 */
2231 function getFuncMenu($mainParams,$elementName,$currentValue,$menuItems,$script='',$addparams='') {
2232 if (is_array($menuItems)) {
2233 if (!is_array($mainParams)) {
2234 $mainParams = array('id' => $mainParams);
2235 }
2236 $mainParams = t3lib_div::implodeArrayForUrl('',$mainParams);
2237
2238 if (!$script) { $script=basename(PATH_thisScript); }
2239
2240 $options = array();
2241 foreach($menuItems as $value => $label) {
2242 $options[] = '<option value="'.htmlspecialchars($value).'"'.(!strcmp($currentValue,$value)?' selected="selected"':'').'>'.
2243 t3lib_div::deHSCentities(htmlspecialchars($label)).
2244 '</option>';
2245 }
2246 if (count($options)) {
2247 $onChange = 'jumpToUrl(\''.$script.'?'.$mainParams.$addparams.'&'.$elementName.'=\'+this.options[this.selectedIndex].value,this);';
2248 return '
2249
2250 <!-- Function Menu of module -->
2251 <select name="'.$elementName.'" onchange="'.htmlspecialchars($onChange).'">
2252 '.implode('
2253 ',$options).'
2254 </select>
2255 ';
2256 }
2257 }
2258 }
2259
2260 /**
2261 * Checkbox function menu.
2262 * Works like ->getFuncMenu() but takes no $menuItem array since this is a simple checkbox.
2263 * Usage: 34
2264 *
2265 * @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=...
2266 * @param string $elementName it the form elements name, probably something like "SET[...]"
2267 * @param string $currentValue is the value to be selected currently.
2268 * @param string $script is the script to send the &id to, if empty it's automatically found
2269 * @param string $addParams is additional parameters to pass to the script.
2270 * @param string Additional attributes for the checkbox input tag
2271 * @return string HTML code for checkbox
2272 * @see getFuncMenu()
2273 */
2274 function getFuncCheck($mainParams,$elementName,$currentValue,$script='',$addparams='',$tagParams='') {
2275 if (!is_array($mainParams)) {
2276 $mainParams = array('id' => $mainParams);
2277 }
2278 $mainParams = t3lib_div::implodeArrayForUrl('',$mainParams);
2279
2280 if (!$script) {basename(PATH_thisScript);}
2281 $onClick = 'jumpToUrl(\''.$script.'?'.$mainParams.$addparams.'&'.$elementName.'=\'+(this.checked?1:0),this);';
2282 return '<input type="checkbox" name="'.$elementName.'"'.($currentValue?' checked="checked"':'').' onclick="'.htmlspecialchars($onClick).'"'.($tagParams?' '.$tagParams:'').' />';
2283 }
2284
2285 /**
2286 * Input field function menu
2287 * Works like ->getFuncMenu() / ->getFuncCheck() but displays a input field instead which updates the script "onchange"
2288 * Usage: 1
2289 *
2290 * @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=...
2291 * @param string $elementName it the form elements name, probably something like "SET[...]"
2292 * @param string $currentValue is the value to be selected currently.
2293 * @param integer Relative size of input field, max is 48
2294 * @param string $script is the script to send the &id to, if empty it's automatically found
2295 * @param string $addParams is additional parameters to pass to the script.
2296 * @return string HTML code for input text field.
2297 * @see getFuncMenu()
2298 */
2299 function getFuncInput($mainParams,$elementName,$currentValue,$size=10,$script="",$addparams="") {
2300 if (!is_array($mainParams)) {
2301 $mainParams = array('id' => $mainParams);
2302 }
2303 $mainParams = t3lib_div::implodeArrayForUrl('',$mainParams);
2304
2305 if (!$script) {basename(PATH_thisScript);}
2306 $onChange = 'jumpToUrl(\''.$script.'?'.$mainParams.$addparams.'&'.$elementName.'=\'+escape(this.value),this);';
2307 return '<input type="text"'.$GLOBALS['TBE_TEMPLATE']->formWidth($size).' name="'.$elementName.'" value="'.htmlspecialchars($currentValue).'" onchange="'.htmlspecialchars($onChange).'" />';
2308 }
2309
2310 /**
2311 * Removes menu items from $itemArray if they are configured to be removed by TSconfig for the module ($modTSconfig)
2312 * See Inside TYPO3 about how to program modules and use this API.
2313 * Usage: 4
2314 *
2315 * @param array Module TS config array
2316 * @param array Array of items from which to remove items.
2317 * @param string $TSref points to the "object string" in $modTSconfig
2318 * @return array The modified $itemArray is returned.
2319 */
2320 function unsetMenuItems($modTSconfig,$itemArray,$TSref) {
2321 // Getting TS-config options for this module for the Backend User:
2322 $conf = $GLOBALS['BE_USER']->getTSConfig($TSref,$modTSconfig);
2323 if (is_array($conf['properties'])) {
2324 reset($conf['properties']);
2325 while(list($key,$val)=each($conf['properties'])) {
2326 if (!$val) {
2327 unset($itemArray[$key]);
2328 }
2329 }
2330 }
2331 return $itemArray;
2332 }
2333
2334 /**
2335 * Call to update the page tree frame (or something else..?) after
2336 * t3lib_BEfunc::getSetUpdateSignal('updatePageTree') -> will set the page tree to be updated.
2337 * t3lib_BEfunc::getSetUpdateSignal() -> will return some JavaScript that does the update (called in the typo3/template.php file, end() function)
2338 * Usage: 11
2339 *
2340 * @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.
2341 * @return string HTML code (<script> section)
2342 */
2343 function getSetUpdateSignal($set='') {
2344 global $BE_USER;
2345 $key = 't3lib_BEfunc::getSetUpdateSignal';
2346 $out='';
2347 if ($set) {
2348 $modData=array();
2349 $modData['set']=$set;
2350 $BE_USER->pushModuleData($key,$modData);
2351 } else {
2352 $modData = $BE_USER->getModuleData($key,'ses');
2353 if (trim($modData['set'])) {
2354 $l=explode(',',$modData['set']);
2355 while(list(,$v)=each($l)) {
2356 switch($v) {
2357 case 'updatePageTree':
2358 case 'updateFolderTree':
2359 $out.='
2360 <script type="text/javascript">
2361 /*<![CDATA[*/
2362 if (top.content && top.content.nav_frame && top.content.nav_frame.refresh_nav) {
2363 top.content.nav_frame.refresh_nav();
2364 }
2365 /*]]>*/
2366 </script>';
2367 break;
2368 }
2369 }
2370 $modData=array();
2371 $modData['set']='';
2372 $BE_USER->pushModuleData($key,$modData);
2373 }
2374 }
2375 return $out;
2376 }
2377
2378
2379 /**
2380 * Returns an array which is most backend modules becomes MOD_SETTINGS containing values from function menus etc. determining the function of the module.
2381 * This is kind of session variable management framework for the backend users.
2382 * 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
2383 * Ultimately, see Inside TYPO3 for how to use this function in relation to your modules.
2384 * Usage: 23
2385 *
2386 * @param array MOD_MENU is an array that defines the options in menus.
2387 * @param array CHANGED_SETTINGS represents the array used when passing values to the script from the menus.
2388 * @param string modName is the name of this module. Used to get the correct module data.
2389 * @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.
2390 * @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.
2391 * @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)
2392 * @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
2393 */
2394 function getModuleData($MOD_MENU, $CHANGED_SETTINGS, $modName, $type='', $dontValidateList='', $setDefaultList='') {
2395
2396 if ($modName && is_string($modName)) {
2397 // GETTING stored user-data from this module:
2398 $settings = $GLOBALS['BE_USER']->getModuleData($modName,$type);
2399
2400 $changed=0;
2401 if (!is_array($settings)) {
2402 $changed=1;
2403 $settings=array();
2404 }
2405 if (is_array($MOD_MENU)) {
2406 reset($MOD_MENU);
2407 while(list($key,$var)=each($MOD_MENU)) {
2408 // If a global var is set before entering here. eg if submitted, then it's substituting the current value the array.
2409 if (is_array($CHANGED_SETTINGS) && isset($CHANGED_SETTINGS[$key]) && strcmp($settings[$key],$CHANGED_SETTINGS[$key])) {
2410 $settings[$key] = (string)$CHANGED_SETTINGS[$key];
2411 $changed=1;
2412 }
2413 // If the $var is an array, which denotes the existence of a menu, we check if the value is permitted
2414 if (is_array($var) && (!$dontValidateList || !t3lib_div::inList($dontValidateList,$key))) {
2415 // If the setting is an array or not present in the menu-array, MOD_MENU, then the default value is inserted.
2416 if (is_array($settings[$key]) || !isset($MOD_MENU[$key][$settings[$key]])) {
2417 $settings[$key]=(string)key($var);
2418 $changed=1;
2419 }
2420 }
2421 if ($setDefaultList && !is_array($var)) { // Sets default values (only strings/checkboxes, not menus)
2422 if (t3lib_div::inList($setDefaultList,$key) && !isset($settings[$key])) {
2423 $settings[$key]=$var;
2424 }
2425 }
2426 }
2427 } else {die ('No menu!');}
2428
2429 if ($changed) {
2430 $GLOBALS['BE_USER']->pushModuleData($modName,$settings);
2431 }
2432
2433 return $settings;
2434 } else {die ('Wrong module name: "'.$modName.'"');}
2435 }
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449 /*******************************************
2450 *
2451 * Core
2452 *
2453 *******************************************/
2454
2455
2456
2457 /**
2458 * Unlock or Lock a record from $table with $uid
2459 * If $table and $uid is not set, then all locking for the current BE_USER is removed!
2460 * Usage: 5
2461 *
2462 * @param string Table name
2463 * @param integer Record uid
2464 * @param integer Record pid
2465 * @return void
2466 * @internal
2467 * @see t3lib_transferData::lockRecord(), alt_doc.php, db_layout.php, db_list.php, wizard_rte.php
2468 */
2469 function lockRecords($table='',$uid=0,$pid=0) {
2470 $user_id = intval($GLOBALS['BE_USER']->user['uid']);
2471 if ($table && $uid) {
2472 $fields_values = array(
2473 'userid' => $user_id,
2474 'tstamp' => $GLOBALS['EXEC_TIME'],
2475 'record_table' => $table,
2476 'record_uid' => $uid,
2477 'username' => $GLOBALS['BE_USER']->user['username'],
2478 'record_pid' => $pid
2479 );
2480
2481 $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_lockedrecords', $fields_values);
2482 } else {
2483 $GLOBALS['TYPO3_DB']->exec_DELETEquery('sys_lockedrecords', 'userid='.intval($user_id));
2484 }
2485 }
2486
2487 /**
2488 * Returns information about whether the record from table, $table, with uid, $uid is currently locked (edited by another user - which should issue a warning).
2489 * 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.
2490 * Usage: 5
2491 *
2492 * @param string Table name
2493 * @param integer Record uid
2494 * @return array
2495 * @internal
2496 * @see class.db_layout.inc, alt_db_navframe.php, alt_doc.php, db_layout.php
2497 */
2498 function isRecordLocked($table,$uid) {
2499 global $LOCKED_RECORDS;
2500 if (!is_array($LOCKED_RECORDS)) {
2501 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
2502 '*',
2503 'sys_lockedrecords',
2504 'sys_lockedrecords.userid!='.intval($GLOBALS['BE_USER']->user['uid']).'
2505 AND sys_lockedrecords.tstamp > '.($GLOBALS['EXEC_TIME']-2*3600)
2506 );
2507 while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
2508 $LOCKED_RECORDS[$row['record_table'].':'.$row['record_uid']]=$row;
2509 $LOCKED_RECORDS[$row['record_table'].':'.$row['record_uid']]['msg']=sprintf(
2510 $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.lockedRecord'),
2511 $row['username'],
2512 t3lib_BEfunc::calcAge($GLOBALS['EXEC_TIME']-$row['tstamp'],$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears'))
2513 );
2514 if ($row['record_pid'] && !isset($LOCKED_RECORDS[$row['record_table'].':'.$row['record_pid']])) {
2515 $LOCKED_RECORDS['pages:'.$row['record_pid']]['msg']=sprintf(
2516 $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.lockedRecord_content'),
2517 $row['username'],
2518 t3lib_BEfunc::calcAge($GLOBALS['EXEC_TIME']-$row['tstamp'],$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears'))
2519 );
2520 }
2521 }
2522 }
2523 return $LOCKED_RECORDS[$table.':'.$uid];
2524 }
2525
2526 /**
2527 * Returns select statement for MM relations (as used by TCEFORMs etc)
2528 * Usage: 3
2529 *
2530 * @param array Configuration array for the field, taken from $TCA
2531 * @param string Field name
2532 * @param array TSconfig array from which to get further configuration settings for the field name
2533 * @param string Prefix string for the key "*foreign_table_where" from $fieldValue array
2534 * @return string Part of query
2535 * @internal
2536 * @see t3lib_transferData::renderRecord(), t3lib_TCEforms::foreignTable()
2537 */
2538 function exec_foreign_table_where_query($fieldValue,$field='',$TSconfig=array(),$prefix='') {
2539 global $TCA;
2540 $foreign_table = $fieldValue['config'][$prefix.'foreign_table'];
2541 $rootLevel = $TCA[$foreign_table]['ctrl']['rootLevel'];
2542
2543 $fTWHERE = $fieldValue['config'][$prefix.'foreign_table_where'];
2544 if (strstr($fTWHERE,'###REC_FIELD_')) {
2545 $fTWHERE_parts = explode('###REC_FIELD_',$fTWHERE);
2546 while(list($kk,$vv)=each($fTWHERE_parts)) {
2547 if ($kk) {
2548 $fTWHERE_subpart = explode('###',$vv,2);
2549 $fTWHERE_parts[$kk]=$TSconfig['_THIS_ROW'][$fTWHERE_subpart[0]].$fTWHERE_subpart[1];
2550 }
2551 }
2552 $fTWHERE = implode('',$fTWHERE_parts);
2553 }
2554
2555 $fTWHERE = str_replace('###CURRENT_PID###',intval($TSconfig['_CURRENT_PID']),$fTWHERE);
2556 $fTWHERE = str_replace('###THIS_UID###',intval($TSconfig['_THIS_UID']),$fTWHERE);
2557 $fTWHERE = str_replace('###THIS_CID###',intval($TSconfig['_THIS_CID']),$fTWHERE);
2558 $fTWHERE = str_replace('###STORAGE_PID###',intval($TSconfig['_STORAGE_PID']),$fTWHERE);
2559 $fTWHERE = str_replace('###SITEROOT###',intval($TSconfig['_SITEROOT']),$fTWHERE);
2560 $fTWHERE = str_replace('###PAGE_TSCONFIG_ID###',intval($TSconfig[$field]['PAGE_TSCONFIG_ID']),$fTWHERE);
2561 $fTWHERE = str_replace('###PAGE_TSCONFIG_IDLIST###',$GLOBALS['TYPO3_DB']->cleanIntList($TSconfig[$field]['PAGE_TSCONFIG_IDLIST']),$fTWHERE);
2562 $fTWHERE = str_replace('###PAGE_TSCONFIG_STR###',$GLOBALS['TYPO3_DB']->quoteStr($TSconfig[$field]['PAGE_TSCONFIG_STR'], $foreign_table),$fTWHERE);
2563
2564 // rootLevel = -1 is not handled 'properly' here - it goes as if it was rootLevel = 1 (that is pid=0)
2565 $wgolParts = $GLOBALS['TYPO3_DB']->splitGroupOrderLimit($fTWHERE);
2566 if ($rootLevel) {
2567 $queryParts = array(
2568 'SELECT' => t3lib_BEfunc::getCommonSelectFields($foreign_table,$foreign_table.'.'),
2569 'FROM' => $foreign_table,
2570 'WHERE' => $foreign_table.'.pid=0 '.
2571 t3lib_BEfunc::deleteClause($foreign_table).' '.
2572 $wgolParts['WHERE'],
2573 'GROUPBY' => $wgolParts['GROUPBY'],
2574 'ORDERBY' => $wgolParts['ORDERBY'],
2575 'LIMIT' => $wgolParts['LIMIT']
2576 );
2577 } else {
2578 $pageClause = $GLOBALS['BE_USER']->getPagePermsClause(1);
2579 if ($foreign_table!='pages') {
2580 $queryParts = array(
2581 'SELECT' => t3lib_BEfunc::getCommonSelectFields($foreign_table,$foreign_table.'.'),
2582 'FROM' => $foreign_table.',pages',
2583 'WHERE' => 'pages.uid='.$foreign_table.'.pid
2584 AND pages.deleted=0 '.
2585 t3lib_BEfunc::deleteClause($foreign_table).
2586 ' AND '.$pageClause.' '.
2587 $wgolParts['WHERE'],
2588 'GROUPBY' => $wgolParts['GROUPBY'],
2589 'ORDERBY' => $wgolParts['ORDERBY'],
2590 'LIMIT' => $wgolParts['LIMIT']
2591 );
2592 } else {
2593 $queryParts = array(
2594 'SELECT' => t3lib_BEfunc::getCommonSelectFields($foreign_table,$foreign_table.'.'),
2595 'FROM' => 'pages',
2596 'WHERE' => 'pages.deleted=0
2597 AND '.$pageClause.' '.
2598 $wgolParts['WHERE'],
2599 'GROUPBY' => $wgolParts['GROUPBY'],
2600 'ORDERBY' => $wgolParts['ORDERBY'],
2601 'LIMIT' => $wgolParts['LIMIT']
2602 );
2603 }
2604 }
2605
2606 return $GLOBALS['TYPO3_DB']->exec_SELECT_queryArray($queryParts);
2607 }
2608
2609 /**
2610 * Returns TSConfig for the TCEFORM object in Page TSconfig.
2611 * Used in TCEFORMs
2612 * Usage: 4
2613 *
2614 * @param string Table name present in TCA
2615 * @param array Row from table
2616 * @return array
2617 * @see t3lib_transferData::renderRecord(), t3lib_TCEforms::setTSconfig(), SC_wizard_list::main(), SC_wizard_add::main()
2618 */
2619 function getTCEFORM_TSconfig($table,$row) {
2620 $res = array();
2621 $typeVal = t3lib_BEfunc::getTCAtypeValue($table,$row);
2622
2623 // Get main config for the table
2624 list($TScID,$cPid) = t3lib_BEfunc::getTSCpid($table,$row['uid'],$row['pid']);
2625
2626 $rootLine = t3lib_BEfunc::BEgetRootLine($TScID,'');
2627 if ($TScID>=0) {
2628 $tempConf = $GLOBALS['BE_USER']->getTSConfig('TCEFORM.'.$table,t3lib_BEfunc::getPagesTSconfig($TScID,$rootLine));
2629 if (is_array($tempConf['properties'])) {
2630 while(list($key,$val)=each($tempConf['properties'])) {
2631 if (is_array($val)) {
2632 $fieldN = substr($key,0,-1);
2633 $res[$fieldN] = $val;
2634 unset($res[$fieldN]['types.']);
2635 if (strcmp($typeVal,'') && is_array($val['types.'][$typeVal.'.'])) {
2636 $res[$fieldN] = t3lib_div::array_merge_recursive_overrule($res[$fieldN],$val['types.'][$typeVal.'.']);
2637 }
2638 }
2639 }
2640 }
2641 }
2642 $res['_CURRENT_PID']=$cPid;
2643 $res['_THIS_UID']=$row['uid'];
2644 $res['_THIS_CID']=$row['cid'];
2645 $res['_THIS_ROW']=$row; // So the row will be passed to foreign_table_where_query()
2646 reset($rootLine);
2647 while(list(,$rC)=each($rootLine)) {
2648 if (!$res['_STORAGE_PID']) $res['_STORAGE_PID']=intval($rC['storage_pid']);
2649 if (!$res['_SITEROOT']) $res['_SITEROOT']=$rC['is_siteroot']?intval($rC['uid']):0;
2650 }
2651
2652 return $res;
2653 }
2654
2655 /**
2656 * 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).
2657 * Usage: 2
2658 *
2659 * @param string Table name
2660 * @param integer Record uid
2661 * @param integer Record pid
2662 * @return integer
2663 * @internal
2664 * @see t3lib_TCEmain::copyRecord(), getTSCpid()
2665 */
2666 function getTSconfig_pidValue($table,$uid,$pid) {
2667 if (t3lib_div::testInt($pid)) { // If pid is an integer this takes precedence in our lookup.
2668 $thePidValue = intval($pid);
2669 if ($thePidValue<0) { // If ref to another record, look that record up.
2670 $pidRec = t3lib_BEfunc::getRecord($table,abs($thePidValue),'pid');
2671 $thePidValue= is_array($pidRec) ? $pidRec['pid'] : -2; // Returns -2 if the record did not exist.
2672 }
2673 // ... else the pos/zero pid is just returned here.
2674 } else { // No integer pid and we are forced to look up the $pid
2675 $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...
2676 if (is_array($rr)) {
2677 $thePidValue = $rr['pid']; // Returning the 'pid' of the record
2678 } else $thePidValue=-1; // Returns -1 if the record with the pid was not found.
2679 }
2680 return $thePidValue;
2681 }
2682
2683 /**
2684 * Return $uid if $table is pages and $uid is integer - otherwise the $pid
2685 * Usage: 1
2686 *
2687 * @param string Table name
2688 * @param integer Record uid
2689 * @param integer Record pid
2690 * @return integer
2691 * @internal
2692 * @see t3lib_TCEforms::getTSCpid()
2693 */
2694 function getPidForModTSconfig($table,$uid,$pid) {
2695 $retVal = ($table=='pages' && t3lib_div::testInt($uid)) ? $uid : $pid;
2696 return $retVal;
2697 }
2698
2699 /**
2700 * 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.
2701 * Usage: 8
2702 *
2703 * @param string Table name
2704 * @param integer Record uid
2705 * @param integer Record pid
2706 * @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)
2707 * @internal
2708 * @see t3lib_TCEmain::setHistory(), t3lib_TCEmain::process_datamap()
2709 */
2710 function getTSCpid($table,$uid,$pid) {
2711 // If pid is negative (referring to another record) the pid of the other record is fetched and returned.
2712 $cPid = t3lib_BEfunc::getTSconfig_pidValue($table,$uid,$pid);
2713 // $TScID is the id of $table=pages, else it's the pid of the record.
2714 $TScID = t3lib_BEfunc::getPidForModTSconfig($table,$uid,$cPid);
2715
2716 return array($TScID,$cPid);
2717 }
2718
2719 /**
2720 * Returns first found domain record "domainName" (without trailing slash) if found in the input $rootLine
2721 * Usage: 2
2722 *
2723 * @param array Root line array
2724 * @return string Domain name, if found.
2725 */
2726 function firstDomainRecord($rootLine) {
2727 if (t3lib_extMgm::isLoaded('cms')) {
2728 reset($rootLine);
2729 while(list(,$row)=each($rootLine)) {
2730 $dRec = t3lib_BEfunc::getRecordsByField('sys_domain','pid',$row['uid'],' AND redirectTo=\'\' AND hidden=0', '', 'sorting');
2731 if (is_array($dRec)) {
2732 reset($dRec);
2733 $dRecord = current($dRec);
2734 return ereg_replace('\/$','',$dRecord['domainName']);
2735 }
2736 }
2737 }
2738 }
2739
2740 /**
2741 * Returns the sys_domain record for $domain, optionally with $path appended.
2742 * Usage: 2
2743 *
2744 * @param string Domain name
2745 * @param string Appended path
2746 * @return array Domain record, if found
2747 */
2748 function getDomainStartPage($domain, $path='') {
2749 if (t3lib_extMgm::isLoaded('cms')) {
2750 $domain = explode(':',$domain);
2751 $domain = strtolower(ereg_replace('\.$','',$domain[0]));
2752 // path is calculated.
2753 $path = trim(ereg_replace('\/[^\/]*$','',$path));
2754 // stuff:
2755 $domain.=$path;
2756
2757 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('sys_domain.*', 'pages,sys_domain', '
2758 pages.uid=sys_domain.pid
2759 AND sys_domain.hidden=0
2760 AND (sys_domain.domainName='.$GLOBALS['TYPO3_DB']->fullQuoteStr($domain, 'sys_domain').' or sys_domain.domainName='.$GLOBALS['TYPO3_DB']->fullQuoteStr($domain.'/', 'sys_domain').')'.
2761 t3lib_BEfunc::deleteClause('pages'),
2762 '', '', '1');
2763 return $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
2764 }
2765 }
2766
2767 /**
2768 * Select all versions of a record, ordered by version id (DESC)
2769 *
2770 * @param string Table name to select from
2771 * @param integer Record uid for which to find versions.
2772 * @param string Field list to select
2773 * @return array Array of versions of table/uid
2774 */
2775 function selectVersionsOfRecord($table, $uid, $fields='*') {
2776 global $TCA;
2777
2778 if ($TCA[$table] && $TCA[$table]['ctrl']['versioning']) {
2779
2780 // Select all versions of record:
2781 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
2782 $fields,
2783 $table,
2784 '(t3ver_oid='.intval($uid).' || uid='.intval($uid).')'.
2785 t3lib_BEfunc::deleteClause($table),
2786 '',
2787 't3ver_id DESC'
2788 );
2789
2790 // Add rows to output array:
2791 $realPid = 0;
2792 $outputRows = array();
2793 while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
2794 if ($uid==$row['uid']) {
2795 $row['_CURRENT_VERSION']=TRUE;
2796 $realPid = $row['pid'];
2797 }
2798 $outputRows[] = $row;
2799 }
2800
2801 // Set real-pid:
2802 foreach($outputRows as $idx => $oRow) {
2803 $outputRows[$idx]['_REAL_PID'] = $realPid;
2804 }
2805
2806 return $outputRows;
2807 }
2808 }
2809
2810 /**
2811 * Returns overlayered RTE setup from an array with TSconfig. Used in TCEforms and TCEmain
2812 * Usage: 8
2813 *
2814 * @param array The properties of Page TSconfig in the key "RTE."
2815 * @param string Table name
2816 * @param string Field name
2817 * @param string Type value of the current record (like from CType of tt_content)
2818 * @return array Array with the configuration for the RTE
2819 * @internal
2820 */
2821 function RTEsetup($RTEprop,$table,$field,$type='') {
2822 $thisConfig = is_array($RTEprop['default.']) ? $RTEprop['default.'] : array();
2823 $thisFieldConf = $RTEprop['config.'][$table.'.'][$field.'.'];
2824 if (is_array($thisFieldConf)) {
2825 unset($thisFieldConf['types.']);
2826 $thisConfig = t3lib_div::array_merge_recursive_overrule($thisConfig,$thisFieldConf);
2827 }
2828 if ($type && is_array($RTEprop['config.'][$table.'.'][$field.'.']['types.'][$type.'.'])) {
2829 $thisConfig = t3lib_div::array_merge_recursive_overrule($thisConfig,$RTEprop['config.'][$table.'.'][$field.'.']['types.'][$type.'.']);
2830 }
2831 return $thisConfig;
2832 }
2833
2834 /**
2835 * Returns first possible RTE object if available.
2836 * Usage: $RTEobj = &t3lib_BEfunc::RTEgetObj();
2837 *
2838 * @return mixed If available, returns RTE object, otherwise an array of messages from possible RTEs
2839 */
2840 function &RTEgetObj() {
2841
2842 // If no RTE object has been set previously, try to create it:
2843 if (!isset($GLOBALS['T3_VAR']['RTEobj'])) {
2844
2845 // Set the object string to blank by default:
2846 $GLOBALS['T3_VAR']['RTEobj'] = array();
2847
2848 // Traverse registered RTEs:
2849 if (is_array($GLOBALS['TYPO3_CONF_VARS']['BE']['RTE_reg'])) {
2850 foreach($GLOBALS['TYPO3_CONF_VARS']['BE']['RTE_reg'] as $extKey => $rteObjCfg) {
2851 $rteObj = &t3lib_div::getUserObj($rteObjCfg['objRef']);
2852 if (is_object($rteObj)) {
2853 if ($rteObj->isAvailable()) {
2854 $GLOBALS['T3_VAR']['RTEobj'] = &$rteObj;
2855 break;
2856 } else {
2857 $GLOBALS['T3_VAR']['RTEobj'] = array_merge($GLOBALS['T3_VAR']['RTEobj'], $rteObj->errorLog);
2858 }
2859 }
2860 }
2861 }
2862
2863 if (!count($GLOBALS['T3_VAR']['RTEobj'])) {
2864 $GLOBALS['T3_VAR']['RTEobj'][] = 'No RTEs configured at all';
2865 }
2866 }
2867
2868 // Return RTE object (if any!)
2869 return $GLOBALS['T3_VAR']['RTEobj'];
2870 }
2871
2872 /**
2873 * Returns soft-reference parser for the softRef processing type
2874 * Usage: $softRefObj = &t3lib_BEfunc::softRefParserObj('[parser key]');
2875 *
2876 * @param string softRef parser key
2877 * @return mixed If available, returns Soft link parser object.
2878 */
2879 function &softRefParserObj($spKey) {
2880
2881 // If no softRef parser object has been set previously, try to create it:
2882 if (!isset($GLOBALS['T3_VAR']['softRefParser'][$spKey])) {
2883
2884 // Set the object string to blank by default:
2885 $GLOBALS['T3_VAR']['softRefParser'][$spKey] = '';
2886
2887 // Now, try to create parser object:
2888 $objRef = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['softRefParser'][$spKey] ?
2889 $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['softRefParser'][$spKey] :
2890 $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['softRefParser_GL'][$spKey];
2891 if ($objRef) {
2892 $softRefParserObj = &t3lib_div::getUserObj($objRef,'');
2893 if (is_object($softRefParserObj)) {
2894 $GLOBALS['T3_VAR']['softRefParser'][$spKey] = &$softRefParserObj;
2895 }
2896 }
2897 }
2898
2899 // Return RTE object (if any!)
2900 return $GLOBALS['T3_VAR']['softRefParser'][$spKey];
2901 }
2902
2903 /**
2904 * Returns array of soft parser references
2905 *
2906 * @param string softRef parser list
2907 * @param string Table name
2908 * @param string Field name
2909 * @return array Array where the parser key is the key and the value is the parameter string
2910 */
2911 function explodeSoftRefParserList($parserList, $table, $field) {
2912
2913 // Looking for global parsers:
2914 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['softRefParser_GL'])) {
2915 $parserList = implode(',',array_keys($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['softRefParser_GL'])).','.$parserList;
2916 }
2917
2918 // Return immediately if list is blank:
2919 if (!strlen($parserList)) return FALSE;
2920
2921 // Otherwise parse the list:
2922 $keyList = t3lib_div::trimExplode(',', $parserList, 1);
2923 $output = array();
2924
2925 foreach($keyList as $val) {
2926 $reg = array();
2927 if (ereg('^([[:alnum:]_-]+)\[(.*)\]$', $val, $reg)) {
2928 $output[$reg[1]] = t3lib_div::trimExplode(';', $reg[2], 1);
2929 } else {
2930 $output[$val] = '';
2931 }
2932 }
2933 return $output;
2934 }
2935
2936 /**
2937 * Returns true if $modName is set and is found as a main- or submodule in $TBE_MODULES array
2938 * Usage: 1
2939 *
2940 * @param string Module name
2941 * @return boolean
2942 */
2943 function isModuleSetInTBE_MODULES($modName) {
2944 reset($GLOBALS['TBE_MODULES']);
2945 $loaded=array();
2946 while(list($mkey,$list)=each($GLOBALS['TBE_MODULES'])) {
2947 $loaded[$mkey]=1;
2948 if (trim($list)) {
2949 $subList = t3lib_div::trimExplode(',',$list,1);
2950 while(list(,$skey)=each($subList)) {
2951 $loaded[$mkey.'_'.$skey]=1;
2952 }
2953 }
2954 }
2955 return $modName && isset($loaded[$modName]);
2956 }
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975 /*******************************************
2976 *
2977 * Miscellaneous
2978 *
2979 *******************************************/
2980
2981
2982 /**
2983 * Print error message with header, text etc.
2984 * Usage: 19
2985 *
2986 * @param string Header string
2987 * @param string Content string
2988 * @param boolean Will return an alert() with the content of header and text.
2989 * @param boolean Print header.
2990 * @return void
2991 */
2992 function typo3PrintError($header,$text,$js='',$head=1) {
2993 // This prints out a TYPO3 error message.
2994 // If $js is set the message will be output in JavaScript
2995 if ($js) {
2996 echo "alert('".t3lib_div::slashJS($header.'\n'.$text)."');";
2997 } else {
2998 echo $head?'<html>
2999 <head>
3000 <title>Error!</title>
3001 </head>
3002 <body bgcolor="white" topmargin="0" leftmargin="0" marginwidth="0" marginheight="0">':'';
3003 echo '<div align="center">
3004 <table border="0" cellspacing="0" cellpadding="0" width="333">
3005 <tr>
3006 <td align="center">'.
3007 ($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" />').
3008 '</td>
3009 </tr>
3010 <tr>
3011 <td bgcolor="black">
3012 <table width="100%" border="0" cellspacing="1" cellpadding="10">
3013 <tr>
3014 <td bgcolor="#F4F0E8">
3015 <font face="verdana,arial,helvetica" size="2">';
3016 echo '<b><center><font size="+1">'.$header.'</font></center></b><br />'.$text;
3017 echo ' </font>
3018 </td>
3019 </tr>
3020 </table>
3021 </td>
3022 </tr>
3023 </table>
3024 </div>';
3025 echo $head?'