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