Added feature #5613: Enable/integrate conditions in Page TSconfig
[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 page TS-Config (or getting from cache)
1336 $pageTS = implode(chr(10) . '[GLOBAL]' . chr(10), $TSdataArray);
1337 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['TSconfigConditions']) {
1338 /* @var $parseObj t3lib_TSparser_TSconfig */
1339 $parseObj = t3lib_div::makeInstance('t3lib_TSparser_TSconfig');
1340 $res = $parseObj->parseTSconfig($pageTS, 'PAGES', $id, $rootLine);
1341 if ($res) {
1342 $TSconfig = $res['TSconfig'];
1343 }
1344 } else {
1345 $hash = md5('pageTS:' . $pageTS);
1346 $cachedContent = t3lib_BEfunc::getHash($hash);
1347 $TSconfig = array();
1348 if (isset($cachedContent)) {
1349 $TSconfig = unserialize($cachedContent);
1350 } else {
1351 $parseObj = t3lib_div::makeInstance('t3lib_TSparser');
1352 $parseObj->parse($pageTS);
1353 $TSconfig = $parseObj->setup;
1354 t3lib_BEfunc::storeHash($hash, serialize($TSconfig), 'PAGES_TSconfig');
1355 }
1356 }
1357
1358 // get User TSconfig overlay
1359 $userTSconfig = $GLOBALS['BE_USER']->userTS['page.'];
1360 if (is_array($userTSconfig)) {
1361 $TSconfig = t3lib_div::array_merge_recursive_overrule($TSconfig, $userTSconfig);
1362 }
1363 return $TSconfig;
1364 }
1365
1366 /**
1367 * Updates Page TSconfig for a page with $id
1368 * 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.
1369 * $impParams can be supplied as already known Page TSconfig, otherwise it's calculated.
1370 *
1371 * THIS DOES NOT CHECK ANY PERMISSIONS. SHOULD IT?
1372 * More documentation is needed.
1373 *
1374 * Usage: 1 (ext. direct_mail)
1375 *
1376 * @param integer Page id
1377 * @param array Page TS array to write
1378 * @param string Prefix for object paths
1379 * @param array [Description needed.]
1380 * @return void
1381 * @internal
1382 * @see implodeTSParams(), getPagesTSconfig()
1383 */
1384 public static function updatePagesTSconfig($id, $pageTS, $TSconfPrefix, $impParams = '') {
1385 $id = intval($id);
1386 if (is_array($pageTS) && $id>0) {
1387 if (!is_array($impParams)) {
1388 $impParams =t3lib_BEfunc::implodeTSParams(t3lib_BEfunc::getPagesTSconfig($id));
1389 }
1390 reset($pageTS);
1391 $set = array();
1392 while(list($f, $v) = each($pageTS)) {
1393 $f = $TSconfPrefix.$f;
1394 if ((!isset($impParams[$f])&&trim($v)) || strcmp(trim($impParams[$f]), trim($v))) {
1395 $set[$f] = trim($v);
1396 }
1397 }
1398 if (count($set)) {
1399 // Get page record and TS config lines
1400 $pRec = t3lib_befunc::getRecord('pages', $id);
1401 $TSlines = explode(chr(10), $pRec['TSconfig']);
1402 $TSlines = array_reverse($TSlines);
1403 // Reset the set of changes.
1404 reset($set);
1405 while(list($f, $v) = each($set)) {
1406 reset($TSlines);
1407 $inserted = 0;
1408 while(list($ki, $kv) = each($TSlines)) {
1409 if (substr($kv, 0, strlen($f)+1)==$f.'=') {
1410 $TSlines[$ki] = $f.'='.$v;
1411 $inserted = 1;
1412 break;
1413 }
1414 }
1415 if (!$inserted) {
1416 $TSlines = array_reverse($TSlines);
1417 $TSlines[] = $f.'='.$v;
1418 $TSlines = array_reverse($TSlines);
1419 }
1420 }
1421 $TSlines = array_reverse($TSlines);
1422
1423 // store those changes
1424 $TSconf = implode(chr(10), $TSlines);
1425
1426 $GLOBALS['TYPO3_DB']->exec_UPDATEquery('pages', 'uid='.intval($id), array('TSconfig' => $TSconf));
1427 }
1428 }
1429 }
1430
1431 /**
1432 * Implodes a multi dimensional TypoScript array, $p, into a one-dimentional array (return value)
1433 * Usage: 3
1434 *
1435 * @param array TypoScript structure
1436 * @param string Prefix string
1437 * @return array Imploded TypoScript objectstring/values
1438 */
1439 public static function implodeTSParams($p, $k = '') {
1440 $implodeParams = array();
1441 if (is_array($p)) {
1442 reset($p);
1443 while(list($kb, $val) = each($p)) {
1444 if (is_array($val)) {
1445 $implodeParams = array_merge($implodeParams, t3lib_BEfunc::implodeTSParams($val, $k.$kb));
1446 } else {
1447 $implodeParams[$k.$kb] = $val;
1448 }
1449 }
1450 }
1451 return $implodeParams;
1452 }
1453
1454
1455
1456
1457
1458
1459
1460
1461 /*******************************************
1462 *
1463 * Users / Groups related
1464 *
1465 *******************************************/
1466
1467 /**
1468 * Returns an array with be_users records of all user NOT DELETED sorted by their username
1469 * Keys in the array is the be_users uid
1470 * Usage: 14 (spec. ext. "beuser" and module "web_perm")
1471 *
1472 * @param string Optional $fields list (default: username,usergroup,usergroup_cached_list,uid) can be used to set the selected fields
1473 * @param string Optional $where clause (fx. "AND username='pete'") can be used to limit query
1474 * @return array
1475 */
1476 public static function getUserNames($fields = 'username,usergroup,usergroup_cached_list,uid', $where = '') {
1477 $be_user_Array = Array();
1478
1479 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fields, 'be_users', 'pid=0 '.$where.t3lib_BEfunc::deleteClause('be_users'), '', 'username');
1480 while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1481 $be_user_Array[$row['uid']] = $row;
1482 }
1483 $GLOBALS['TYPO3_DB']->sql_free_result($res);
1484
1485 return $be_user_Array;
1486 }
1487
1488 /**
1489 * Returns an array with be_groups records (title, uid) of all groups NOT DELETED sorted by their title
1490 * Usage: 8 (spec. ext. "beuser" and module "web_perm")
1491 *
1492 * @param string Field list
1493 * @param string WHERE clause
1494 * @return array
1495 */
1496 public static function getGroupNames($fields = 'title,uid', $where = '') {
1497 $be_group_Array = Array();
1498
1499 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fields, 'be_groups', 'pid=0 '.$where.t3lib_BEfunc::deleteClause('be_groups'), '', 'title');
1500 while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1501 $be_group_Array[$row['uid']] = $row;
1502 }
1503 $GLOBALS['TYPO3_DB']->sql_free_result($res);
1504
1505 return $be_group_Array;
1506 }
1507
1508 /**
1509 * Returns an array with be_groups records (like ->getGroupNames) but:
1510 * - 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.
1511 * Usage: 2 (module "web_perm" and ext. taskcenter)
1512 *
1513 * @param string Field list; $fields specify the fields selected (default: title,uid)
1514 * @return array
1515 */
1516 public static function getListGroupNames($fields = 'title, uid') {
1517 $exQ = ' AND hide_in_lists=0';
1518 if (!$GLOBALS['BE_USER']->isAdmin()) {
1519 $exQ.=' AND uid IN ('.($GLOBALS['BE_USER']->user['usergroup_cached_list']?$GLOBALS['BE_USER']->user['usergroup_cached_list']:0).')';
1520 }
1521 return t3lib_BEfunc::getGroupNames($fields, $exQ);
1522 }
1523
1524 /**
1525 * Returns the array $usernames with the names of all users NOT IN $groupArray changed to the uid (hides the usernames!).
1526 * If $excludeBlindedFlag is set, then these records are unset from the array $usernames
1527 * Takes $usernames (array made by t3lib_BEfunc::getUserNames()) and a $groupArray (array with the groups a certain user is member of) as input
1528 * Usage: 8
1529 *
1530 * @param array User names
1531 * @param array Group names
1532 * @param boolean If $excludeBlindedFlag is set, then these records are unset from the array $usernames
1533 * @return array User names, blinded
1534 */
1535 public static function blindUserNames($usernames, $groupArray, $excludeBlindedFlag = 0) {
1536 if (is_array($usernames) && is_array($groupArray)) {
1537 while(list($uid, $row) = each($usernames)) {
1538 $userN = $uid;
1539 $set = 0;
1540 if ($row['uid']!=$GLOBALS['BE_USER']->user['uid']) {
1541 reset($groupArray);
1542 while(list(,$v) = each($groupArray)) {
1543 if ($v && t3lib_div::inList($row['usergroup_cached_list'], $v)) {
1544 $userN = $row['username'];
1545 $set = 1;
1546 }
1547 }
1548 } else {
1549 $userN = $row['username'];
1550 $set = 1;
1551 }
1552 $usernames[$uid]['username'] = $userN;
1553 if ($excludeBlindedFlag && !$set) {unset($usernames[$uid]);}
1554 }
1555 }
1556 return $usernames;
1557 }
1558
1559 /**
1560 * Corresponds to blindUserNames but works for groups instead
1561 * Usage: 2 (module web_perm)
1562 *
1563 * @param array Group names
1564 * @param array Group names (reference)
1565 * @param boolean If $excludeBlindedFlag is set, then these records are unset from the array $usernames
1566 * @return array
1567 */
1568 public static function blindGroupNames($groups, $groupArray, $excludeBlindedFlag = 0) {
1569 if (is_array($groups) && is_array($groupArray)) {
1570 while(list($uid, $row) = each($groups)) {
1571 $groupN = $uid;
1572 $set = 0;
1573 if (t3lib_div::inArray($groupArray, $uid)) {
1574 $groupN = $row['title'];
1575 $set = 1;
1576 }
1577 $groups[$uid]['title'] = $groupN;
1578 if ($excludeBlindedFlag && !$set) {unset($groups[$uid]);}
1579 }
1580 }
1581 return $groups;
1582 }
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596 /*******************************************
1597 *
1598 * Output related
1599 *
1600 *******************************************/
1601
1602 /**
1603 * Returns the difference in days between input $tstamp and $EXEC_TIME
1604 * Usage: 2 (class t3lib_BEfunc)
1605 *
1606 * @param integer Time stamp, seconds
1607 * @return integer
1608 */
1609 public static function daysUntil($tstamp) {
1610 $delta_t = $tstamp-$GLOBALS['EXEC_TIME'];
1611 return ceil($delta_t/(3600*24));
1612 }
1613
1614 /**
1615 * Returns $tstamp formatted as "ddmmyy" (According to $TYPO3_CONF_VARS['SYS']['ddmmyy'])
1616 * Usage: 11
1617 *
1618 * @param integer Time stamp, seconds
1619 * @return string Formatted time
1620 */
1621 public static function date($tstamp) {
1622 return date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'], (int)$tstamp);
1623 }
1624
1625 /**
1626 * Returns $tstamp formatted as "ddmmyy hhmm" (According to $TYPO3_CONF_VARS['SYS']['ddmmyy'] AND $TYPO3_CONF_VARS['SYS']['hhmm'])
1627 * Usage: 28
1628 *
1629 * @param integer Time stamp, seconds
1630 * @return string Formatted time
1631 */
1632 public static function datetime($value) {
1633 return date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'].' '.$GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'], $value);
1634 }
1635
1636 /**
1637 * Returns $value (in seconds) formatted as hh:mm:ss
1638 * For instance $value = 3600 + 60*2 + 3 should return "01:02:03"
1639 * Usage: 1 (class t3lib_BEfunc)
1640 *
1641 * @param integer Time stamp, seconds
1642 * @param boolean Output hh:mm:ss. If false: hh:mm
1643 * @return string Formatted time
1644 */
1645 public static function time($value, $withSeconds = TRUE) {
1646 $hh = floor($value/3600);
1647 $min = floor(($value-$hh*3600)/60);
1648 $sec = $value-$hh*3600-$min*60;
1649 $l = sprintf('%02d', $hh).':'.sprintf('%02d', $min);
1650 if ($withSeconds) {
1651 $l .= ':'.sprintf('%02d', $sec);
1652 }
1653 return $l;
1654 }
1655
1656 /**
1657 * Returns the "age" in minutes / hours / days / years of the number of $seconds inputted.
1658 * Usage: 15
1659 *
1660 * @param integer $seconds could be the difference of a certain timestamp and time()
1661 * @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")
1662 * @return string Formatted time
1663 */
1664 public static function calcAge($seconds, $labels = 'min|hrs|days|yrs') {
1665 $labelArr = explode('|', $labels);
1666 $prefix = '';
1667 if ($seconds<0) {$prefix = '-'; $seconds = abs($seconds);}
1668 if ($seconds<3600) {
1669 $seconds = round ($seconds/60).' '.trim($labelArr[0]);
1670 } elseif ($seconds<24*3600) {
1671 $seconds = round ($seconds/3600).' '.trim($labelArr[1]);
1672 } elseif ($seconds<365*24*3600) {
1673 $seconds = round ($seconds/(24*3600)).' '.trim($labelArr[2]);
1674 } else {
1675 $seconds = round ($seconds/(365*24*3600)).' '.trim($labelArr[3]);
1676 }
1677 return $prefix.$seconds;
1678 }
1679
1680 /**
1681 * Returns a formatted timestamp if $tstamp is set.
1682 * The date/datetime will be followed by the age in parenthesis.
1683 * Usage: 3
1684 *
1685 * @param integer Time stamp, seconds
1686 * @param integer 1/-1 depending on polarity of age.
1687 * @param string $date=="date" will yield "dd:mm:yy" formatting, otherwise "dd:mm:yy hh:mm"
1688 * @return string
1689 */
1690 public static function dateTimeAge($tstamp, $prefix = 1, $date = '') {
1691 return $tstamp ?
1692 ($date=='date' ? t3lib_BEfunc::date($tstamp) : t3lib_BEfunc::datetime($tstamp)) .
1693 ' (' . t3lib_BEfunc::calcAge($prefix * ($GLOBALS['EXEC_TIME'] - $tstamp), $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears')) . ')'
1694 : '';
1695 }
1696
1697 /**
1698 * Returns either title = '' or alt = '' attribute. This depends on the client browser and whether it supports title = '' or not (which is the default)
1699 * If no $content is given only the attribute name is returned.
1700 * The returned attribute with content will have a leading space char.
1701 * Warning: Be careful to submit empty $content var - that will return just the attribute name!
1702 * Usage: 0
1703 *
1704 * @param string String to set as title-attribute. If no $content is given only the attribute name is returned.
1705 * @param boolean If $hsc is set, then content of the attribute is htmlspecialchar()'ed (which is good for XHTML and other reasons...)
1706 * @return string
1707 * @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!
1708 */
1709 public static function titleAttrib($content = '', $hsc = 0) {
1710 global $CLIENT;
1711 $attrib= ($CLIENT['BROWSER']=='net'&&$CLIENT['VERSION']<5)||$CLIENT['BROWSER']=='konqu' ? 'alt' : 'title';
1712 return strcmp($content, '')?' '.$attrib.'="'.($hsc?htmlspecialchars($content):$content).'"' : $attrib;
1713 }
1714
1715 /**
1716 * Returns alt="" and title="" attributes with the value of $content.
1717 * Usage: 7
1718 *
1719 * @param string Value for 'alt' and 'title' attributes (will be htmlspecialchars()'ed before output)
1720 * @return string
1721 */
1722 public static function titleAltAttrib($content) {
1723 $out = '';
1724 $out.=' alt="'.htmlspecialchars($content).'"';
1725 $out.=' title="'.htmlspecialchars($content).'"';
1726 return $out;
1727 }
1728
1729 /**
1730 * 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
1731 * All $TYPO3_CONF_VARS['GFX']['imagefile_ext'] extension are made to thumbnails + ttf file (renders font-example)
1732 * Thumbsnails are linked to the show_item.php script which will display further details.
1733 * Usage: 7
1734 *
1735 * @param array $row is the database row from the table, $table.
1736 * @param string Table name for $row (present in TCA)
1737 * @param string $field is pointing to the field with the list of image files
1738 * @param string Back path prefix for image tag src="" field
1739 * @param string Optional: $thumbScript os by default 'thumbs.php' if you don't set it otherwise
1740 * @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!)
1741 * @param boolean If set, uploaddir is NOT prepended with "../"
1742 * @param string Optional: $tparams is additional attributes for the image tags
1743 * @param integer Optional: $size is [w]x[h] of the thumbnail. 56 is default.
1744 * @return string Thumbnail image tag.
1745 */
1746 public static function thumbCode($row, $table, $field, $backPath, $thumbScript = '', $uploaddir = NULL, $abs = 0, $tparams = '', $size = '') {
1747 global $TCA;
1748 // Load table.
1749 t3lib_div::loadTCA($table);
1750
1751 // Find uploaddir automatically
1752 $uploaddir = (is_null($uploaddir)) ? $TCA[$table]['columns'][$field]['config']['uploadfolder'] : $uploaddir;
1753 $uploaddir = preg_replace('#/$#','', $uploaddir);
1754
1755 // Set thumbs-script:
1756 if (!$GLOBALS['TYPO3_CONF_VARS']['GFX']['thumbnails']) {
1757 $thumbScript = 'gfx/notfound_thumb.gif';
1758 } elseif(!$thumbScript) {
1759 $thumbScript = 'thumbs.php';
1760 }
1761 // Check and parse the size parameter
1762 $sizeParts = array();
1763 if ($size = trim($size)) {
1764 $sizeParts = explode('x', $size.'x'.$size);
1765 if(!intval($sizeParts[0])) $size = '';
1766 }
1767
1768 // Traverse files:
1769 $thumbs = explode(',', $row[$field]);
1770 $thumbData = '';
1771 while(list(,$theFile) = each($thumbs)) {
1772 if (trim($theFile)) {
1773 $fI = t3lib_div::split_fileref($theFile);
1774 $ext = $fI['fileext'];
1775 // New 190201 start
1776 $max = 0;
1777 if (t3lib_div::inList('gif,jpg,png', $ext)) {
1778 $imgInfo = @getimagesize(PATH_site.$uploaddir.'/'.$theFile);
1779 if (is_array($imgInfo)) {$max = max($imgInfo[0], $imgInfo[1]);}
1780 }
1781 // use the original image if it's size fits to the thumbnail size
1782 if ($max && $max<=(count($sizeParts)&&max($sizeParts)?max($sizeParts):56)) {
1783 $theFile = $url = ($abs?'':'../').($uploaddir?$uploaddir.'/':'').trim($theFile);
1784 $onClick = 'top.launchView(\''.$theFile.'\',\'\',\''.$backPath.'\');return false;';
1785 $thumbData.= '<a href="#" onclick="'.htmlspecialchars($onClick).'"><img src="'.$backPath.$url.'" '.$imgInfo[3].' hspace="2" border="0" title="'.trim($url).'"'.$tparams.' alt="" /></a> ';
1786 // New 190201 stop
1787 } elseif ($ext=='ttf' || t3lib_div::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'], $ext)) {
1788 $theFile_abs = PATH_site.($uploaddir?$uploaddir.'/':'').trim($theFile);
1789 $theFile = ($abs?'':'../').($uploaddir?$uploaddir.'/':'').trim($theFile);
1790
1791 $check = basename($theFile_abs).':'.filemtime($theFile_abs).':'.$GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
1792 $params = '&file='.rawurlencode($theFile);
1793 $params.= $size?'&size='.$size:'';
1794 $params.= '&md5sum='.t3lib_div::shortMD5($check);
1795
1796 $url = $thumbScript.'?&dummy='.$GLOBALS['EXEC_TIME'].$params;
1797 $onClick = 'top.launchView(\''.$theFile.'\',\'\',\''.$backPath.'\');return false;';
1798 $thumbData.= '<a href="#" onclick="'.htmlspecialchars($onClick).'"><img src="'.htmlspecialchars($backPath.$url).'" hspace="2" border="0" title="'.trim($theFile).'"'.$tparams.' alt="" /></a> ';
1799 } else {
1800 $icon = t3lib_BEfunc::getFileIcon($ext);
1801 $url = 'gfx/fileicons/'.$icon;
1802 $thumbData.= '<img src="'.$backPath.$url.'" hspace="2" border="0" title="'.trim($theFile).'"'.$tparams.' alt="" /> ';
1803 }
1804 }
1805 }
1806 return $thumbData;
1807 }
1808
1809 /**
1810 * Returns single image tag to thumbnail using a thumbnail script (like thumbs.php)
1811 * Usage: 3
1812 *
1813 * @param string $thumbScript must point to "thumbs.php" relative to the script position
1814 * @param string $theFile must be the proper reference to the file thumbs.php should show
1815 * @param string $tparams are additional attributes for the image tag
1816 * @param integer $size is the size of the thumbnail send along to "thumbs.php"
1817 * @return string Image tag
1818 */
1819 public static function getThumbNail($thumbScript, $theFile, $tparams = '', $size = '') {
1820 $check = basename($theFile).':'.filemtime($theFile).':'.$GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
1821 $params = '&file='.rawurlencode($theFile);
1822 $params.= trim($size)?'&size='.trim($size):'';
1823 $params.= '&md5sum='.t3lib_div::shortMD5($check);
1824
1825 $url = $thumbScript.'?&dummy='.$GLOBALS['EXEC_TIME'].$params;
1826 $th = '<img src="'.htmlspecialchars($url).'" title="'.trim(basename($theFile)).'"'.($tparams?" ".$tparams:"").' alt="" />';
1827 return $th;
1828 }
1829
1830 /**
1831 * Returns title-attribute information for a page-record informing about id, alias, doktype, hidden, starttime, endtime, fe_group etc.
1832 * Usage: 8
1833 *
1834 * @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)
1835 * @param string $perms_clause is used to get the record path of the shortcut page, if any (and doktype==4)
1836 * @param boolean If $includeAttrib is set, then the 'title=""' attribute is wrapped about the return value, which is in any case htmlspecialchar()'ed already
1837 * @return string
1838 */
1839 public static function titleAttribForPages($row, $perms_clause = '', $includeAttrib = 1) {
1840 global $TCA, $LANG;
1841 $parts = array();
1842 $parts[] = 'id='.$row['uid'];
1843 if ($row['alias']) $parts[] = $LANG->sL($TCA['pages']['columns']['alias']['label']).' '.$row['alias'];
1844 if ($row['pid']<0) $parts[] = 'v#1.'.$row['t3ver_id'];
1845
1846 switch($row['t3ver_state']) {
1847 case 1:
1848 $parts[] = 'PLH WSID#'.$row['t3ver_wsid'];
1849 break;
1850 case 2:
1851 $parts[] = 'Deleted element!';
1852 break;
1853 case 3:
1854 $parts[] = 'NEW LOCATION (PLH) WSID#'.$row['t3ver_wsid'];
1855 break;
1856 case 4:
1857 $parts[] = 'OLD LOCATION (PNT) WSID#'.$row['t3ver_wsid'];
1858 break;
1859 case -1:
1860 $parts[] = 'New element!';
1861 break;
1862 }
1863
1864 if ($row['doktype']=='3') {
1865 $parts[] = $LANG->sL($TCA['pages']['columns']['url']['label']).' '.$row['url'];
1866 } elseif ($row['doktype']=='4') {
1867 if ($perms_clause) {
1868 $label = t3lib_BEfunc::getRecordPath(intval($row['shortcut']), $perms_clause, 20);
1869 } else {
1870 $lRec = t3lib_BEfunc::getRecordWSOL('pages', intval($row['shortcut']), 'title');
1871 $label = $lRec['title'];
1872 }
1873 if ($row['shortcut_mode']>0) {
1874 $label.=', '.$LANG->sL($TCA['pages']['columns']['shortcut_mode']['label']).' '.
1875 $LANG->sL(t3lib_BEfunc::getLabelFromItemlist('pages', 'shortcut_mode', $row['shortcut_mode']));
1876 }
1877 $parts[] = $LANG->sL($TCA['pages']['columns']['shortcut']['label']).' '.$label;
1878 } elseif ($row['doktype']=='7') {
1879 if ($perms_clause) {
1880 $label = t3lib_BEfunc::getRecordPath(intval($row['mount_pid']), $perms_clause, 20);
1881 } else {
1882 $lRec = t3lib_BEfunc::getRecordWSOL('pages', intval($row['mount_pid']), 'title');
1883 $label = $lRec['title'];
1884 }
1885 $parts[] = $LANG->sL($TCA['pages']['columns']['mount_pid']['label']).' '.$label;
1886 if ($row['mount_pid_ol']) {
1887 $parts[] = $LANG->sL($TCA['pages']['columns']['mount_pid_ol']['label']);
1888 }
1889 }
1890 if ($row['nav_hide']) $parts[] = rtrim($LANG->sL($TCA['pages']['columns']['nav_hide']['label']), ':');
1891 if ($row['hidden']) $parts[] = $LANG->sL('LLL:EXT:lang/locallang_core.php:labels.hidden');
1892 if ($row['starttime']) $parts[] = $LANG->sL($TCA['pages']['columns']['starttime']['label']).' '.t3lib_BEfunc::dateTimeAge($row['starttime'], -1, 'date');
1893 if ($row['endtime']) $parts[] = $LANG->sL($TCA['pages']['columns']['endtime']['label']).' '.t3lib_BEfunc::dateTimeAge($row['endtime'], -1, 'date');
1894 if ($row['fe_group']) {
1895 $fe_groups = array();
1896 foreach (t3lib_div::intExplode(',', $row['fe_group']) as $fe_group) {
1897 if ($fe_group<0) {
1898 $fe_groups[] = $LANG->sL(t3lib_BEfunc::getLabelFromItemlist('pages', 'fe_group', $fe_group));
1899 } else {
1900 $lRec = t3lib_BEfunc::getRecordWSOL('fe_groups', $fe_group, 'title');
1901 $fe_groups[] = $lRec['title'];
1902 }
1903 }
1904 $label = implode(', ', $fe_groups);
1905 $parts[] = $LANG->sL($TCA['pages']['columns']['fe_group']['label']).' '.$label;
1906 }
1907 $out = htmlspecialchars(implode(' - ', $parts));
1908 return $includeAttrib ? 'title="'.$out.'"' : $out;
1909 }
1910
1911 /**
1912 * Returns title-attribute information for ANY record (from a table defined in TCA of course)
1913 * 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.
1914 * "pages" table can be used as well and will return the result of ->titleAttribForPages() for that page.
1915 * Usage: 10
1916 *
1917 * @param array Table row; $row is a row from the table, $table
1918 * @param string Table name
1919 * @return string
1920 */
1921 public static function getRecordIconAltText($row, $table = 'pages') {
1922 if ($table=='pages') {
1923 $out = t3lib_BEfunc::titleAttribForPages($row, '', 0);
1924 } else {
1925 $ctrl = $GLOBALS['TCA'][$table]['ctrl']['enablecolumns'];
1926
1927 $out = 'id='.$row['uid']; // Uid is added
1928 if ($table=='pages' && $row['alias']) {
1929 $out.=' / '.$row['alias'];
1930 }
1931 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS'] && $row['pid']<0) {
1932 $out.=' - v#1.'.$row['t3ver_id'];
1933 }
1934 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
1935 switch($row['t3ver_state']) {
1936 case 1:
1937 $out.= ' - PLH WSID#'.$row['t3ver_wsid'];
1938 break;
1939 case 2:
1940 $out.= ' - Deleted element!';
1941 break;
1942 case 3:
1943 $out.= ' - NEW LOCATION (PLH) WSID#'.$row['t3ver_wsid'];
1944 break;
1945 case 4:
1946 $out.= ' - OLD LOCATION (PNT) WSID#'.$row['t3ver_wsid'];
1947 break;
1948 case -1:
1949 $out.= ' - New element!';
1950 break;
1951 }
1952 }
1953
1954 if ($ctrl['disabled']) { // Hidden ...
1955 $out.=($row[$ctrl['disabled']]?' - '.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.hidden'):'');
1956 }
1957 if ($ctrl['starttime']) {
1958 if ($row[$ctrl['starttime']] > $GLOBALS['EXEC_TIME']) {
1959 $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').')';
1960 }
1961 }
1962 if ($row[$ctrl['endtime']]) {
1963 $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').')';
1964 }
1965 }
1966 return htmlspecialchars($out);
1967 }
1968
1969 /**
1970 * Returns the label of the first found entry in an "items" array from $TCA (tablename = $table/fieldname = $col) where the value is $key
1971 * Usage: 9
1972 *
1973 * @param string Table name, present in $TCA
1974 * @param string Field name, present in $TCA
1975 * @param string items-array value to match
1976 * @return string Label for item entry
1977 */
1978 public static function getLabelFromItemlist($table, $col, $key) {
1979 global $TCA;
1980 // Load full TCA for $table
1981 t3lib_div::loadTCA($table);
1982
1983 // Check, if there is an "items" array:
1984 if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$col]) && is_array($TCA[$table]['columns'][$col]['config']['items'])) {
1985 // Traverse the items-array...
1986 reset($TCA[$table]['columns'][$col]['config']['items']);
1987 while(list($k, $v) = each($TCA[$table]['columns'][$col]['config']['items'])) {
1988 // ... and return the first found label where the value was equal to $key
1989 if (!strcmp($v[1], $key)) return $v[0];
1990 }
1991 }
1992 }
1993
1994 /**
1995 * Returns the label-value for fieldname $col in table, $table
1996 * 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>'
1997 * Usage: 17
1998 *
1999 * @param string Table name, present in $TCA
2000 * @param string Field name
2001 * @param string Wrap value - set function description
2002 * @return string
2003 */
2004 public static function getItemLabel($table, $col, $printAllWrap = '') {
2005 global $TCA;
2006 // Load full TCA for $table
2007 t3lib_div::loadTCA($table);
2008 // Check if column exists
2009 if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$col])) {
2010 // Re
2011 return $TCA[$table]['columns'][$col]['label'];
2012 }
2013 if ($printAllWrap) {
2014 $parts = explode('|', $printAllWrap);
2015 return $parts[0].$col.$parts[1];
2016 }
2017 }
2018
2019 /**
2020 * Returns the "title"-value in record, $row, from table, $table
2021 * The field(s) from which the value is taken is determined by the "ctrl"-entries 'label', 'label_alt' and 'label_alt_force'
2022 * Usage: 26
2023 *
2024 * @param string Table name, present in TCA
2025 * @param array Row from table
2026 * @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
2027 * @param boolean If set, the function always returns an output. If no value is found for the title, '[No title]' is returned (localized).
2028 * @return string
2029 */
2030 public static function getRecordTitle($table, $row, $prep = FALSE, $forceResult = TRUE) {
2031 global $TCA;
2032 if (is_array($TCA[$table])) {
2033
2034 // If configured, call userFunc
2035 if ($TCA[$table]['ctrl']['label_userFunc']) {
2036 $params['table'] = $table;
2037 $params['row'] = $row;
2038 $params['title'] = '';
2039
2040 t3lib_div::callUserFunction($TCA[$table]['ctrl']['label_userFunc'], $params, $this);
2041 $t = $params['title'];
2042 } else {
2043
2044 // No userFunc: Build label
2045 $t = t3lib_BEfunc::getProcessedValue($table, $TCA[$table]['ctrl']['label'], $row[$TCA[$table]['ctrl']['label']], 0, 0, false, $row['uid'], $forceResult);
2046 if ($TCA[$table]['ctrl']['label_alt'] && ($TCA[$table]['ctrl']['label_alt_force'] || !strcmp($t, ''))) {
2047 $altFields = t3lib_div::trimExplode(',', $TCA[$table]['ctrl']['label_alt'], 1);
2048 $tA = array();
2049 if (!empty($t)) $tA[] = $t;
2050 foreach ($altFields as $fN) {
2051 $t = trim(strip_tags($row[$fN]));
2052 if (strcmp($t, '')) {
2053 $t = t3lib_BEfunc::getProcessedValue($table, $fN, $t, 0, 0, false, $row['uid']);
2054 if (!$TCA[$table]['ctrl']['label_alt_force']) {
2055 break;
2056 }
2057 $tA[] = $t;
2058 }
2059 }
2060 if ($TCA[$table]['ctrl']['label_alt_force']) {
2061 $t = implode(', ', $tA);
2062 }
2063 }
2064 }
2065
2066 // If the current result is empty, set it to '[No title]' (localized) and prepare for output if requested
2067 if ($prep || $forceResult) {
2068 if ($prep) {
2069 $t = t3lib_BEfunc::getRecordTitlePrep($t);
2070 }
2071 if (!strcmp(trim($t), '')) {
2072 $t = t3lib_BEfunc::getNoRecordTitle($prep);
2073 }
2074 }
2075
2076 return $t;
2077 }
2078 }
2079
2080 /**
2081 * Crops a title string to a limited lenght and if it really was cropped, wrap it in a <span title="...">|</span>,
2082 * which offers a tooltip with the original title when moving mouse over it.
2083 *
2084 * @param string $title: The title string to be cropped
2085 * @param integer $titleLength: Crop title after this length - if not set, BE_USER->uc['titleLen'] is used
2086 * @return string The processed title string, wrapped in <span title="...">|</span> if cropped
2087 */
2088 public static function getRecordTitlePrep($title, $titleLength = 0) {
2089 // If $titleLength is not a valid positive integer, use BE_USER->uc['titleLen']:
2090 if (!$titleLength || !t3lib_div::testInt($titleLength) || $titleLength < 0) {
2091 $titleLength = $GLOBALS['BE_USER']->uc['titleLen'];
2092 }
2093 $titleOrig = htmlspecialchars($title);
2094 $title = htmlspecialchars(t3lib_div::fixed_lgd_cs($title, $titleLength));
2095 // If title was cropped, offer a tooltip:
2096 if ($titleOrig != $title) {
2097 $title = '<span title="'.$titleOrig.'">'.$title.'</span>';
2098 }
2099 return $title;
2100 }
2101
2102 /**
2103 * Get a localized [No title] string, wrapped in <em>|</em> if $prep is true.
2104 *
2105 * @param boolean $prep: Wrap result in <em>|</em>
2106 * @return string Localized [No title] string
2107 */
2108 public static function getNoRecordTitle($prep = FALSE) {
2109 $noTitle = '['.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.no_title', 1).']';
2110 if ($prep) $noTitle = '<em>'.$noTitle.'</em>';
2111 return $noTitle;
2112 }
2113
2114 /**
2115 * Returns a human readable output of a value from a record
2116 * 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.
2117 * $table/$col is tablename and fieldname
2118 * REMEMBER to pass the output through htmlspecialchars() if you output it to the browser! (To protect it from XSS attacks and be XHTML compliant)
2119 * Usage: 24
2120 *
2121 * @param string Table name, present in TCA
2122 * @param string Field name, present in TCA
2123 * @param string $value is the value of that field from a selected record
2124 * @param integer $fixed_lgd_chars is the max amount of characters the value may occupy
2125 * @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")
2126 * @param boolean If set, no records will be looked up, UIDs are just shown.
2127 * @param integer uid of the current record
2128 * @param boolean If t3lib_BEfunc::getRecordTitle is used to process the value, this parameter is forwarded.
2129 * @return string
2130 */
2131 public static function getProcessedValue($table, $col, $value, $fixed_lgd_chars = 0, $defaultPassthrough = 0, $noRecordLookup = FALSE, $uid = 0, $forceResult = TRUE) {
2132 global $TCA;
2133 global $TYPO3_CONF_VARS;
2134
2135 if ($col == 'uid') {
2136 // no need to load TCA as uid is not in TCA-array
2137 return $value;
2138 }
2139 // Load full TCA for $table
2140 t3lib_div::loadTCA($table);
2141 // Check if table and field is configured:
2142 if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$col])) {
2143 // Depending on the fields configuration, make a meaningful output value.
2144 $theColConf = $TCA[$table]['columns'][$col]['config'];
2145
2146 /*****************
2147 *HOOK: pre-processing the human readable output from a record
2148 ****************/
2149 if (is_array ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['preProcessValue'])) {
2150 foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['preProcessValue'] as $_funcRef) {
2151 t3lib_div::callUserFunction($_funcRef,$theColConf,$this);
2152 }
2153 }
2154
2155 $l = '';
2156 switch((string)$theColConf['type']) {
2157 case 'radio':
2158 $l = t3lib_BEfunc::getLabelFromItemlist($table,$col,$value);
2159 $l = $GLOBALS['LANG']->sL($l);
2160 break;
2161 case 'select':
2162 if ($theColConf['MM']) {
2163 // Display the title of MM related records in lists
2164 if ($noRecordLookup) {
2165 $MMfield = $theColConf['foreign_table'].'.uid';
2166 } else {
2167 $MMfields = array($theColConf['foreign_table'].'.'.$TCA[$theColConf['foreign_table']]['ctrl']['label']);
2168 foreach (t3lib_div::trimExplode(',', $TCA[$theColConf['foreign_table']]['ctrl']['label_alt'], 1) as $f) {
2169 $MMfields[] = $theColConf['foreign_table'].'.'.$f;
2170 }
2171 $MMfield = join(',',$MMfields);
2172 }
2173
2174 $dbGroup = t3lib_div::makeInstance('t3lib_loadDBGroup');
2175 $dbGroup->start($value, $theColConf['foreign_table'], $theColConf['MM'], $uid, $table, $theColConf);
2176 $selectUids = $dbGroup->tableArray[$theColConf['foreign_table']];
2177
2178 if (is_array($selectUids) && count($selectUids)>0) {
2179 $MMres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
2180 'uid, '.$MMfield,
2181 $theColConf['foreign_table'],
2182 'uid IN ('.implode(',', $selectUids).')'
2183 );
2184 while($MMrow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($MMres)) {
2185 $mmlA[] = ($noRecordLookup?$MMrow['uid']:t3lib_BEfunc::getRecordTitle($theColConf['foreign_table'], $MMrow, FALSE, $forceResult));
2186 }
2187 $GLOBALS['TYPO3_DB']->sql_free_result($MMres);
2188
2189 if (is_array($mmlA)) {
2190 $l = implode('; ', $mmlA);
2191 } else {
2192 $l = '';
2193 }
2194 } else {
2195 $l = 'N/A';
2196 }
2197 } else {
2198 $l = t3lib_BEfunc::getLabelFromItemlist($table, $col, $value);
2199 $l = $GLOBALS['LANG']->sL($l);
2200 if ($theColConf['foreign_table'] && !$l && $TCA[$theColConf['foreign_table']]) {
2201 if ($noRecordLookup) {
2202 $l = $value;
2203 } else {
2204 $rParts = t3lib_div::trimExplode(',', $value, 1);
2205 reset($rParts);
2206 $lA = array();
2207 while(list(,$rVal) = each($rParts)) {
2208 $rVal = intval($rVal);
2209 if ($rVal>0) {
2210 $r = t3lib_BEfunc::getRecordWSOL($theColConf['foreign_table'], $rVal);
2211 } else {
2212 $r = t3lib_BEfunc::getRecordWSOL($theColConf['neg_foreign_table'], -$rVal);
2213 }
2214 if (is_array($r)) {
2215 $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);
2216 } else {
2217 $lA[] = $rVal?'['.$rVal.'!]':'';
2218 }
2219 }
2220 $l = implode(', ', $lA);
2221 }
2222 }
2223 }
2224 break;
2225 case 'group':
2226 $l = implode(', ', t3lib_div::trimExplode(',', $value, 1));
2227 break;
2228 case 'check':
2229 if (!is_array($theColConf['items']) || count($theColConf['items'])==1) {
2230 $l = $value ? $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:yes') : $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:no');
2231 } else {
2232 reset($theColConf['items']);
2233 $lA = Array();
2234 while(list($key, $val) = each($theColConf['items'])) {
2235 if ($value & pow(2, $key)) {$lA[] = $GLOBALS['LANG']->sL($val[0]);}
2236 }
2237 $l = implode(', ', $lA);
2238 }
2239 break;
2240 case 'input':
2241 if (isset($value)) {
2242 if (t3lib_div::inList($theColConf['eval'], 'date')) {
2243 $l = t3lib_BEfunc::date($value) .
2244 ' (' .
2245 ($GLOBALS['EXEC_TIME'] - $value > 0 ? '-' : '') .
2246 t3lib_BEfunc::calcAge(abs($GLOBALS['EXEC_TIME'] - $value), $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears')) .
2247 ')';
2248 } elseif (t3lib_div::inList($theColConf['eval'], 'time')) {
2249 $l = t3lib_BEfunc::time($value, FALSE);
2250 } elseif (t3lib_div::inList($theColConf['eval'], 'timesec')) {
2251 $l = t3lib_BEfunc::time($value);
2252 } elseif (t3lib_div::inList($theColConf['eval'], 'datetime')) {
2253 $l = t3lib_BEfunc::datetime($value);
2254 } else {
2255 $l = $value;
2256 }
2257 }
2258 break;
2259 case 'flex':
2260 $l = strip_tags($value);
2261 break;
2262 default:
2263 if ($defaultPassthrough) {
2264 $l = $value;
2265 } elseif ($theColConf['MM']) {
2266 $l = 'N/A';
2267 } elseif ($value) {
2268 $l = t3lib_div::fixed_lgd_cs(strip_tags($value), 200);
2269 }
2270 break;
2271 }
2272
2273 /*****************
2274 *HOOK: post-processing the human readable output from a record
2275 ****************/
2276 if (is_array ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['postProcessValue'])) {
2277 foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['postProcessValue'] as $_funcRef) {
2278 $params = array(
2279 'value' => $l,
2280 'colConf' => $theColConf
2281 );
2282 $l = t3lib_div::callUserFunction($_funcRef, $params, $this);
2283 }
2284 }
2285
2286 if ($fixed_lgd_chars) {
2287 return t3lib_div::fixed_lgd_cs($l, $fixed_lgd_chars);
2288 } else {
2289 return $l;
2290 }
2291 }
2292 }
2293
2294 /**
2295 * 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.
2296 * Usage: 2
2297 *
2298 * @param string Table name, present in TCA
2299 * @param string Field name
2300 * @param string Field value
2301 * @param integer $fixed_lgd_chars is the max amount of characters the value may occupy
2302 * @param integer uid of the current record
2303 * @param boolean If t3lib_BEfunc::getRecordTitle is used to process the value, this parameter is forwarded.
2304 * @return string
2305 * @see getProcessedValue()
2306 */
2307 public static function getProcessedValueExtra($table, $fN, $fV, $fixed_lgd_chars = 0, $uid = 0, $forceResult = TRUE) {
2308 global $TCA;
2309 $fVnew = t3lib_BEfunc::getProcessedValue($table, $fN, $fV, $fixed_lgd_chars, 0, 0, $uid, $forceResult);
2310 if (!isset($fVnew)) {
2311 if (is_array($TCA[$table])) {
2312 if ($fN==$TCA[$table]['ctrl']['tstamp'] || $fN==$TCA[$table]['ctrl']['crdate']) {
2313 $fVnew = t3lib_BEfunc::datetime($fV);
2314 } elseif ($fN=='pid'){
2315 $fVnew = t3lib_BEfunc::getRecordPath($fV, '1=1', 20); // Fetches the path with no regard to the users permissions to select pages.
2316 } else {
2317 $fVnew = $fV;
2318 }
2319 }
2320 }
2321 return $fVnew;
2322 }
2323
2324 /**
2325 * Returns file icon name (from $FILEICONS) for the fileextension $ext
2326 * Usage: 10
2327 *
2328 * @param string File extension, lowercase
2329 * @return string File icon filename
2330 */
2331 public static function getFileIcon($ext) {
2332 return $GLOBALS['FILEICONS'][$ext] ? $GLOBALS['FILEICONS'][$ext] : $GLOBALS['FILEICONS']['default'];
2333 }
2334
2335 /**
2336 * Returns fields for a table, $table, which would typically be interesting to select
2337 * This includes uid, the fields defined for title, icon-field.
2338 * 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)
2339 * Usage: 3
2340 *
2341 * @param string Table name, present in TCA
2342 * @param string Table prefix
2343 * @param array Preset fields (must include prefix if that is used)
2344 * @return string List of fields.
2345 */
2346 public static function getCommonSelectFields($table, $prefix = '', $fields = array()) {
2347 global $TCA;
2348 $fields[] = $prefix.'uid';
2349 $fields[] = $prefix.$TCA[$table]['ctrl']['label'];
2350
2351 if ($TCA[$table]['ctrl']['label_alt']) {
2352 $secondFields = t3lib_div::trimExplode(',', $TCA[$table]['ctrl']['label_alt'], 1);
2353 foreach($secondFields as $fieldN) {
2354 $fields[] = $prefix.$fieldN;
2355 }
2356 }
2357 if ($TCA[$table]['ctrl']['versioningWS']) {
2358 $fields[] = $prefix.'t3ver_id';
2359 $fields[] = $prefix.'t3ver_state';
2360 $fields[] = $prefix.'t3ver_wsid';
2361 $fields[] = $prefix.'t3ver_count';
2362 }
2363
2364 if ($TCA[$table]['ctrl']['selicon_field']) $fields[] = $prefix.$TCA[$table]['ctrl']['selicon_field'];
2365 if ($TCA[$table]['ctrl']['typeicon_column']) $fields[] = $prefix.$TCA[$table]['ctrl']['typeicon_column'];
2366
2367 if (is_array($TCA[$table]['ctrl']['enablecolumns'])) {
2368 if ($TCA[$table]['ctrl']['enablecolumns']['disabled']) $fields[] = $prefix.$TCA[$table]['ctrl']['enablecolumns']['disabled'];
2369 if ($TCA[$table]['ctrl']['enablecolumns']['starttime']) $fields[] = $prefix.$TCA[$table]['ctrl']['enablecolumns']['starttime'];
2370 if ($TCA[$table]['ctrl']['enablecolumns']['endtime']) $fields[] = $prefix.$TCA[$table]['ctrl']['enablecolumns']['endtime'];
2371 if ($TCA[$table]['ctrl']['enablecolumns']['fe_group']) $fields[] = $prefix.$TCA[$table]['ctrl']['enablecolumns']['fe_group'];
2372 }
2373
2374 return implode(',', array_unique($fields));
2375 }
2376
2377 /**
2378 * 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
2379 * <form>-tags must be supplied separately
2380 * 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.
2381 * Usage: 1 (ext. direct_mail)
2382 *
2383 * @param array Field configuration code.
2384 * @param array Defaults
2385 * @param string Prefix for formfields
2386 * @return string HTML for a form.
2387 */
2388 public static function makeConfigForm($configArray, $defaults, $dataPrefix) {
2389 $params = $defaults;
2390 if (is_array($configArray)) {
2391 reset($configArray);
2392 $lines = array();
2393 while(list($fname, $config) = each($configArray)) {
2394 if (is_array($config)) {
2395 $lines[$fname] = '<strong>'.htmlspecialchars($config[1]).'</strong><br />';
2396 $lines[$fname].=$config[2].'<br />';
2397 switch($config[0]) {
2398 case 'string':
2399 case 'short':
2400 $formEl = '<input type="text" name="'.$dataPrefix.'['.$fname.']" value="'.$params[$fname].'"'.$GLOBALS['TBE_TEMPLATE']->formWidth($config[0]=='short'?24:48).' />';
2401 break;
2402 case 'check':
2403 $formEl = '<input type="hidden" name="'.$dataPrefix.'['.$fname.']" value="0" /><input type="checkbox" name="'.$dataPrefix.'['.$fname.']" value="1"'.($params[$fname]?' checked="checked"':'').' />';
2404 break;
2405 case 'comment':
2406 $formEl = '';
2407 break;
2408 case 'select':
2409 reset($config[3]);
2410 $opt = array();
2411 while(list($k, $v) = each($config[3])) {
2412 $opt[] = '<option value="'.htmlspecialchars($k).'"'.($params[$fname]==$k?' selected="selected"':'').'>'.htmlspecialchars($v).'</option>';
2413 }
2414 $formEl = '<select name="'.$dataPrefix.'['.$fname.']">'.implode('', $opt).'</select>';
2415 break;
2416 default:
2417 debug($config);
2418 break;
2419 }
2420 $lines[$fname].=$formEl;
2421 $lines[$fname].='<br /><br />';
2422 } else {
2423 $lines[$fname] = '<hr />';
2424 if ($config) $lines[$fname].='<strong>'.strtoupper(htmlspecialchars($config)).'</strong><br />';
2425 if ($config) $lines[$fname].='<br />';
2426 }
2427 }
2428 }
2429 $out = implode('', $lines);
2430 $out.='<input type="submit" name="submit" value="Update configuration" />';
2431 return $out;
2432 }
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446 /*******************************************
2447 *
2448 * Backend Modules API functions
2449 *
2450 *******************************************/
2451
2452 /**
2453 * Returns help-text icon if configured for.
2454 * TCA_DESCR must be loaded prior to this function and $BE_USER must have 'edit_showFieldHelp' set to 'icon', otherwise nothing is returned
2455 * Usage: 6
2456 *
2457 * @param string Table name
2458 * @param string Field name
2459 * @param string Back path
2460 * @param boolean Force display of icon nomatter BE_USER setting for help
2461 * @return string HTML content for a help icon/text
2462 */
2463 public static function helpTextIcon($table, $field, $BACK_PATH, $force = 0) {
2464 global $TCA_DESCR, $BE_USER;
2465
2466 $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;';
2467 if (is_array($TCA_DESCR[$table]) && is_array($TCA_DESCR[$table]['columns'][$field]) && (isset($BE_USER->uc['edit_showFieldHelp']) || $force)) {
2468 if ($BE_USER->uc['edit_showFieldHelp'] == 'icon') {
2469 $text = t3lib_BEfunc::helpText($table, $field, $BACK_PATH, '');
2470 $text = '<span class="typo3-csh-inline">'.$GLOBALS['LANG']->hscAndCharConv($text, false).'</span>';
2471 }
2472 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>';
2473 }
2474 }
2475
2476
2477 /**
2478 * Returns CSH help text (description), if configured for.
2479 * TCA_DESCR must be loaded prior to this function and $BE_USER must have "edit_showFieldHelp" set to "text",
2480 * otherwise nothing is returned
2481 * Will automatically call t3lib_BEfunc::helpTextIcon() to get the icon for the text.
2482 * Usage: 4
2483 *
2484 * @param string Table name
2485 * @param string Field name
2486 * @param string Back path
2487 * @param string DEPRECATED: Additional style-attribute content for wrapping table (now: only in function cshItem needed)
2488 * @return string HTML content for help text
2489 */
2490 public static function helpText($table, $field, $BACK_PATH, $styleAttrib = '') {
2491 global $TCA_DESCR, $BE_USER;
2492 $output = '';
2493
2494 if (is_array($TCA_DESCR[$table]) && is_array($TCA_DESCR[$table]['columns'][$field])) {
2495 $data = $TCA_DESCR[$table]['columns'][$field];
2496 // add see also arrow
2497 if ($data['image_descr'] || $data['seeAlso'] || $data['details'] || $data['syntax']) {
2498 $arrow = '<img'.t3lib_iconWorks::skinImg($BACK_PATH, 'gfx/rel_db.gif', 'width="13" height="12"').' class="absmiddle" alt="" />';
2499 }
2500 // add description text
2501 if ($data['description'] || $arrow) {
2502 $output = '<span class="paragraph">'.nl2br(htmlspecialchars($data['description'])).$arrow.'</span>';
2503 }
2504
2505 // put header before the rest of the text
2506 if ($data['alttitle']) {
2507 $output = '<span class="header">'.$data['alttitle'].'</span><br />'.$output;
2508 }
2509 }
2510 return $output;
2511 }
2512
2513
2514 /**
2515 * API for getting CSH icons/text for use in backend modules.
2516 * TCA_DESCR will be loaded if it isn't already
2517 * Usage: ?
2518 *
2519 * @param string Table name ('_MOD_'+module name)
2520 * @param string Field name (CSH locallang main key)
2521 * @param string Back path
2522 * @param string Wrap code for icon-mode, splitted by "|". Not used for full-text mode.
2523 * @param boolean If set, the full text will never be shown (only icon).
2524 * Useful for places where it will break the page if the table with full text is shown.
2525 * @param string Additional style-attribute content for wrapping table (full text mode only)
2526 * @return string HTML content for help text
2527 * @see helpText(), helpTextIcon()
2528 */
2529 public static function cshItem($table, $field, $BACK_PATH, $wrap = '', $onlyIconMode = FALSE, $styleAttrib = '') {
2530 global $TCA_DESCR, $LANG, $BE_USER;
2531
2532 if ($BE_USER->uc['edit_showFieldHelp']) {
2533 $LANG->loadSingleTableDescription($table);
2534
2535 if (is_array($TCA_DESCR[$table])) {
2536 // Creating CSH icon and short description:
2537 $fullText = t3lib_BEfunc::helpText($table, $field, $BACK_PATH, '');
2538 $icon = t3lib_BEfunc::helpTextIcon($table, $field, $BACK_PATH);
2539
2540 if ($fullText && !$onlyIconMode && $BE_USER->uc['edit_showFieldHelp'] == 'text') {
2541
2542 // Additional styles?
2543 $params = $styleAttrib ? ' style="'.$styleAttrib.'"' : '';
2544
2545 // Compile table with CSH information:
2546 $fullText = '<table border="0" cellpadding="0" cellspacing="0" class="typo3-csh-inline"'.$params.'>
2547 <tr>
2548 <td valign="top" width="14">'.$icon.'</td>
2549 <td valign="top">'.$fullText.'</td>
2550 </tr>
2551 </table>';
2552
2553 $output = $LANG->hscAndCharConv($fullText, false);
2554 } else {
2555 $output = $icon;
2556
2557 if ($output && $wrap) {
2558 $wrParts = explode('|', $wrap);
2559 $output = $wrParts[0].$output.$wrParts[1];
2560 }
2561 }
2562
2563 return $output;
2564 }
2565 }
2566 }
2567
2568 /**
2569 * 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.
2570 * REMEMBER to always htmlspecialchar() content in href-properties to ampersands get converted to entities (XHTML requirement and XSS precaution)
2571 * Usage: 35
2572 *
2573 * @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.
2574 * @param string $backPath must point back to the TYPO3_mainDir directory (where alt_doc.php is)
2575 * @param string $requestUri is an optional returnUrl you can set - automatically set to REQUEST_URI.
2576 * @return string
2577 * @see template::issueCommand()
2578 */
2579 public static function editOnClick($params, $backPath = '', $requestUri = '') {
2580 $retUrl = 'returnUrl='.($requestUri==-1?"'+T3_THIS_LOCATION+'":rawurlencode($requestUri?$requestUri:t3lib_div::getIndpEnv('REQUEST_URI')));
2581 return "window.location.href='".$backPath."alt_doc.php?".$retUrl.$params."'; return false;";
2582 }
2583
2584 /**
2585 * Returns a JavaScript string for viewing the page id, $id
2586 * 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.
2587 * Usage: 8
2588 *
2589 * @param integer $id is page id
2590 * @param string $backpath must point back to TYPO3_mainDir (where the site is assumed to be one level above)
2591 * @param array If root line is supplied the function will look for the first found domain record and use that URL instead (if found)
2592 * @param string $anchor is optional anchor to the URL
2593 * @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!
2594 * @param string Additional GET variables.
2595 * @param boolean If true, then the preview window will gain the focus.
2596 * @return string
2597 */
2598 public static function viewOnClick($id, $backPath = '', $rootLine = '', $anchor = '', $altUrl = '', $addGetVars = '', $switchFocus = TRUE) {
2599 if ($altUrl) {
2600 $url = $altUrl;
2601 } else {
2602
2603 $viewScriptPreviewEnabled = '/' . TYPO3_mainDir . 'mod/user/ws/wsol_preview.php?id=';
2604 $viewScriptPreviewDisabled = '/index.php?id=';
2605
2606 // check alternate Domains
2607 if ($rootLine) {
2608 $parts = parse_url(t3lib_div::getIndpEnv('TYPO3_SITE_URL'));
2609 if (t3lib_BEfunc::getDomainStartPage($parts['host'],$parts['path'])) {
2610 $preUrl_temp = t3lib_BEfunc::firstDomainRecord($rootLine);
2611 }
2612 }
2613 $preUrl = $preUrl_temp ? (t3lib_div::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://').$preUrl_temp : $backPath.'..';
2614
2615 // Look if a fixed preview language should be added:
2616 $viewLanguageOrder = $GLOBALS['BE_USER']->getTSConfigVal('options.view.languageOrder');
2617 if (strlen($viewLanguageOrder)) {
2618 $suffix = '';
2619
2620 // Find allowed languages (if none, all are allowed!)
2621 if (!$GLOBALS['BE_USER']->user['admin'] &&
2622 strlen($GLOBALS['BE_USER']->groupData['allowed_languages'])) {
2623 $allowed_languages = array_flip(explode(',', $GLOBALS['BE_USER']->groupData['allowed_languages']));
2624 }
2625
2626 // Traverse the view order, match first occurence:
2627 $lOrder = t3lib_div::intExplode(',',$viewLanguageOrder);
2628 foreach($lOrder as $langUid) {
2629 if (is_array($allowed_languages) && count($allowed_languages)) {
2630 if (isset($allowed_languages[$langUid])) { // Choose if set.
2631 $suffix = '&L='.$langUid;
2632 break;
2633 }
2634 } else { // All allowed since no lang. are listed.
2635 $suffix = '&L='.$langUid;
2636 break;
2637 }
2638 }
2639
2640 // Add it:
2641 $addGetVars.= $suffix;
2642 }
2643
2644 $urlPreviewEnabled = $preUrl . $viewScriptPreviewEnabled . $id . $addGetVars . $anchor;
2645 $urlPreviewDisabled = $preUrl . $viewScriptPreviewDisabled . $id . $addGetVars . $anchor;
2646 }
2647
2648 return "previewWin=window.open(top.WorkspaceFrontendPreviewEnabled?'" .
2649 $urlPreviewDisabled . "':'" . $urlPreviewEnabled .
2650 "','newTYPO3frontendWindow');" . ( $switchFocus ? 'previewWin.focus();' : '');
2651 }
2652
2653 /**
2654 * Returns the merged User/Page TSconfig for page id, $id.
2655 * Please read details about module programming elsewhere!
2656 * Usage: 15
2657 *
2658 * @param integer Page uid
2659 * @param string $TSref is an object string which determines the path of the TSconfig to return.
2660 * @return array
2661 */
2662 public static function getModTSconfig($id, $TSref) {
2663 $pageTS_modOptions = $GLOBALS['BE_USER']->getTSConfig($TSref, t3lib_BEfunc::getPagesTSconfig($id));
2664 $BE_USER_modOptions = $GLOBALS['BE_USER']->getTSConfig($TSref);
2665 $modTSconfig = t3lib_div::array_merge_recursive_overrule($pageTS_modOptions, $BE_USER_modOptions);
2666 return $modTSconfig;
2667 }
2668
2669 /**
2670 * Returns a selector box "function menu" for a module
2671 * Requires the JS function jumpToUrl() to be available
2672 * See Inside TYPO3 for details about how to use / make Function menus
2673 * Usage: 50
2674 *
2675 * @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=...
2676 * @param string $elementName it the form elements name, probably something like "SET[...]"
2677 * @param string $currentValue is the value to be selected currently.
2678 * @param array $menuItems is an array with the menu items for the selector box
2679 * @param string $script is the script to send the &id to, if empty it's automatically found
2680 * @param string $addParams is additional parameters to pass to the script.
2681 * @return string HTML code for selector box
2682 */
2683 public static function getFuncMenu($mainParams, $elementName, $currentValue, $menuItems, $script = '', $addparams = '') {
2684 if (is_array($menuItems)) {
2685 if (!is_array($mainParams)) {
2686 $mainParams = array('id' => $mainParams);
2687 }
2688 $mainParams = t3lib_div::implodeArrayForUrl('', $mainParams);
2689
2690 if (!$script) {
2691 $script = basename(PATH_thisScript);
2692 $mainParams.= (t3lib_div::_GET('M') ? '&M='.rawurlencode(t3lib_div::_GET('M')) : '');
2693 }
2694
2695 $options = array();
2696 foreach($menuItems as $value => $label) {
2697 $options[] = '<option value="'.htmlspecialchars($value).'"'.(!strcmp($currentValue, $value)?' selected="selected"':'').'>'.
2698 t3lib_div::deHSCentities(htmlspecialchars($label)).
2699 '</option>';
2700 }
2701 if (count($options)) {
2702 $onChange = 'jumpToUrl(\''.$script.'?'.$mainParams.$addparams.'&'.$elementName.'=\'+this.options[this.selectedIndex].value,this);';
2703 return '
2704
2705 <!-- Function Menu of module -->
2706 <select name="'.$elementName.'" onchange="'.htmlspecialchars($onChange).'">
2707 '.implode('
2708 ',$options).'
2709 </select>
2710 ';
2711 }
2712 }
2713 }
2714
2715 /**
2716 * Checkbox function menu.
2717 * Works like ->getFuncMenu() but takes no $menuItem array since this is a simple checkbox.
2718 * Usage: 34
2719 *
2720 * @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=...
2721 * @param string $elementName it the form elements name, probably something like "SET[...]"
2722 * @param string $currentValue is the value to be selected currently.
2723 * @param string $script is the script to send the &id to, if empty it's automatically found
2724 * @param string $addParams is additional parameters to pass to the script.
2725 * @param string Additional attributes for the checkbox input tag
2726 * @return string HTML code for checkbox
2727 * @see getFuncMenu()
2728 */
2729 public static function getFuncCheck($mainParams, $elementName, $currentValue, $script = '', $addparams = '', $tagParams = '') {
2730 if (!is_array($mainParams)) {
2731 $mainParams = array('id' => $mainParams);
2732 }
2733 $mainParams = t3lib_div::implodeArrayForUrl('', $mainParams);
2734
2735 if (!$script) {
2736 $script = basename(PATH_thisScript);
2737 $mainParams.= (t3lib_div::_GET('M') ? '&M='.rawurlencode(t3lib_div::_GET('M')) : '');
2738 }
2739
2740 $onClick = 'jumpToUrl(\''.$script.'?'.$mainParams.$addparams.'&'.$elementName.'=\'+(this.checked?1:0),this);';
2741 return '<input type="checkbox" class="checkbox" name="'.$elementName.'"'.($currentValue?' checked="checked"':'').' onclick="'.htmlspecialchars($onClick).'"'.($tagParams?' '.$tagParams:'').' />';
2742 }
2743
2744 /**
2745 * Input field function menu
2746 * Works like ->getFuncMenu() / ->getFuncCheck() but displays a input field instead which updates the script "onchange"
2747 * Usage: 1
2748 *
2749 * @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=...
2750 * @param string $elementName it the form elements name, probably something like "SET[...]"
2751 * @param string $currentValue is the value to be selected currently.
2752 * @param integer Relative size of input field, max is 48
2753 * @param string $script is the script to send the &id to, if empty it's automatically found
2754 * @param string $addParams is additional parameters to pass to the script.
2755 * @return string HTML code for input text field.
2756 * @see getFuncMenu()
2757 */
2758 public static function getFuncInput($mainParams, $elementName, $currentValue, $size = 10, $script = "", $addparams = "") {
2759 if (!is_array($mainParams)) {
2760 $mainParams = array('id' => $mainParams);
2761 }
2762 $mainParams = t3lib_div::implodeArrayForUrl('', $mainParams);
2763
2764 if (!$script) {
2765 $script = basename(PATH_thisScript);
2766 $mainParams.= (t3lib_div::_GET('M') ? '&M='.rawurlencode(t3lib_div::_GET('M')) : '');
2767 }
2768
2769 $onChange = 'jumpToUrl(\''.$script.'?'.$mainParams.$addparams.'&'.$elementName.'=\'+escape(this.value),this);';
2770 return '<input type="text"'.$GLOBALS['TBE_TEMPLATE']->formWidth($size).' name="'.$elementName.'" value="'.htmlspecialchars($currentValue).'" onchange="'.htmlspecialchars($onChange).'" />';
2771 }
2772
2773 /**
2774 * Removes menu items from $itemArray if they are configured to be removed by TSconfig for the module ($modTSconfig)
2775 * See Inside TYPO3 about how to program modules and use this API.
2776 * Usage: 4
2777 *
2778 * @param array Module TS config array
2779 * @param array Array of items from which to remove items.
2780 * @param string $TSref points to the "object string" in $modTSconfig
2781 * @return array The modified $itemArray is returned.
2782 */
2783 public static function unsetMenuItems($modTSconfig, $itemArray, $TSref) {
2784 // Getting TS-config options for this module for the Backend User:
2785 $conf = $GLOBALS['BE_USER']->getTSConfig($TSref, $modTSconfig);
2786 if (is_array($conf['properties'])) {
2787 reset($conf['properties']);
2788 while(list($key, $val) = each($conf['properties'])) {
2789 if (!$val) {
2790 unset($itemArray[$key]);
2791 }
2792 }
2793 }
2794 return $itemArray;
2795 }
2796
2797 /**
2798 * Call to update the page tree frame (or something else..?) after
2799 * t3lib_BEfunc::getSetUpdateSignal('updatePageTree') -> will set the page tree to be updated.
2800 * t3lib_BEfunc::getSetUpdateSignal() -> will return some JavaScript that does the update (called in the typo3/template.php file, end() function)
2801 * please use the setUpdateSignal function instead now, as it allows you to add more parameters
2802 * Usage: 11
2803 *
2804 * @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.
2805 * @return string HTML code (<script> section)
2806 * @see t3lib_BEfunc::getUpdateSignalCode()
2807 * @see t3lib_BEfunc::setUpdateSignal()
2808 * @deprecated since TYPO3 4.2, please use the setUpdateSignal function instead, as it allows you to add more parameters
2809 */
2810 public static function getSetUpdateSignal($set = '') {
2811 // kept for backwards compatibility if $set is empty, use "getUpdateSignalCode()" instead
2812 if ($set) {
2813 return t3lib_BEfunc::setUpdateSignal($set);
2814 } else {
2815 return t3lib_BEfunc::getUpdateSignalCode();
2816 }
2817 }
2818
2819
2820 /**
2821 * Call to update the page tree frame (or something else..?) after
2822 * use 'updatePageTree' as a first parameter will set the page tree to be updated.
2823 * Usage: 10
2824 *
2825 * @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.
2826 * @param mixed Additional information for the update signal, used to only refresh a branch of the tree
2827 * @return void
2828 * @see t3lib_BEfunc::getUpdateSignalCode()
2829 */
2830 public function setUpdateSignal($set = '', $params = '') {
2831 global $BE_USER;
2832 $modData = $BE_USER->getModuleData('t3lib_BEfunc::getUpdateSignal', 'ses');
2833
2834 if ($set) {
2835 $modData[$set] = array(
2836 'set' => $set,
2837 'parameter' => $params);
2838 } else { // clear the module data
2839 $modData = array();
2840 }
2841 $BE_USER->pushModuleData('t3lib_BEfunc::getUpdateSignal', $modData);
2842 }
2843
2844
2845 /**
2846 * Call to update the page tree frame (or something else..?) if this is set by the function
2847 * setUpdateSignal(). It will return some JavaScript that does the update (called in the typo3/template.php file, end() function)
2848 * Usage: 1
2849 *
2850 * @return string HTML javascript code
2851 * @see t3lib_BEfunc::setUpdateSignal()
2852 */
2853 public function getUpdateSignalCode() {
2854 $signals = array();
2855 $modData = $GLOBALS['BE_USER']->getModuleData('t3lib_BEfunc::getUpdateSignal', 'ses');
2856 if (!count($modData)) {
2857 return '';
2858 }
2859
2860 // Hook: Allows to let TYPO3 execute your JS code
2861 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['updateSignalHook'])) {
2862 $updateSignals = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['updateSignalHook'];
2863 } else {
2864 $updateSignals = array();
2865 }
2866
2867 // loop through all setUpdateSignals and get the JS code
2868 foreach ($modData as $set => $val) {
2869 if (isset($updateSignals[$set])) {
2870 $params = array('set' => $set, 'parameter' => $val['parameter'], 'JScode' => '');
2871 $ref = NULL;
2872 t3lib_div::callUserFunction($updateSignals[$set], $params, $ref);
2873 $signals[] = $params['JScode'];
2874 } else if ($set == 'updatePageTree' || $set == 'updateFolderTree') {
2875 $signals[] = '
2876 if (top && top.content && top.content.nav_frame && top.content.nav_frame.Tree) {
2877 top.content.nav_frame.Tree.refresh();
2878 }';
2879 }
2880 }
2881
2882 $content = implode(chr(10), $signals);
2883
2884 t3lib_BEfunc::setUpdateSignal(); // for backwards compatibility, should be replaced
2885 return $content;
2886 }
2887
2888
2889 /**
2890 * Returns an array which is most backend modules becomes MOD_SETTINGS containing values from function menus etc. determining the function of the module.
2891 * This is kind of session variable management framework for the backend users.
2892 * 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
2893 * Ultimately, see Inside TYPO3 for how to use this function in relation to your modules.
2894 * Usage: 23
2895 *
2896 * @param array MOD_MENU is an array that defines the options in menus.
2897 * @param array CHANGED_SETTINGS represents the array used when passing values to the script from the menus.
2898 * @param string modName is the name of this module. Used to get the correct module data.
2899 * @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.
2900 * @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.
2901 * @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)
2902 * @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
2903 */
2904 public static function getModuleData($MOD_MENU, $CHANGED_SETTINGS, $modName, $type = '', $dontValidateList = '', $setDefaultList = '') {
2905
2906 if ($modName && is_string($modName)) {
2907 // GETTING stored user-data from this module:
2908 $settings = $GLOBALS['BE_USER']->getModuleData($modName, $type);
2909
2910 $changed = 0;
2911 if (!is_array($settings)) {
2912 $changed = 1;
2913 $settings = array();
2914 }
2915 if (is_array($MOD_MENU)) {
2916 foreach ($MOD_MENU as $key=>$var) {
2917 // If a global var is set before entering here. eg if submitted, then it's substituting the current value the array.
2918 if (is_array($CHANGED_SETTINGS) && isset($CHANGED_SETTINGS[$key]) && strcmp($settings[$key], $CHANGED_SETTINGS[$key])) {
2919 $settings[$key] = (string)$CHANGED_SETTINGS[$key];
2920 $changed = 1;
2921 }
2922 // If the $var is an array, which denotes the existence of a menu, we check if the value is permitted
2923 if (is_array($var) && (!$dontValidateList || !t3lib_div::inList($dontValidateList, $key))) {
2924 // If the setting is an array or not present in the menu-array, MOD_MENU, then the default value is inserted.
2925 if (is_array($settings[$key]) || !isset($MOD_MENU[$key][$settings[$key]])) {
2926 $settings[$key] = (string)key($var);
2927 $changed = 1;
2928 }
2929 }
2930 if ($setDefaultList && !is_array($var)) { // Sets default values (only strings/checkboxes, not menus)
2931 if (t3lib_div::inList($setDefaultList, $key) && !isset($settings[$key])) {
2932 $settings[$key] = (string)$var;
2933 }
2934 }
2935 }
2936 } else {die ('No menu!');}
2937
2938 if ($changed) {
2939 $GLOBALS['BE_USER']->pushModuleData($modName, $settings);
2940 }
2941
2942 return $settings;
2943 } else {die ('Wrong module name: "'.$modName.'"');}
2944 }
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954