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