*** empty log message ***
[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['doktype']=='3') {
1622 $parts[]=$LANG->sL($TCA['pages']['columns']['url']['label']).' '.$row['url'];
1623 } elseif ($row['doktype']=='4') {
1624 if ($perms_clause) {
1625 $label = t3lib_BEfunc::getRecordPath(intval($row['shortcut']),$perms_clause,20);
1626 } else {
1627 $lRec = t3lib_BEfunc::getRecordWSOL('pages',intval($row['shortcut']),'title');
1628 $label = $lRec['title'];
1629 }
1630 if ($row['shortcut_mode']>0) {
1631 $label.=', '.$LANG->sL($TCA['pages']['columns']['shortcut_mode']['label']).' '.
1632 $LANG->sL(t3lib_BEfunc::getLabelFromItemlist('pages','shortcut_mode',$row['shortcut_mode']));
1633 }
1634 $parts[]=$LANG->sL($TCA['pages']['columns']['shortcut']['label']).' '.$label;
1635 } elseif ($row['doktype']=='7') {
1636 if ($perms_clause) {
1637 $label = t3lib_BEfunc::getRecordPath(intval($row['mount_pid']),$perms_clause,20);
1638 } else {
1639 $lRec = t3lib_BEfunc::getRecordWSOL('pages',intval($row['mount_pid']),'title');
1640 $label = $lRec['title'];
1641 }
1642 $parts[]=$LANG->sL($TCA['pages']['columns']['mount_pid']['label']).' '.$label;
1643 if ($row['mount_pid_ol']) {
1644 $parts[] = $LANG->sL($TCA['pages']['columns']['mount_pid_ol']['label']);
1645 }
1646 }
1647 if ($row['nav_hide']) $parts[] = ereg_replace(':$','',$LANG->sL($TCA['pages']['columns']['nav_hide']['label']));
1648 if ($row['hidden']) $parts[] = $LANG->sL('LLL:EXT:lang/locallang_core.php:labels.hidden');
1649 if ($row['starttime']) $parts[] = $LANG->sL($TCA['pages']['columns']['starttime']['label']).' '.t3lib_BEfunc::dateTimeAge($row['starttime'],-1,'date');
1650 if ($row['endtime']) $parts[] = $LANG->sL($TCA['pages']['columns']['endtime']['label']).' '.t3lib_BEfunc::dateTimeAge($row['endtime'],-1,'date');
1651 if ($row['fe_group']) {
1652 if ($row['fe_group']<0) {
1653 $label = $LANG->sL(t3lib_BEfunc::getLabelFromItemlist('pages','fe_group',$row['fe_group']));
1654 } else {
1655 $lRec = t3lib_BEfunc::getRecordWSOL('fe_groups',$row['fe_group'],'title');
1656 $label = $lRec['title'];
1657 }
1658 $parts[] = $LANG->sL($TCA['pages']['columns']['fe_group']['label']).' '.$label;
1659 }
1660 $out = htmlspecialchars(implode(' - ',$parts));
1661 return $includeAttrib ? 'title="'.$out.'"' : $out;
1662 }
1663
1664 /**
1665 * Returns title-attribute information for ANY record (from a table defined in TCA of course)
1666 * 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.
1667 * "pages" table can be used as well and will return the result of ->titleAttribForPages() for that page.
1668 * Usage: 10
1669 *
1670 * @param array Table row; $row is a row from the table, $table
1671 * @param string Table name
1672 * @return string
1673 */
1674 function getRecordIconAltText($row,$table='pages') {
1675 if ($table=='pages') {
1676 $out = t3lib_BEfunc::titleAttribForPages($row,'',0);
1677 } else {
1678 $ctrl = $GLOBALS['TCA'][$table]['ctrl']['enablecolumns'];
1679
1680 $out='id='.$row['uid']; // Uid is added
1681 if ($table=='pages' && $row['alias']) {
1682 $out.=' / '.$row['alias'];
1683 }
1684 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS'] && $row['pid']<0) {
1685 $out.=' - v#1.'.$row['t3ver_id'];
1686 }
1687 if ($ctrl['disabled']) { // Hidden ...
1688 $out.=($row[$ctrl['disabled']]?' - '.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.hidden'):'');
1689 }
1690 if ($ctrl['starttime']) {
1691 if ($row[$ctrl['starttime']] > $GLOBALS['EXEC_TIME']) {
1692 $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').')';
1693 }
1694 }
1695 if ($row[$ctrl['endtime']]) {
1696 $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').')';
1697 }
1698 }
1699 return htmlspecialchars($out);
1700 }
1701
1702 /**
1703 * Returns the label of the first found entry in an "items" array from $TCA (tablename=$table/fieldname=$col) where the value is $key
1704 * Usage: 9
1705 *
1706 * @param string Table name, present in $TCA
1707 * @param string Field name, present in $TCA
1708 * @param string items-array value to match
1709 * @return string Label for item entry
1710 */
1711 function getLabelFromItemlist($table,$col,$key) {
1712 global $TCA;
1713 // Load full TCA for $table
1714 t3lib_div::loadTCA($table);
1715
1716 // Check, if there is an "items" array:
1717 if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$col]) && is_array($TCA[$table]['columns'][$col]['config']['items'])) {
1718 // Traverse the items-array...
1719 reset($TCA[$table]['columns'][$col]['config']['items']);
1720 while(list($k,$v)=each($TCA[$table]['columns'][$col]['config']['items'])) {
1721 // ... and return the first found label where the value was equal to $key
1722 if (!strcmp($v[1],$key)) return $v[0];
1723 }
1724 }
1725 }
1726
1727 /**
1728 * Returns the label-value for fieldname $col in table, $table
1729 * 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>'
1730 * Usage: 17
1731 *
1732 * @param string Table name, present in $TCA
1733 * @param string Field name
1734 * @param string Wrap value - set function description
1735 * @return string
1736 */
1737 function getItemLabel($table,$col,$printAllWrap='') {
1738 global $TCA;
1739 // Load full TCA for $table
1740 t3lib_div::loadTCA($table);
1741 // Check if column exists
1742 if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$col])) {
1743 // Re
1744 return $TCA[$table]['columns'][$col]['label'];
1745 }
1746 if ($printAllWrap) {
1747 $parts = explode('|',$printAllWrap);
1748 return $parts[0].$col.$parts[1];
1749 }
1750 }
1751
1752 /**
1753 * Returns the "title"-value in record, $row, from table, $table
1754 * The field(s) from which the value is taken is determined by the "ctrl"-entries 'label', 'label_alt' and 'label_alt_force'
1755 * Usage: 26
1756 *
1757 * @param string Table name, present in TCA
1758 * @param array Row from table
1759 * @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
1760 * @return string
1761 */
1762 function getRecordTitle($table,$row,$prep=0) {
1763 global $TCA;
1764 if (is_array($TCA[$table])) {
1765 $t = $row[$TCA[$table]['ctrl']['label']];
1766 if ($TCA[$table]['ctrl']['label_alt'] && ($TCA[$table]['ctrl']['label_alt_force'] || !strcmp($t,''))) {
1767 $altFields=t3lib_div::trimExplode(',',$TCA[$table]['ctrl']['label_alt'],1);
1768 $tA=array();
1769 $tA[]=$t;
1770 while(list(,$fN)=each($altFields)) {
1771 $t = $tA[] = trim(strip_tags($row[$fN]));
1772 if (strcmp($t,'') && !$TCA[$table]['ctrl']['label_alt_force']) break;
1773 }
1774 if ($TCA[$table]['ctrl']['label_alt_force']) $t=implode(', ',$tA);
1775 }
1776 if ($prep) {
1777 $t = htmlspecialchars(t3lib_div::fixed_lgd_cs($t,$GLOBALS['BE_USER']->uc['titleLen']));
1778 if (!strcmp(trim($t),'')) $t='<em>['.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.no_title',1).']</em>';
1779 }
1780 return $t;
1781 }
1782 }
1783
1784 /**
1785 * Returns a human readable output of a value from a record
1786 * 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.
1787 * $table/$col is tablename and fieldname
1788 * REMEMBER to pass the output through htmlspecialchars() if you output it to the browser! (To protect it from XSS attacks and be XHTML compliant)
1789 * Usage: 24
1790 *
1791 * @param string Table name, present in TCA
1792 * @param string Field name, present in TCA
1793 * @param string $value is the value of that field from a selected record
1794 * @param integer $fixed_lgd_chars is the max amount of characters the value may occupy
1795 * @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")
1796 * @param boolean If set, no records will be looked up, UIDs are just shown.
1797 * @param integer uid of the current record
1798 * @return string
1799 */
1800 function getProcessedValue($table,$col,$value,$fixed_lgd_chars=0,$defaultPassthrough=0,$noRecordLookup=FALSE,$uid=0) {
1801 global $TCA;
1802 // Load full TCA for $table
1803 t3lib_div::loadTCA($table);
1804 // Check if table and field is configured:
1805 if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$col])) {
1806 // Depending on the fields configuration, make a meaningful output value.
1807 $theColConf = $TCA[$table]['columns'][$col]['config'];
1808 $l='';
1809 switch((string)$theColConf['type']) {
1810 case 'radio':
1811 $l=t3lib_BEfunc::getLabelFromItemlist($table,$col,$value);
1812 $l=$GLOBALS['LANG']->sL($l);
1813 break;
1814 case 'select':
1815 if ($theColConf['MM']) {
1816 // Display the title of MM related records in lists
1817 $MMres = $GLOBALS['TYPO3_DB']->exec_SELECT_mm_query(
1818 $theColConf['foreign_table'].'.'.$TCA[$theColConf['foreign_table']]['ctrl']['label'],
1819 $table,
1820 $theColConf['MM'],
1821 $theColConf['foreign_table'],
1822 'AND '.$table.'.uid ='.intval($uid).t3lib_BEfunc::deleteClause($theColConf['foreign_table'])
1823 );
1824 if ($MMres) {
1825 while($MMrow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($MMres)) {
1826 $mmlA[] = $MMrow[$TCA[$theColConf['foreign_table']]['ctrl']['label']];
1827 }
1828 if (is_array($mmlA)) {
1829 $l=implode(', ',$mmlA);
1830 } else {
1831 $l = '';
1832 }
1833 } else {
1834 $l = 'n/A';
1835 }
1836 } else {
1837 $l = t3lib_BEfunc::getLabelFromItemlist($table,$col,$value);
1838 $l = $GLOBALS['LANG']->sL($l);
1839 if ($theColConf['foreign_table'] && !$l && $TCA[$theColConf['foreign_table']]) {
1840 if ($noRecordLookup) {
1841 $l = $value;
1842 } else {
1843 $rParts = t3lib_div::trimExplode(',',$value,1);
1844 reset($rParts);
1845 $lA = array();
1846 while(list(,$rVal)=each($rParts)) {
1847 $rVal = intval($rVal);
1848 if ($rVal>0) {
1849 $r=t3lib_BEfunc::getRecordWSOL($theColConf['foreign_table'],$rVal);
1850 } else {
1851 $r=t3lib_BEfunc::getRecordWSOL($theColConf['neg_foreign_table'],-$rVal);
1852 }
1853 if (is_array($r)) {
1854 $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);
1855 } else {
1856 $lA[]=$rVal?'['.$rVal.'!]':'';
1857 }
1858 }
1859 $l = implode(', ',$lA);
1860 }
1861 }
1862 }
1863 break;
1864 case 'group':
1865 $l = implode(', ',t3lib_div::trimExplode(',',$value,1));
1866 break;
1867 case 'check':
1868 if (!is_array($theColConf['items']) || count($theColConf['items'])==1) {
1869 $l = $value ? 'Yes' : '';
1870 } else {
1871 reset($theColConf['items']);
1872 $lA=Array();
1873 while(list($key,$val)=each($theColConf['items'])) {
1874 if ($value & pow(2,$key)) {$lA[]=$GLOBALS['LANG']->sL($val[0]);}
1875 }
1876 $l = implode(', ',$lA);
1877 }
1878 break;
1879 case 'input':
1880 if ($value) {
1881 if (t3lib_div::inList($theColConf['eval'],'date')) {
1882 $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')).')';
1883 } elseif (t3lib_div::inList($theColConf['eval'],'time')) {
1884 $l = t3lib_BEfunc::time($value);
1885 } elseif (t3lib_div::inList($theColConf['eval'],'datetime')) {
1886 $l = t3lib_BEfunc::datetime($value);
1887 } else {
1888 $l = $value;
1889 }
1890 }
1891 break;
1892 default:
1893 if ($defaultPassthrough) {
1894 $l=$value;
1895 } elseif ($theColConf['MM']) {
1896 $l='N/A';
1897 } elseif ($value) {
1898 $l=t3lib_div::fixed_lgd_cs(strip_tags($value),200);
1899 }
1900 break;
1901 }
1902 if ($fixed_lgd_chars) {
1903 return t3lib_div::fixed_lgd_cs($l,$fixed_lgd_chars);
1904 } else {
1905 return $l;
1906 }
1907 }
1908 }
1909
1910 /**
1911 * 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.
1912 * Usage: 2
1913 *
1914 * @param string Table name, present in TCA
1915 * @param string Field name
1916 * @param string Field value
1917 * @param integer $fixed_lgd_chars is the max amount of characters the value may occupy
1918 * @param integer uid of the current record
1919 * @return string
1920 * @see getProcessedValue()
1921 */
1922 function getProcessedValueExtra($table,$fN,$fV,$fixed_lgd_chars=0,$uid=0) {
1923 global $TCA;
1924 $fVnew = t3lib_BEfunc::getProcessedValue($table,$fN,$fV,$fixed_lgd_chars,0,0,$uid);
1925 if (!isset($fVnew)) {
1926 if (is_array($TCA[$table])) {
1927 if ($fN==$TCA[$table]['ctrl']['tstamp'] || $fN==$TCA[$table]['ctrl']['crdate']) {
1928 $fVnew = t3lib_BEfunc::datetime($fV);
1929 } elseif ($fN=='pid'){
1930 $fVnew = t3lib_BEfunc::getRecordPath($fV,'1=1',20); // Fetches the path with no regard to the users permissions to select pages.
1931 } else {
1932 $fVnew = $fV;
1933 }
1934 }
1935 }
1936 return $fVnew;
1937 }
1938
1939 /**
1940 * Returns file icon name (from $FILEICONS) for the fileextension $ext
1941 * Usage: 10
1942 *
1943 * @param string File extension, lowercase
1944 * @return string File icon filename
1945 */
1946 function getFileIcon($ext) {
1947 return $GLOBALS['FILEICONS'][$ext] ? $GLOBALS['FILEICONS'][$ext] : $GLOBALS['FILEICONS']['default'];
1948 }
1949
1950 /**
1951 * Returns fields for a table, $table, which would typically be interesting to select
1952 * This includes uid, the fields defined for title, icon-field.
1953 * 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)
1954 * Usage: 3
1955 *
1956 * @param string Table name, present in TCA
1957 * @param string Table prefix
1958 * @return string List of fields.
1959 */
1960 function getCommonSelectFields($table,$prefix) {
1961 global $TCA;
1962 $fields = array();
1963 $fields[] = $prefix.'uid';
1964 $fields[] = $prefix.$TCA[$table]['ctrl']['label'];
1965
1966 if ($TCA[$table]['ctrl']['label_alt']) {
1967 $secondFields = t3lib_div::trimExplode(',',$TCA[$table]['ctrl']['label_alt'],1);
1968 foreach($secondFields as $fieldN) {
1969 $fields[] = $prefix.$fieldN;
1970 }
1971 }
1972 if ($TCA[$table]['ctrl']['versioningWS']) {
1973 $fields[] = $prefix.'t3ver_id';
1974 $fields[] = $prefix.'t3ver_state';
1975 }
1976
1977 if ($TCA[$table]['ctrl']['selicon_field']) $fields[] = $prefix.$TCA[$table]['ctrl']['selicon_field'];
1978 if ($TCA[$table]['ctrl']['typeicon_column']) $fields[] = $prefix.$TCA[$table]['ctrl']['typeicon_column'];
1979
1980 if (is_array($TCA[$table]['ctrl']['enablecolumns'])) {
1981 if ($TCA[$table]['ctrl']['enablecolumns']['disabled']) $fields[] = $prefix.$TCA[$table]['ctrl']['enablecolumns']['disabled'];
1982 if ($TCA[$table]['ctrl']['enablecolumns']['starttime']) $fields[] = $prefix.$TCA[$table]['ctrl']['enablecolumns']['starttime'];
1983 if ($TCA[$table]['ctrl']['enablecolumns']['endtime']) $fields[] = $prefix.$TCA[$table]['ctrl']['enablecolumns']['endtime'];
1984 if ($TCA[$table]['ctrl']['enablecolumns']['fe_group']) $fields[] = $prefix.$TCA[$table]['ctrl']['enablecolumns']['fe_group'];
1985 }
1986
1987 return implode(',', array_unique($fields));
1988 }
1989
1990 /**
1991 * 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
1992 * <form>-tags must be supplied separately
1993 * 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.
1994 * Usage: 1 (ext. direct_mail)
1995 *
1996 * @param array Field configuration code.
1997 * @param array Defaults
1998 * @param string Prefix for formfields
1999 * @return string HTML for a form.
2000 */
2001 function makeConfigForm($configArray,$defaults,$dataPrefix) {
2002 $params = $defaults;
2003 if (is_array($configArray)) {
2004 reset($configArray);
2005 $lines=array();
2006 while(list($fname,$config)=each($configArray)) {
2007 if (is_array($config)) {
2008 $lines[$fname]='<strong>'.htmlspecialchars($config[1]).'</strong><br />';
2009 $lines[$fname].=$config[2].'<br />';
2010 switch($config[0]) {
2011 case 'string':
2012 case 'short':
2013 $formEl = '<input type="text" name="'.$dataPrefix.'['.$fname.']" value="'.$params[$fname].'"'.$GLOBALS['TBE_TEMPLATE']->formWidth($config[0]=='short'?24:48).' />';
2014 break;
2015 case 'check':
2016 $formEl = '<input type="hidden" name="'.$dataPrefix.'['.$fname.']" value="0" /><input type="checkbox" name="'.$dataPrefix.'['.$fname.']" value="1"'.($params[$fname]?' checked="checked"':'').' />';
2017 break;
2018 case 'comment':
2019 $formEl = '';
2020 break;
2021 case 'select':
2022 reset($config[3]);
2023 $opt=array();
2024 while(list($k,$v)=each($config[3])) {
2025 $opt[]='<option value="'.htmlspecialchars($k).'"'.($params[$fname]==$k?' selected="selected"':'').'>'.htmlspecialchars($v).'</option>';
2026 }
2027 $formEl = '<select name="'.$dataPrefix.'['.$fname.']">'.implode('',$opt).'</select>';
2028 break;
2029 default:
2030 debug($config);
2031 break;
2032 }
2033 $lines[$fname].=$formEl;
2034 $lines[$fname].='<br /><br />';
2035 } else {
2036 $lines[$fname]='<hr />';
2037 if ($config) $lines[$fname].='<strong>'.strtoupper(htmlspecialchars($config)).'</strong><br />';
2038 if ($config) $lines[$fname].='<br />';
2039 }
2040 }
2041 }
2042 $out = implode('',$lines);
2043 $out.='<input type="submit" name="submit" value="Update configuration" />';
2044 return $out;
2045 }
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059 /*******************************************
2060 *
2061 * Backend Modules API functions
2062 *
2063 *******************************************/
2064
2065 /**
2066 * Returns help-text icon if configured for.
2067 * TCA_DESCR must be loaded prior to this function and $BE_USER must have 'edit_showFieldHelp' set to 'icon', otherwise nothing is returned
2068 * Usage: 6
2069 *
2070 * @param string Table name
2071 * @param string Field name
2072 * @param string Back path
2073 * @param boolean Force display of icon nomatter BE_USER setting for help
2074 * @return string HTML content for a help icon/text
2075 */
2076 function helpTextIcon($table,$field,$BACK_PATH,$force=0) {
2077 global $TCA_DESCR,$BE_USER;
2078 if (is_array($TCA_DESCR[$table]) && is_array($TCA_DESCR[$table]['columns'][$field]) && ($BE_USER->uc['edit_showFieldHelp']=='icon' || $force)) {
2079 $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;';
2080 return '<a href="#" onclick="'.htmlspecialchars($onClick).'">'.
2081 '<img'.t3lib_iconWorks::skinImg($BACK_PATH,'gfx/helpbubble.gif','width="14" height="14"').' hspace="2" border="0" class="typo3-csh-icon" alt="" />'.
2082 '</a>';
2083 }
2084 }
2085
2086 /**
2087 * Returns CSH help text (description), if configured for.
2088 * TCA_DESCR must be loaded prior to this function and $BE_USER must have "edit_showFieldHelp" set to "text", otherwise nothing is returned
2089 * Will automatically call t3lib_BEfunc::helpTextIcon() to get the icon for the text.
2090 * Usage: 4
2091 *
2092 * @param string Table name
2093 * @param string Field name
2094 * @param string Back path
2095 * @param string Additional style-attribute content for wrapping table
2096 * @return string HTML content for help text
2097 */
2098 function helpText($table,$field,$BACK_PATH,$styleAttrib='') {
2099 global $TCA_DESCR,$BE_USER;
2100 if (is_array($TCA_DESCR[$table]) && is_array($TCA_DESCR[$table]['columns'][$field]) && $BE_USER->uc['edit_showFieldHelp']=='text') {
2101 $fDat = $TCA_DESCR[$table]['columns'][$field];
2102
2103 // Get Icon:
2104 $editIcon = t3lib_BEfunc::helpTextIcon(
2105 $table,
2106 $field,
2107 $BACK_PATH,
2108 TRUE
2109 );
2110 // Add title?
2111 $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;';
2112 $text =
2113 ($fDat['alttitle'] ? '<h4><a href="#" onclick="'.htmlspecialchars($onClick).'">'.$fDat['alttitle'].'</a></h4>' : '').
2114 $fDat['description'];
2115
2116 // More information to get?
2117 if ($fDat['image_descr'] || $fDat['seeAlso'] || $fDat['details'] || $fDat['syntax']) { // || $fDat['image'];
2118 $text.=' <a href="#" onclick="'.htmlspecialchars($onClick).'">'.
2119 '<img'.t3lib_iconWorks::skinImg($BACK_PATH,'gfx/rel_db.gif','width="13" height="12"').' class="absmiddle typo3-csh-more" alt="" />'.
2120 '</a>';
2121 }
2122
2123 // Additional styles?
2124 $params = $styleAttrib ? ' style="'.$styleAttrib.'"' : '';
2125
2126 // Compile table with CSH information:
2127 return '<table border="0" cellpadding="2" cellspacing="0" class="typo3-csh-inline"'.$params.'>
2128 <tr>
2129 <td valign="top" width="14">'.$editIcon.'</td>
2130 <td valign="top">'.$text.'</td>
2131 </tr>
2132 </table>';
2133 }
2134 }
2135
2136 /**
2137 * API for getting CSH icons/text for use in backend modules.
2138 * TCA_DESCR will be loaded if it isn't already
2139 * Usage: ?
2140 *
2141 * @param string Table name ('_MOD_'+module name)
2142 * @param string Field name (CSH locallang main key)
2143 * @param string Back path
2144 * @param string Wrap code for icon-mode, splitted by "|". Not used for full-text mode.
2145 * @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.
2146 * @param string Additional style-attribute content for wrapping table (full text mode only)
2147 * @return string HTML content for help text
2148 * @see helpText(), helpTextIcon()
2149 */
2150 function cshItem($table,$field,$BACK_PATH,$wrap='',$onlyIconMode=FALSE, $styleAttrib='') {
2151 global $TCA_DESCR, $LANG, $BE_USER;
2152 if ($BE_USER->uc['edit_showFieldHelp']) {
2153 $LANG->loadSingleTableDescription($table);
2154
2155 if (is_array($TCA_DESCR[$table])) {
2156 // Creating CSH icon and short description:
2157 $fullText = t3lib_BEfunc::helpText($table,$field,$BACK_PATH,$styleAttrib);
2158 $icon = t3lib_BEfunc::helpTextIcon($table,$field,$BACK_PATH,$onlyIconMode);
2159
2160 if ($fullText && !$onlyIconMode) {
2161 $output = $fullText;
2162 } else {
2163 #$output = '<span style="position:absolute; filter: alpha(opacity=50); -moz-opacity: 0.50;">'.$icon.'</span>';
2164 $output = $icon;
2165
2166 if ($output && $wrap) {
2167 $wrParts = explode('|',$wrap);
2168 $output = $wrParts[0].$output.$wrParts[1];
2169 }
2170 }
2171
2172 return $output;
2173 }
2174 }
2175 }
2176
2177 /**
2178 * 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.
2179 * REMEMBER to always htmlspecialchar() content in href-properties to ampersands get converted to entities (XHTML requirement and XSS precaution)
2180 * Usage: 35
2181 *
2182 * @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.
2183 * @param string $backPath must point back to the TYPO3_mainDir directory (where alt_doc.php is)
2184 * @param string $requestUri is an optional returnUrl you can set - automatically set to REQUEST_URI.
2185 * @return string
2186 * @see template::issueCommand()
2187 */
2188 function editOnClick($params,$backPath='',$requestUri='') {
2189 $retUrl = 'returnUrl='.($requestUri==-1?"'+T3_THIS_LOCATION+'":rawurlencode($requestUri?$requestUri:t3lib_div::getIndpEnv('REQUEST_URI')));
2190 return "document.location='".$backPath."alt_doc.php?".$retUrl.$params."'; return false;";
2191 }
2192
2193 /**
2194 * Returns a JavaScript string for viewing the page id, $id
2195 * 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.
2196 * Usage: 8
2197 *
2198 * @param integer $id is page id
2199 * @param string $backpath must point back to TYPO3_mainDir (where the site is assumed to be one level above)
2200 * @param array If root line is supplied the function will look for the first found domain record and use that URL instead (if found)
2201 * @param string $anchor is optional anchor to the URL
2202 * @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!
2203 * @param string Additional GET variables.
2204 * @param boolean If true, then the preview window will gain the focus.
2205 * @return string
2206 */
2207 function viewOnClick($id,$backPath='',$rootLine='',$anchor='',$altUrl='',$addGetVars='',$switchFocus=TRUE) {
2208 if ($altUrl) {
2209 $url = $altUrl;
2210 } else {
2211 if ($rootLine) {
2212 $parts = parse_url(t3lib_div::getIndpEnv('TYPO3_SITE_URL'));
2213 if (t3lib_BEfunc::getDomainStartPage($parts['host'],$parts['path'])) {
2214 $preUrl_temp = t3lib_BEfunc::firstDomainRecord($rootLine);
2215 }
2216 }
2217 $preUrl = $preUrl_temp ? (t3lib_div::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://').$preUrl_temp : $backPath.'..';
2218 $url = $preUrl.'/index.php?id='.$id.$addGetVars.$anchor;
2219 }
2220
2221 return "previewWin=window.open('".$url."','newTypo3FrontendWindow','status=1,menubar=1,resizable=1,location=1,scrollbars=1,toolbar=1');".
2222 ($switchFocus ? 'previewWin.focus();' : '');
2223 }
2224
2225 /**
2226 * Returns the merged User/Page TSconfig for page id, $id.
2227 * Please read details about module programming elsewhere!
2228 * Usage: 15
2229 *
2230 * @param integer Page uid
2231 * @param string $TSref is an object string which determines the path of the TSconfig to return.
2232 * @return array
2233 */
2234 function getModTSconfig($id,$TSref) {
2235 $pageTS_modOptions = $GLOBALS['BE_USER']->getTSConfig($TSref,t3lib_BEfunc::getPagesTSconfig($id));
2236 $BE_USER_modOptions = $GLOBALS['BE_USER']->getTSConfig($TSref);
2237 $modTSconfig = t3lib_div::array_merge_recursive_overrule($pageTS_modOptions,$BE_USER_modOptions);
2238 return $modTSconfig;
2239 }
2240
2241 /**
2242 * Returns a selector box "function menu" for a module
2243 * Requires the JS function jumpToUrl() to be available
2244 * See Inside TYPO3 for details about how to use / make Function menus
2245 * Usage: 50
2246 *
2247 * @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=...
2248 * @param string $elementName it the form elements name, probably something like "SET[...]"
2249 * @param string $currentValue is the value to be selected currently.
2250 * @param array $menuItems is an array with the menu items for the selector box
2251 * @param string $script is the script to send the &id to, if empty it's automatically found
2252 * @param string $addParams is additional parameters to pass to the script.
2253 * @return string HTML code for selector box
2254 */
2255 function getFuncMenu($mainParams,$elementName,$currentValue,$menuItems,$script='',$addparams='') {
2256 if (is_array($menuItems)) {
2257 if (!is_array($mainParams)) {
2258 $mainParams = array('id' => $mainParams);
2259 }
2260 $mainParams = t3lib_div::implodeArrayForUrl('',$mainParams);
2261
2262 if (!$script) { $script=basename(PATH_thisScript); }
2263
2264 $options = array();
2265 foreach($menuItems as $value => $label) {
2266 $options[] = '<option value="'.htmlspecialchars($value).'"'.(!strcmp($currentValue,$value)?' selected="selected"':'').'>'.
2267 t3lib_div::deHSCentities(htmlspecialchars($label)).
2268 '</option>';
2269 }
2270 if (count($options)) {
2271 $onChange = 'jumpToUrl(\''.$script.'?'.$mainParams.$addparams.'&'.$elementName.'=\'+this.options[this.selectedIndex].value,this);';
2272 return '
2273
2274 <!-- Function Menu of module -->
2275 <select name="'.$elementName.'" onchange="'.htmlspecialchars($onChange).'">
2276 '.implode('
2277 ',$options).'
2278 </select>
2279 ';
2280 }
2281 }
2282 }
2283
2284 /**
2285 * Checkbox function menu.
2286 * Works like ->getFuncMenu() but takes no $menuItem array since this is a simple checkbox.
2287 * Usage: 34
2288 *
2289 * @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=...
2290 * @param string $elementName it the form elements name, probably something like "SET[...]"
2291 * @param string $currentValue is the value to be selected currently.
2292 * @param string $script is the script to send the &id to, if empty it's automatically found
2293 * @param string $addParams is additional parameters to pass to the script.
2294 * @param string Additional attributes for the checkbox input tag
2295 * @return string HTML code for checkbox
2296 * @see getFuncMenu()
2297 */
2298 function getFuncCheck($mainParams,$elementName,$currentValue,$script='',$addparams='',$tagParams='') {
2299 if (!is_array($mainParams)) {
2300 $mainParams = array('id' => $mainParams);
2301 }
2302 $mainParams = t3lib_div::implodeArrayForUrl('',$mainParams);
2303
2304 if (!$script) {basename(PATH_thisScript);}
2305 $onClick = 'jumpToUrl(\''.$script.'?'.$mainParams.$addparams.'&'.$elementName.'=\'+(this.checked?1:0),this);';
2306 return '<input type="checkbox" name="'.$elementName.'"'.($currentValue?' checked="checked"':'').' onclick="'.htmlspecialchars($onClick).'"'.($tagParams?' '.$tagParams:'').' />';
2307 }
2308
2309 /**
2310 * Input field function menu
2311 * Works like ->getFuncMenu() / ->getFuncCheck() but displays a input field instead which updates the script "onchange"
2312 * Usage: 1
2313 *
2314 * @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=...
2315 * @param string $elementName it the form elements name, probably something like "SET[...]"
2316 * @param string $currentValue is the value to be selected currently.
2317 * @param integer Relative size of input field, max is 48
2318 * @param string $script is the script to send the &id to, if empty it's automatically found
2319 * @param string $addParams is additional parameters to pass to the script.
2320 * @return string HTML code for input text field.
2321 * @see getFuncMenu()
2322 */
2323 function getFuncInput($mainParams,$elementName,$currentValue,$size=10,$script="",$addparams="") {
2324 if (!is_array($mainParams)) {
2325 $mainParams = array('id' => $mainParams);
2326 }
2327 $mainParams = t3lib_div::implodeArrayForUrl('',$mainParams);
2328
2329 if (!$script) {basename(PATH_thisScript);}
2330 $onChange = 'jumpToUrl(\''.$script.'?'.$mainParams.$addparams.'&'.$elementName.'=\'+escape(this.value),this);';
2331 return '<input type="text"'.$GLOBALS['TBE_TEMPLATE']->formWidth($size).' name="'.$elementName.'" value="'.htmlspecialchars($currentValue).'" onchange="'.htmlspecialchars($onChange).'" />';
2332 }
2333
2334 /**
2335 * Removes menu items from $itemArray if they are configured to be removed by TSconfig for the module ($modTSconfig)
2336 * See Inside TYPO3 about how to program modules and use this API.
2337 * Usage: 4
2338 *
2339 * @param array Module TS config array
2340 * @param array Array of items from which to remove items.
2341 * @param string $TSref points to the "object string" in $modTSconfig
2342 * @return array The modified $itemArray is returned.
2343 */
2344 function unsetMenuItems($modTSconfig,$itemArray,$TSref) {
2345 // Getting TS-config options for this module for the Backend User:
2346 $conf = $GLOBALS['BE_USER']->getTSConfig($TSref,$modTSconfig);
2347 if (is_array($conf['properties'])) {
2348 reset($conf['properties']);
2349 while(list($key,$val)=each($conf['properties'])) {
2350 if (!$val) {
2351 unset($itemArray[$key]);
2352 }
2353 }
2354 }
2355 return $itemArray;
2356 }
2357
2358 /**
2359 * Call to update the page tree frame (or something else..?) after
2360 * t3lib_BEfunc::getSetUpdateSignal('updatePageTree') -> will set the page tree to be updated.
2361 * t3lib_BEfunc::getSetUpdateSignal() -> will return some JavaScript that does the update (called in the typo3/template.php file, end() function)
2362 * Usage: 11
2363 *
2364 * @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.
2365 * @return string HTML code (<script> section)
2366 */
2367 function getSetUpdateSignal($set='') {
2368 global $BE_USER;
2369 $key = 't3lib_BEfunc::getSetUpdateSignal';
2370 $out='';
2371 if ($set) {
2372 $modData=array();
2373 $modData['set']=$set;
2374 $BE_USER->pushModuleData($key,$modData);
2375 } else {
2376 $modData = $BE_USER->getModuleData($key,'ses');
2377 if (trim($modData['set'])) {
2378 $l=explode(',',$modData['set']);
2379 while(list(,$v)=each($l)) {
2380 switch($v) {
2381 case 'updatePageTree':
2382 case 'updateFolderTree':
2383 $out.='
2384 <script type="text/javascript">
2385 /*<![CDATA[*/
2386 if (top.content && top.content.nav_frame && top.content.nav_frame.refresh_nav) {
2387 top.content.nav_frame.refresh_nav();
2388 }
2389 /*]]>*/
2390 </script>';
2391 break;
2392 }
2393 }
2394 $modData=array();
2395 $modData['set']='';
2396 $BE_USER->pushModuleData($key,$modData);
2397 }
2398 }
2399 return $out;
2400 }
2401
2402
2403 /**
2404 * Returns an array which is most backend modules becomes MOD_SETTINGS containing values from function menus etc. determining the function of the module.
2405 * This is kind of session variable management framework for the backend users.
2406 * 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
2407 * Ultimately, see Inside TYPO3 for how to use this function in relation to your modules.
2408 * Usage: 23
2409 *
2410 * @param array MOD_MENU is an array that defines the options in menus.
2411 * @param array CHANGED_SETTINGS represents the array used when passing values to the script from the menus.
2412 * @param string modName is the name of this module. Used to get the correct module data.
2413 * @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.
2414 * @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.
2415 * @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)
2416 * @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
2417 */
2418 function getModuleData($MOD_MENU, $CHANGED_SETTINGS, $modName, $type='', $dontValidateList='', $setDefaultList='') {
2419
2420 if ($modName && is_string($modName)) {
2421 // GETTING stored user-data from this module:
2422 $settings = $GLOBALS['BE_USER']->getModuleData($modName,$type);
2423
2424 $changed=0;
2425 if (!is_array($settings)) {
2426 $changed=1;
2427 $settings=array();
2428 }
2429 if (is_array($MOD_MENU)) {
2430 reset($MOD_MENU);
2431 while(list($key,$var)=each($MOD_MENU)) {
2432 // If a global var is set before entering here. eg if submitted, then it's substituting the current value the array.
2433 if (is_array($CHANGED_SETTINGS) && isset($CHANGED_SETTINGS[$key]) && strcmp($settings[$key],$CHANGED_SETTINGS[$key])) {
2434 $settings[$key] = (string)$CHANGED_SETTINGS[$key];
2435 $changed=1;
2436 }
2437 // If the $var is an array, which denotes the existence of a menu, we check if the value is permitted
2438 if (is_array($var) && (!$dontValidateList || !t3lib_div::inList($dontValidateList,$key))) {
2439 // If the setting is an array or not present in the menu-array, MOD_MENU, then the default value is inserted.
2440 if (is_array($settings[$key]) || !isset($MOD_MENU[$key][$settings[$key]])) {
2441 $settings[$key]=(string)key($var);
2442 $changed=1;
2443 }
2444 }
2445 if ($setDefaultList && !is_array($var)) { // Sets default values (only strings/checkboxes, not menus)
2446 if (t3lib_div::inList($setDefaultList,$key) && !isset($settings[$key])) {
2447 $settings[$key]=$var;
2448 }
2449 }
2450 }
2451 } else {die ('No menu!');}
2452
2453 if ($changed) {
2454 $GLOBALS['BE_USER']->pushModuleData($modName,$settings);
2455 }
2456
2457 return $settings;
2458 } else {die ('Wrong module name: "'.$modName.'"');}
2459 }
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473 /*******************************************
2474 *
2475 * Core
2476 *
2477 *******************************************/
2478
2479 /**
2480 * Unlock or Lock a record from $table with $uid
2481 * If $table and $uid is not set, then all locking for the current BE_USER is removed!
2482 * Usage: 5
2483 *
2484 * @param string Table name
2485 * @param integer Record uid
2486 * @param integer Record pid
2487 * @return void
2488 * @internal
2489 * @see t3lib_transferData::lockRecord(), alt_doc.php, db_layout.php, db_list.php, wizard_rte.php
2490 */
2491 function lockRecords($table='',$uid=0,$pid=0) {
2492 $user_id = intval($GLOBALS['BE_USER']->user['uid']);
2493 if ($table && $uid) {
2494 $fields_values = array(
2495 'userid' => $user_id,
2496 'tstamp' => $GLOBALS['EXEC_TIME'],
2497 'record_table' => $table,
2498 'record_uid' => $uid,
2499 'username' => $GLOBALS['BE_USER']->user['username'],
2500 'record_pid' => $pid
2501 );
2502
2503 $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_lockedrecords', $fields_values);
2504 } else {
2505 $GLOBALS['TYPO3_DB']->exec_DELETEquery('sys_lockedrecords', 'userid='.intval($user_id));
2506 }
2507 }
2508
2509 /**
2510 * Returns information about whether the record from table, $table, with uid, $uid is currently locked (edited by another user - which should issue a warning).
2511 * 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.
2512 * Usage: 5
2513 *
2514 * @param string Table name
2515 * @param integer Record uid
2516 * @return array
2517 * @internal
2518 * @see class.db_layout.inc, alt_db_navframe.php, alt_doc.php, db_layout.php
2519 */
2520 function isRecordLocked($table,$uid) {
2521 global $LOCKED_RECORDS;
2522 if (!is_array($LOCKED_RECORDS)) {
2523 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
2524 '*',
2525 'sys_lockedrecords',
2526 'sys_lockedrecords.userid!='.intval($GLOBALS['BE_USER']->user['uid']).'
2527 AND sys_lockedrecords.tstamp > '.($GLOBALS['EXEC_TIME']-2*3600)
2528 );
2529 while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
2530 $LOCKED_RECORDS[$row['record_table'].':'.$row['record_uid']]=$row;
2531 $LOCKED_RECORDS[$row['record_table'].':'.$row['record_uid']]['msg']=sprintf(
2532 $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.lockedRecord'),
2533 $row['username'],
2534 t3lib_BEfunc::calcAge($GLOBALS['EXEC_TIME']-$row['tstamp'],$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears'))
2535 );
2536 if ($row['record_pid'] && !isset($LOCKED_RECORDS[$row['record_table'].':'.$row['record_pid']])) {
2537 $LOCKED_RECORDS['pages:'.$row['record_pid']]['msg']=sprintf(
2538 $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.lockedRecord_content'),
2539 $row['username'],
2540 t3lib_BEfunc::calcAge($GLOBALS['EXEC_TIME']-$row['tstamp'],$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears'))
2541 );
2542 }
2543 }
2544 }
2545 return $LOCKED_RECORDS[$table.':'.$uid];
2546 }
2547
2548 /**
2549 * Returns select statement for MM relations (as used by TCEFORMs etc)
2550 * Usage: 3
2551 *
2552 * @param array Configuration array for the field, taken from $TCA
2553 * @param string Field name
2554 * @param array TSconfig array from which to get further configuration settings for the field name
2555 * @param string Prefix string for the key "*foreign_table_where" from $fieldValue array
2556 * @return string Part of query
2557 * @internal
2558 * @see t3lib_transferData::renderRecord(), t3lib_TCEforms::foreignTable()
2559 */
2560 function exec_foreign_table_where_query($fieldValue,$field='',$TSconfig=array(),$prefix='') {
2561 global $TCA;
2562 $foreign_table = $fieldValue['config'][$prefix.'foreign_table'];
2563 $rootLevel = $TCA[$foreign_table]['ctrl']['rootLevel'];
2564
2565 $fTWHERE = $fieldValue['config'][$prefix.'foreign_table_where'];
2566 if (strstr($fTWHERE,'###REC_FIELD_')) {
2567 $fTWHERE_parts = explode('###REC_FIELD_',$fTWHERE);
2568 while(list($kk,$vv)=each($fTWHERE_parts)) {
2569 if ($kk) {
2570 $fTWHERE_subpart = explode('###',$vv,2);
2571 $fTWHERE_parts[$kk]=$TSconfig['_THIS_ROW'][$fTWHERE_subpart[0]].$fTWHERE_subpart[1];
2572 }
2573 }
2574 $fTWHERE = implode('',$fTWHERE_parts);
2575 }
2576
2577 $fTWHERE = str_replace('###CURRENT_PID###',intval($TSconfig['_CURRENT_PID']),$fTWHERE);
2578 $fTWHERE = str_replace('###THIS_UID###',intval($TSconfig['_THIS_UID']),$fTWHERE);
2579 $fTWHERE = str_replace('###THIS_CID###',intval($TSconfig['_THIS_CID']),$fTWHERE);
2580 $fTWHERE = str_replace('###STORAGE_PID###',intval($TSconfig['_STORAGE_PID']),$fTWHERE);
2581 $fTWHERE = str_replace('###SITEROOT###',intval($TSconfig['_SITEROOT']),$fTWHERE);
2582 $fTWHERE = str_replace('###PAGE_TSCONFIG_ID###',intval($TSconfig[$field]['PAGE_TSCONFIG_ID']),$fTWHERE);
2583 $fTWHERE = str_replace('###PAGE_TSCONFIG_IDLIST###',$GLOBALS['TYPO3_DB']->cleanIntList($TSconfig[$field]['PAGE_TSCONFIG_IDLIST']),$fTWHERE);
2584 $fTWHERE = str_replace('###PAGE_TSCONFIG_STR###',$GLOBALS['TYPO3_DB']->quoteStr($TSconfig[$field]['PAGE_TSCONFIG_STR'], $foreign_table),$fTWHERE);
2585
2586 // rootLevel = -1 is not handled 'properly' here - it goes as if it was rootLevel = 1 (that is pid=0)
2587 $wgolParts = $GLOBALS['TYPO3_DB']->splitGroupOrderLimit($fTWHERE);
2588 if ($rootLevel) {
2589 $queryParts = array(
2590 'SELECT' => t3lib_BEfunc::getCommonSelectFields($foreign_table,$foreign_table.'.'),
2591 'FROM' => $foreign_table,
2592 'WHERE' => $foreign_table.'.pid=0 '.
2593 t3lib_BEfunc::deleteClause($foreign_table).' '.
2594 $wgolParts['WHERE'],
2595 'GROUPBY' => $wgolParts['GROUPBY'],
2596 'ORDERBY' => $wgolParts['ORDERBY'],
2597 'LIMIT' => $wgolParts['LIMIT']
2598 );
2599 } else {
2600 $pageClause = $GLOBALS['BE_USER']->getPagePermsClause(1);
2601 if ($foreign_table!='pages') {
2602 $queryParts = array(
2603 'SELECT' => t3lib_BEfunc::getCommonSelectFields($foreign_table,$foreign_table.'.'),
2604 'FROM' => $foreign_table.',pages',
2605 'WHERE' => 'pages.uid='.$foreign_table.'.pid
2606 AND pages.deleted=0 '.
2607 t3lib_BEfunc::deleteClause($foreign_table).
2608 ' AND '.$pageClause.' '.
2609 $wgolParts['WHERE'],
2610 'GROUPBY' => $wgolParts['GROUPBY'],
2611 'ORDERBY' => $wgolParts['ORDERBY'],
2612 'LIMIT' => $wgolParts['LIMIT']
2613 );
2614 } else {
2615 $queryParts = array(
2616 'SELECT' => t3lib_BEfunc::getCommonSelectFields($foreign_table,$foreign_table.'.'),
2617 'FROM' => 'pages',
2618 'WHERE' => 'pages.deleted=0
2619 AND '.$pageClause.' '.
2620 $wgolParts['WHERE'],
2621 'GROUPBY' => $wgolParts['GROUPBY'],
2622 'ORDERBY' => $wgolParts['ORDERBY'],
2623 'LIMIT' => $wgolParts['LIMIT']
2624 );
2625 }
2626 }
2627
2628 return $GLOBALS['TYPO3_DB']->exec_SELECT_queryArray($queryParts);
2629 }
2630
2631 /**
2632 * Returns TSConfig for the TCEFORM object in Page TSconfig.
2633 * Used in TCEFORMs
2634 * Usage: 4
2635 *
2636 * @param string Table name present in TCA
2637 * @param array Row from table
2638 * @return array
2639 * @see t3lib_transferData::renderRecord(), t3lib_TCEforms::setTSconfig(), SC_wizard_list::main(), SC_wizard_add::main()
2640 */
2641 function getTCEFORM_TSconfig($table,$row) {
2642 t3lib_BEfunc::fixVersioningPid($table,$row);
2643
2644 $res = array();
2645 $typeVal = t3lib_BEfunc::getTCAtypeValue($table,$row);
2646
2647 // Get main config for the table
2648 list($TScID,$cPid) = t3lib_BEfunc::getTSCpid($table,$row['uid'],$row['pid']);
2649
2650 $rootLine = t3lib_BEfunc::BEgetRootLine($TScID,'',TRUE);
2651 if ($TScID>=0) {
2652 $tempConf = $GLOBALS['BE_USER']->getTSConfig('TCEFORM.'.$table,t3lib_BEfunc::getPagesTSconfig($TScID,$rootLine));
2653 if (is_array($tempConf['properties'])) {
2654 while(list($key,$val)=each($tempConf['properties'])) {
2655 if (is_array($val)) {
2656 $fieldN = substr($key,0,-1);
2657 $res[$fieldN] = $val;
2658 unset($res[$fieldN]['types.']);
2659 if (strcmp($typeVal,'') && is_array($val['types.'][$typeVal.'.'])) {
2660 $res[$fieldN] = t3lib_div::array_merge_recursive_overrule($res[$fieldN],$val['types.'][$typeVal.'.']);
2661 }
2662 }
2663 }
2664 }
2665 }
2666 $res['_CURRENT_PID']=$cPid;
2667 $res['_THIS_UID']=$row['uid'];
2668 $res['_THIS_CID']=$row['cid'];
2669 $res['_THIS_ROW']=$row; // So the row will be passed to foreign_table_where_query()
2670
2671 reset($rootLine);
2672 while(list(,$rC)=each($rootLine)) {
2673 if (!$res['_STORAGE_PID']) $res['_STORAGE_PID']=intval($rC['storage_pid']);
2674 if (!$res['_SITEROOT']) $res['_SITEROOT']=$rC['is_siteroot']?intval($rC['uid']):0;
2675 }
2676
2677 return $res;
2678 }
2679
2680 /**
2681 * 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).
2682 * Usage: 2
2683 *
2684 * @param string Table name
2685 * @param integer Record uid
2686 * @param integer Record pid
2687 * @return integer
2688 * @internal
2689 * @see t3lib_TCEmain::copyRecord(), getTSCpid()
2690 */
2691 function getTSconfig_pidValue($table,$uid,$pid) {
2692 if (t3lib_div::testInt($pid)) { // If pid is an integer this takes precedence in our lookup.
2693 $thePidValue = intval($pid);
2694 if ($thePidValue<0) { // If ref to another record, look that record up.
2695 $pidRec = t3lib_BEfunc::getRecord($table,abs($thePidValue),'pid');
2696 $thePidValue= is_array($pidRec) ? $pidRec['pid'] : -2; // Returns -2 if the record did not exist.
2697 }
2698 // ... else the pos/zero pid is just returned here.
2699 } else { // No integer pid and we are forced to look up the $pid
2700 $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...
2701 if (is_array($rr)) {
2702 $thePidValue = $rr['pid']; // Returning the 'pid' of the record
2703 } else $thePidValue=-1; // Returns -1 if the record with the pid was not found.
2704 }
2705 return $thePidValue;
2706 }
2707
2708 /**
2709 * Return $uid if $table is pages and $uid is integer - otherwise the $pid
2710 * Usage: 1
2711 *
2712 * @param string Table name
2713 * @param integer Record uid
2714 * @param integer Record pid
2715 * @return integer
2716 * @internal
2717 * @see t3lib_TCEforms::getTSCpid()
2718 */
2719 function getPidForModTSconfig($table,$uid,$pid) {
2720 $retVal = ($table=='pages' && t3lib_div::testInt($uid)) ? $uid : $pid;
2721 return $retVal;
2722 }
2723
2724 /**
2725 * 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.
2726 * Usage: 8
2727 *
2728 * @param string Table name
2729 * @param integer Record uid
2730 * @param integer Record pid
2731 * @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)
2732 * @internal
2733 * @see t3lib_TCEmain::setHistory(), t3lib_TCEmain::process_datamap()
2734 */
2735 function getTSCpid($table,$uid,$pid) {
2736 // If pid is negative (referring to another record) the pid of the other record is fetched and returned.
2737 $cPid = t3lib_BEfunc::getTSconfig_pidValue($table,$uid,$pid);
2738 // $TScID is the id of $table=pages, else it's the pid of the record.
2739 $TScID = t3lib_BEfunc::getPidForModTSconfig($table,$uid,$cPid);
2740
2741 return array($TScID,$cPid);
2742 }
2743
2744 /**
2745 * Returns first found domain record "domainName" (without trailing slash) if found in the input $rootLine
2746 * Usage: 2
2747 *
2748 * @param array Root line array
2749 * @return string Domain name, if found.
2750 */
2751 function firstDomainRecord($rootLine) {
2752 if (t3lib_extMgm::isLoaded('cms')) {
2753 reset($rootLine);
2754 while(list(,$row)=each($rootLine)) {
2755 $dRec = t3lib_BEfunc::getRecordsByField('sys_domain','pid',$row['uid'],' AND redirectTo=\'\' AND hidden=0', '', 'sorting');
2756 if (is_array($dRec)) {
2757 reset($dRec);
2758 $dRecord = current($dRec);
2759 return ereg_replace('\/$','',$dRecord['domainName']);
2760 }
2761 }
2762 }
2763 }
2764
2765 /**
2766 * Returns the sys_domain record for $domain, optionally with $path appended.
2767 * Usage: 2
2768 *
2769 * @param string Domain name
2770 * @param string Appended path
2771 * @return array Domain record, if found
2772 */
2773 function getDomainStartPage($domain, $path='') {
2774 if (t3lib_extMgm::isLoaded('cms')) {
2775 $domain = explode(':',$domain);
2776 $domain = strtolower(ereg_replace('\.$','',$domain[0]));
2777 // path is calculated.
2778 $path = trim(ereg_replace('\/[^\/]*$','',$path));
2779 // stuff:
2780 $domain.=$path;
2781
2782 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('sys_domain.*', 'pages,sys_domain', '
2783 pages.uid=sys_domain.pid
2784 AND sys_domain.hidden=0
2785 AND (sys_domain.domainName='.$GLOBALS['TYPO3_DB']->fullQuoteStr($domain, 'sys_domain').' or sys_domain.domainName='.$GLOBALS['TYPO3_DB']->fullQuoteStr($domain.'/', 'sys_domain').')'.
2786 t3lib_BEfunc::deleteClause('pages'),
2787 '', '', '1');
2788 return $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
2789 }
2790 }
2791
2792 /**
2793 * Returns overlayered RTE setup from an array with TSconfig. Used in TCEforms and TCEmain
2794 * Usage: 8
2795 *
2796 * @param array The properties of Page TSconfig in the key "RTE."
2797 * @param string Table name
2798 * @param string Field name
2799 * @param string Type value of the current record (like from CType of tt_content)
2800 * @return array Array with the configuration for the RTE
2801 * @internal
2802 */
2803 function RTEsetup($RTEprop,$table,$field,$type='') {
2804 $thisConfig = is_array($RTEprop['default.']) ? $RTEprop['default.'] : array();
2805 $thisFieldConf = $RTEprop['config.'][$table.'.'][$field.'.'];
2806 if (is_array($thisFieldConf)) {
2807 unset($thisFieldConf['types.']);
2808 $thisConfig = t3lib_div::array_merge_recursive_overrule($thisConfig,$thisFieldConf);
2809 }
2810 if ($type && is_array($RTEprop['config.'][$table.'.'][$field.'.']['types.'][$type.'.'])) {
2811 $thisConfig = t3lib_div::array_merge_recursive_overrule($thisConfig,$RTEprop['config.'][$table.'.'][$field.'.']['types.'][$type.'.']);
2812 }
2813 return $thisConfig;
2814 }
2815
2816 /**
2817 * Returns first possible RTE object if available.
2818 * Usage: $RTEobj = &t3lib_BEfunc::RTEgetObj();
2819 *
2820 * @return mixed If available, returns RTE object, otherwise an array of messages from possible RTEs
2821 */
2822 function &RTEgetObj() {
2823
2824 // If no RTE object has been set previously, try to create it:
2825 if (!isset($GLOBALS['T3_VAR']['RTEobj'])) {
2826
2827 // Set the object string to blank by default:
2828 $GLOBALS['T3_VAR']['RTEobj'] = array();
2829
2830 // Traverse registered RTEs:
2831 if (is_array($GLOBALS['TYPO3_CONF_VARS']['BE']['RTE_reg'])) {
2832 foreach($GLOBALS['TYPO3_CONF_VARS']['BE']['RTE_reg'] as $extKey => $rteObjCfg) {
2833 $rteObj = &t3lib_div::getUserObj($rteObjCfg['objRef']);
2834 if (is_object($rteObj)) {
2835 if ($rteObj->isAvailable()) {
2836 $GLOBALS['T3_VAR']['RTEobj'] = &$rteObj;
2837 break;
2838 } else {
2839 $GLOBALS['T3_VAR']['RTEobj'] = array_merge($GLOBALS['T3_VAR']['RTEobj'], $rteObj->errorLog);
2840 }
2841 }
2842 }
2843 }
2844
2845 if (!count($GLOBALS['T3_VAR']['RTEobj'])) {
2846 $GLOBALS['T3_VAR']['RTEobj'][] = 'No RTEs configured at all';
2847 }
2848 }
2849
2850 // Return RTE object (if any!)
2851 return $GLOBALS['T3_VAR']['RTEobj'];
2852 }
2853
2854 /**
2855 * Returns soft-reference parser for the softRef processing type
2856 * Usage: $softRefObj = &t3lib_BEfunc::softRefParserObj('[parser key]');
2857 *
2858 * @param string softRef parser key
2859 * @return mixed If available, returns Soft link parser object.
2860 */
2861 function &softRefParserObj($spKey) {
2862
2863 // If no softRef parser object has been set previously, try to create it:
2864 if (!isset($GLOBALS['T3_VAR']['softRefParser'][$spKey])) {
2865
2866 // Set the object string to blank by default:
2867 $GLOBALS['T3_VAR']['softRefParser'][$spKey] = '';
2868
2869 // Now, try to create parser object:
2870 $objRef = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['softRefParser'][$spKey] ?
2871 $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['softRefParser'][$spKey] :
2872 $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['softRefParser_GL'][$spKey];
2873 if ($objRef) {
2874 $softRefParserObj = &t3lib_div::getUserObj($objRef,'');
2875 if (is_object($softRefParserObj)) {
2876 $GLOBALS['T3_VAR']['softRefParser'][$spKey] = &$softRefParserObj;
2877 }
2878 }
2879 }
2880
2881 // Return RTE object (if any!)
2882 return $GLOBALS['T3_VAR']['softRefParser'][$spKey];
2883 }
2884
2885 /**
2886 * Returns array of soft parser references
2887 *
2888 * @param string softRef parser list
2889 * @param string Table name
2890 * @param string Field name
2891 * @return array Array where the parser key is the key and the value is the parameter string
2892 */
2893 function explodeSoftRefParserList($parserList, $table, $field) {
2894
2895 // Looking for global parsers:
2896 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['softRefParser_GL'])) {
2897 $parserList = implode(',',array_keys($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['softRefParser_GL'])).','.$parserList;
2898 }
2899
2900 // Return immediately if list is blank:
2901 if (!strlen($parserList)) return FALSE;
2902
2903 // Otherwise parse the list:
2904 $keyList = t3lib_div::trimExplode(',', $parserList, 1);
2905 $output = array();
2906
2907 foreach($keyList as $val) {
2908 $reg = array();
2909 if (ereg('^([[:alnum:]_-]+)\[(.*)\]$', $val, $reg)) {
2910 $output[$reg[1]] = t3lib_div::trimExplode(';', $reg[2], 1);
2911 } else {
2912 $output[$val] = '';
2913 }
2914 }
2915 return $output;
2916 }
2917
2918 /**
2919 * Returns true if $modName is set and is found as a main- or submodule in $TBE_MODULES array
2920 * Usage: 1
2921 *
2922 * @param string Module name
2923 * @return boolean
2924 */
2925 function isModuleSetInTBE_MODULES($modName) {
2926 reset($GLOBALS['TBE_MODULES']);
2927 $loaded=array();
2928 while(list($mkey,$list)=each($GLOBALS['TBE_MODULES'])) {
2929 $loaded[$mkey]=1;
2930 if (trim($list)) {
2931 $subList = t3lib_div::trimExplode(',',$list,1);
2932 while(list(,$skey)=each($subList)) {
2933 $loaded[$mkey.'_'.$skey]=1;
2934 }
2935 }
2936 }
2937 return $modName && isset($loaded[$modName]);
2938 }
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954 /*******************************************
2955 *
2956 * Workspaces / Versioning
2957 *
2958 *******************************************/
2959
2960 /**
2961 * Select all versions of a record, ordered by version id (DESC)
2962 *
2963 * @param string Table name to select from
2964 * @param integer Record uid for which to find versions.
2965 * @param string Field list to select
2966 * @param integer Workspace ID, if zero all versions regardless of workspace is found.
2967 * @return array Array of versions of table/uid
2968 */
2969 function selectVersionsOfRecord($table, $uid, $fields='*', $workspace=0) {
2970 global $TCA;
2971
2972 if ($TCA[$table] && $TCA[$table]['ctrl']['versioningWS']) {
2973
2974 // Select all versions of record:
2975 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
2976 $fields,
2977 $table,
2978 '((t3ver_oid='.intval($uid).($workspace!=0?' AND t3ver_wsid='.intval($workspace):'').') OR uid='.intval($uid).')'.
2979 t3lib_BEfunc::deleteClause($table),
2980 '',
2981 't3ver_id DESC'
2982 );
2983
2984 // Add rows to output array:
2985 $realPid = 0;
2986 $outputRows = array();
2987 while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
2988 if ($uid==$row['uid']) {
2989 $row['_CURRENT_VERSION']=TRUE;
2990 $realPid = $row['pid'];
2991 }
2992 $outputRows[] = $row;
2993 }
2994
2995 // Set real-pid:
2996 foreach($outputRows as $idx => $oRow) {
2997 $outputRows[$idx]['_REAL_PID'] = $realPid;
2998 }
2999
3000 return $outputRows;
3001 }
3002 }
3003
3004 /**
3005 * Find page-tree PID for versionized record
3006 * Will look if the "pid" value of the input record is -1 and if the table supports versioning - if so, it will translate the -1 PID into the PID of the original record
3007 * Used whenever you are tracking something back, like making the root line.
3008 * Principle; Record offline! => Find online?
3009 *
3010 * @param string Table name
3011 * @param array Record array passed by reference. As minimum, "pid" and "uid" fields must exist! "t3ver_oid" and "t3ver_wsid" is nice and will save you a DB query.
3012 * @return void (Passed by ref). If the record had its pid corrected to the online versions pid, then "_ORIG_pid" is set to the original pid value (-1 of course). The field "_ORIG_pid" is used by various other functions to detect if a record was in fact in a versionized branch.
3013 * @see t3lib_page::fixVersioningPid()