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