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