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