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