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