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