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