Fixed bug #17305: Login/ Logout was not possible after introducing the locking in...
[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 'backend_layout_next_level' => $val['backend_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,backend_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
1911 $theFile_abs = PATH_site . ($uploaddir ? $uploaddir . '/' : '') . trim($theFile);
1912 $theFile = ($abs ? '' : '../') . ($uploaddir ? $uploaddir . '/' : '') . trim($theFile);
1913
1914 $fileIcon = t3lib_iconWorks::getSpriteIconForFile(
1915 strtolower($ext),
1916 array('title' => htmlspecialchars(trim($theFile)))
1917 );
1918
1919 $check = basename($theFile_abs) . ':' . filemtime($theFile_abs) . ':' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
1920 $params = '&file=' . rawurlencode($theFile);
1921 $params .= $size ? '&size=' . $size : '';
1922 $params .= '&md5sum=' . t3lib_div::shortMD5($check);
1923
1924 $url = $thumbScript . '?&dummy=' . $GLOBALS['EXEC_TIME'] . $params;
1925 $onClick = 'top.launchView(\'' . $theFile . '\',\'\',\'' . $backPath . '\');return false;';
1926 $thumbData .= '<a href="#" onclick="' . htmlspecialchars($onClick) . '">' . $fileIcon . '</a> ';
1927 }
1928 }
1929 }
1930 return $thumbData;
1931 }
1932
1933 /**
1934 * Returns single image tag to thumbnail using a thumbnail script (like thumbs.php)
1935 * Usage: 3
1936 *
1937 * @param string $thumbScript must point to "thumbs.php" relative to the script position
1938 * @param string $theFile must be the proper reference to the file thumbs.php should show
1939 * @param string $tparams are additional attributes for the image tag
1940 * @param integer $size is the size of the thumbnail send along to "thumbs.php"
1941 * @return string Image tag
1942 */
1943 public static function getThumbNail($thumbScript, $theFile, $tparams = '', $size = '') {
1944 $check = basename($theFile) . ':' . filemtime($theFile) . ':' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
1945 $params = '&file=' . rawurlencode($theFile);
1946 $params .= trim($size) ? '&size=' . trim($size) : '';
1947 $params .= '&md5sum=' . t3lib_div::shortMD5($check);
1948
1949 $url = $thumbScript . '?&dummy=' . $GLOBALS['EXEC_TIME'] . $params;
1950 $th = '<img src="' . htmlspecialchars($url) . '" title="' . trim(basename($theFile)) . '"' . ($tparams ? " " . $tparams : "") . ' alt="" />';
1951 return $th;
1952 }
1953
1954 /**
1955 * Returns title-attribute information for a page-record informing about id, alias, doktype, hidden, starttime, endtime, fe_group etc.
1956 * Usage: 8
1957 *
1958 * @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)
1959 * @param string $perms_clause is used to get the record path of the shortcut page, if any (and doktype==4)
1960 * @param boolean If $includeAttrib is set, then the 'title=""' attribute is wrapped about the return value, which is in any case htmlspecialchar()'ed already
1961 * @return string
1962 */
1963 public static function titleAttribForPages($row, $perms_clause = '', $includeAttrib = 1) {
1964 global $TCA, $LANG;
1965 $parts = array();
1966 $parts[] = 'id=' . $row['uid'];
1967 if ($row['alias']) {
1968 $parts[] = $LANG->sL($TCA['pages']['columns']['alias']['label']) . ' ' . $row['alias'];
1969 }
1970 if ($row['pid'] < 0) {
1971 $parts[] = 'v#1.' . $row['t3ver_id'];
1972 }
1973
1974 switch ($row['t3ver_state']) {
1975 case 1:
1976 $parts[] = 'PLH WSID#' . $row['t3ver_wsid'];
1977 break;
1978 case 2:
1979 $parts[] = 'Deleted element!';
1980 break;
1981 case 3:
1982 $parts[] = 'NEW LOCATION (PLH) WSID#' . $row['t3ver_wsid'];
1983 break;
1984 case 4:
1985 $parts[] = 'OLD LOCATION (PNT) WSID#' . $row['t3ver_wsid'];
1986 break;
1987 case -1:
1988 $parts[] = 'New element!';
1989 break;
1990 }
1991
1992 if ($row['doktype'] == t3lib_pageSelect::DOKTYPE_LINK) {
1993 $parts[] = $LANG->sL($TCA['pages']['columns']['url']['label']) . ' ' . $row['url'];
1994 } elseif ($row['doktype'] == t3lib_pageSelect::DOKTYPE_SHORTCUT) {
1995 if ($perms_clause) {
1996 $label = self::getRecordPath(intval($row['shortcut']), $perms_clause, 20);
1997 } else {
1998 $lRec = self::getRecordWSOL('pages', intval($row['shortcut']), 'title');
1999 $label = $lRec['title'];
2000 }
2001 if ($row['shortcut_mode'] != t3lib_pageSelect::SHORTCUT_MODE_NONE) {
2002 $label .= ', ' . $LANG->sL($TCA['pages']['columns']['shortcut_mode']['label']) . ' ' .
2003 $LANG->sL(self::getLabelFromItemlist('pages', 'shortcut_mode', $row['shortcut_mode']));
2004 }
2005 $parts[] = $LANG->sL($TCA['pages']['columns']['shortcut']['label']) . ' ' . $label;
2006 } elseif ($row['doktype'] == t3lib_pageSelect::DOKTYPE_MOUNTPOINT) {
2007 if ($perms_clause) {
2008 $label = self::getRecordPath(intval($row['mount_pid']), $perms_clause, 20);
2009 } else {
2010 $lRec = self::getRecordWSOL('pages', intval($row['mount_pid']), 'title');
2011 $label = $lRec['title'];
2012 }
2013 $parts[] = $LANG->sL($TCA['pages']['columns']['mount_pid']['label']) . ' ' . $label;
2014 if ($row['mount_pid_ol']) {
2015 $parts[] = $LANG->sL($TCA['pages']['columns']['mount_pid_ol']['label']);
2016 }
2017 }
2018 if ($row['nav_hide']) {
2019 $parts[] = rtrim($LANG->sL($TCA['pages']['columns']['nav_hide']['label']), ':');
2020 }
2021 if ($row['hidden']) {
2022 $parts[] = $LANG->sL('LLL:EXT:lang/locallang_core.php:labels.hidden');
2023 }
2024 if ($row['starttime']) {
2025 $parts[] = $LANG->sL($TCA['pages']['columns']['starttime']['label']) . ' ' . self::dateTimeAge($row['starttime'], -1, 'date');
2026 }
2027 if ($row['endtime']) {
2028 $parts[] = $LANG->sL($TCA['pages']['columns']['endtime']['label']) . ' ' . self::dateTimeAge($row['endtime'], -1, 'date');
2029 }
2030 if ($row['fe_group']) {
2031 $fe_groups = array();
2032 foreach (t3lib_div::intExplode(',', $row['fe_group']) as $fe_group) {
2033 if ($fe_group < 0) {
2034 $fe_groups[] = $LANG->sL(self::getLabelFromItemlist('pages', 'fe_group', $fe_group));
2035 } else {
2036 $lRec = self::getRecordWSOL('fe_groups', $fe_group, 'title');
2037 $fe_groups[] = $lRec['title'];
2038 }
2039 }
2040 $label = implode(', ', $fe_groups);
2041 $parts[] = $LANG->sL($TCA['pages']['columns']['fe_group']['label']) . ' ' . $label;
2042 }
2043 $out = htmlspecialchars(implode(' - ', $parts));
2044 return $includeAttrib ? 'title="' . $out . '"' : $out;
2045 }
2046
2047 /**
2048 * Returns title-attribute information for ANY record (from a table defined in TCA of course)
2049 * 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.
2050 * "pages" table can be used as well and will return the result of ->titleAttribForPages() for that page.
2051 * Usage: 10
2052 *
2053 * @param array Table row; $row is a row from the table, $table
2054 * @param string Table name
2055 * @return string
2056 */
2057 public static function getRecordIconAltText($row, $table = 'pages') {
2058 if ($table == 'pages') {
2059 $out = self::titleAttribForPages($row, '', 0);
2060 } else {
2061 $ctrl = $GLOBALS['TCA'][$table]['ctrl']['enablecolumns'];
2062
2063 $out = 'id=' . $row['uid']; // Uid is added
2064 if ($table == 'pages' && $row['alias']) {
2065 $out .= ' / ' . $row['alias'];
2066 }
2067 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS'] && $row['pid'] < 0) {
2068 $out .= ' - v#1.' . $row['t3ver_id'];
2069 }
2070 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
2071 switch ($row['t3ver_state']) {
2072 case 1:
2073 $out .= ' - PLH WSID#' . $row['t3ver_wsid'];
2074 break;
2075 case 2:
2076 $out .= ' - Deleted element!';
2077 break;
2078 case 3:
2079 $out .= ' - NEW LOCATION (PLH) WSID#' . $row['t3ver_wsid'];
2080 break;
2081 case 4:
2082 $out .= ' - OLD LOCATION (PNT) WSID#' . $row['t3ver_wsid'];
2083 break;
2084 case -1:
2085 $out .= ' - New element!';
2086 break;
2087 }
2088 }
2089
2090 if ($ctrl['disabled']) { // Hidden ...
2091 $out .= ($row[$ctrl['disabled']] ? ' - ' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.hidden') : '');
2092 }
2093 if ($ctrl['starttime']) {
2094 if ($row[$ctrl['starttime']] > $GLOBALS['EXEC_TIME']) {
2095 $out .= ' - ' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.starttime') . ':' .
2096 self::date($row[$ctrl['starttime']]) . ' (' . self::daysUntil($row[$ctrl['starttime']]) . ' ' .
2097 $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.days') . ')';
2098 }
2099 }
2100 if ($row[$ctrl['endtime']]) {
2101 $out .= ' - ' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.endtime') . ': ' .
2102 self::date($row[$ctrl['endtime']]) . ' (' . self::daysUntil($row[$ctrl['endtime']]) . ' ' .
2103 $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.days') . ')';
2104 }
2105 }
2106 return htmlspecialchars($out);
2107 }
2108
2109 /**
2110 * Returns the label of the first found entry in an "items" array from $TCA (tablename = $table/fieldname = $col) where the value is $key
2111 * Usage: 9
2112 *
2113 * @param string Table name, present in $TCA
2114 * @param string Field name, present in $TCA
2115 * @param string items-array value to match
2116 * @return string Label for item entry
2117 */
2118 public static function getLabelFromItemlist($table, $col, $key) {
2119 global $TCA;
2120 // Load full TCA for $table
2121 t3lib_div::loadTCA($table);
2122
2123 // Check, if there is an "items" array:
2124 if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$col]) && is_array($TCA[$table]['columns'][$col]['config']['items'])) {
2125 // Traverse the items-array...
2126 foreach ($TCA[$table]['columns'][$col]['config']['items'] as $k => $v) {
2127 // ... and return the first found label where the value was equal to $key
2128 if (!strcmp($v[1], $key)) {
2129 return $v[0];
2130 }
2131 }
2132 }
2133 }
2134
2135 /**
2136 * Returns the label-value for fieldname $col in table, $table
2137 * 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>'
2138 * Usage: 17
2139 *
2140 * @param string Table name, present in $TCA
2141 * @param string Field name
2142 * @param string Wrap value - set function description
2143 * @return string
2144 */
2145 public static function getItemLabel($table, $col, $printAllWrap = '') {
2146 global $TCA;
2147 // Load full TCA for $table
2148 t3lib_div::loadTCA($table);
2149 // Check if column exists
2150 if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$col])) {
2151 // Re
2152 return $TCA[$table]['columns'][$col]['label'];
2153 }
2154 if ($printAllWrap) {
2155 $parts = explode('|', $printAllWrap);
2156 return $parts[0] . $col . $parts[1];
2157 }
2158 }
2159
2160 /**
2161 * Returns the "title"-value in record, $row, from table, $table
2162 * The field(s) from which the value is taken is determined by the "ctrl"-entries 'label', 'label_alt' and 'label_alt_force'
2163 * Usage: 26
2164 *
2165 * @param string Table name, present in TCA
2166 * @param array Row from table
2167 * @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
2168 * @param boolean If set, the function always returns an output. If no value is found for the title, '[No title]' is returned (localized).
2169 * @return string
2170 */
2171 public static function getRecordTitle($table, $row, $prep = FALSE, $forceResult = TRUE) {
2172 global $TCA;
2173 if (is_array($TCA[$table])) {
2174
2175 // If configured, call userFunc
2176 if ($TCA[$table]['ctrl']['label_userFunc']) {
2177 $params['table'] = $table;
2178 $params['row'] = $row;
2179 $params['title'] = '';
2180 //create NULL-reference
2181 $null = NULL;
2182 t3lib_div::callUserFunction($TCA[$table]['ctrl']['label_userFunc'], $params, $null);
2183 $t = $params['title'];
2184 } else {
2185
2186 // No userFunc: Build label
2187 $t = self::getProcessedValue($table, $TCA[$table]['ctrl']['label'], $row[$TCA[$table]['ctrl']['label']], 0, 0, FALSE, $row['uid'], $forceResult);
2188 if ($TCA[$table]['ctrl']['label_alt'] && ($TCA[$table]['ctrl']['label_alt_force'] || !strcmp($t, ''))) {
2189 $altFields = t3lib_div::trimExplode(',', $TCA[$table]['ctrl']['label_alt'], 1);
2190 $tA = array();
2191 if (!empty($t)) {
2192 $tA[] = $t;
2193 }
2194 foreach ($altFields as $fN) {
2195 $t = trim(strip_tags($row[$fN]));
2196 if (strcmp($t, '')) {
2197 $t = self::getProcessedValue($table, $fN, $t, 0, 0, FALSE, $row['uid']);
2198 if (!$TCA[$table]['ctrl']['label_alt_force']) {
2199 break;
2200 }
2201 $tA[] = $t;
2202 }
2203 }
2204 if ($TCA[$table]['ctrl']['label_alt_force']) {
2205 $t = implode(', ', $tA);
2206 }
2207 }
2208 }
2209
2210 // If the current result is empty, set it to '[No title]' (localized) and prepare for output if requested
2211 if ($prep || $forceResult) {
2212 if ($prep) {
2213 $t = self::getRecordTitlePrep($t);
2214 }
2215 if (!strcmp(trim($t), '')) {
2216 $t = self::getNoRecordTitle($prep);
2217 }
2218 }
2219
2220 return $t;
2221 }
2222 }
2223
2224 /**
2225 * Crops a title string to a limited lenght and if it really was cropped, wrap it in a <span title="...">|</span>,
2226 * which offers a tooltip with the original title when moving mouse over it.
2227 *
2228 * @param string $title: The title string to be cropped
2229 * @param integer $titleLength: Crop title after this length - if not set, BE_USER->uc['titleLen'] is used
2230 * @return string The processed title string, wrapped in <span title="...">|</span> if cropped
2231 */
2232 public static function getRecordTitlePrep($title, $titleLength = 0) {
2233 // If $titleLength is not a valid positive integer, use BE_USER->uc['titleLen']:
2234 if (!$titleLength || !t3lib_div::testInt($titleLength) || $titleLength < 0) {
2235 $titleLength = $GLOBALS['BE_USER']->uc['titleLen'];
2236 }
2237 $titleOrig = htmlspecialchars($title);
2238 $title = htmlspecialchars(t3lib_div::fixed_lgd_cs($title, $titleLength));
2239 // If title was cropped, offer a tooltip:
2240 if ($titleOrig != $title) {
2241 $title = '<span title="' . $titleOrig . '">' . $title . '</span>';
2242 }
2243 return $title;
2244 }
2245
2246 /**
2247 * Get a localized [No title] string, wrapped in <em>|</em> if $prep is true.
2248 *
2249 * @param boolean $prep: Wrap result in <em>|</em>
2250 * @return string Localized [No title] string
2251 */
2252 public static function getNoRecordTitle($prep = FALSE) {
2253 $noTitle = '[' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.no_title', 1) . ']';
2254 if ($prep) {
2255 $noTitle = '<em>' . $noTitle . '</em>';
2256 }
2257 return $noTitle;
2258 }
2259
2260 /**
2261 * Returns a human readable output of a value from a record
2262 * 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.
2263 * $table/$col is tablename and fieldname
2264 * REMEMBER to pass the output through htmlspecialchars() if you output it to the browser! (To protect it from XSS attacks and be XHTML compliant)
2265 * Usage: 24
2266 *
2267 * @param string Table name, present in TCA
2268 * @param string Field name, present in TCA
2269 * @param string $value is the value of that field from a selected record
2270 * @param integer $fixed_lgd_chars is the max amount of characters the value may occupy
2271 * @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")
2272 * @param boolean If set, no records will be looked up, UIDs are just shown.
2273 * @param integer uid of the current record
2274 * @param boolean If t3lib_BEfunc::getRecordTitle is used to process the value, this parameter is forwarded.
2275 * @return string
2276 */
2277 public static function getProcessedValue($table, $col, $value, $fixed_lgd_chars = 0, $defaultPassthrough = 0, $noRecordLookup = FALSE, $uid = 0, $forceResult = TRUE) {
2278 global $TCA;
2279 global $TYPO3_CONF_VARS;
2280
2281 if ($col == 'uid') {
2282 // no need to load TCA as uid is not in TCA-array
2283 return $value;
2284 }
2285 // Load full TCA for $table
2286 t3lib_div::loadTCA($table);
2287 // Check if table and field is configured:
2288 if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$col])) {
2289 // Depending on the fields configuration, make a meaningful output value.
2290 $theColConf = $TCA[$table]['columns'][$col]['config'];
2291
2292 /*****************
2293 *HOOK: pre-processing the human readable output from a record
2294 ****************/
2295 if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['preProcessValue'])) {
2296 // create NULL-reference
2297 $null = NULL;
2298 foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['preProcessValue'] as $_funcRef) {
2299 t3lib_div::callUserFunction($_funcRef, $theColConf, $null);
2300 }
2301 }
2302
2303 $l = '';
2304 switch ((string) $theColConf['type']) {
2305 case 'radio':
2306 $l = self::getLabelFromItemlist($table, $col, $value);
2307 $l = $GLOBALS['LANG']->sL($l);
2308 break;
2309 case 'select':
2310 if ($theColConf['MM']) {
2311 if ($uid) {
2312 // Display the title of MM related records in lists
2313 if ($noRecordLookup) {
2314 $MMfield = $theColConf['foreign_table'] . '.uid';
2315 } else {
2316 $MMfields = array($theColConf['foreign_table'] . '.' . $TCA[$theColConf['foreign_table']]['ctrl']['label']);
2317 foreach (t3lib_div::trimExplode(',', $TCA[$theColConf['foreign_table']]['ctrl']['label_alt'], 1) as $f) {
2318 $MMfields[] = $theColConf['foreign_table'] . '.' . $f;
2319 }
2320 $MMfield = join(',', $MMfields);
2321 }
2322
2323 $dbGroup = t3lib_div::makeInstance('t3lib_loadDBGroup');
2324 $dbGroup->start($value, $theColConf['foreign_table'], $theColConf['MM'], $uid, $table, $theColConf);
2325 $selectUids = $dbGroup->tableArray[$theColConf['foreign_table']];
2326
2327 if (is_array($selectUids) && count($selectUids) > 0) {
2328 $MMres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
2329 'uid, ' . $MMfield,
2330 $theColConf['foreign_table'],
2331 'uid IN (' . implode(',', $selectUids) . ')'
2332 );
2333 while ($MMrow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($MMres)) {
2334 $mmlA[] = ($noRecordLookup ? $MMrow['uid'] : self::getRecordTitle($theColConf['foreign_table'], $MMrow, FALSE, $forceResult));
2335 }
2336 $GLOBALS['TYPO3_DB']->sql_free_result($MMres);
2337
2338 if (is_array($mmlA)) {
2339 $l = implode('; ', $mmlA);
2340 } else {
2341 $l = '';
2342 }
2343 } else {
2344 $l = 'N/A';
2345 }
2346 } else {
2347 $l = 'N/A';
2348 }
2349 } else {
2350 $l = self::getLabelFromItemlist($table, $col, $value);
2351 $l = $GLOBALS['LANG']->sL($l);
2352 if ($theColConf['foreign_table'] && !$l && $TCA[$theColConf['foreign_table']]) {
2353 if ($noRecordLookup) {
2354 $l = $value;
2355 } else {
2356 $rParts = t3lib_div::trimExplode(',', $value, 1);
2357 $lA = array();
2358 foreach ($rParts as $rVal) {
2359 $rVal = intval($rVal);
2360 if ($rVal > 0) {
2361 $r = self::getRecordWSOL($theColConf['foreign_table'], $rVal);
2362 } else {
2363 $r = self::getRecordWSOL($theColConf['neg_foreign_table'], -$rVal);
2364 }
2365 if (is_array($r)) {
2366 $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);
2367 } else {
2368 $lA[] = $rVal ? '[' . $rVal . '!]' : '';
2369 }
2370 }
2371 $l = implode(', ', $lA);
2372 }
2373 }
2374 }
2375 break;
2376 case 'group':
2377 $l = implode(', ', t3lib_div::trimExplode(',', $value, 1));
2378 break;
2379 case 'check':
2380 if (!is_array($theColConf['items']) || count($theColConf['items']) == 1) {
2381 $l = $value ? $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:yes') : $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:no');
2382 } else {
2383 $lA = Array();
2384 foreach ($theColConf['items'] as $key => $val) {
2385 if ($value & pow(2, $key)) {
2386 $lA[] = $GLOBALS['LANG']->sL($val[0]);
2387 }
2388 }
2389 $l = implode(', ', $lA);
2390 }
2391 break;
2392 case 'input':
2393 if (isset($value)) {
2394 if (t3lib_div::inList($theColConf['eval'], 'date')) {
2395 $l = self::date($value) .
2396 ' (' .
2397 ($GLOBALS['EXEC_TIME'] - $value > 0 ? '-' : '') .
2398 self::calcAge(abs($GLOBALS['EXEC_TIME'] - $value), $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears')) .
2399 ')';
2400 } elseif (t3lib_div::inList($theColConf['eval'], 'time')) {
2401 $l = self::time($value, FALSE);
2402 } elseif (t3lib_div::inList($theColConf['eval'], 'timesec')) {
2403 $l = self::time($value);
2404 } elseif (t3lib_div::inList($theColConf['eval'], 'datetime')) {
2405 $l = self::datetime($value);
2406 } else {
2407 $l = $value;
2408 }
2409 }
2410 break;
2411 case 'flex':
2412 $l = strip_tags($value);
2413 break;
2414 default:
2415 if ($defaultPassthrough) {
2416 $l = $value;
2417 } elseif ($theColConf['MM']) {
2418 $l = 'N/A';
2419 } elseif ($value) {
2420 $l = t3lib_div::fixed_lgd_cs(strip_tags($value), 200);
2421 }
2422 break;
2423 }
2424
2425 // If this field is a password field, then hide the password by changing it to a random number of asterisk (*)
2426 if (stristr($theColConf['eval'], 'password')) {
2427 unset($l);
2428 $randomNumber = rand(5, 12);
2429 for ($i = 0; $i < $randomNumber; $i++) {
2430 $l .= '*';
2431 }
2432 }
2433
2434 /*****************
2435 *HOOK: post-processing the human readable output from a record
2436 ****************/
2437 if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['postProcessValue'])) {
2438 // create NULL-reference
2439 $null = NULL;
2440 foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['postProcessValue'] as $_funcRef) {
2441 $params = array(
2442 'value' => $l,
2443 'colConf' => $theColConf
2444 );
2445 $l = t3lib_div::callUserFunction($_funcRef, $params, $null);
2446 }
2447 }
2448
2449 if ($fixed_lgd_chars) {
2450 return t3lib_div::fixed_lgd_cs($l, $fixed_lgd_chars);
2451 } else {
2452 return $l;
2453 }
2454 }
2455 }
2456
2457 /**
2458 * 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.
2459 * Usage: 2
2460 *
2461 * @param string Table name, present in TCA
2462 * @param string Field name
2463 * @param string Field value
2464 * @param integer $fixed_lgd_chars is the max amount of characters the value may occupy
2465 * @param integer uid of the current record
2466 * @param boolean If t3lib_BEfunc::getRecordTitle is used to process the value, this parameter is forwarded.
2467 * @return string
2468 * @see getProcessedValue()
2469 */
2470 public static function getProcessedValueExtra($table, $fN, $fV, $fixed_lgd_chars = 0, $uid = 0, $forceResult = TRUE) {
2471 global $TCA;
2472 $fVnew = self::getProcessedValue($table, $fN, $fV, $fixed_lgd_chars, 1, 0, $uid, $forceResult);
2473 if (!isset($fVnew)) {
2474 if (is_array($TCA[$table])) {
2475 if ($fN == $TCA[$table]['ctrl']['tstamp'] || $fN == $TCA[$table]['ctrl']['crdate']) {
2476 $fVnew = self::datetime($fV);
2477 } elseif ($fN == 'pid') {
2478 $fVnew = self::getRecordPath($fV, '1=1', 20); // Fetches the path with no regard to the users permissions to select pages.
2479 } else {
2480 $fVnew = $fV;
2481 }
2482 }
2483 }
2484 return $fVnew;
2485 }
2486
2487 /**
2488 * Returns file icon name (from $FILEICONS) for the fileextension $ext
2489 * Usage: 10
2490 *
2491 * @param string File extension, lowercase
2492 * @return string File icon filename
2493 */
2494 public static function getFileIcon($ext) {
2495 return $GLOBALS['FILEICONS'][$ext] ? $GLOBALS['FILEICONS'][$ext] : $GLOBALS['FILEICONS']['default'];
2496 }
2497
2498 /**
2499 * Returns fields for a table, $table, which would typically be interesting to select
2500 * This includes uid, the fields defined for title, icon-field.
2501 * 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)
2502 * Usage: 3
2503 *
2504 * @param string Table name, present in TCA
2505 * @param string Table prefix
2506 * @param array Preset fields (must include prefix if that is used)
2507 * @return string List of fields.
2508 */
2509 public static function getCommonSelectFields($table, $prefix = '', $fields = array()) {
2510 global $TCA;
2511 $fields[] = $prefix . 'uid';
2512 $fields[] = $prefix . $TCA[$table]['ctrl']['label'];
2513
2514 if ($TCA[$table]['ctrl']['label_alt']) {
2515 $secondFields = t3lib_div::trimExplode(',', $TCA[$table]['ctrl']['label_alt'], 1);
2516 foreach ($secondFields as $fieldN) {
2517 $fields[] = $prefix . $fieldN;
2518 }
2519 }
2520 if ($TCA[$table]['ctrl']['versioningWS']) {
2521 $fields[] = $prefix . 't3ver_id';
2522 $fields[] = $prefix . 't3ver_state';
2523 $fields[] = $prefix . 't3ver_wsid';
2524 $fields[] = $prefix . 't3ver_count';
2525 }
2526
2527 if ($TCA[$table]['ctrl']['selicon_field']) {
2528 $fields[] = $prefix . $TCA[$table]['ctrl']['selicon_field'];
2529 }
2530 if ($TCA[$table]['ctrl']['typeicon_column']) {
2531 $fields[] = $prefix . $TCA[$table]['ctrl']['typeicon_column'];
2532 }
2533
2534 if (is_array($TCA[$table]['ctrl']['enablecolumns'])) {
2535 if ($TCA[$table]['ctrl']['enablecolumns']['disabled']) {
2536 $fields[] = $prefix . $TCA[$table]['ctrl']['enablecolumns']['disabled'];
2537 }
2538 if ($TCA[$table]['ctrl']['enablecolumns']['starttime']) {
2539 $fields[] = $prefix . $TCA[$table]['ctrl']['enablecolumns']['starttime'];
2540 }
2541 if ($TCA[$table]['ctrl']['enablecolumns']['endtime']) {
2542 $fields[] = $prefix . $TCA[$table]['ctrl']['enablecolumns']['endtime'];
2543 }
2544 if ($TCA[$table]['ctrl']['enablecolumns']['fe_group']) {
2545 $fields[] = $prefix . $TCA[$table]['ctrl']['enablecolumns']['fe_group'];
2546 }
2547 }
2548
2549 return implode(',', array_unique($fields));
2550 }
2551
2552 /**
2553 * 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
2554 * <form>-tags must be supplied separately
2555 * 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.
2556 * Usage: 1 (ext. direct_mail)
2557 *
2558 * @param array Field configuration code.
2559 * @param array Defaults
2560 * @param string Prefix for formfields
2561 * @return string HTML for a form.
2562 */
2563 public static function makeConfigForm($configArray, $defaults, $dataPrefix) {
2564 $params = $defaults;
2565 if (is_array($configArray)) {
2566 $lines = array();
2567 foreach ($configArray as $fname => $config) {
2568 if (is_array($config)) {
2569 $lines[$fname] = '<strong>' . htmlspecialchars($config[1]) . '</strong><br />';
2570 $lines[$fname] .= $config[2] . '<br />';
2571 switch ($config[0]) {
2572 case 'string':
2573 case 'short':
2574 $formEl = '<input type="text" name="' . $dataPrefix . '[' . $fname . ']" value="' . $params[$fname] . '"' . $GLOBALS['TBE_TEMPLATE']->formWidth($config[0] == 'short' ? 24 : 48) . ' />';
2575 break;
2576 case 'check':
2577 $formEl = '<input type="hidden" name="' . $dataPrefix . '[' . $fname . ']" value="0" /><input type="checkbox" name="' . $dataPrefix . '[' . $fname . ']" value="1"' . ($params[$fname] ? ' checked="checked"' : '') . ' />';
2578 break;
2579 case 'comment':
2580 $formEl = '';
2581 break;
2582 case 'select':
2583 $opt = array();
2584 foreach ($config[3] as $k => $v) {
2585 $opt[] = '<option value="' . htmlspecialchars($k) . '"' . ($params[$fname] == $k ? ' selected="selected"' : '') . '>' . htmlspecialchars($v) . '</option>';
2586 }
2587 $formEl = '<select name="' . $dataPrefix . '[' . $fname . ']">' . implode('', $opt) . '</select>';
2588 break;
2589 default:
2590 debug($config);
2591 break;
2592 }
2593 $lines[$fname] .= $formEl;
2594 $lines[$fname] .= '<br /><br />';
2595 } else {
2596 $lines[$fname] = '<hr />';
2597 if ($config) {
2598 $lines[$fname] .= '<strong>' . strtoupper(htmlspecialchars($config)) . '</strong><br />';
2599 }
2600 if ($config) {
2601 $lines[$fname] .= '<br />';
2602 }
2603 }
2604 }
2605 }
2606 $out = implode('', $lines);
2607 $out .= '<input type="submit" name="submit" value="Update configuration" />';
2608 return $out;
2609 }
2610
2611
2612 /*******************************************
2613 *
2614 * Backend Modules API functions
2615 *
2616 *******************************************/
2617
2618 /**
2619 * Returns help-text icon if configured for.
2620 * TCA_DESCR must be loaded prior to this function and $BE_USER must
2621 * have 'edit_showFieldHelp' set to 'icon', otherwise nothing is returned
2622 * Usage: 6
2623 *
2624 * Please note: since TYPO3 4.5 the UX team decided to not use CSH in its former way,
2625 * but to wrap the given text (where before the help icon was, and you could hover over it)
2626 * Please also note that since TYPO3 4.5 the option to enable help (none, icon only, full text)
2627 * was completely removed.
2628 *
2629 * @param string Table name
2630 * @param string Field name
2631 * @param string Back path
2632 * @param boolean Force display of icon nomatter BE_USER setting for help
2633 * @return string HTML content for a help icon/text
2634 */
2635 public static function helpTextIcon($table, $field, $BACK_PATH, $force = 0) {
2636 global $TCA_DESCR, $BE_USER;
2637
2638 if (is_array($TCA_DESCR[$table]) && is_array($TCA_DESCR[$table]['columns'][$field]) && (isset($BE_USER->uc['edit_showFieldHelp']) || $force)) {
2639 return self::wrapInHelp($table, $field);
2640 }
2641 }
2642
2643 /**
2644 * Returns CSH help text (description), if configured for, as an array (title, description)
2645 * Will automatically call t3lib_BEfunc::helpTextIcon() to get the icon for the text.
2646 *
2647 * @param string Table name
2648 * @param string Field name
2649 * @return array With keys 'description' (raw, as available in locallang), 'title' (optional), 'moreInfo'
2650 */
2651 public static function helpTextArray($table, $field) {
2652 if (!isset($GLOBALS['TCA_DESCR'][$table]['columns'])) {
2653 $GLOBALS['LANG']->loadSingleTableDescription($table);
2654 }
2655 $output = array(
2656 'description' => NULL,
2657 'title' => NULL,
2658 'moreInfo' => FALSE,
2659 );
2660 if (is_array($GLOBALS['TCA_DESCR'][$table]) && is_array($GLOBALS['TCA_DESCR'][$table]['columns'][$field])) {
2661 $data = $GLOBALS['TCA_DESCR'][$table]['columns'][$field];
2662
2663 // add alternative title, if defined
2664 if ($data['alttitle']) {
2665 $output['title'] = $data['alttitle'];
2666 }
2667
2668 // if we have more information to show
2669 if ($data['image_descr'] || $data['seeAlso'] || $data['details'] || $data['syntax']) {
2670 $output['moreInfo'] = TRUE;
2671 }
2672
2673 // add description
2674 if ($data['description']) {
2675 $output['description'] = $data['description'];
2676 }
2677 }
2678 return $output;
2679 }
2680
2681 /**
2682 * Returns CSH help text (description), if configured for.
2683 * TCA_DESCR must be loaded prior to this function and $BE_USER must have "edit_showFieldHelp" set to "text",
2684 * otherwise nothing is returned
2685 * Will automatically call t3lib_BEfunc::helpTextIcon() to get the icon for the text.
2686 * Usage: 4
2687 *
2688 * @param string Table name
2689 * @param string Field name
2690 * @param string Back path, deprecated since TYPO3 4.5, will be removed in TYPO3 4.7, because not used at all
2691 * @param string DEPRECATED: Additional style-attribute content for wrapping table (now: only in function cshItem needed)
2692 * @return string HTML content for help text
2693 */
2694 public static function helpText($table, $field, $BACK_PATH = '', $styleAttrib = '') {
2695 $helpTextArray = self::helpTextArray($table, $field);
2696
2697 $output = '';
2698
2699 // put header before the rest of the text
2700 if ($helpTextArray['title'] !== NULL) {
2701 $output .= '<h2 class="t3-row-header">' . $helpTextArray['title'] . '</h2>';
2702 }
2703 // add the content
2704 if ($helpTextArray['description'] !== NULL) {
2705 $output .= $helpTextArray['description'];
2706 }
2707 // add see also arrow if we have more info
2708 if ($helpTextArray['moreInfo']) {
2709 $arrow = t3lib_iconWorks::getSpriteIcon('actions-view-go-forward');
2710 }
2711 // add description text
2712 if ($helpTextArray['description'] || $arrow) {
2713 $output['description'] = '<p class="t3-help-short">' . nl2br(htmlspecialchars($helpTextArray['description'])) . $arrow . '</p>';
2714 }
2715
2716 return $output;
2717 }
2718
2719 /**
2720 * API function that wraps the text / html in help text, so if a user hovers over it
2721 * the help text will show up
2722 * This is the new help API function since TYPO3 4.5, and uses the new behaviour
2723 * (hover over text, no icon, no fulltext option, no option to disable the help)
2724 *
2725 * @param string $table The table name for which the help should be shown
2726 * @param string $field The field name for which the help should be shown
2727 * @param string $text the text which should be wrapped with the help text
2728 * @return string the HTML code ready to render
2729 * @api public
2730 */
2731 public static function wrapInHelp($table, $field, $text = '', array $overloadHelpText = array()) {
2732 // Initialize some variables
2733 $helpText = '';
2734 $abbrClassAdd = '';
2735 $wrappedText = $text;
2736 $hasHelpTextOverload = count($overloadHelpText) > 0;
2737
2738 // Get the help text that should be shown on hover
2739 if (!$hasHelpTextOverload) {
2740 $helpText = self::helpText($table, $field);
2741 }
2742
2743 // If there's a help text or some overload information, proceed with preparing an output
2744 if (!empty($helpText) || $hasHelpTextOverload) {
2745 // If no text was given, just use the regular help icon
2746 if ($text == '') {
2747 $text = t3lib_iconWorks::getSpriteIcon('actions-system-help-open');
2748 $abbrClassAdd = '-icon';
2749 }
2750 $text = '<abbr class="t3-help-teaser' . $abbrClassAdd . '">' . $text . '</abbr>';
2751 $wrappedText = '<span class="t3-help-link" href="#" data-table="' . $table . '" data-field="' . $field . '"';
2752 // The overload array may provide a title and a description
2753 // If either one is defined, add them to the "data" attributes
2754 if ($hasHelpTextOverload) {
2755 if (isset($overloadHelpText['title'])) {
2756 $wrappedText .= ' data-title="' . htmlspecialchars($overloadHelpText['title']) . '"';
2757 }
2758 if (isset($overloadHelpText['description'])) {
2759 $wrappedText .= ' data-description="' . htmlspecialchars($overloadHelpText['description']) . '"';
2760 }
2761 }
2762 $wrappedText .= '>' . $text . '</span>';
2763 }
2764
2765 return $wrappedText;
2766 }
2767
2768
2769 /**
2770 * API for getting CSH icons/text for use in backend modules.
2771 * TCA_DESCR will be loaded if it isn't already
2772 * Usage: ?
2773 *
2774 * @param string Table name ('_MOD_'+module name)
2775 * @param string Field name (CSH locallang main key)
2776 * @param string Back path
2777 * @param string Wrap code for icon-mode, splitted by "|". Not used for full-text mode.
2778 * @param boolean If set, the full text will never be shown (only icon).
2779 * Useful for places where it will break the page if the table with full text is shown.
2780 * @param string Additional style-attribute content for wrapping table (full text mode only)
2781 * @return string HTML content for help text
2782 * @see helpText(), helpTextIcon()
2783 */
2784 public static function cshItem($table, $field, $BACK_PATH, $wrap = '', $onlyIconMode = FALSE, $styleAttrib = '') {
2785 global $TCA_DESCR, $LANG, $BE_USER;
2786
2787 if ($BE_USER->uc['edit_showFieldHelp']) {
2788 $LANG->loadSingleTableDescription($table);
2789
2790 if (is_array($TCA_DESCR[$table])) {
2791 // Creating CSH icon and short description:
2792 $fullText = self::helpText($table, $field, $BACK_PATH, '');
2793 $icon = self::helpTextIcon($table, $field, $BACK_PATH);
2794
2795 if ($fullText && !$onlyIconMode && $BE_USER->uc['edit_showFieldHelp'] == 'text') {
2796
2797 // Additional styles?
2798 $params = $styleAttrib ? ' style="' . $styleAttrib . '"' : '';
2799
2800 // Compile table with CSH information:
2801 $fullText = '<table border="0" cellpadding="0" cellspacing="0" class="typo3-csh-inline"' . $params . '>
2802 <tr>
2803 <td valign="top" width="14"><div class="t3-row-header">' . $icon . '</div></td>
2804 <td valign="top">' . $fullText . '</td>
2805 </tr>
2806 </table>';
2807
2808 $output = $LANG->hscAndCharConv($fullText, FALSE);
2809 } else {
2810 $output = $icon;
2811
2812 if ($output && $wrap) {
2813 $wrParts = explode('|', $wrap);
2814 $output = $wrParts[0] . $output . $wrParts[1];
2815 }
2816 }
2817
2818 return $output;
2819 }
2820 }
2821 }
2822
2823 /**
2824 * 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.
2825 * REMEMBER to always htmlspecialchar() content in href-properties to ampersands get converted to entities (XHTML requirement and XSS precaution)
2826 * Usage: 35
2827 *
2828 * @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.
2829 * @param string $backPath must point back to the TYPO3_mainDir directory (where alt_doc.php is)
2830 * @param string $requestUri is an optional returnUrl you can set - automatically set to REQUEST_URI.
2831 * @return string
2832 * @see template::issueCommand()
2833 */
2834 public static function editOnClick($params, $backPath = '', $requestUri = '') {
2835 $retUrl = 'returnUrl=' . ($requestUri == -1 ? "'+T3_THIS_LOCATION+'" : rawurlencode($requestUri ? $requestUri : t3lib_div::getIndpEnv('REQUEST_URI')));
2836 return "window.location.href='" . $backPath . "alt_doc.php?" . $retUrl . $params . "'; return false;";
2837 }
2838
2839 /**
2840 * Returns a JavaScript string for viewing the page id, $id
2841 * 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.
2842 * Usage: 8
2843 *
2844 * @param integer $pageUid is page id
2845 * @param string $backPath must point back to TYPO3_mainDir (where the site is assumed to be one level above)
2846 * @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)
2847 * @param string $anchorSection is optional anchor to the URL
2848 * @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!
2849 * @param string $additionalGetVars Additional GET variables.
2850 * @param boolean If true, then the preview window will gain the focus.
2851 * @return string
2852 */
2853 public static function viewOnClick($pageUid, $backPath = '', $rootLine = '', $anchorSection = '', $alternativeUrl = '', $additionalGetVars = '', $switchFocus = TRUE) {
2854 $viewScript = '/index.php?id=';
2855 if ($alternativeUrl) {
2856 $viewScript = $alternativeUrl;
2857 }
2858
2859 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['viewOnClickClass'])
2860 && is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['viewOnClickClass'])) {
2861 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['viewOnClickClass'] as $funcRef) {
2862 $hookObj = t3lib_div::getUserObj($funcRef);
2863 if (method_exists($hookObj, 'preProcess')) {
2864 $hookObj->preProcess($pageUid, $backPath, $rootLine, $anchorSection, $viewScript, $additionalGetVars, $switchFocus);
2865 }
2866 }
2867 }
2868
2869 // Look if a fixed preview language should be added:
2870 $viewLanguageOrder = $GLOBALS['BE_USER']->getTSConfigVal('options.view.languageOrder');
2871 if (strlen($viewLanguageOrder)) {
2872 $suffix = '';
2873
2874 // Find allowed languages (if none, all are allowed!)
2875 if (!$GLOBALS['BE_USER']->user['admin'] &&
2876 strlen($GLOBALS['BE_USER']->groupData['allowed_languages'])) {
2877 $allowedLanguages = array_flip(explode(',', $GLOBALS['BE_USER']->groupData['allowed_languages']));
2878 }
2879
2880 // Traverse the view order, match first occurence:
2881 $languageOrder = t3lib_div::intExplode(',', $viewLanguageOrder);
2882 foreach ($languageOrder as $langUid) {
2883 if (is_array($allowedLanguages) && count($allowedLanguages)) {
2884 // Choose if set.
2885 if (isset($allowedLanguages[$langUid])) {
2886 $suffix = '&L=' . $langUid;
2887 break;
2888 }
2889 } else {
2890 // All allowed since no lang. are listed.
2891 $suffix = '&L=' . $langUid;
2892 break;
2893 }
2894 }
2895 // Add it:
2896 $additionalGetVars .= $suffix;
2897 }
2898
2899 // check a mount point needs to be previewed
2900 $sys_page = t3lib_div::makeInstance('t3lib_pageSelect');
2901 $sys_page->init(FALSE);
2902 $mountPointInfo = $sys_page->getMountPointInfo($pageUid);
2903 if ($mountPointInfo && $mountPointInfo['overlay']) {
2904 $pageUid = $mountPointInfo['mount_pid'];
2905 $additionalGetVars .= '&MP=' . $mountPointInfo['MPvar'];
2906 }
2907
2908 $viewDomain = self::getViewDomain($pageUid, $rootLine);
2909 $previewUrl = $viewDomain . $viewScript . $pageUid . $additionalGetVars . $anchorSection;
2910 $onclickCode = "var previewWin = window.open('" . $previewUrl . "','newTYPO3frontendWindow');" . ($switchFocus ? 'previewWin.focus();' : '');
2911 return $onclickCode;
2912 }
2913
2914 /**
2915 * Builds the frontend view domain for a given page ID with a given root
2916 * line.
2917 *
2918 * @param integer $pageId the page ID to use, must be > 0
2919 * @param array $rootLine the root line structure to use
2920 *
2921 * @return string the full domain including the protocol http:// or https://, but without the trailing '/'
2922 *
2923 * @author Michael Klapper <michael.klapper@aoemedia.de>
2924 */
2925 public static function getViewDomain($pageId, $rootLine = NULL) {
2926 $domain = rtrim(t3lib_div::getIndpEnv('TYPO3_SITE_URL'), '/');
2927
2928 if (!is_array($rootLine)) {
2929 $rootLine = self::BEgetRootLine($pageId);
2930 }
2931
2932 // checks alternate domains
2933 if (count($rootLine) > 0) {
2934 $urlParts = parse_url($domain);
2935 if (self::getDomainStartPage($urlParts['host'], $urlParts['path'])) {
2936 $protocol = t3lib_div::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://';
2937 $domain = $protocol . self::firstDomainRecord($rootLine);
2938 }
2939 }
2940
2941 return $domain;
2942 }
2943
2944 /**
2945 * Returns the merged User/Page TSconfig for page id, $id.
2946 * Please read details about module programming elsewhere!
2947 * Usage: 15
2948 *
2949 * @param integer Page uid
2950 * @param string $TSref is an object string which determines the path of the TSconfig to return.
2951 * @return array
2952 */
2953 public static function getModTSconfig($id, $TSref) {
2954 $pageTS_modOptions = $GLOBALS['BE_USER']->getTSConfig($TSref, self::getPagesTSconfig($id));
2955 $BE_USER_modOptions = $GLOBALS['BE_USER']->getTSConfig($TSref);
2956 $modTSconfig = t3lib_div::array_merge_recursive_overrule($pageTS_modOptions, $BE_USER_modOptions);
2957 return $modTSconfig;
2958 }
2959
2960 /**
2961 * Returns a selector box "function menu" for a module
2962 * Requires the JS function jumpToUrl() to be available
2963 * See Inside TYPO3 for details about how to use / make Function menus
2964 * Usage: 50
2965 *
2966 * @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=...
2967 * @param string $elementName it the form elements name, probably something like "SET[...]"
2968 * @param string $currentValue is the value to be selected currently.
2969 * @param array $menuItems is an array with the menu items for the selector box
2970 * @param string $script is the script to send the &id to, if empty it's automatically found
2971 * @param string $addParams is additional parameters to pass to the script.
2972 * @return string HTML code for selector box
2973 */
2974 public static function getFuncMenu($mainParams, $elementName, $currentValue, $menuItems, $script = '', $addparams = '') {
2975 if (is_array($menuItems)) {
2976 if (!is_array($mainParams)) {
2977 $mainParams = array('id' => $mainParams);
2978 }
2979 $mainParams = t3lib_div::implodeArrayForUrl('', $mainParams);
2980
2981 if (!$script) {
2982 $script = basename(PATH_thisScript);
2983 $mainParams .= (t3lib_div::_GET('M') ? '&M=' . rawurlencode(t3lib_div::_GET('M')) : '');
2984 }
2985
2986 $options = array();
2987 foreach ($menuItems as $value => $label) {
2988 $options[] = '<option value="' . htmlspecialchars($value