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