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