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