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