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