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