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