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