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