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