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