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