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