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