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