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