288826ffb525b21490523709880bf7461c37db5c
[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?'':'../').($uploaddir?$uploaddir.'/':'').trim($theFile);
1616 $params = '&file='.rawurlencode($theFile);
1617 $params .= $size?'&size='.$size:'';
1618 $url = $thumbScript.'?&dummy='.$GLOBALS['EXEC_TIME'].$params;
1619 $onClick='top.launchView(\''.$theFile.'\',\'\',\''.$backPath.'\');return false;';
1620 $thumbData.='<a href="#" onclick="'.htmlspecialchars($onClick).'"><img src="'.htmlspecialchars($backPath.$url).'" hspace="2" border="0" title="'.trim($theFile).'"'.$tparams.' alt="" /></a> ';
1621 } else {
1622 $icon = t3lib_BEfunc::getFileIcon($ext);
1623 $url = 'gfx/fileicons/'.$icon;
1624 $thumbData.='<img src="'.$backPath.$url.'" hspace="2" border="0" title="'.trim($theFile).'"'.$tparams.' alt="" /> ';
1625 }
1626 }
1627 }
1628 return $thumbData;
1629 }
1630
1631 /**
1632 * Returns single image tag to thumbnail using a thumbnail script (like thumbs.php)
1633 * Usage: 3
1634 *
1635 * @param string $thumbScript must point to "thumbs.php" relative to the script position
1636 * @param string $theFile must be the proper reference to the file thumbs.php should show
1637 * @param string $tparams are additional attributes for the image tag
1638 * @param integer $size is the size of the thumbnail send along to "thumbs.php"
1639 * @return string Image tag
1640 */
1641 function getThumbNail($thumbScript,$theFile,$tparams='',$size='') {
1642 $params = '&file='.rawurlencode($theFile);
1643 $params .= trim($size)?'&size='.trim($size):'';
1644 $url = $thumbScript.'?&dummy='.$GLOBALS['EXEC_TIME'].$params;
1645 $th='<img src="'.htmlspecialchars($url).'" title="'.trim(basename($theFile)).'"'.($tparams?" ".$tparams:"").' alt="" />';
1646 return $th;
1647 }
1648
1649 /**
1650 * Returns title-attribute information for a page-record informing about id, alias, doktype, hidden, starttime, endtime, fe_group etc.
1651 * Usage: 8
1652 *
1653 * @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)
1654 * @param string $perms_clause is used to get the record path of the shortcut page, if any (and doktype==4)
1655 * @param boolean If $includeAttrib is set, then the 'title=""' attribute is wrapped about the return value, which is in any case htmlspecialchar()'ed already
1656 * @return string
1657 */
1658 function titleAttribForPages($row,$perms_clause='',$includeAttrib=1) {
1659 global $TCA,$LANG;
1660 $parts=array();
1661 $parts[] = 'id='.$row['uid'];
1662 if ($row['alias']) $parts[]=$LANG->sL($TCA['pages']['columns']['alias']['label']).' '.$row['alias'];
1663 if ($row['pid']<0) $parts[] = 'v#1.'.$row['t3ver_id'];
1664 if ($row['t3ver_state']==1) $parts[] = 'PLH WSID#'.$row['t3ver_wsid'];
1665 if ($row['t3ver_state']==-1) $parts[] = 'New element!';
1666
1667 if ($row['doktype']=='3') {
1668 $parts[]=$LANG->sL($TCA['pages']['columns']['url']['label']).' '.$row['url'];
1669 } elseif ($row['doktype']=='4') {
1670 if ($perms_clause) {
1671 $label = t3lib_BEfunc::getRecordPath(intval($row['shortcut']),$perms_clause,20);
1672 } else {
1673 $lRec = t3lib_BEfunc::getRecordWSOL('pages',intval($row['shortcut']),'title');
1674 $label = $lRec['title'];
1675 }
1676 if ($row['shortcut_mode']>0) {
1677 $label.=', '.$LANG->sL($TCA['pages']['columns']['shortcut_mode']['label']).' '.
1678 $LANG->sL(t3lib_BEfunc::getLabelFromItemlist('pages','shortcut_mode',$row['shortcut_mode']));
1679 }
1680 $parts[]=$LANG->sL($TCA['pages']['columns']['shortcut']['label']).' '.$label;
1681 } elseif ($row['doktype']=='7') {
1682 if ($perms_clause) {
1683 $label = t3lib_BEfunc::getRecordPath(intval($row['mount_pid']),$perms_clause,20);
1684 } else {
1685 $lRec = t3lib_BEfunc::getRecordWSOL('pages',intval($row['mount_pid']),'title');
1686 $label = $lRec['title'];
1687 }
1688 $parts[]=$LANG->sL($TCA['pages']['columns']['mount_pid']['label']).' '.$label;
1689 if ($row['mount_pid_ol']) {
1690 $parts[] = $LANG->sL($TCA['pages']['columns']['mount_pid_ol']['label']);
1691 }
1692 }
1693 if ($row['nav_hide']) $parts[] = ereg_replace(':$','',$LANG->sL($TCA['pages']['columns']['nav_hide']['label']));
1694 if ($row['hidden']) $parts[] = $LANG->sL('LLL:EXT:lang/locallang_core.php:labels.hidden');
1695 if ($row['starttime']) $parts[] = $LANG->sL($TCA['pages']['columns']['starttime']['label']).' '.t3lib_BEfunc::dateTimeAge($row['starttime'],-1,'date');
1696 if ($row['endtime']) $parts[] = $LANG->sL($TCA['pages']['columns']['endtime']['label']).' '.t3lib_BEfunc::dateTimeAge($row['endtime'],-1,'date');
1697 if ($row['fe_group']) {
1698 if ($row['fe_group']<0) {
1699 $label = $LANG->sL(t3lib_BEfunc::getLabelFromItemlist('pages','fe_group',$row['fe_group']));
1700 } else {
1701 $lRec = t3lib_BEfunc::getRecordWSOL('fe_groups',$row['fe_group'],'title');
1702 $label = $lRec['title'];
1703 }
1704 $parts[] = $LANG->sL($TCA['pages']['columns']['fe_group']['label']).' '.$label;
1705 }
1706 $out = htmlspecialchars(implode(' - ',$parts));
1707 return $includeAttrib ? 'title="'.$out.'"' : $out;
1708 }
1709
1710 /**
1711 * Returns title-attribute information for ANY record (from a table defined in TCA of course)
1712 * 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.
1713 * "pages" table can be used as well and will return the result of ->titleAttribForPages() for that page.
1714 * Usage: 10
1715 *
1716 * @param array Table row; $row is a row from the table, $table
1717 * @param string Table name
1718 * @return string
1719 */
1720 function getRecordIconAltText($row,$table='pages') {
1721 if ($table=='pages') {
1722 $out = t3lib_BEfunc::titleAttribForPages($row,'',0);
1723 } else {
1724 $ctrl = $GLOBALS['TCA'][$table]['ctrl']['enablecolumns'];
1725
1726 $out='id='.$row['uid']; // Uid is added
1727 if ($table=='pages' && $row['alias']) {
1728 $out.=' / '.$row['alias'];
1729 }
1730 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS'] && $row['pid']<0) {
1731 $out.=' - v#1.'.$row['t3ver_id'];
1732 }
1733 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
1734 if ($row['t3ver_state']==1) $out.= ' - PLH WSID#'.$row['t3ver_wsid'];
1735 if ($row['t3ver_state']==-1) $out.= ' - New element!';
1736 }
1737
1738 if ($ctrl['disabled']) { // Hidden ...
1739 $out.=($row[$ctrl['disabled']]?' - '.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.hidden'):'');
1740 }
1741 if ($ctrl['starttime']) {
1742 if ($row[$ctrl['starttime']] > $GLOBALS['EXEC_TIME']) {
1743 $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').')';
1744 }
1745 }
1746 if ($row[$ctrl['endtime']]) {
1747 $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').')';
1748 }
1749 }
1750 return htmlspecialchars($out);
1751 }
1752
1753 /**
1754 * Returns the label of the first found entry in an "items" array from $TCA (tablename=$table/fieldname=$col) where the value is $key
1755 * Usage: 9
1756 *
1757 * @param string Table name, present in $TCA
1758 * @param string Field name, present in $TCA
1759 * @param string items-array value to match
1760 * @return string Label for item entry
1761 */
1762 function getLabelFromItemlist($table,$col,$key) {
1763 global $TCA;
1764 // Load full TCA for $table
1765 t3lib_div::loadTCA($table);
1766
1767 // Check, if there is an "items" array:
1768 if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$col]) && is_array($TCA[$table]['columns'][$col]['config']['items'])) {
1769 // Traverse the items-array...
1770 reset($TCA[$table]['columns'][$col]['config']['items']);
1771 while(list($k,$v)=each($TCA[$table]['columns'][$col]['config']['items'])) {
1772 // ... and return the first found label where the value was equal to $key
1773 if (!strcmp($v[1],$key)) return $v[0];
1774 }
1775 }
1776 }
1777
1778 /**
1779 * Returns the label-value for fieldname $col in table, $table
1780 * 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>'
1781 * Usage: 17
1782 *
1783 * @param string Table name, present in $TCA
1784 * @param string Field name
1785 * @param string Wrap value - set function description
1786 * @return string
1787 */
1788 function getItemLabel($table,$col,$printAllWrap='') {
1789 global $TCA;
1790 // Load full TCA for $table
1791 t3lib_div::loadTCA($table);
1792 // Check if column exists
1793 if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$col])) {
1794 // Re
1795 return $TCA[$table]['columns'][$col]['label'];
1796 }
1797 if ($printAllWrap) {
1798 $parts = explode('|',$printAllWrap);
1799 return $parts[0].$col.$parts[1];
1800 }
1801 }
1802
1803 /**
1804 * Returns the "title"-value in record, $row, from table, $table
1805 * The field(s) from which the value is taken is determined by the "ctrl"-entries 'label', 'label_alt' and 'label_alt_force'
1806 * Usage: 26
1807 *
1808 * @param string Table name, present in TCA
1809 * @param array Row from table
1810 * @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
1811 * @return string
1812 */
1813 function getRecordTitle($table,$row,$prep=0) {
1814 global $TCA;
1815 if (is_array($TCA[$table])) {
1816 $t = $row[$TCA[$table]['ctrl']['label']];
1817 if ($TCA[$table]['ctrl']['label_alt'] && ($TCA[$table]['ctrl']['label_alt_force'] || !strcmp($t,''))) {
1818 $altFields=t3lib_div::trimExplode(',',$TCA[$table]['ctrl']['label_alt'],1);
1819 $tA=array();
1820 $tA[]=$t;
1821 while(list(,$fN)=each($altFields)) {
1822 $t = $tA[] = trim(strip_tags($row[$fN]));
1823 if (strcmp($t,'') && !$TCA[$table]['ctrl']['label_alt_force']) break;
1824 }
1825 if ($TCA[$table]['ctrl']['label_alt_force']) $t=implode(', ',$tA);
1826 }
1827 if ($prep) {
1828 $t = htmlspecialchars(t3lib_div::fixed_lgd_cs($t,$GLOBALS['BE_USER']->uc['titleLen']));
1829 if (!strcmp(trim($t),'')) $t='<em>['.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.no_title',1).']</em>';
1830 }
1831 return $t;
1832 }
1833 }
1834
1835 /**
1836 * Returns a human readable output of a value from a record
1837 * 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.
1838 * $table/$col is tablename and fieldname
1839 * REMEMBER to pass the output through htmlspecialchars() if you output it to the browser! (To protect it from XSS attacks and be XHTML compliant)
1840 * Usage: 24
1841 *
1842 * @param string Table name, present in TCA
1843 * @param string Field name, present in TCA
1844 * @param string $value is the value of that field from a selected record
1845 * @param integer $fixed_lgd_chars is the max amount of characters the value may occupy
1846 * @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")
1847 * @param boolean If set, no records will be looked up, UIDs are just shown.
1848 * @param integer uid of the current record
1849 * @return string
1850 */
1851 function getProcessedValue($table,$col,$value,$fixed_lgd_chars=0,$defaultPassthrough=0,$noRecordLookup=FALSE,$uid=0) {
1852 global $TCA;
1853 global $TYPO3_CONF_VARS;
1854 // Load full TCA for $table
1855 t3lib_div::loadTCA($table);
1856 // Check if table and field is configured:
1857 if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$col])) {
1858 // Depending on the fields configuration, make a meaningful output value.
1859 $theColConf = $TCA[$table]['columns'][$col]['config'];
1860
1861 /*****************
1862 *HOOK: pre-processing the human readable output from a record
1863 ****************/
1864 if (is_array ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['preProcessValue'])) {
1865 foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['preProcessValue'] as $_funcRef) {
1866 t3lib_div::callUserFunction($_funcRef,$theColConf,$this);
1867 }
1868 }
1869
1870 $l='';
1871 switch((string)$theColConf['type']) {
1872 case 'radio':
1873 $l=t3lib_BEfunc::getLabelFromItemlist($table,$col,$value);
1874 $l=$GLOBALS['LANG']->sL($l);
1875 break;
1876 case 'select':
1877 if ($theColConf['MM']) {
1878 // Display the title of MM related records in lists
1879 if ($noRecordLookup) {
1880 $MMfield = $theColConf['foreign_table'].'.uid';
1881 } else {
1882 $MMfields = array($theColConf['foreign_table'].'.'.$TCA[$theColConf['foreign_table']]['ctrl']['label']);
1883 foreach (t3lib_div::trimExplode(',', $TCA[$theColConf['foreign_table']]['ctrl']['label_alt'], 1) as $f) {
1884 $MMfields[] = $theColConf['foreign_table'].'.'.$f;
1885 }
1886 $MMfield = join(',',$MMfields);
1887 }
1888
1889 $dbGroup = t3lib_div::makeInstance('t3lib_loadDBGroup');
1890 $dbGroup->start($value, $theColConf['foreign_table'], $theColConf['MM'], $uid, $table, $theColConf);
1891 $selectUids = $dbGroup->tableArray[$theColConf['foreign_table']];
1892
1893 if (is_array($selectUids) && count($selectUids)>0) {
1894 $MMres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
1895 'uid, '.$MMfield,
1896 $theColConf['foreign_table'],
1897 'uid IN ('.implode(',', $selectUids).')'
1898 );
1899 while($MMrow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($MMres)) {
1900 $mmlA[] = ($noRecordLookup?$MMrow['uid']:t3lib_BEfunc::getRecordTitle($theColConf['foreign_table'], $MMrow));
1901 }
1902 if (is_array($mmlA)) {
1903 $l=implode('; ',$mmlA);
1904 } else {
1905 $l = '';
1906 }
1907 } else {
1908 $l = 'n/A';
1909 }
1910 } else {
1911 $l = t3lib_BEfunc::getLabelFromItemlist($table,$col,$value);
1912 $l = $GLOBALS['LANG']->sL($l);
1913 if ($theColConf['foreign_table'] && !$l && $TCA[$theColConf['foreign_table']]) {
1914 if ($noRecordLookup) {
1915 $l = $value;
1916 } else {
1917 $rParts = t3lib_div::trimExplode(',',$value,1);
1918 reset($rParts);
1919 $lA = array();
1920 while(list(,$rVal)=each($rParts)) {
1921 $rVal = intval($rVal);
1922 if ($rVal>0) {
1923 $r=t3lib_BEfunc::getRecordWSOL($theColConf['foreign_table'],$rVal);
1924 } else {
1925 $r=t3lib_BEfunc::getRecordWSOL($theColConf['neg_foreign_table'],-$rVal);
1926 }
1927 if (is_array($r)) {
1928 $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);
1929 } else {
1930 $lA[]=$rVal?'['.$rVal.'!]':'';
1931 }
1932 }
1933 $l = implode(', ',$lA);
1934 }
1935 }
1936 }
1937 break;
1938 case 'group':
1939 $l = implode(', ',t3lib_div::trimExplode(',',$value,1));
1940 break;
1941 case 'check':
1942 if (!is_array($theColConf['items']) || count($theColConf['items'])==1) {
1943 $l = $value ? 'Yes' : '';
1944 } else {
1945 reset($theColConf['items']);
1946 $lA=Array();
1947 while(list($key,$val)=each($theColConf['items'])) {
1948 if ($value & pow(2,$key)) {$lA[]=$GLOBALS['LANG']->sL($val[0]);}
1949 }
1950 $l = implode(', ',$lA);
1951 }
1952 break;
1953 case 'input':
1954 if ($value) {
1955 if (t3lib_div::inList($theColConf['eval'],'date')) {
1956 $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')).')';
1957 } elseif (t3lib_div::inList($theColConf['eval'],'time')) {
1958 $l = t3lib_BEfunc::time($value);
1959 } elseif (t3lib_div::inList($theColConf['eval'],'datetime')) {
1960 $l = t3lib_BEfunc::datetime($value);
1961 } else {
1962 $l = $value;
1963 }
1964 }
1965 break;
1966 case 'flex':
1967 $l = strip_tags($value);
1968 break;
1969 default:
1970 if ($defaultPassthrough) {
1971 $l=$value;
1972 } elseif ($theColConf['MM']) {
1973 $l='N/A';
1974 } elseif ($value) {
1975 $l=t3lib_div::fixed_lgd_cs(strip_tags($value),200);
1976 }
1977 break;
1978 }
1979
1980 /*****************
1981 *HOOK: post-processing the human readable output from a record
1982 ****************/
1983 if (is_array ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['postProcessValue'])) {
1984 foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['postProcessValue'] as $_funcRef) {
1985 $params = array(
1986 'value' => $l,
1987 'colConf' => $theColConf
1988 );
1989 $l = t3lib_div::callUserFunction($_funcRef,$params,$this);
1990 }
1991 }
1992
1993 if ($fixed_lgd_chars) {
1994 return t3lib_div::fixed_lgd_cs($l,$fixed_lgd_chars);
1995 } else {
1996 return $l;
1997 }
1998 }
1999 }
2000
2001 /**
2002 * 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.
2003 * Usage: 2
2004 *
2005 * @param string Table name, present in TCA
2006 * @param string Field name
2007 * @param string Field value
2008 * @param integer $fixed_lgd_chars is the max amount of characters the value may occupy
2009 * @param integer uid of the current record
2010 * @return string
2011 * @see getProcessedValue()
2012 */
2013 function getProcessedValueExtra($table,$fN,$fV,$fixed_lgd_chars=0,$uid=0) {
2014 global $TCA;
2015 $fVnew = t3lib_BEfunc::getProcessedValue($table,$fN,$fV,$fixed_lgd_chars,0,0,$uid);
2016 if (!isset($fVnew)) {
2017 if (is_array($TCA[$table])) {
2018 if ($fN==$TCA[$table]['ctrl']['tstamp'] || $fN==$TCA[$table]['ctrl']['crdate']) {
2019 $fVnew = t3lib_BEfunc::datetime($fV);
2020 } elseif ($fN=='pid'){
2021 $fVnew = t3lib_BEfunc::getRecordPath($fV,'1=1',20); // Fetches the path with no regard to the users permissions to select pages.
2022 } else {
2023 $fVnew = $fV;
2024 }
2025 }
2026 }
2027 return $fVnew;
2028 }
2029
2030 /**
2031 * Returns file icon name (from $FILEICONS) for the fileextension $ext
2032 * Usage: 10
2033 *
2034 * @param string File extension, lowercase
2035 * @return string File icon filename
2036 */
2037 function getFileIcon($ext) {
2038 return $GLOBALS['FILEICONS'][$ext] ? $GLOBALS['FILEICONS'][$ext] : $GLOBALS['FILEICONS']['default'];
2039 }
2040
2041 /**
2042 * Returns fields for a table, $table, which would typically be interesting to select
2043 * This includes uid, the fields defined for title, icon-field.
2044 * 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)
2045 * Usage: 3
2046 *
2047 * @param string Table name, present in TCA
2048 * @param string Table prefix
2049 * @param array Preset fields (must include prefix if that is used)
2050 * @return string List of fields.
2051 */
2052 function getCommonSelectFields($table,$prefix='',$fields = array()) {
2053 global $TCA;
2054 $fields[] = $prefix.'uid';
2055 $fields[] = $prefix.$TCA[$table]['ctrl']['label'];
2056
2057 if ($TCA[$table]['ctrl']['label_alt']) {
2058 $secondFields = t3lib_div::trimExplode(',',$TCA[$table]['ctrl']['label_alt'],1);
2059 foreach($secondFields as $fieldN) {
2060 $fields[] = $prefix.$fieldN;
2061 }
2062 }
2063 if ($TCA[$table]['ctrl']['versioningWS']) {
2064 $fields[] = $prefix.'t3ver_id';
2065 $fields[] = $prefix.'t3ver_state';
2066 $fields[] = $prefix.'t3ver_wsid';
2067 $fields[] = $prefix.'t3ver_count';
2068 }
2069
2070 if ($TCA[$table]['ctrl']['selicon_field']) $fields[] = $prefix.$TCA[$table]['ctrl']['selicon_field'];
2071 if ($TCA[$table]['ctrl']['typeicon_column']) $fields[] = $prefix.$TCA[$table]['ctrl']['typeicon_column'];
2072
2073 if (is_array($TCA[$table]['ctrl']['enablecolumns'])) {
2074 if ($TCA[$table]['ctrl']['enablecolumns']['disabled']) $fields[] = $prefix.$TCA[$table]['ctrl']['enablecolumns']['disabled'];
2075 if ($TCA[$table]['ctrl']['enablecolumns']['starttime']) $fields[] = $prefix.$TCA[$table]['ctrl']['enablecolumns']['starttime'];
2076 if ($TCA[$table]['ctrl']['enablecolumns']['endtime']) $fields[] = $prefix.$TCA[$table]['ctrl']['enablecolumns']['endtime'];
2077 if ($TCA[$table]['ctrl']['enablecolumns']['fe_group']) $fields[] = $prefix.$TCA[$table]['ctrl']['enablecolumns']['fe_group'];
2078 }
2079
2080 return implode(',', array_unique($fields));
2081 }
2082
2083 /**
2084 * 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
2085 * <form>-tags must be supplied separately
2086 * 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.
2087 * Usage: 1 (ext. direct_mail)
2088 *
2089 * @param array Field configuration code.
2090 * @param array Defaults
2091 * @param string Prefix for formfields
2092 * @return string HTML for a form.
2093 */
2094 function makeConfigForm($configArray,$defaults,$dataPrefix) {
2095 $params = $defaults;
2096 if (is_array($configArray)) {
2097 reset($configArray);
2098 $lines=array();
2099 while(list($fname,$config)=each($configArray)) {
2100 if (is_array($config)) {
2101 $lines[$fname]='<strong>'.htmlspecialchars($config[1]).'</strong><br />';
2102 $lines[$fname].=$config[2].'<br />';
2103 switch($config[0]) {
2104 case 'string':
2105 case 'short':
2106 $formEl = '<input type="text" name="'.$dataPrefix.'['.$fname.']" value="'.$params[$fname].'"'.$GLOBALS['TBE_TEMPLATE']->formWidth($config[0]=='short'?24:48).' />';
2107 break;
2108 case 'check':
2109 $formEl = '<input type="hidden" name="'.$dataPrefix.'['.$fname.']" value="0" /><input type="checkbox" name="'.$dataPrefix.'['.$fname.']" value="1"'.($params[$fname]?' checked="checked"':'').' />';
2110 break;
2111 case 'comment':
2112 $formEl = '';
2113 break;
2114 case 'select':
2115 reset($config[3]);
2116 $opt=array();
2117 while(list($k,$v)=each($config[3])) {
2118 $opt[]='<option value="'.htmlspecialchars($k).'"'.($params[$fname]==$k?' selected="selected"':'').'>'.htmlspecialchars($v).'</option>';
2119 }
2120 $formEl = '<select name="'.$dataPrefix.'['.$fname.']">'.implode('',$opt).'</select>';
2121 break;
2122 default:
2123 debug($config);
2124 break;
2125 }
2126 $lines[$fname].=$formEl;
2127 $lines[$fname].='<br /><br />';
2128 } else {
2129 $lines[$fname]='<hr />';
2130 if ($config) $lines[$fname].='<strong>'.strtoupper(htmlspecialchars($config)).'</strong><br />';
2131 if ($config) $lines[$fname].='<br />';
2132 }
2133 }
2134 }
2135 $out = implode('',$lines);
2136 $out.='<input type="submit" name="submit" value="Update configuration" />';
2137 return $out;
2138 }
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152 /*******************************************
2153 *
2154 * Backend Modules API functions
2155 *
2156 *******************************************/
2157
2158 /**
2159 * Returns help-text icon if configured for.
2160 * TCA_DESCR must be loaded prior to this function and $BE_USER must have 'edit_showFieldHelp' set to 'icon', otherwise nothing is returned
2161 * Usage: 6
2162 *
2163 * @param string Table name
2164 * @param string Field name
2165 * @param string Back path
2166 * @param boolean Force display of icon nomatter BE_USER setting for help
2167 * @return string HTML content for a help icon/text
2168 */
2169 function helpTextIcon($table,$field,$BACK_PATH,$force=0) {
2170 global $TCA_DESCR,$BE_USER;
2171 if (is_array($TCA_DESCR[$table]) && is_array($TCA_DESCR[$table]['columns'][$field]) && ($BE_USER->uc['edit_showFieldHelp']=='icon' || $force)) {
2172 $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;';
2173 return '<a href="#" onclick="'.htmlspecialchars($onClick).'">'.
2174 '<img'.t3lib_iconWorks::skinImg($BACK_PATH,'gfx/helpbubble.gif','width="14" height="14"').' hspace="2" border="0" class="typo3-csh-icon" alt="" />'.
2175 '</a>';
2176 }
2177 }
2178
2179 /**
2180 * Returns CSH help text (description), if configured for.
2181 * TCA_DESCR must be loaded prior to this function and $BE_USER must have "edit_showFieldHelp" set to "text", otherwise nothing is returned
2182 * Will automatically call t3lib_BEfunc::helpTextIcon() to get the icon for the text.
2183 * Usage: 4
2184 *
2185 * @param string Table name
2186 * @param string Field name
2187 * @param string Back path
2188 * @param string Additional style-attribute content for wrapping table
2189 * @return string HTML content for help text
2190 */
2191 function helpText($table,$field,$BACK_PATH,$styleAttrib='') {
2192 global $TCA_DESCR,$BE_USER;
2193 if (is_array($TCA_DESCR[$table]) && is_array($TCA_DESCR[$table]['columns'][$field]) && $BE_USER->uc['edit_showFieldHelp']=='text') {
2194 $fDat = $TCA_DESCR[$table]['columns'][$field];
2195
2196 // Get Icon:
2197 $editIcon = t3lib_BEfunc::helpTextIcon(
2198 $table,
2199 $field,
2200 $BACK_PATH,
2201 TRUE
2202 );
2203 // Add title?
2204 $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;';
2205 $text =
2206 ($fDat['alttitle'] ? '<h4><a href="#" onclick="'.htmlspecialchars($onClick).'">'.$fDat['alttitle'].'</a></h4>' : '').
2207 $fDat['description'];
2208
2209 // More information to get?
2210 if ($fDat['image_descr'] || $fDat['seeAlso'] || $fDat['details'] || $fDat['syntax']) { // || $fDat['image'];
2211 $text.=' <a href="#" onclick="'.htmlspecialchars($onClick).'">'.
2212 '<img'.t3lib_iconWorks::skinImg($BACK_PATH,'gfx/rel_db.gif','width="13" height="12"').' class="absmiddle typo3-csh-more" alt="" />'.
2213 '</a>';
2214 }
2215
2216 // Additional styles?
2217 $params = $styleAttrib ? ' style="'.$styleAttrib.'"' : '';
2218
2219 // Compile table with CSH information:
2220 return '<table border="0" cellpadding="2" cellspacing="0" class="typo3-csh-inline"'.$params.'>
2221 <tr>
2222 <td valign="top" width="14">'.$editIcon.'</td>
2223 <td valign="top">'.$text.'</td>
2224 </tr>
2225 </table>';
2226 }
2227 }
2228
2229 /**
2230 * API for getting CSH icons/text for use in backend modules.
2231 * TCA_DESCR will be loaded if it isn't already
2232 * Usage: ?
2233 *
2234 * @param string Table name ('_MOD_'+module name)
2235 * @param string Field name (CSH locallang main key)
2236 * @param string Back path
2237 * @param string Wrap code for icon-mode, splitted by "|". Not used for full-text mode.
2238 * @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.
2239 * @param string Additional style-attribute content for wrapping table (full text mode only)
2240 * @return string HTML content for help text
2241 * @see helpText(), helpTextIcon()
2242 */
2243 function cshItem($table,$field,$BACK_PATH,$wrap='',$onlyIconMode=FALSE, $styleAttrib='') {
2244 global $TCA_DESCR, $LANG, $BE_USER;
2245 if ($BE_USER->uc['edit_showFieldHelp']) {
2246 $LANG->loadSingleTableDescription($table);
2247
2248 if (is_array($TCA_DESCR[$table])) {
2249 // Creating CSH icon and short description:
2250 $fullText = t3lib_BEfunc::helpText($table,$field,$BACK_PATH,$styleAttrib);
2251 $icon = t3lib_BEfunc::helpTextIcon($table,$field,$BACK_PATH,$onlyIconMode);
2252
2253 if ($fullText && !$onlyIconMode) {
2254 $output = $GLOBALS['LANG']->hscAndCharConv($fullText, false);
2255 } else {
2256 #$output = '<span style="position:absolute; filter: alpha(opacity=50); -moz-opacity: 0.50;">'.$icon.'</span>';
2257 $output = $icon;
2258
2259 if ($output && $wrap) {
2260 $wrParts = explode('|',$wrap);
2261 $output = $wrParts[0].$output.$wrParts[1];
2262 }
2263 }
2264
2265 return $output;
2266 }
2267 }
2268 }
2269
2270 /**
2271 * 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.
2272 * REMEMBER to always htmlspecialchar() content in href-properties to ampersands get converted to entities (XHTML requirement and XSS precaution)
2273 * Usage: 35
2274 *
2275 * @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.
2276 * @param string $backPath must point back to the TYPO3_mainDir directory (where alt_doc.php is)
2277 * @param string $requestUri is an optional returnUrl you can set - automatically set to REQUEST_URI.
2278 * @return string
2279 * @see template::issueCommand()
2280 */
2281 function editOnClick($params,$backPath='',$requestUri='') {
2282 $retUrl = 'returnUrl='.($requestUri==-1?"'+T3_THIS_LOCATION+'":rawurlencode($requestUri?$requestUri:t3lib_div::getIndpEnv('REQUEST_URI')));
2283 return "window.location.href='".$backPath."alt_doc.php?".$retUrl.$params."'; return false;";
2284 }
2285
2286 /**
2287 * Returns a JavaScript string for viewing the page id, $id
2288 * 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.
2289 * Usage: 8
2290 *
2291 * @param integer $id is page id
2292 * @param string $backpath must point back to TYPO3_mainDir (where the site is assumed to be one level above)
2293 * @param array If root line is supplied the function will look for the first found domain record and use that URL instead (if found)
2294 * @param string $anchor is optional anchor to the URL
2295 * @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!
2296 * @param string Additional GET variables.
2297 * @param boolean If true, then the preview window will gain the focus.
2298 * @return string
2299 */
2300 function viewOnClick($id,$backPath='',$rootLine='',$anchor='',$altUrl='',$addGetVars='',$switchFocus=TRUE) {
2301 if ($altUrl) {
2302 $url = $altUrl;
2303 } else {
2304
2305 if ($GLOBALS['BE_USER']->workspace!=0) {
2306 $url = t3lib_div::getIndpEnv('TYPO3_SITE_URL').TYPO3_mainDir.'mod/user/ws/wsol_preview.php?id='.$id.$addGetVars.$anchor;
2307 } else {
2308 if ($rootLine) {
2309 $parts = parse_url(t3lib_div::getIndpEnv('TYPO3_SITE_URL'));
2310 if (t3lib_BEfunc::getDomainStartPage($parts['host'],$parts['path'])) {
2311 $preUrl_temp = t3lib_BEfunc::firstDomainRecord($rootLine);
2312 }
2313 }
2314 $preUrl = $preUrl_temp ? (t3lib_div::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://').$preUrl_temp : $backPath.'..';
2315 $url = $preUrl.'/index.php?id='.$id.$addGetVars.$anchor;
2316 }
2317 }
2318
2319 return "previewWin=window.open('".$url."','newTYPO3frontendWindow');".
2320 ($switchFocus ? 'previewWin.focus();' : '');
2321 }
2322
2323 /**
2324 * Returns the merged User/Page TSconfig for page id, $id.
2325 * Please read details about module programming elsewhere!
2326 * Usage: 15
2327 *
2328 * @param integer Page uid
2329 * @param string $TSref is an object string which determines the path of the TSconfig to return.
2330 * @return array
2331 */
2332 function getModTSconfig($id,$TSref) {
2333 $pageTS_modOptions = $GLOBALS['BE_USER']->getTSConfig($TSref,t3lib_BEfunc::getPagesTSconfig($id));
2334 $BE_USER_modOptions = $GLOBALS['BE_USER']->getTSConfig($TSref);
2335 $modTSconfig = t3lib_div::array_merge_recursive_overrule($pageTS_modOptions,$BE_USER_modOptions);
2336 return $modTSconfig;
2337 }
2338
2339 /**
2340 * Returns a selector box "function menu" for a module
2341 * Requires the JS function jumpToUrl() to be available
2342 * See Inside TYPO3 for details about how to use / make Function menus
2343 * Usage: 50
2344 *
2345 * @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=...
2346 * @param string $elementName it the form elements name, probably something like "SET[...]"
2347 * @param string $currentValue is the value to be selected currently.
2348 * @param array $menuItems is an array with the menu items for the selector box
2349 * @param string $script is the script to send the &id to, if empty it's automatically found
2350 * @param string $addParams is additional parameters to pass to the script.
2351 * @return string HTML code for selector box
2352 */
2353 function getFuncMenu($mainParams,$elementName,$currentValue,$menuItems,$script='',$addparams='') {
2354 if (is_array($menuItems)) {
2355 if (!is_array($mainParams)) {
2356 $mainParams = array('id' => $mainParams);
2357 }
2358 $mainParams = t3lib_div::implodeArrayForUrl('',$mainParams);
2359
2360 if (!$script) {
2361 $script = basename(PATH_thisScript);
2362 $mainParams.= (t3lib_div::_GET('M') ? '&M='.rawurlencode(t3lib_div::_GET('M')) : '');
2363 }
2364
2365 $options = array();
2366 foreach($menuItems as $value => $label) {
2367 $options[] = '<option value="'.htmlspecialchars($value).'"'.(!strcmp($currentValue,$value)?' selected="selected"':'').'>'.
2368 t3lib_div::deHSCentities(htmlspecialchars($label)).
2369 '</option>';
2370 }
2371 if (count($options)) {
2372 $onChange = 'jumpToUrl(\''.$script.'?'.$mainParams.$addparams.'&'.$elementName.'=\'+this.options[this.selectedIndex].value,this);';
2373 return '
2374
2375 <!-- Function Menu of module -->
2376 <select name="'.$elementName.'" onchange="'.htmlspecialchars($onChange).'">
2377 '.implode('
2378 ',$options).'
2379 </select>
2380 ';
2381 }
2382 }
2383 }
2384
2385 /**
2386 * Checkbox function menu.
2387 * Works like ->getFuncMenu() but takes no $menuItem array since this is a simple checkbox.
2388 * Usage: 34
2389 *
2390 * @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=...
2391 * @param string $elementName it the form elements name, probably something like "SET[...]"
2392 * @param string $currentValue is the value to be selected currently.
2393 * @param string $script is the script to send the &id to, if empty it's automatically found
2394 * @param string $addParams is additional parameters to pass to the script.
2395 * @param string Additional attributes for the checkbox input tag
2396 * @return string HTML code for checkbox
2397 * @see getFuncMenu()
2398 */
2399 function getFuncCheck($mainParams,$elementName,$currentValue,$script='',$addparams='',$tagParams='') {
2400 if (!is_array($mainParams)) {
2401 $mainParams = array('id' => $mainParams);
2402 }
2403 $mainParams = t3lib_div::implodeArrayForUrl('',$mainParams);
2404
2405 if (!$script) {basename(PATH_thisScript);}
2406 $onClick = 'jumpToUrl(\''.$script.'?'.$mainParams.$addparams.'&'.$elementName.'=\'+(this.checked?1:0),this);';
2407 return '<input type="checkbox" name="'.$elementName.'"'.($currentValue?' checked="checked"':'').' onclick="'.htmlspecialchars($onClick).'"'.($tagParams?' '.$tagParams:'').' />';
2408 }
2409
2410 /**
2411 * Input field function menu
2412 * Works like ->getFuncMenu() / ->getFuncCheck() but displays a input field instead which updates the script "onchange"
2413 * Usage: 1
2414 *
2415 * @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=...
2416 * @param string $elementName it the form elements name, probably something like "SET[...]"
2417 * @param string $currentValue is the value to be selected currently.
2418 * @param integer Relative size of input field, max is 48
2419 * @param string $script is the script to send the &id to, if empty it's automatically found
2420 * @param string $addParams is additional parameters to pass to the script.
2421 * @return string HTML code for input text field.
2422 * @see getFuncMenu()
2423 */
2424 function getFuncInput($mainParams,$elementName,$currentValue,$size=10,$script="",$addparams="") {
2425 if (!is_array($mainParams)) {
2426 $mainParams = array('id' => $mainParams);
2427 }
2428 $mainParams = t3lib_div::implodeArrayForUrl('',$mainParams);
2429
2430 if (!$script) {basename(PATH_thisScript);}
2431 $onChange = 'jumpToUrl(\''.$script.'?'.$mainParams.$addparams.'&'.$elementName.'=\'+escape(this.value),this);';
2432 return '<input type="text"'.$GLOBALS['TBE_TEMPLATE']->formWidth($size).' name="'.$elementName.'" value="'.htmlspecialchars($currentValue).'" onchange="'.htmlspecialchars($onChange).'" />';
2433 }
2434
2435 /**
2436 * Removes menu items from $itemArray if they are configured to be removed by TSconfig for the module ($modTSconfig)
2437 * See Inside TYPO3 about how to program modules and use this API.
2438 * Usage: 4
2439 *
2440 * @param array Module TS config array
2441 * @param array Array of items from which to remove items.
2442 * @param string $TSref points to the "object string" in $modTSconfig
2443 * @return array The modified $itemArray is returned.
2444 */
2445 function unsetMenuItems($modTSconfig,$itemArray,$TSref) {
2446 // Getting TS-config options for this module for the Backend User:
2447 $conf = $GLOBALS['BE_USER']->getTSConfig($TSref,$modTSconfig);
2448 if (is_array($conf['properties'])) {
2449 reset($conf['properties']);
2450 while(list($key,$val)=each($conf['properties'])) {
2451 if (!$val) {
2452 unset($itemArray[$key]);
2453 }
2454 }
2455 }
2456 return $itemArray;
2457 }
2458
2459 /**
2460 * Call to update the page tree frame (or something else..?) after
2461 * t3lib_BEfunc::getSetUpdateSignal('updatePageTree') -> will set the page tree to be updated.
2462 * t3lib_BEfunc::getSetUpdateSignal() -> will return some JavaScript that does the update (called in the typo3/template.php file, end() function)
2463 * Usage: 11
2464 *
2465 * @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.
2466 * @return string HTML code (<script> section)
2467 */
2468 function getSetUpdateSignal($set='') {
2469 global $BE_USER;
2470 $key = 't3lib_BEfunc::getSetUpdateSignal';
2471 $out='';
2472 if ($set) {
2473 $modData=array();
2474 $modData['set']=$set;
2475 $BE_USER->pushModuleData($key,$modData);
2476 } else {
2477 $modData = $BE_USER->getModuleData($key,'ses');
2478 if (trim($modData['set'])) {
2479 $l=explode(',',$modData['set']);
2480 while(list(,$v)=each($l)) {
2481 switch($v) {
2482 case 'updatePageTree':
2483 case 'updateFolderTree':
2484 $out.='
2485 <script type="text/javascript">
2486 /*<![CDATA[*/
2487 if (top.content && top.content.nav_frame && top.content.nav_frame.refresh_nav) {
2488 top.content.nav_frame.refresh_nav();
2489 }
2490 /*]]>*/
2491 </script>';
2492 break;
2493 }
2494 }
2495 $modData=array();
2496 $modData['set']='';
2497 $BE_USER->pushModuleData($key,$modData);
2498 }
2499 }
2500 return $out;
2501 }
2502
2503
2504 /**
2505 * Returns an array which is most backend modules becomes MOD_SETTINGS containing values from function menus etc. determining the function of the module.
2506 * This is kind of session variable management framework for the backend users.
2507 * 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
2508 * Ultimately, see Inside TYPO3 for how to use this function in relation to your modules.
2509 * Usage: 23
2510 *
2511 * @param array MOD_MENU is an array that defines the options in menus.
2512 * @param array CHANGED_SETTINGS represents the array used when passing values to the script from the menus.
2513 * @param string modName is the name of this module. Used to get the correct module data.
2514 * @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.
2515 * @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.
2516 * @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)
2517 * @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
2518 */
2519 function getModuleData($MOD_MENU, $CHANGED_SETTINGS, $modName, $type='', $dontValidateList='', $setDefaultList='') {
2520
2521 if ($modName && is_string($modName)) {
2522 // GETTING stored user-data from this module:
2523 $settings = $GLOBALS['BE_USER']->getModuleData($modName,$type);
2524
2525 $changed=0;
2526 if (!is_array($settings)) {
2527 $changed=1;
2528 $settings=array();
2529 }
2530 if (is_array($MOD_MENU)) {
2531 foreach ($MOD_MENU as $key=>$var) {
2532 // If a global var is set before entering here. eg if submitted, then it's substituting the current value the array.
2533 if (is_array($CHANGED_SETTINGS) && isset($CHANGED_SETTINGS[$key]) && strcmp($settings[$key],$CHANGED_SETTINGS[$key])) {
2534 $settings[$key] = (string)$CHANGED_SETTINGS[$key];
2535 $changed=1;
2536 }
2537 // If the $var is an array, which denotes the existence of a menu, we check if the value is permitted
2538 if (is_array($var) && (!$dontValidateList || !t3lib_div::inList($dontValidateList,$key))) {
2539 // If the setting is an array or not present in the menu-array, MOD_MENU, then the default value is inserted.
2540 if (is_array($settings[$key]) || !isset($MOD_MENU[$key][$settings[$key]])) {
2541 $settings[$key]=(string)key($var);
2542 $changed=1;
2543 }
2544 }
2545 if ($setDefaultList && !is_array($var)) { // Sets default values (only strings/checkboxes, not menus)
2546 if (t3lib_div::inList($setDefaultList,$key) && !isset($settings[$key])) {
2547 $settings[$key]=$var;
2548 }
2549 }
2550 }
2551 } else {die ('No menu!');}
2552
2553 if ($changed) {
2554 $GLOBALS['BE_USER']->pushModuleData($modName,$settings);
2555 }
2556
2557 return $settings;
2558 } else {die ('Wrong module name: "'.$modName.'"');}
2559 }
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573 /*******************************************
2574 *
2575 * Core
2576 *
2577 *******************************************/
2578
2579 /**
2580 * Set preview keyword, eg:
2581 * $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);
2582 *
2583 * todo for sys_preview:
2584 * - Add a comment which can be shown to previewer in frontend in some way (plus maybe ability to write back, take other action?)
2585 * - 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?
2586 *
2587 * @param string Get variables to preview, eg. 'id=1150&L=0&ADMCMD_view=1&ADMCMD_editIcons=1&ADMCMD_previewWS=8'
2588 * @param string 32 byte MD5 hash keyword for the URL: "?ADMCMD_prev=[keyword]"
2589 * @param integer Time-To-Live for keyword
2590 * @return string Returns keyword to use in URL for ADMCMD_prev=
2591 */
2592 function compilePreviewKeyword($getVarsStr, $beUserUid, $ttl=172800) {
2593 $field_array = array(
2594 'keyword' => md5(uniqid(microtime())),
2595 'tstamp' => time(),
2596 'endtime' => time()+$ttl,
2597 'config' => serialize(array(
2598 'getVars' => $getVarsStr,
2599 'BEUSER_uid' => $beUserUid
2600 ))
2601 );
2602
2603 $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_preview', $field_array);
2604
2605 return $field_array['keyword'];
2606 }
2607
2608 /**
2609 * Unlock or Lock a record from $table with $uid
2610 * If $table and $uid is not set, then all locking for the current BE_USER is removed!
2611 * Usage: 5
2612 *
2613 * @param string Table name
2614 * @param integer Record uid
2615 * @param integer Record pid
2616 * @return void
2617 * @internal
2618 * @see t3lib_transferData::lockRecord(), alt_doc.php, db_layout.php, db_list.php, wizard_rte.php
2619 */
2620 function lockRecords($table='',$uid=0,$pid=0) {
2621 $user_id = intval($GLOBALS['BE_USER']->user['uid']);
2622 if ($table && $uid) {
2623 $fields_values = array(
2624 'userid' => $user_id,
2625 'tstamp' => $GLOBALS['EXEC_TIME'],
2626 'record_table' => $table,
2627 'record_uid' => $uid,
2628 'username' => $GLOBALS['BE_USER']->user['username'],
2629 'record_pid' => $pid
2630 );
2631
2632 $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_lockedrecords', $fields_values);
2633 } else {
2634 $GLOBALS['TYPO3_DB']->exec_DELETEquery('sys_lockedrecords', 'userid='.intval($user_id));
2635 }
2636 }
2637
2638 /**
2639 * Returns information about whether the record from table, $table, with uid, $uid is currently locked (edited by another user - which should issue a warning).
2640 * 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.
2641 * Usage: 5
2642 *
2643 * @param string Table name
2644 * @param integer Record uid
2645 * @return array
2646 * @internal
2647 * @see class.db_layout.inc, alt_db_navframe.php, alt_doc.php, db_layout.php
2648 */
2649 function isRecordLocked($table,$uid) {
2650 global $LOCKED_RECORDS;
2651 if (!is_array($LOCKED_RECORDS)) {
2652 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
2653 '*',
2654 'sys_lockedrecords',
2655 'sys_lockedrecords.userid!='.intval($GLOBALS['BE_USER']->user['uid']).'
2656 AND sys_lockedrecords.tstamp > '.($GLOBALS['EXEC_TIME']-2*3600)
2657 );
2658 while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
2659 $LOCKED_RECORDS[$row['record_table'].':'.$row['record_uid']]=$row;
2660 $LOCKED_RECORDS[$row['record_table'].':'.$row['record_uid']]['msg']=sprintf(
2661 $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.lockedRecord'),
2662 $row['username'],
2663 t3lib_BEfunc::calcAge($GLOBALS['EXEC_TIME']-$row['tstamp'],$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears'))
2664 );
2665 if ($row['record_pid'] && !isset($LOCKED_RECORDS[$row['record_table'].':'.$row['record_pid']])) {
2666 $LOCKED_RECORDS['pages:'.$row['record_pid']]['msg']=sprintf(
2667 $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.lockedRecord_content'),
2668 $row['username'],
2669 t3lib_BEfunc::calcAge($GLOBALS['EXEC_TIME']-$row['tstamp'],$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears'))
2670 );
2671 }
2672 }
2673 }
2674 return $LOCKED_RECORDS[$table.':'.$uid];
2675 }
2676
2677 /**
2678 * Returns select statement for MM relations (as used by TCEFORMs etc)
2679 * Usage: 3
2680 *
2681 * @param array Configuration array for the field, taken from $TCA
2682 * @param string Field name
2683 * @param array TSconfig array from which to get further configuration settings for the field name
2684 * @param string Prefix string for the key "*foreign_table_where" from $fieldValue array
2685 * @return string Part of query
2686 * @internal
2687 * @see t3lib_transferData::renderRecord(), t3lib_TCEforms::foreignTable()
2688 */
2689 function exec_foreign_table_where_query($fieldValue,$field='',$TSconfig=array(),$prefix='') {
2690 global $TCA;
2691 $foreign_table = $fieldValue['config'][$prefix.'foreign_table'];
2692 $rootLevel = $TCA[$foreign_table]['ctrl']['rootLevel'];
2693
2694 $fTWHERE = $fieldValue['config'][$prefix.'foreign_table_where'];
2695 if (strstr($fTWHERE,'###REC_FIELD_')) {
2696 $fTWHERE_parts = explode('###REC_FIELD_',$fTWHERE);
2697 while(list($kk,$vv)=each($fTWHERE_parts)) {
2698 if ($kk) {
2699 $fTWHERE_subpart = explode('###',$vv,2);
2700 $fTWHERE_parts[$kk]=$TSconfig['_THIS_ROW'][$fTWHERE_subpart[0]].$fTWHERE_subpart[1];
2701 }
2702 }
2703 $fTWHERE = implode('',$fTWHERE_parts);
2704 }
2705
2706 $fTWHERE = str_replace('###CURRENT_PID###',intval($TSconfig['_CURRENT_PID']),$fTWHERE);
2707 $fTWHERE = str_replace('###THIS_UID###',intval($TSconfig['_THIS_UID']),$fTWHERE);
2708 $fTWHERE = str_replace('###THIS_CID###',intval($TSconfig['_THIS_CID']),$fTWHERE);
2709 $fTWHERE = str_replace('###STORAGE_PID###',intval($TSconfig['_STORAGE_PID']),$fTWHERE);
2710 $fTWHERE = str_replace('###SITEROOT###',intval($TSconfig['_SITEROOT']),$fTWHERE);
2711 $fTWHERE = str_replace('###PAGE_TSCONFIG_ID###',intval($TSconfig[$field]['PAGE_TSCONFIG_ID']),$fTWHERE);
2712 $fTWHERE = str_replace('###PAGE_TSCONFIG_IDLIST###',$GLOBALS['TYPO3_DB']->cleanIntList($TSconfig[$field]['PAGE_TSCONFIG_IDLIST']),$fTWHERE);
2713 $fTWHERE = str_replace('###PAGE_TSCONFIG_STR###',$GLOBALS['TYPO3_DB']->quoteStr($TSconfig[$field]['PAGE_TSCONFIG_STR'], $foreign_table),$fTWHERE);
2714
2715 // rootLevel = -1 is not handled 'properly' here - it goes as if it was rootLevel = 1 (that is pid=0)
2716 $wgolParts = $GLOBALS['TYPO3_DB']->splitGroupOrderLimit($fTWHERE);
2717 if ($rootLevel) {
2718 $queryParts = array(
2719 'SELECT' => t3lib_BEfunc::getCommonSelectFields($foreign_table,$foreign_table.'.'),
2720 'FROM' => $foreign_table,
2721 'WHERE' => $foreign_table.'.pid=0 '.
2722 t3lib_BEfunc::deleteClause($foreign_table).' '.
2723 $wgolParts['WHERE'],
2724 'GROUPBY' => $wgolParts['GROUPBY'],
2725 'ORDERBY' => $wgolParts['ORDERBY'],
2726 'LIMIT' => $wgolParts['LIMIT']
2727 );
2728 } else {
2729 $pageClause = $GLOBALS['BE_USER']->getPagePermsClause(1);
2730 if ($foreign_table!='pages') {
2731 $queryParts = array(
2732 'SELECT' => t3lib_BEfunc::getCommonSelectFields($foreign_table,$foreign_table.'.'),
2733 'FROM' => $foreign_table.',pages',
2734 'WHERE' => 'pages.uid='.$foreign_table.'.pid
2735 AND pages.deleted=0 '.
2736 t3lib_BEfunc::deleteClause($foreign_table).
2737 ' AND '.$pageClause.' '.
2738 $wgolParts['WHERE'],
2739 'GROUPBY' => $wgolParts['GROUPBY'],
2740 'ORDERBY' => $wgolParts['ORDERBY'],
2741 'LIMIT' => $wgolParts['LIMIT']
2742 );
2743 } else {
2744 $queryParts = array(
2745 'SELECT' => t3lib_BEfunc::getCommonSelectFields($foreign_table,$foreign_table.'.'),
2746 'FROM' => 'pages',
2747 'WHERE' => 'pages.deleted=0
2748 AND '.$pageClause.' '.
2749 $wgolParts['WHERE'],
2750 'GROUPBY' => $wgolParts['GROUPBY'],
2751 'ORDERBY' => $wgolParts['ORDERBY'],
2752 'LIMIT' => $wgolParts['LIMIT']
2753 );
2754 }
2755 }
2756
2757 return $GLOBALS['TYPO3_DB']->exec_SELECT_queryArray($queryParts);
2758 }
2759
2760 /**
2761 * Returns TSConfig for the TCEFORM object in Page TSconfig.
2762 * Used in TCEFORMs
2763 * Usage: 4
2764 *
2765 * @param string Table name present in TCA
2766 * @param array Row from table
2767 * @return array
2768 * @see t3lib_transferData::renderRecord(), t3lib_TCEforms::setTSconfig(), SC_wizard_list::main(), SC_wizard_add::main()
2769 */
2770 function getTCEFORM_TSconfig($table,$row) {
2771 t3lib_BEfunc::fixVersioningPid($table,$row);
2772
2773 $res = array();
2774 $typeVal = t3lib_BEfunc::getTCAtypeValue($table,$row);
2775
2776 // Get main config for the table
2777 list($TScID,$cPid) = t3lib_BEfunc::getTSCpid($table,$row['uid'],$row['pid']);
2778
2779 $rootLine = t3lib_BEfunc::BEgetRootLine($TScID,'',TRUE);
2780 if ($TScID>=0) {
2781 $tempConf = $GLOBALS['BE_USER']->getTSConfig('TCEFORM.'.$table,t3lib_BEfunc::getPagesTSconfig($TScID,$rootLine));
2782 if (is_array($tempConf['properties'])) {
2783 while(list($key,$val)=each($tempConf['properties'])) {
2784 if (is_array($val)) {
2785 $fieldN = substr($key,0,-1);
2786 $res[$fieldN] = $val;
2787 unset($res[$fieldN]['types.']);
2788 if (strcmp($typeVal,'') && is_array($val['types.'][$typeVal.'.'])) {
2789 $res[$fieldN] = t3lib_div::array_merge_recursive_overrule($res[$fieldN],$val['types.'][$typeVal.'.']);
2790 }
2791 }
2792 }
2793 }
2794 }
2795 $res['_CURRENT_PID']=$cPid;
2796 $res['_THIS_UID']=$row['uid'];
2797 $res['_THIS_CID']=$row['cid'];
2798 $res['_THIS_ROW']=$row; // So the row will be passed to foreign_table_where_query()
2799
2800 reset($rootLine);
2801 while(list(,$rC)=each($rootLine)) {
2802 if (!$res['_STORAGE_PID']) $res['_STORAGE_PID']=intval($rC['storage_pid']);
2803 if (!$res['_SITEROOT']) $res['_SITEROOT']=$rC['is_siteroot']?intval($rC['uid']):0;
2804 }
2805
2806 return $res;
2807 }
2808
2809 /**
2810 * 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).
2811 * 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!
2812 * Usage: 2
2813 *
2814 * @param string Table name
2815 * @param integer Record uid
2816 * @param integer Record pid, could be negative then pointing to a record from same table whose pid to find and return.
2817 * @return integer
2818 * @internal
2819 * @see t3lib_TCEmain::copyRecord(), getTSCpid()
2820 */
2821 function getTSconfig_pidValue($table,$uid,$pid) {
2822
2823 if (t3lib_div::testInt($pid)) { // If pid is an integer this takes precedence in our lookup.
2824 $thePidValue = intval($pid);
2825 if ($thePidValue<0) { // If ref to another record, look that record up.
2826 $pidRec = t3lib_BEfunc::getRecord($table,abs($thePidValue),'pid');
2827 $thePidValue = is_array($pidRec) ? $pidRec['pid'] : -2; // Returns -2 if the record did not exist.
2828 }
2829 // ... else the pos/zero pid is just returned here.
2830 } else { // No integer pid and we are forced to look up the $pid
2831 $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...
2832 if (is_array($rr)) {
2833 $thePidValue = $rr['pid']; // Returning the 'pid' of the record
2834 } else $thePidValue=-1; // Returns -1 if the record with the pid was not found.
2835 }
2836
2837 return $thePidValue;
2838 }
2839
2840 /**
2841 * Return $uid if $table is pages and $uid is integer - otherwise the $pid
2842 * Usage: 1
2843 *
2844 * @param string Table name
2845 * @param integer Record uid
2846 * @param integer Record pid
2847 * @return integer
2848 * @internal
2849 * @see t3lib_TCEforms::getTSCpid()
2850 */
2851 function getPidForModTSconfig($table,$uid,$pid) {
2852 $retVal = ($table=='pages' && t3lib_div::testInt($uid)) ? $uid : $pid;
2853 return $retVal;
2854 }
2855
2856 /**
2857 * 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.
2858 * Usage: 8
2859 *
2860 * @param string Table name
2861 * @param integer Record uid
2862 * @param integer Record pid
2863 * @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)
2864 * @internal
2865 * @see t3lib_TCEmain::setHistory(), t3lib_TCEmain::process_datamap()
2866 */
2867 function getTSCpid($table,$uid,$pid) {
2868 // If pid is negative (referring to another record) the pid of the other record is fetched and returned.
2869 $cPid = t3lib_BEfunc::getTSconfig_pidValue($table,$uid,$pid);
2870 // $TScID is the id of $table=pages, else it's the pid of the record.
2871 $TScID = t3lib_BEfunc::getPidForModTSconfig($table,$uid,$cPid);
2872
2873 return array($TScID,$cPid);
2874 }
2875
2876 /**
2877 * Returns first found domain record "domainName" (without trailing slash) if found in the input $rootLine
2878 * Usage: 2
2879 *
2880 * @param array Root line array
2881 * @return string Domain name, if found.
2882 */
2883 function firstDomainRecord($rootLine) {
2884 if (t3lib_extMgm::isLoaded('cms')) {
2885 reset($rootLine);
2886 while(list(,$row)=each($rootLine)) {
2887 $dRec = t3lib_BEfunc::getRecordsByField('sys_domain','pid',$row['uid'],' AND redirectTo=\'\' AND hidden=0', '', 'sorting');
2888 if (is_array($dRec)) {
2889 reset($dRec);
2890 $dRecord = current($dRec);
2891 return ereg_replace('\/$','',$dRecord['domainName']);
2892 }
2893 }
2894 }
2895 }
2896
2897 /**
2898 * Returns the sys_domain record for $domain, optionally with $path appended.
2899 * Usage: 2
2900 *
2901 * @param string Domain name
2902 * @param string Appended path
2903 * @return array Domain record, if found
2904 */
2905 function getDomainStartPage($domain, $path='') {
2906 if (t3lib_extMgm::isLoaded('cms')) {
2907 $domain = explode(':',$domain);
2908 $domain = strtolower(ereg_replace('\.$','',$domain[0]));
2909 // path is calculated.
2910 $path = trim(ereg_replace('\/[^\/]*$','',$path));
2911 // stuff:
2912 $domain.=$path;
2913
2914 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('sys_domain.*', 'pages,sys_domain', '
2915 pages.uid=sys_domain.pid
2916 AND sys_domain.hidden=0
2917 AND (sys_domain.domainName='.$GLOBALS['TYPO3_DB']->fullQuoteStr($domain, 'sys_domain').' or sys_domain.domainName='.$GLOBALS['TYPO3_DB']->fullQuoteStr($domain.'/', 'sys_domain').')'.
2918 t3lib_BEfunc::deleteClause('pages'),
2919 '', '', '1');
2920 return $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
2921 }
2922 }
2923
2924 /**
2925 * Returns overlayered RTE setup from an array with TSconfig. Used in TCEforms and TCEmain
2926 * Usage: 8
2927 *
2928 * @param array The properties of Page TSconfig in the key "RTE."
2929 * @param string Table name
2930 * @param string Field name
2931 * @param string Type value of the current record (like from CType of tt_content)
2932 * @return array Array with the configuration for the RTE
2933 * @internal
2934 */
2935 function RTEsetup($RTEprop,$table,$field,$type='') {
2936 $thisConfig = is_array($RTEprop['default.']) ? $RTEprop['default.'] : array();