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