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