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