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