[TASK] FormEngine: Simplify element name resolving
[Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Classes / Form / FormEngine.php
1 <?php
2 namespace TYPO3\CMS\Backend\Form;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Backend\Form\Utility\FormEngineUtility;
18 use TYPO3\CMS\Backend\Template\DocumentTemplate;
19 use TYPO3\CMS\Backend\Utility\BackendUtility;
20 use TYPO3\CMS\Backend\Utility\IconUtility;
21 use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
22 use TYPO3\CMS\Core\FormProtection\FormProtectionFactory;
23 use TYPO3\CMS\Core\Html\HtmlParser;
24 use TYPO3\CMS\Core\Http\AjaxRequestHandler;
25 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
26 use TYPO3\CMS\Core\Utility\GeneralUtility;
27 use TYPO3\CMS\Core\Utility\MathUtility;
28 use TYPO3\CMS\Lang\LanguageService;
29 use TYPO3\CMS\Backend\Form\Container\FullRecordContainer;
30 use TYPO3\CMS\Backend\Form\Container\SoloFieldContainer;
31 use TYPO3\CMS\Backend\Form\Container\InlineRecordContainer;
32 use TYPO3\CMS\Backend\Form\Container\ListOfFieldsContainer;
33 use TYPO3\CMS\Core\Utility\ArrayUtility;
34
35 /**
36 * This is form engine - Class for creating the backend editing forms.
37 */
38 class FormEngine {
39
40 /**
41 * @var bool
42 */
43 public $disableWizards = FALSE;
44
45 /**
46 * List of additional preview languages that should be shown to the user. Initialized early.
47 *
48 * array(
49 * $languageUid => array(
50 * 'uid' => $languageUid,
51 * 'ISOcode' => $isoCodeOfLanguage
52 * )
53 * )
54 *
55 * @var array
56 */
57 protected $additionalPreviewLanguages = array();
58
59 /**
60 * @var string
61 */
62 protected $extJSCODE = '';
63
64 /**
65 * @var array HTML of additional hidden fields rendered by sub containers
66 */
67 protected $hiddenFieldAccum = array();
68
69 /**
70 * @var string
71 */
72 public $TBE_EDITOR_fieldChanged_func = '';
73
74 /**
75 * @var bool
76 */
77 public $loadMD5_JS = TRUE;
78
79 /**
80 * Alternative return URL path (default is \TYPO3\CMS\Core\Utility\GeneralUtility::linkThisScript())
81 *
82 * @var string
83 */
84 public $returnUrl = '';
85
86 /**
87 * Can be set to point to a field name in the form which will be set to '1' when the form
88 * is submitted with a *save* button. This way the recipient script can determine that
89 * the form was submitted for save and not "close" for example.
90 *
91 * @var string
92 */
93 public $doSaveFieldName = '';
94
95 /**
96 * Can be set TRUE/FALSE to whether palettes (secondary options) are in the topframe or in form.
97 * TRUE means they are NOT IN-form. So a collapsed palette is one, which is shown in the top frame, not in the page.
98 *
99 * @var bool
100 */
101 public $palettesCollapsed = FALSE;
102
103 /**
104 * If this evaluates to TRUE, the forms are rendering only localization relevant fields of the records.
105 *
106 * @var string
107 */
108 public $localizationMode = '';
109
110 /**
111 * When enabled all elements are rendered non-editable
112 *
113 * @var bool
114 */
115 protected $renderReadonly = FALSE;
116
117 /**
118 * @var InlineStackProcessor
119 */
120 protected $inlineStackProcessor;
121
122 /**
123 * @var array Data array from IRRE pushed to frontend as json array
124 */
125 protected $inlineData = array();
126
127 /**
128 * Set by readPerms() (caching)
129 *
130 * @var string
131 */
132 public $perms_clause = '';
133
134 /**
135 * Set by readPerms() (caching-flag)
136 *
137 * @var bool
138 */
139 public $perms_clause_set = FALSE;
140
141 /**
142 * Total wrapping for the table rows
143 *
144 * @var string
145 * @todo: This is overwritten in __construct
146 */
147 public $totalWrap = '<hr />|<hr />';
148
149 /**
150 * This array of fields will be set as hidden-fields instead of rendered normally!
151 * This is used by EditDocumentController to force some field values if set as "overrideVals" in _GP
152 *
153 * @var array
154 */
155 public $hiddenFieldListArr = array();
156
157 /**
158 * Used to register input-field names, which are required. (Done during rendering of the fields).
159 * This information is then used later when the JavaScript is made.
160 *
161 * @var array
162 */
163 protected $requiredFields = array();
164
165 /**
166 * Used to register input-field names, which are required an have additional requirements.
167 * (e.g. like a date/time must be positive integer)
168 * The information of this array is merged with $this->requiredFields later.
169 *
170 * @var array
171 */
172 protected $requiredAdditional = array();
173
174 /**
175 * Used to register the min and max number of elements
176 * for selector boxes where that apply (in the "group" type for instance)
177 *
178 * @var array
179 */
180 protected $requiredElements = array();
181
182 /**
183 * Used to determine where $requiredFields or $requiredElements are nested (in Tabs or IRRE)
184 *
185 * @var array
186 */
187 public $requiredNested = array();
188
189 // Internal, registers for user defined functions etc.
190 /**
191 * Additional HTML code, printed before the form
192 *
193 * @var array
194 */
195 public $additionalCode_pre = array();
196
197 /**
198 * Additional JavaScript printed after the form
199 *
200 * @var array
201 */
202 protected $additionalJS_post = array();
203
204 /**
205 * Additional JavaScript executed on submit; If you set "OK" variable it will raise an error
206 * about RTEs not being loaded and offer to block further submission.
207 *
208 * @var array
209 */
210 public $additionalJS_submit = array();
211
212 /**
213 * Array containing hook class instances called once for a form
214 *
215 * @var array
216 */
217 public $hookObjectsMainFields = array();
218
219 /**
220 * Rows getting inserted into the headers (when called from the EditDocumentController)
221 *
222 * @var array
223 */
224 public $extraFormHeaders = array();
225
226 /**
227 * Form template, relative to typo3 directory
228 *
229 * @var string
230 */
231 public $templateFile = '';
232
233 /**
234 * @var string The table that is handled
235 */
236 protected $table = '';
237
238 /**
239 * @var array Database row data
240 */
241 protected $databaseRow = array();
242
243 /**
244 * Constructor function, setting internal variables, loading the styles used.
245 *
246 */
247 public function __construct() {
248 $this->inlineStackProcessor = GeneralUtility::makeInstance(InlineStackProcessor::class);
249 $this->initializeAdditionalPreviewLanguages();
250 // Prepare user defined objects (if any) for hooks which extend this function:
251 $this->hookObjectsMainFields = array();
252 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tceforms.php']['getMainFieldsClass'])) {
253 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tceforms.php']['getMainFieldsClass'] as $classRef) {
254 $this->hookObjectsMainFields[] = GeneralUtility::getUserObj($classRef);
255 }
256 }
257 $this->templateFile = 'sysext/backend/Resources/Private/Templates/FormEngine.html';
258 $template = GeneralUtility::getUrl(PATH_typo3 . $this->templateFile);
259 // Wrapping all table rows for a particular record being edited:
260 $this->totalWrap = HtmlParser::getSubpart($template, '###TOTALWRAP###');
261 }
262
263 /**
264 * Set render read only flag
265 *
266 * @param bool $value
267 */
268 public function setRenderReadonly($value) {
269 $this->renderReadonly = (bool)$value;
270 }
271
272 /*******************************************************
273 *
274 * Rendering the forms, fields etc
275 *
276 *******************************************************/
277
278 /**
279 * Based on the $table and $row of content, this displays the complete TCEform for the record.
280 * The input-$row is required to be preprocessed if necessary by eg.
281 * the \TYPO3\CMS\Backend\Form\DataPreprocessor class. For instance the RTE content
282 * should be transformed through this class first.
283 *
284 * @param string $table The table name
285 * @param array $databaseRow The record from the table for which to render a field.
286 * @return string HTML output
287 */
288 public function getMainFields($table, array $databaseRow) {
289 $this->table = $table;
290 $this->databaseRow = $databaseRow;
291
292 // Hook: getMainFields_preProcess
293 foreach ($this->hookObjectsMainFields as $hookObj) {
294 if (method_exists($hookObj, 'getMainFields_preProcess')) {
295 $hookObj->getMainFields_preProcess($table, $databaseRow, $this);
296 }
297 }
298
299 /** @var FullRecordContainer $entryContainer */
300 $entryContainer = GeneralUtility::makeInstance(FullRecordContainer::class);
301 $entryContainer->setGlobalOptions($this->getConfigurationOptionsForChildElements());
302 $resultArray = $entryContainer->render();
303 $content = $resultArray['html'];
304 $this->requiredElements = $resultArray['requiredElements'];
305 $this->requiredFields = $resultArray['requiredFields'];
306 $this->requiredAdditional = $resultArray['requiredAdditional'];
307 $this->requiredNested = $resultArray['requiredNested'];
308 $this->additionalJS_post = $resultArray['additionalJavaScriptPost'];
309 $this->additionalJS_submit = $resultArray['additionalJavaScriptSubmit'];
310 $this->extJSCODE = $resultArray['extJSCODE'];
311 $this->inlineData = $resultArray['inlineData'];
312 $this->hiddenFieldAccum = $resultArray['additionalHiddenFields'];
313 $this->additionalCode_pre = $resultArray['additionalHeadTags'];
314
315 // Hook: getMainFields_postProcess
316 foreach ($this->hookObjectsMainFields as $hookObj) {
317 if (method_exists($hookObj, 'getMainFields_postProcess')) {
318 $hookObj->getMainFields_postProcess($table, $databaseRow, $this);
319 }
320 }
321
322 return $content;
323 }
324
325 /**
326 * Will return the TCEform element for just a single field from a record.
327 * The field must be listed in the currently displayed fields (as found in [types][showitem]) for the record.
328 * This also means that the $table/$row supplied must be complete so the list of fields to show can be found correctly
329 * This method is used by "full screen RTE". Difference to getListedFields() is basically that no wrapper html is rendered around the element.
330 *
331 * @param string $table The table name
332 * @param array $databaseRow The record from the table for which to render a field.
333 * @param string $theFieldToReturn The field name to return the TCEform element for.
334 * @return string HTML output
335 */
336 public function getSoloField($table, $databaseRow, $theFieldToReturn) {
337 $this->table = $table;
338 $this->databaseRow = $databaseRow;
339
340 $options = $this->getConfigurationOptionsForChildElements();
341 $options['singleFieldToRender'] = $theFieldToReturn;
342 /** @var SoloFieldContainer $soloFieldContainer */
343 $soloFieldContainer = GeneralUtility::makeInstance(SoloFieldContainer::class);
344 $soloFieldContainer->setGlobalOptions($options);
345 $resultArray = $soloFieldContainer->render();
346 $html = $resultArray['html'];
347
348 $this->requiredElements = $resultArray['requiredElements'];
349 $this->requiredFields = $resultArray['requiredFields'];
350 $this->requiredAdditional = $resultArray['requiredAdditional'];
351 $this->requiredNested = $resultArray['requiredNested'];
352 $this->additionalJS_post = $resultArray['additionalJavaScriptPost'];
353 $this->additionalJS_submit = $resultArray['additionalJavaScriptSubmit'];
354 $this->extJSCODE = $resultArray['extJSCODE'];
355 $this->inlineData = $resultArray['inlineData'];
356 $this->hiddenFieldAccum = $resultArray['additionalHiddenFields'];
357 $this->additionalCode_pre = $resultArray['additionalHeadTags'];
358
359 return $html;
360 }
361
362 /**
363 * Will return the TCEform elements for a pre-defined list of fields.
364 * Notice that this will STILL use the configuration found in the list [types][showitem] for those fields which are found there.
365 * So ideally the list of fields given as argument to this function should also be in the current [types][showitem] list of the record.
366 * Used for displaying forms for the frontend edit icons for instance.
367 *
368 * @todo: The list module calls this method multiple times on the same class instance if single fields
369 * @todo: of multiple records are edited. This is why the properties are accumulated here.
370 *
371 * @param string $table The table name
372 * @param array $databaseRow The record array.
373 * @param string $list Commalist of fields from the table. These will be shown in the specified order in a form.
374 * @return string TCEform elements in a string.
375 */
376 public function getListedFields($table, $databaseRow, $list) {
377 $this->table = $table;
378 $this->databaseRow = $databaseRow;
379
380 $options = $this->getConfigurationOptionsForChildElements();
381 $options['fieldListToRender'] = $list;
382 /** @var ListOfFieldsContainer $listOfFieldsContainer */
383 $listOfFieldsContainer = GeneralUtility::makeInstance(ListOfFieldsContainer::class);
384 $listOfFieldsContainer->setGlobalOptions($options);
385 $resultArray = $listOfFieldsContainer->render();
386 $html = $resultArray['html'];
387
388 foreach ($resultArray['requiredElements'] as $element) {
389 $this->requiredElements[] = $element;
390 }
391 foreach ($resultArray['requiredFields'] as $element) {
392 $this->requiredFields[] = $element;
393 }
394 foreach ($resultArray['requiredAdditional'] as $element) {
395 $this->requiredAdditional[] = $element;
396 }
397 foreach ($resultArray['requiredNested'] as $element) {
398 $this->requiredNested[] = $element;
399 }
400 foreach ($resultArray['additionalJavaScriptPost'] as $element) {
401 $this->additionalJS_post[] = $element;
402 }
403 foreach ($resultArray['additionalJavaScriptSubmit'] as $element) {
404 $this->additionalJS_submit[] = $element;
405 }
406 $this->extJSCODE = $this->extJSCODE . $resultArray['extJSCODE'];
407 $this->inlineData = $resultArray['inlineData'];
408 foreach ($resultArray['additionalHiddenFields'] as $element) {
409 $this->hiddenFieldAccum[] = $element;
410 }
411 foreach ($resultArray['additionalHeadTags'] as $element) {
412 $this->additionalCode_pre[] = $element;
413 }
414
415 return $html;
416 }
417
418 /**
419 * Returns an array of global form settings to be given to child elements.
420 *
421 * @return array
422 */
423 protected function getConfigurationOptionsForChildElements() {
424 return array(
425 'renderReadonly' => $this->renderReadonly,
426 'disabledWizards' => $this->disableWizards,
427 'returnUrl' => $this->thisReturnUrl(),
428 'palettesCollapsed' => $this->palettesCollapsed,
429 'table' => $this->table,
430 'databaseRow' => $this->databaseRow,
431 'additionalPreviewLanguages' => $this->additionalPreviewLanguages,
432 'localizationMode' => $this->localizationMode, // @todo: find out the details, Warning, this overlaps with inline behaviour localizationMode
433 'elementBaseName' => '',
434 'tabAndInlineStack' => array(),
435 'inlineFirstPid' => $this->getInlineFirstPid(),
436 'inlineExpandCollapseStateArray' => $this->getInlineExpandCollapseStateArrayForTableUid($this->table, $this->databaseRow['uid']),
437 'inlineData' => $this->inlineData,
438 'inlineStructure' => $this->inlineStackProcessor->getStructure(),
439 'overruleTypesArray' => array(),
440 'hiddenFieldListArray' => $this->hiddenFieldListArr,
441 'isAjaxContext' => FALSE,
442 'flexFormFieldIdentifierPrefix' => 'ID',
443 );
444 }
445
446 /**
447 * General processor for AJAX requests concerning IRRE.
448 *
449 * @param array $_ Additional parameters (not used here)
450 * @param AjaxRequestHandler $ajaxObj The AjaxRequestHandler object of this request
451 * @throws \RuntimeException
452 * @return void
453 */
454 public function processInlineAjaxRequest($_, AjaxRequestHandler $ajaxObj) {
455 $ajaxArguments = GeneralUtility::_GP('ajax');
456 $ajaxIdParts = explode('::', $GLOBALS['ajaxID'], 2);
457 if (isset($ajaxArguments) && is_array($ajaxArguments) && count($ajaxArguments)) {
458 $ajaxMethod = $ajaxIdParts[1];
459 $ajaxObj->setContentFormat('jsonbody');
460 // Construct runtime environment for Inline Relational Record Editing
461 $this->setUpRuntimeEnvironmentForAjaxRequests();
462 // @todo: ajaxArguments[2] is "returnUrl" in the first 3 calls - still needed?
463 switch ($ajaxMethod) {
464 case 'synchronizeLocalizeRecords':
465 $domObjectId = $ajaxArguments[0];
466 $type = $ajaxArguments[1];
467 // Parse the DOM identifier (string), add the levels to the structure stack (array), load the TCA config:
468 $this->inlineStackProcessor->initializeByParsingDomObjectIdString($domObjectId);
469 $this->inlineStackProcessor->injectAjaxConfiguration($ajaxArguments['context']);
470 $inlineFirstPid = FormEngineUtility::getInlineFirstPidFromDomObjectId($domObjectId);
471 $ajaxObj->setContent($this->renderInlineSynchronizeLocalizeRecords($type, $inlineFirstPid));
472 break;
473 case 'createNewRecord':
474 $domObjectId = $ajaxArguments[0];
475 $createAfterUid = 0;
476 if (isset($ajaxArguments[1])) {
477 $createAfterUid = $ajaxArguments[1];
478 }
479 // Parse the DOM identifier (string), add the levels to the structure stack (array), load the TCA config:
480 $this->inlineStackProcessor->initializeByParsingDomObjectIdString($domObjectId);
481 $this->inlineStackProcessor->injectAjaxConfiguration($ajaxArguments['context']);
482 $ajaxObj->setContent($this->renderInlineNewChildRecord($domObjectId, $createAfterUid));
483 break;
484 case 'getRecordDetails':
485 $domObjectId = $ajaxArguments[0];
486 // Parse the DOM identifier (string), add the levels to the structure stack (array), load the TCA config:
487 $this->inlineStackProcessor->initializeByParsingDomObjectIdString($domObjectId);
488 $this->inlineStackProcessor->injectAjaxConfiguration($ajaxArguments['context']);
489 $ajaxObj->setContent($this->renderInlineChildRecord($domObjectId));
490 break;
491 case 'setExpandedCollapsedState':
492 $domObjectId = $ajaxArguments[0];
493 // Parse the DOM identifier (string), add the levels to the structure stack (array), don't load TCA config
494 $this->inlineStackProcessor->initializeByParsingDomObjectIdString($domObjectId, FALSE);
495 $expand = $ajaxArguments[1];
496 $collapse = $ajaxArguments[2];
497 $this->setInlineExpandedCollapsedState($expand, $collapse);
498 break;
499 default:
500 throw new \RuntimeException('Not a valid ajax identifier', 1428227862);
501 }
502 }
503 }
504
505 /**
506 * Handle AJAX calls to dynamically load the form fields of a given inline record.
507 *
508 * @param string $domObjectId The calling object in hierarchy, that requested a new record.
509 * @return array An array to be used for JSON
510 */
511 protected function renderInlineChildRecord($domObjectId) {
512 // The current table - for this table we should add/import records
513 $current = $this->inlineStackProcessor->getUnstableStructure();
514 // The parent table - this table embeds the current table
515 $parent = $this->inlineStackProcessor->getStructureLevel(-1);
516 $config = $parent['config'];
517
518 if (empty($config['foreign_table']) || !is_array($GLOBALS['TCA'][$config['foreign_table']])) {
519 return $this->getErrorMessageForAJAX('Wrong configuration in table ' . $parent['table']);
520 }
521
522 $config = FormEngineUtility::mergeInlineConfiguration($config);
523
524 // Set flag in config so that only the fields are rendered
525 $config['renderFieldsOnly'] = TRUE;
526 $collapseAll = isset($config['appearance']['collapseAll']) && $config['appearance']['collapseAll'];
527 $expandSingle = isset($config['appearance']['expandSingle']) && $config['appearance']['expandSingle'];
528
529 $inlineRelatedRecordResolver = GeneralUtility::makeInstance(InlineRelatedRecordResolver::class);
530 $record = $inlineRelatedRecordResolver->getRecord($current['table'], $current['uid']);
531
532 $inlineFirstPid = FormEngineUtility::getInlineFirstPidFromDomObjectId($domObjectId);
533 // The HTML-object-id's prefix of the dynamically created record
534 $objectPrefix = $this->inlineStackProcessor->getCurrentStructureDomObjectIdPrefix($inlineFirstPid) . '-' . $current['table'];
535 $objectId = $objectPrefix . '-' . $record['uid'];
536
537 $options = $this->getConfigurationOptionsForChildElements();
538 $options['databaseRow'] = array('uid' => $parent['uid']);
539 $options['inlineFirstPid'] = $inlineFirstPid;
540 $options['inlineRelatedRecordToRender'] = $record;
541 $options['inlineRelatedRecordConfig'] = $config;
542 $options['inlineStructure'] = $this->inlineStackProcessor->getStructure();
543 $options['isAjaxContext'] = TRUE;
544
545 /** @var InlineRecordContainer $inlineRecordContainer */
546 $inlineRecordContainer = GeneralUtility::makeInstance(InlineRecordContainer::class);
547 $childArray = $inlineRecordContainer->setGlobalOptions($options)->render();
548
549 if ($childArray === FALSE) {
550 return $this->getErrorMessageForAJAX('Access denied');
551 }
552
553 // @todo: Refactor this mess ... see other methods like getMainFields, too
554 $this->requiredElements = $childArray['requiredElements'];
555 $this->requiredFields = $childArray['requiredFields'];
556 $this->requiredAdditional = $childArray['requiredAdditional'];
557 $this->requiredNested = $childArray['requiredNested'];
558 $this->additionalJS_post = $childArray['additionalJavaScriptPost'];
559 $this->additionalJS_submit = $childArray['additionalJavaScriptSubmit'];
560 $this->extJSCODE = $childArray['extJSCODE'];
561 $this->inlineData = $childArray['inlineData'];
562 $this->hiddenFieldAccum = $childArray['additionalHiddenFields'];
563 $this->additionalCode_pre = $childArray['additionalHeadTags'];
564
565 $jsonArray = array(
566 'data' => $childArray['html'],
567 'scriptCall' => array(),
568 );
569 $jsonArray['scriptCall'][] = 'inline.domAddRecordDetails(' . GeneralUtility::quoteJSvalue($domObjectId) . ',' . GeneralUtility::quoteJSvalue($objectPrefix) . ',' . ($expandSingle ? '1' : '0') . ',json.data);';
570 if ($config['foreign_unique']) {
571 $jsonArray['scriptCall'][] = 'inline.removeUsed(\'' . $objectPrefix . '\',\'' . $record['uid'] . '\');';
572 }
573
574 $jsonArray = $this->getInlineAjaxCommonScriptCalls($jsonArray, $config, $inlineFirstPid);
575
576 // Collapse all other records if requested:
577 if (!$collapseAll && $expandSingle) {
578 $jsonArray['scriptCall'][] = 'inline.collapseAllRecords(\'' . $objectId . '\',\'' . $objectPrefix . '\',\'' . $record['uid'] . '\');';
579 }
580
581 return $jsonArray;
582 }
583
584 /**
585 * Handle AJAX calls to show a new inline-record of the given table.
586 *
587 * @param string $domObjectId The calling object in hierarchy, that requested a new record.
588 * @param string|int $foreignUid If set, the new record should be inserted after that one.
589 * @return array An array to be used for JSON
590 */
591 protected function renderInlineNewChildRecord($domObjectId, $foreignUid) {
592 // The current table - for this table we should add/import records
593 $current = $this->inlineStackProcessor->getUnstableStructure();
594 // The parent table - this table embeds the current table
595 $parent = $this->inlineStackProcessor->getStructureLevel(-1);
596 $config = $parent['config'];
597
598 if (empty($config['foreign_table']) || !is_array($GLOBALS['TCA'][$config['foreign_table']])) {
599 return $this->getErrorMessageForAJAX('Wrong configuration in table ' . $parent['table']);
600 }
601
602 $inlineRelatedRecordResolver = GeneralUtility::makeInstance(InlineRelatedRecordResolver::class);
603
604 $config = FormEngineUtility::mergeInlineConfiguration($config);
605
606 $collapseAll = isset($config['appearance']['collapseAll']) && $config['appearance']['collapseAll'];
607 $expandSingle = isset($config['appearance']['expandSingle']) && $config['appearance']['expandSingle'];
608
609 $inlineFirstPid = FormEngineUtility::getInlineFirstPidFromDomObjectId($domObjectId);
610
611 // Dynamically create a new record using \TYPO3\CMS\Backend\Form\DataPreprocessor
612 if (!$foreignUid || !MathUtility::canBeInterpretedAsInteger($foreignUid) || $config['foreign_selector']) {
613 $record = $inlineRelatedRecordResolver->getNewRecord($inlineFirstPid, $current['table']);
614 // Set default values for new created records
615 if (isset($config['foreign_record_defaults']) && is_array($config['foreign_record_defaults'])) {
616 $foreignTableConfig = $GLOBALS['TCA'][$current['table']];
617 // The following system relevant fields can't be set by foreign_record_defaults
618 $notSettableFields = array(
619 'uid', 'pid', 't3ver_oid', 't3ver_id', 't3ver_label', 't3ver_wsid', 't3ver_state', 't3ver_stage',
620 't3ver_count', 't3ver_tstamp', 't3ver_move_id'
621 );
622 $configurationKeysForNotSettableFields = array(
623 'crdate', 'cruser_id', 'delete', 'origUid', 'transOrigDiffSourceField', 'transOrigPointerField',
624 'tstamp'
625 );
626 foreach ($configurationKeysForNotSettableFields as $configurationKey) {
627 if (isset($foreignTableConfig['ctrl'][$configurationKey])) {
628 $notSettableFields[] = $foreignTableConfig['ctrl'][$configurationKey];
629 }
630 }
631 foreach ($config['foreign_record_defaults'] as $fieldName => $defaultValue) {
632 if (isset($foreignTableConfig['columns'][$fieldName]) && !in_array($fieldName, $notSettableFields)) {
633 $record[$fieldName] = $defaultValue;
634 }
635 }
636 }
637 // Set language of new child record to the language of the parent record:
638 if ($parent['localizationMode'] === 'select') {
639 $parentRecord = $inlineRelatedRecordResolver->getRecord($parent['table'], $parent['uid']);
640 $parentLanguageField = $GLOBALS['TCA'][$parent['table']]['ctrl']['languageField'];
641 $childLanguageField = $GLOBALS['TCA'][$current['table']]['ctrl']['languageField'];
642 if ($parentRecord[$parentLanguageField] > 0) {
643 $record[$childLanguageField] = $parentRecord[$parentLanguageField];
644 }
645 }
646 } else {
647 // @todo: Check this: Else also hits if $foreignUid = 0?
648 $record = $inlineRelatedRecordResolver->getRecord($current['table'], $foreignUid);
649 }
650 // Now there is a foreign_selector, so there is a new record on the intermediate table, but
651 // this intermediate table holds a field, which is responsible for the foreign_selector, so
652 // we have to set this field to the uid we get - or if none, to a new uid
653 if ($config['foreign_selector'] && $foreignUid) {
654 $selConfig = FormEngineUtility::getInlinePossibleRecordsSelectorConfig($config, $config['foreign_selector']);
655 // For a selector of type group/db, prepend the tablename (<tablename>_<uid>):
656 $record[$config['foreign_selector']] = $selConfig['type'] != 'groupdb' ? '' : $selConfig['table'] . '_';
657 $record[$config['foreign_selector']] .= $foreignUid;
658 if ($selConfig['table'] === 'sys_file') {
659 $fileRecord = $inlineRelatedRecordResolver->getRecord($selConfig['table'], $foreignUid);
660 if ($fileRecord !== FALSE && !$this->checkInlineFileTypeAccessForField($selConfig, $fileRecord)) {
661 return $this->getErrorMessageForAJAX('File extension ' . $fileRecord['extension'] . ' is not allowed here!');
662 }
663 }
664 }
665 // The HTML-object-id's prefix of the dynamically created record
666 $objectName = $this->inlineStackProcessor->getCurrentStructureDomObjectIdPrefix($inlineFirstPid);
667 $objectPrefix = $objectName . '-' . $current['table'];
668 $objectId = $objectPrefix . '-' . $record['uid'];
669
670 $options = $this->getConfigurationOptionsForChildElements();
671 $options['databaseRow'] = array('uid' => $parent['uid']);
672 $options['inlineFirstPid'] = $inlineFirstPid;
673 $options['inlineRelatedRecordToRender'] = $record;
674 $options['inlineRelatedRecordConfig'] = $config;
675 $options['inlineStructure'] = $this->inlineStackProcessor->getStructure();
676 $options['isAjaxContext'] = TRUE;
677
678 /** @var InlineRecordContainer $inlineRecordContainer */
679 $inlineRecordContainer = GeneralUtility::makeInstance(InlineRecordContainer::class);
680 $childArray = $inlineRecordContainer->setGlobalOptions($options)->render();
681
682 if ($childArray === FALSE) {
683 return $this->getErrorMessageForAJAX('Access denied');
684 }
685
686 // @todo: Refactor this mess ... see other methods like getMainFields, too
687 $this->requiredElements = $childArray['requiredElements'];
688 $this->requiredFields = $childArray['requiredFields'];
689 $this->requiredAdditional = $childArray['requiredAdditional'];
690 $this->requiredNested = $childArray['requiredNested'];
691 $this->additionalJS_post = $childArray['additionalJavaScriptPost'];
692 $this->additionalJS_submit = $childArray['additionalJavaScriptSubmit'];
693 $this->extJSCODE = $childArray['extJSCODE'];
694 $this->inlineData = $childArray['inlineData'];
695 $this->hiddenFieldAccum = $childArray['additionalHiddenFields'];
696 $this->additionalCode_pre = $childArray['additionalHeadTags'];
697
698 $jsonArray = array(
699 'data' => $childArray['html'],
700 'scriptCall' => array(),
701 );
702
703 if (!$current['uid']) {
704 $jsonArray['scriptCall'][] = 'inline.domAddNewRecord(\'bottom\',\'' . $objectName . '_records\',\'' . $objectPrefix . '\',json.data);';
705 $jsonArray['scriptCall'][] = 'inline.memorizeAddRecord(\'' . $objectPrefix . '\',\'' . $record['uid'] . '\',null,\'' . $foreignUid . '\');';
706 } else {
707 $jsonArray['scriptCall'][] = 'inline.domAddNewRecord(\'after\',\'' . $domObjectId . '_div' . '\',\'' . $objectPrefix . '\',json.data);';
708 $jsonArray['scriptCall'][] = 'inline.memorizeAddRecord(\'' . $objectPrefix . '\',\'' . $record['uid'] . '\',\'' . $current['uid'] . '\',\'' . $foreignUid . '\');';
709 }
710
711 $jsonArray = $this->getInlineAjaxCommonScriptCalls($jsonArray, $config, $inlineFirstPid);
712
713 // Collapse all other records if requested:
714 if (!$collapseAll && $expandSingle) {
715 $jsonArray['scriptCall'][] = 'inline.collapseAllRecords(\'' . $objectId . '\', \'' . $objectPrefix . '\', \'' . $record['uid'] . '\');';
716 }
717 // Tell the browser to scroll to the newly created record
718
719 $jsonArray['scriptCall'][] = 'Element.scrollTo(\'' . $objectId . '_div\');';
720 // Fade out and fade in the new record in the browser view to catch the user's eye
721 $jsonArray['scriptCall'][] = 'inline.fadeOutFadeIn(\'' . $objectId . '_div\');';
722
723 return $jsonArray;
724 }
725
726 /**
727 * Handle AJAX calls to localize all records of a parent, localize a single record or to synchronize with the original language parent.
728 *
729 * @param string $type Defines the type 'localize' or 'synchronize' (string) or a single uid to be localized (int)
730 * @param int $inlineFirstPid Inline first pid
731 * @return array An array to be used for JSON
732 */
733 protected function renderInlineSynchronizeLocalizeRecords($type, $inlineFirstPid) {
734 $jsonArray = FALSE;
735 if (GeneralUtility::inList('localize,synchronize', $type) || MathUtility::canBeInterpretedAsInteger($type)) {
736 $inlineRelatedRecordResolver = GeneralUtility::makeInstance(InlineRelatedRecordResolver::class);
737 // The parent level:
738 $parent = $this->inlineStackProcessor->getStructureLevel(-1);
739 $current = $this->inlineStackProcessor->getUnstableStructure();
740 $parentRecord = $inlineRelatedRecordResolver->getRecord($parent['table'], $parent['uid']);
741
742 $cmd = array();
743 $cmd[$parent['table']][$parent['uid']]['inlineLocalizeSynchronize'] = $parent['field'] . ',' . $type;
744 /** @var $tce \TYPO3\CMS\Core\DataHandling\DataHandler */
745 $tce = GeneralUtility::makeInstance(\TYPO3\CMS\Core\DataHandling\DataHandler::class);
746 $tce->stripslashes_values = FALSE;
747 $tce->start(array(), $cmd);
748 $tce->process_cmdmap();
749
750 $oldItemList = $parentRecord[$parent['field']];
751 $newItemList = $tce->registerDBList[$parent['table']][$parent['uid']][$parent['field']];
752
753 $jsonArray = array(
754 'scriptCall' => array(),
755 );
756 $nameObject = $this->inlineStackProcessor->getCurrentStructureDomObjectIdPrefix($inlineFirstPid);
757 $nameObjectForeignTable = $nameObject . '-' . $current['table'];
758 // Get the name of the field pointing to the original record:
759 $transOrigPointerField = $GLOBALS['TCA'][$current['table']]['ctrl']['transOrigPointerField'];
760 // Get the name of the field used as foreign selector (if any):
761 $foreignSelector = isset($parent['config']['foreign_selector']) && $parent['config']['foreign_selector'] ? $parent['config']['foreign_selector'] : FALSE;
762 // Convert lists to array with uids of child records:
763 $oldItems = FormEngineUtility::getInlineRelatedRecordsUidArray($oldItemList);
764 $newItems = FormEngineUtility::getInlineRelatedRecordsUidArray($newItemList);
765 // Determine the items that were localized or localized:
766 $removedItems = array_diff($oldItems, $newItems);
767 $localizedItems = array_diff($newItems, $oldItems);
768 // Set the items that should be removed in the forms view:
769 foreach ($removedItems as $item) {
770 $jsonArray['scriptCall'][] = 'inline.deleteRecord(\'' . $nameObjectForeignTable . '-' . $item . '\', {forceDirectRemoval: true});';
771 }
772 // Set the items that should be added in the forms view:
773 $html = '';
774 $resultArray = NULL;
775 // @todo: This should be another container ...
776 foreach ($localizedItems as $item) {
777 $row = $inlineRelatedRecordResolver->getRecord($current['table'], $item);
778 $selectedValue = $foreignSelector ? '\'' . $row[$foreignSelector] . '\'' : 'null';
779
780 $options = $this->getConfigurationOptionsForChildElements();
781 $options['databaseRow'] = array('uid' => $parent['uid']);
782 $options['inlineFirstPid'] = $inlineFirstPid;
783 $options['inlineRelatedRecordToRender'] = $row;
784 $options['inlineRelatedRecordConfig'] = $parent['config'];
785 $options['inlineStructure'] = $this->inlineStackProcessor->getStructure();
786 $options['isAjaxContext'] = TRUE;
787
788 /** @var InlineRecordContainer $inlineRecordContainer */
789 $inlineRecordContainer = GeneralUtility::makeInstance(InlineRecordContainer::class);
790 $childArray = $inlineRecordContainer->setGlobalOptions($options)->render();
791 $html .= $childArray['html'];
792 $childArray['html'] = '';
793
794 // @todo: Obsolete if a container and copied from AbstractContainer for now
795 if ($resultArray === NULL) {
796 $resultArray = $childArray;
797 } else {
798 if (!empty($childArray['extJSCODE'])) {
799 $resultArray['extJSCODE'] .= LF . $childArray['extJSCODE'];
800 }
801 foreach ($childArray['requiredElements'] as $name => $value) {
802 $resultArray['requiredElements'][$name] = $value;
803 }
804 foreach ($childArray['requiredFields'] as $value => $name) { // Params swapped ?!
805 $resultArray['requiredFields'][$value] = $name;
806 }
807 foreach ($childArray['requiredAdditional'] as $name => $subArray) {
808 $resultArray['requiredAdditional'][$name] = $subArray;
809 }
810 foreach ($childArray['requiredNested'] as $value => $name) {
811 $resultArray['requiredNested'][$value] = $name;
812 }
813 foreach ($childArray['additionalJavaScriptPost'] as $value) {
814 $resultArray['additionalJavaScriptPost'][] = $value;
815 }
816 foreach ($childArray['additionalJavaScriptSubmit'] as $value) {
817 $resultArray['additionalJavaScriptSubmit'][] = $value;
818 }
819 if (!empty($childArray['inlineData'])) {
820 $resultArrayInlineData = $resultArray['inlineData'];
821 $childInlineData = $childArray['inlineData'];
822 ArrayUtility::mergeRecursiveWithOverrule($resultArrayInlineData, $childInlineData);
823 $resultArray['inlineData'] = $resultArrayInlineData;
824 }
825 }
826
827 $jsonArray['scriptCall'][] = 'inline.memorizeAddRecord(\'' . $nameObjectForeignTable . '\', \'' . $item . '\', null, ' . $selectedValue . ');';
828 // Remove possible virtual records in the form which showed that a child records could be localized:
829 if (isset($row[$transOrigPointerField]) && $row[$transOrigPointerField]) {
830 $jsonArray['scriptCall'][] = 'inline.fadeAndRemove(\'' . $nameObjectForeignTable . '-' . $row[$transOrigPointerField] . '_div' . '\');';
831 }
832 }
833 if (!empty($html)) {
834 $jsonArray['data'] = $html;
835 array_unshift($jsonArray['scriptCall'], 'inline.domAddNewRecord(\'bottom\', \'' . $nameObject . '_records\', \'' . $nameObjectForeignTable . '\', json.data);');
836 }
837
838 // @todo: Refactor this mess ... see other methods like getMainFields, too
839 $this->requiredElements = $resultArray['requiredElements'];
840 $this->requiredFields = $resultArray['requiredFields'];
841 $this->requiredAdditional = $resultArray['requiredAdditional'];
842 $this->requiredNested = $resultArray['requiredNested'];
843 $this->additionalJS_post = $resultArray['additionalJavaScriptPost'];
844 $this->additionalJS_submit = $resultArray['additionalJavaScriptSubmit'];
845 $this->extJSCODE = $resultArray['extJSCODE'];
846 $this->inlineData = $resultArray['inlineData'];
847 $this->hiddenFieldAccum = $resultArray['additionalHiddenFields'];
848 $this->additionalCode_pre = $resultArray['additionalHeadTags'];
849
850 $jsonArray = $this->getInlineAjaxCommonScriptCalls($jsonArray, $parent['config'], $inlineFirstPid);
851 }
852 return $jsonArray;
853 }
854
855 /**
856 * Save the expanded/collapsed state of a child record in the BE_USER->uc.
857 *
858 * @param string $expand Whether this record is expanded.
859 * @param string $collapse Whether this record is collapsed.
860 * @return void
861 */
862 protected function setInlineExpandedCollapsedState($expand, $collapse) {
863 $backendUser = $this->getBackendUserAuthentication();
864 // The current table - for this table we should add/import records
865 $currentTable = $this->inlineStackProcessor->getUnstableStructure();
866 $currentTable = $currentTable['table'];
867 // The top parent table - this table embeds the current table
868 $top = $this->inlineStackProcessor->getStructureLevel(0);
869 $topTable = $top['table'];
870 $topUid = $top['uid'];
871 $inlineView = $this->getInlineExpandCollapseStateArray();
872 // Only do some action if the top record and the current record were saved before
873 if (MathUtility::canBeInterpretedAsInteger($topUid)) {
874 $expandUids = GeneralUtility::trimExplode(',', $expand);
875 $collapseUids = GeneralUtility::trimExplode(',', $collapse);
876 // Set records to be expanded
877 foreach ($expandUids as $uid) {
878 $inlineView[$topTable][$topUid][$currentTable][] = $uid;
879 }
880 // Set records to be collapsed
881 foreach ($collapseUids as $uid) {
882 $inlineView[$topTable][$topUid][$currentTable] = $this->removeFromArray($uid, $inlineView[$topTable][$topUid][$currentTable]);
883 }
884 // Save states back to database
885 if (is_array($inlineView[$topTable][$topUid][$currentTable])) {
886 $inlineView[$topTable][$topUid][$currentTable] = array_unique($inlineView[$topTable][$topUid][$currentTable]);
887 $backendUser->uc['inlineView'] = serialize($inlineView);
888 $backendUser->writeUC();
889 }
890 }
891 }
892
893 /**
894 * Construct runtime environment for Inline Relational Record Editing.
895 * - creates an anonymous \TYPO3\CMS\Backend\Controller\EditDocumentController in $GLOBALS['SOBE']
896 * - sets $this to $GLOBALS['SOBE']->tceforms
897 * -
898 * @return void
899 */
900 protected function setUpRuntimeEnvironmentForAjaxRequests() {
901 $this->getLanguageService()->includeLLFile('EXT:lang/locallang_alt_doc.xlf');
902 // Create a new anonymous object:
903 $GLOBALS['SOBE'] = new \stdClass();
904 $GLOBALS['SOBE']->MOD_MENU = array(
905 'showPalettes' => '',
906 'showDescriptions' => '',
907 );
908 // Setting virtual document name
909 $GLOBALS['SOBE']->MCONF['name'] = 'xMOD_alt_doc.php';
910 // CLEANSE SETTINGS
911 $GLOBALS['SOBE']->MOD_SETTINGS = BackendUtility::getModuleData($GLOBALS['SOBE']->MOD_MENU, GeneralUtility::_GP('SET'), $GLOBALS['SOBE']->MCONF['name']);
912 // Create an instance of the document template object
913 // @todo: resolve clash getDocumentTemplate() / getControllerDocumenttemplate()
914 $GLOBALS['SOBE']->doc = GeneralUtility::makeInstance(DocumentTemplate::class);
915 $GLOBALS['SOBE']->doc->backPath = $GLOBALS['BACK_PATH'];
916 // Initialize FormEngine (rendering the forms)
917 // @todo: check what of this part is still needed, simplify
918 $this->palettesCollapsed = !$GLOBALS['SOBE']->MOD_SETTINGS['showPalettes'];
919 $GLOBALS['SOBE']->tceforms = $this;
920 }
921
922 /**
923 * Return expand / collapse state array for a given table / uid combination
924 *
925 * @param string $table Handled table
926 * @param integer $uid Handled uid
927 * @return array
928 */
929 protected function getInlineExpandCollapseStateArrayForTableUid($table, $uid) {
930 $inlineView = $this->getInlineExpandCollapseStateArray();
931 $result = array();
932 if (MathUtility::canBeInterpretedAsInteger($uid)) {
933 if (!empty($inlineView[$table][$uid])) {
934 $result = $inlineView[$table][$uid];
935 }
936 }
937 return $result;
938 }
939
940 /**
941 * Get expand / collapse state of inline items
942 *
943 * @return array
944 */
945 protected function getInlineExpandCollapseStateArray() {
946 $backendUser = $this->getBackendUserAuthentication();
947 $inlineView = unserialize($backendUser->uc['inlineView']);
948 if (!is_array($inlineView)) {
949 $inlineView = array();
950 }
951 return $inlineView;
952 }
953
954 /**
955 * The "entry" pid for inline records. Nested inline records can potentially hang around on different
956 * pid's, but the entry pid is needed for AJAX calls, so that they would know where the action takes place on the page structure.
957 *
958 * @return integer
959 */
960 protected function getInlineFirstPid() {
961 $table = $this->table;
962 $row = $this->databaseRow;
963 // If the parent is a page, use the uid(!) of the (new?) page as pid for the child records:
964 if ($table == 'pages') {
965 $liveVersionId = BackendUtility::getLiveVersionIdOfRecord('pages', $row['uid']);
966 $pid = is_null($liveVersionId) ? $row['uid'] : $liveVersionId;
967 } elseif ($row['pid'] < 0) {
968 $prevRec = BackendUtility::getRecord($table, abs($row['pid']));
969 $pid = $prevRec['pid'];
970 } else {
971 $pid = $row['pid'];
972 }
973 return $pid;
974 }
975
976 /**
977 * Checks if a record selector may select a certain file type
978 *
979 * @param array $selectorConfiguration
980 * @param array $fileRecord
981 * @return bool
982 */
983 protected function checkInlineFileTypeAccessForField(array $selectorConfiguration, array $fileRecord) {
984 if (!empty($selectorConfiguration['PA']['fieldConf']['config']['appearance']['elementBrowserAllowed'])) {
985 $allowedFileExtensions = GeneralUtility::trimExplode(
986 ',',
987 $selectorConfiguration['PA']['fieldConf']['config']['appearance']['elementBrowserAllowed'],
988 TRUE
989 );
990 if (!in_array(strtolower($fileRecord['extension']), $allowedFileExtensions, TRUE)) {
991 return FALSE;
992 }
993 }
994 return TRUE;
995 }
996
997 /**
998 * Remove an element from an array.
999 *
1000 * @param mixed $needle The element to be removed.
1001 * @param array $haystack The array the element should be removed from.
1002 * @param mixed $strict Search elements strictly.
1003 * @return array The array $haystack without the $needle
1004 */
1005 protected function removeFromArray($needle, $haystack, $strict = NULL) {
1006 $pos = array_search($needle, $haystack, $strict);
1007 if ($pos !== FALSE) {
1008 unset($haystack[$pos]);
1009 }
1010 return $haystack;
1011 }
1012
1013 /**
1014 * Generates an error message that transferred as JSON for AJAX calls
1015 *
1016 * @param string $message The error message to be shown
1017 * @return array The error message in a JSON array
1018 */
1019 protected function getErrorMessageForAJAX($message) {
1020 $jsonArray = array(
1021 'data' => $message,
1022 'scriptCall' => array(
1023 'alert("' . $message . '");'
1024 )
1025 );
1026 return $jsonArray;
1027 }
1028
1029 /**
1030 * Determines and sets several script calls to a JSON array, that would have been executed if processed in non-AJAX mode.
1031 *
1032 * @param array &$jsonArray Reference of the array to be used for JSON
1033 * @param array $config The configuration of the IRRE field of the parent record
1034 * @param integer $inlineFirstPid Inline first pid
1035 * @return array Modified array
1036 * @todo: Basically, this methods shouldn't be there at all ...
1037 */
1038 protected function getInlineAjaxCommonScriptCalls($jsonArray, $config, $inlineFirstPid) {
1039 // Add data that would have been added at the top of a regular FormEngine call:
1040 if ($headTags = $this->getInlineHeadTags()) {
1041 $jsonArray['headData'] = $headTags;
1042 }
1043 // Add the JavaScript data that would have been added at the bottom of a regular FormEngine call:
1044 $jsonArray['scriptCall'][] = $this->JSbottom('editform', TRUE);
1045 // If script.aculo.us Sortable is used, update the Observer to know the record:
1046 if ($config['appearance']['useSortable']) {
1047 $inlineObjectName = $this->inlineStackProcessor->getCurrentStructureDomObjectIdPrefix($inlineFirstPid);
1048 $jsonArray['scriptCall'][] = 'inline.createDragAndDropSorting(\'' . $inlineObjectName . '_records\');';
1049 }
1050 // If FormEngine has some JavaScript code to be executed, just do it
1051 // @todo: this is done by JSBottom() already?!
1052 if ($this->extJSCODE) {
1053 $jsonArray['scriptCall'][] = $this->extJSCODE;
1054 }
1055 return $jsonArray;
1056 }
1057
1058 /**
1059 * Parses the HTML tags that would have been inserted to the <head> of a HTML document and returns the found tags as multidimensional array.
1060 *
1061 * @return array The parsed tags with their attributes and innerHTML parts
1062 * @todo: WTF?
1063 */
1064 protected function getInlineHeadTags() {
1065 $headTags = array();
1066 $headDataRaw = $this->JStop() . $this->getJavaScriptAndStyleSheetsOfPageRenderer();
1067 if ($headDataRaw) {
1068 // Create instance of the HTML parser:
1069 $parseObj = GeneralUtility::makeInstance(HtmlParser::class);
1070 // Removes script wraps:
1071 $headDataRaw = str_replace(array('/*<![CDATA[*/', '/*]]>*/'), '', $headDataRaw);
1072 // Removes leading spaces of a multi-line string:
1073 $headDataRaw = trim(preg_replace('/(^|\\r|\\n)( |\\t)+/', '$1', $headDataRaw));
1074 // Get script and link tags:
1075 $tags = array_merge($parseObj->getAllParts($parseObj->splitTags('link', $headDataRaw)), $parseObj->getAllParts($parseObj->splitIntoBlock('script', $headDataRaw)));
1076 foreach ($tags as $tagData) {
1077 $tagAttributes = $parseObj->get_tag_attributes($parseObj->getFirstTag($tagData), TRUE);
1078 $headTags[] = array(
1079 'name' => $parseObj->getFirstTagName($tagData),
1080 'attributes' => $tagAttributes[0],
1081 'innerHTML' => $parseObj->removeFirstAndLastTag($tagData)
1082 );
1083 }
1084 }
1085 return $headTags;
1086 }
1087
1088 /**
1089 * Gets the JavaScript of the pageRenderer.
1090 * This can be used to extract newly added files which have been added
1091 * during an AJAX request. Due to the spread possibilities of the pageRenderer
1092 * to add JavaScript rendering and extracting seems to be the easiest way.
1093 *
1094 * @return string
1095 * @todo: aaaargs ...
1096 */
1097 protected function getJavaScriptAndStyleSheetsOfPageRenderer() {
1098 /** @var $pageRenderer \TYPO3\CMS\Core\Page\PageRenderer */
1099 $pageRenderer = clone $GLOBALS['SOBE']->doc->getPageRenderer();
1100 $pageRenderer->setCharSet($this->getLanguageService()->charSet);
1101 $pageRenderer->setTemplateFile('EXT:backend/Resources/Private/Templates/helper_javascript_css.html');
1102 $javaScriptAndStyleSheets = $pageRenderer->render();
1103 return $javaScriptAndStyleSheets;
1104 }
1105
1106 /**
1107 * Returns the "returnUrl" of the form. Can be set externally or will be taken from "GeneralUtility::linkThisScript()"
1108 *
1109 * @return string Return URL of current script
1110 */
1111 protected function thisReturnUrl() {
1112 return $this->returnUrl ? $this->returnUrl : GeneralUtility::linkThisScript();
1113 }
1114
1115 /********************************************
1116 *
1117 * Template functions
1118 *
1119 ********************************************/
1120 /**
1121 * Wraps all the table rows into a single table.
1122 * Used externally from scripts like EditDocumentController and PageLayoutController (which uses FormEngine)
1123 *
1124 * @param string $c Code to output between table-parts; table rows
1125 * @param array $rec The record
1126 * @param string $table The table name
1127 * @return string
1128 */
1129 public function wrapTotal($c, $rec, $table) {
1130 $parts = $this->replaceTableWrap(explode('|', $this->totalWrap, 2), $rec, $table);
1131 return $parts[0] . $c . $parts[1] . implode(LF, $this->hiddenFieldAccum);
1132 }
1133
1134 /**
1135 * Generates a token and returns an input field with it
1136 *
1137 * @param string $formName Context of the token
1138 * @param string $tokenName The name of the token GET/POST variable
1139 * @return string A complete input field
1140 */
1141 static public function getHiddenTokenField($formName = 'securityToken', $tokenName = 'formToken') {
1142 $formprotection = FormProtectionFactory::get();
1143 return '<input type="hidden" name="' . $tokenName . '" value="' . $formprotection->generateToken($formName) . '" />';
1144 }
1145
1146 /**
1147 * This replaces markers in the total wrap
1148 *
1149 * @param array $arr An array of template parts containing some markers.
1150 * @param array $rec The record
1151 * @param string $table The table name
1152 * @return string
1153 */
1154 public function replaceTableWrap($arr, $rec, $table) {
1155 $icon = IconUtility::getSpriteIconForRecord($table, $rec, array('title' => $this->getRecordPath($table, $rec)));
1156 // Make "new"-label
1157 $languageService = $this->getLanguageService();
1158 if (strstr($rec['uid'], 'NEW')) {
1159 $newLabel = ' <span class="typo3-TCEforms-newToken">' . $languageService->sL('LLL:EXT:lang/locallang_core.xlf:labels.new', TRUE) . '</span>';
1160 // BackendUtility::fixVersioningPid Should not be used here because NEW records are not offline workspace versions...
1161 $truePid = BackendUtility::getTSconfig_pidValue($table, $rec['uid'], $rec['pid']);
1162 $prec = BackendUtility::getRecordWSOL('pages', $truePid, 'title');
1163 $pageTitle = BackendUtility::getRecordTitle('pages', $prec, TRUE, FALSE);
1164 $rLabel = '<em>[PID: ' . $truePid . '] ' . $pageTitle . '</em>';
1165 // Fetch translated title of the table
1166 $tableTitle = $languageService->sL($GLOBALS['TCA'][$table]['ctrl']['title']);
1167 if ($table === 'pages') {
1168 $label = $languageService->sL('LLL:EXT:lang/locallang_core.xlf:labels.createNewPage', TRUE);
1169 $pageTitle = sprintf($label, $tableTitle);
1170 } else {
1171 $label = $languageService->sL('LLL:EXT:lang/locallang_core.xlf:labels.createNewRecord', TRUE);
1172 if ($rec['pid'] == 0) {
1173 $label = $languageService->sL('LLL:EXT:lang/locallang_core.xlf:labels.createNewRecordRootLevel', TRUE);
1174 }
1175 $pageTitle = sprintf($label, $tableTitle, $pageTitle);
1176 }
1177 } else {
1178 $newLabel = ' <span class="typo3-TCEforms-recUid">[' . $rec['uid'] . ']</span>';
1179 $rLabel = BackendUtility::getRecordTitle($table, $rec, TRUE, FALSE);
1180 $prec = BackendUtility::getRecordWSOL('pages', $rec['pid'], 'uid,title');
1181 // Fetch translated title of the table
1182 $tableTitle = $languageService->sL($GLOBALS['TCA'][$table]['ctrl']['title']);
1183 if ($table === 'pages') {
1184 $label = $languageService->sL('LLL:EXT:lang/locallang_core.xlf:labels.editPage', TRUE);
1185 // Just take the record title and prepend an edit label.
1186 $pageTitle = sprintf($label, $tableTitle, $rLabel);
1187 } else {
1188 $label = $languageService->sL('LLL:EXT:lang/locallang_core.xlf:labels.editRecord', TRUE);
1189 $pageTitle = BackendUtility::getRecordTitle('pages', $prec, TRUE, FALSE);
1190 if ($rLabel === BackendUtility::getNoRecordTitle(TRUE)) {
1191 $label = $languageService->sL('LLL:EXT:lang/locallang_core.xlf:labels.editRecordNoTitle', TRUE);
1192 }
1193 if ($rec['pid'] == 0) {
1194 $label = $languageService->sL('LLL:EXT:lang/locallang_core.xlf:labels.editRecordRootLevel', TRUE);
1195 }
1196 if ($rLabel !== BackendUtility::getNoRecordTitle(TRUE)) {
1197 // Just take the record title and prepend an edit label.
1198 $pageTitle = sprintf($label, $tableTitle, $rLabel, $pageTitle);
1199 } else {
1200 // Leave out the record title since it is not set.
1201 $pageTitle = sprintf($label, $tableTitle, $pageTitle);
1202 }
1203 }
1204 $icon = $this->getControllerDocumentTemplate()->wrapClickMenuOnIcon($icon, $table, $rec['uid'], 1, '', '+copy,info,edit,view');
1205 }
1206 foreach ($arr as $k => $v) {
1207 // Make substitutions:
1208 $arr[$k] = str_replace(
1209 array(
1210 '###PAGE_TITLE###',
1211 '###ID_NEW_INDICATOR###',
1212 '###RECORD_LABEL###',
1213 '###TABLE_TITLE###',
1214 '###RECORD_ICON###'
1215 ),
1216 array(
1217 $pageTitle,
1218 $newLabel,
1219 $rLabel,
1220 htmlspecialchars($languageService->sL($GLOBALS['TCA'][$table]['ctrl']['title'])),
1221 $icon
1222 ),
1223 $arr[$k]
1224 );
1225 }
1226 return $arr;
1227 }
1228
1229
1230 /********************************************
1231 *
1232 * JavaScript related functions
1233 *
1234 ********************************************/
1235 /**
1236 * JavaScript code added BEFORE the form is drawn:
1237 *
1238 * @return string A <script></script> section with JavaScript.
1239 */
1240 public function JStop() {
1241 $out = '';
1242 // Additional top HTML:
1243 if (count($this->additionalCode_pre)) {
1244 $out .= implode('
1245
1246 <!-- NEXT: -->
1247 ', $this->additionalCode_pre);
1248 }
1249 return $out;
1250 }
1251
1252 /**
1253 * JavaScript bottom code
1254 *
1255 * @param string $formname The identification of the form on the page.
1256 * @param bool $update Just extend/update existing settings, e.g. for AJAX call
1257 * @return string A section with JavaScript - if $update is FALSE, embedded in <script></script>
1258 */
1259 public function JSbottom($formname = 'forms[0]', $update = FALSE) {
1260 $languageService = $this->getLanguageService();
1261 $jsFile = array();
1262 $elements = array();
1263 $out = '';
1264 // Required:
1265 foreach ($this->requiredFields as $itemImgName => $itemName) {
1266 $match = array();
1267 if (preg_match('/^(.+)\\[((\\w|\\d|_)+)\\]$/', $itemName, $match)) {
1268 $record = $match[1];
1269 $field = $match[2];
1270 $elements[$record][$field]['required'] = 1;
1271 $elements[$record][$field]['requiredImg'] = $itemImgName;
1272 if (isset($this->requiredAdditional[$itemName]) && is_array($this->requiredAdditional[$itemName])) {
1273 $elements[$record][$field]['additional'] = $this->requiredAdditional[$itemName];
1274 }
1275 }
1276 }
1277 // Range:
1278 foreach ($this->requiredElements as $itemName => $range) {
1279 if (preg_match('/^(.+)\\[((\\w|\\d|_)+)\\]$/', $itemName, $match)) {
1280 $record = $match[1];
1281 $field = $match[2];
1282 $elements[$record][$field]['range'] = array($range[0], $range[1]);
1283 $elements[$record][$field]['rangeImg'] = $range['imgName'];
1284 }
1285 }
1286 $this->TBE_EDITOR_fieldChanged_func = 'TBE_EDITOR.fieldChanged_fName(fName,formObj[fName+"_list"]);';
1287 if (!$update) {
1288 if ($this->loadMD5_JS) {
1289 $this->loadJavascriptLib('sysext/backend/Resources/Public/JavaScript/md5.js');
1290 }
1291 $pageRenderer = $this->getPageRenderer();
1292 // load the main module for FormEngine with all important JS functions
1293 $pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/FormEngine', 'function(FormEngine) {
1294 FormEngine.setBrowserUrl(' . GeneralUtility::quoteJSvalue(BackendUtility::getModuleUrl('browser')) . ');
1295 }');
1296 $pageRenderer->loadPrototype();
1297 $pageRenderer->loadJquery();
1298 $pageRenderer->loadExtJS();
1299 $beUserAuth = $this->getBackendUserAuthentication();
1300 // Make textareas resizable and flexible ("autogrow" in height)
1301 $textareaSettings = array(
1302 'autosize' => (bool)$beUserAuth->uc['resizeTextareas_Flexible']
1303 );
1304 $pageRenderer->addInlineSettingArray('Textarea', $textareaSettings);
1305
1306 $this->loadJavascriptLib('sysext/backend/Resources/Public/JavaScript/jsfunc.evalfield.js');
1307 $this->loadJavascriptLib('sysext/backend/Resources/Public/JavaScript/jsfunc.tbe_editor.js');
1308 $this->loadJavascriptLib('sysext/backend/Resources/Public/JavaScript/ValueSlider.js');
1309 // Needed for FormEngine manipulation (date picker)
1310 $dateFormat = ($GLOBALS['TYPO3_CONF_VARS']['SYS']['USdateFormat'] ? array('MM-DD-YYYY', 'HH:mm MM-DD-YYYY') : array('DD-MM-YYYY', 'HH:mm DD-MM-YYYY'));
1311 $pageRenderer->addInlineSetting('DateTimePicker', 'DateFormat', $dateFormat);
1312
1313 // support placeholders for IE9 and lower
1314 $clientInfo = GeneralUtility::clientInfo();
1315 if ($clientInfo['BROWSER'] == 'msie' && $clientInfo['VERSION'] <= 9) {
1316 $this->loadJavascriptLib('sysext/core/Resources/Public/JavaScript/Contrib/placeholders.jquery.min.js');
1317 }
1318
1319 // @todo: remove scriptaclous once suggest & flex form foo is moved to RequireJS, see #55575
1320 $pageRenderer->loadScriptaculous();
1321 $this->loadJavascriptLib('sysext/backend/Resources/Public/JavaScript/tceforms.js');
1322 $this->loadJavascriptLib('sysext/backend/Resources/Public/JavaScript/jsfunc.tceforms_suggest.js');
1323
1324 $pageRenderer->loadRequireJs();
1325 $pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/FormEngineFlexForm');
1326 $pageRenderer->loadRequireJsModule('TYPO3/CMS/Filelist/FileListLocalisation');
1327 $pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/DragUploader');
1328
1329 $pageRenderer->addInlineLanguagelabelFile(
1330 \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('lang') . 'locallang_core.xlf',
1331 'file_upload'
1332 );
1333
1334 // We want to load jQuery-ui inside our js. Enable this using requirejs.
1335 $this->loadJavascriptLib('sysext/backend/Resources/Public/JavaScript/jsfunc.inline.js');
1336 $out .= '
1337 inline.setNoTitleString("' . addslashes(BackendUtility::getNoRecordTitle(TRUE)) . '");
1338 ';
1339
1340 $out .= '
1341 TBE_EDITOR.images.req.src = "' . IconUtility::skinImg('', 'gfx/required_h.gif', '', 1) . '";
1342 TBE_EDITOR.images.clear.src = "clear.gif";
1343
1344 TBE_EDITOR.formname = "' . $formname . '";
1345 TBE_EDITOR.formnameUENC = "' . rawurlencode($formname) . '";
1346 TBE_EDITOR.backPath = "";
1347 TBE_EDITOR.isPalettedoc = null;
1348 TBE_EDITOR.doSaveFieldName = "' . ($this->doSaveFieldName ? addslashes($this->doSaveFieldName) : '') . '";
1349 TBE_EDITOR.labels.fieldsChanged = ' . GeneralUtility::quoteJSvalue($languageService->sL('LLL:EXT:lang/locallang_core.xlf:labels.fieldsChanged')) . ';
1350 TBE_EDITOR.labels.fieldsMissing = ' . GeneralUtility::quoteJSvalue($languageService->sL('LLL:EXT:lang/locallang_core.xlf:labels.fieldsMissing')) . ';
1351 TBE_EDITOR.labels.maxItemsAllowed = ' . GeneralUtility::quoteJSvalue($languageService->sL('LLL:EXT:lang/locallang_core.xlf:labels.maxItemsAllowed')) . ';
1352 TBE_EDITOR.labels.refresh_login = ' . GeneralUtility::quoteJSvalue($languageService->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_login')) . ';
1353 TBE_EDITOR.labels.onChangeAlert = ' . GeneralUtility::quoteJSvalue($languageService->sL('LLL:EXT:lang/locallang_core.xlf:mess.onChangeAlert')) . ';
1354 TBE_EDITOR.labels.remainingCharacters = ' . GeneralUtility::quoteJSvalue($languageService->sL('LLL:EXT:lang/locallang_core.xlf:labels.remainingCharacters')) . ';
1355 evalFunc.USmode = ' . ($GLOBALS['TYPO3_CONF_VARS']['SYS']['USdateFormat'] ? '1' : '0') . ';
1356
1357 TBE_EDITOR.customEvalFunctions = {};
1358
1359 ';
1360 }
1361 // Add JS required for inline fields
1362 if (!empty($this->inlineData)) {
1363 $out .= '
1364 inline.addToDataArray(' . json_encode($this->inlineData) . ');
1365 ';
1366 }
1367 // Registered nested elements for tabs or inline levels:
1368 if (count($this->requiredNested)) {
1369 $out .= '
1370 TBE_EDITOR.addNested(' . json_encode($this->requiredNested) . ');
1371 ';
1372 }
1373 // Elements which are required or have a range definition:
1374 if (count($elements)) {
1375 $out .= '
1376 TBE_EDITOR.addElements(' . json_encode($elements) . ');
1377 TBE_EDITOR.initRequired();
1378 ';
1379 }
1380 // $this->additionalJS_submit:
1381 if ($this->additionalJS_submit) {
1382 $additionalJS_submit = implode('', $this->additionalJS_submit);
1383 $additionalJS_submit = str_replace(array(CR, LF), '', $additionalJS_submit);
1384 $out .= '
1385 TBE_EDITOR.addActionChecks("submit", "' . addslashes($additionalJS_submit) . '");
1386 ';
1387 }
1388 $out .= LF . implode(LF, $this->additionalJS_post) . LF . $this->extJSCODE;
1389 // Regular direct output:
1390 if (!$update) {
1391 $spacer = LF . TAB;
1392 $out = $spacer . implode($spacer, $jsFile) . GeneralUtility::wrapJS($out);
1393 }
1394 return $out;
1395 }
1396
1397 /**
1398 * Prints necessary JavaScript for TCEforms (after the form HTML).
1399 * currently this is used to transform page-specific options in the TYPO3.Settings array for JS
1400 * so the JS module can access these values
1401 *
1402 * @return string
1403 */
1404 public function printNeededJSFunctions() {
1405 /** @var $pageRenderer \TYPO3\CMS\Core\Page\PageRenderer */
1406 $pageRenderer = $this->getControllerDocumentTemplate()->getPageRenderer();
1407
1408 // set variables to be accessible for JS
1409 $pageRenderer->addInlineSetting('FormEngine', 'formName', 'editform');
1410 $pageRenderer->addInlineSetting('FormEngine', 'backPath', '');
1411
1412 // Integrate JS functions for the element browser if such fields or IRRE fields were processed
1413 $pageRenderer->addInlineSetting('FormEngine', 'legacyFieldChangedCb', 'function() { ' . $this->TBE_EDITOR_fieldChanged_func . ' };');
1414
1415 return $this->JSbottom('editform');
1416 }
1417
1418 /**
1419 * Returns necessary JavaScript for the top
1420 *
1421 * @return string
1422 */
1423 public function printNeededJSFunctions_top() {
1424 return $this->JStop('editform');
1425 }
1426
1427 /**
1428 * Includes a javascript library that exists in the core /typo3/ directory. The
1429 * backpath is automatically applied.
1430 * This method acts as wrapper for $GLOBALS['SOBE']->doc->loadJavascriptLib($lib).
1431 *
1432 * @param string $lib Library name. Call it with the full path like "contrib/prototype/prototype.js" to load it
1433 * @return void
1434 */
1435 public function loadJavascriptLib($lib) {
1436 $this->getControllerDocumentTemplate()->loadJavascriptLib($lib);
1437 }
1438
1439 /********************************************
1440 *
1441 * Various helper functions
1442 *
1443 ********************************************/
1444
1445 /**
1446 * Return record path (visually formatted, using BackendUtility::getRecordPath() )
1447 *
1448 * @param string $table Table name
1449 * @param array $rec Record array
1450 * @return string The record path.
1451 * @see BackendUtility::getRecordPath()
1452 */
1453 public function getRecordPath($table, $rec) {
1454 BackendUtility::fixVersioningPid($table, $rec);
1455 list($tscPID, $thePidValue) = BackendUtility::getTSCpidCached($table, $rec['uid'], $rec['pid']);
1456 if ($thePidValue >= 0) {
1457 return BackendUtility::getRecordPath($tscPID, $this->readPerms(), 15);
1458 }
1459 return '';
1460 }
1461
1462 /**
1463 * Returns the select-page read-access SQL clause.
1464 * Returns cached string, so you can call this function as much as you like without performance loss.
1465 *
1466 * @return string
1467 */
1468 public function readPerms() {
1469 if (!$this->perms_clause_set) {
1470 $this->perms_clause = $this->getBackendUserAuthentication()->getPagePermsClause(1);
1471 $this->perms_clause_set = TRUE;
1472 }
1473 return $this->perms_clause;
1474 }
1475
1476 /**
1477 * Returns TRUE if descriptions should be loaded always
1478 *
1479 * @param string $table Table for which to check
1480 * @return bool
1481 */
1482 public function doLoadTableDescr($table) {
1483 return $GLOBALS['TCA'][$table]['interface']['always_description'];
1484 }
1485
1486 /**
1487 * Initialize list of additional preview languages.
1488 * Sets according list in $this->additionalPreviewLanguages
1489 *
1490 * @return void
1491 */
1492 protected function initializeAdditionalPreviewLanguages() {
1493 $backendUserAuthentication = $this->getBackendUserAuthentication();
1494 $additionalPreviewLanguageListOfUser = $backendUserAuthentication->getTSConfigVal('options.additionalPreviewLanguages');
1495 $additionalPreviewLanguages = array();
1496 if ($additionalPreviewLanguageListOfUser) {
1497 $uids = GeneralUtility::intExplode(',', $additionalPreviewLanguageListOfUser);
1498 foreach ($uids as $uid) {
1499 if ($sys_language_rec = BackendUtility::getRecord('sys_language', $uid)) {
1500 $additionalPreviewLanguages[$uid]['uid'] = $uid;
1501 if (!empty($sys_language_rec['language_isocode'])) {
1502 $additionalPreviewLanguages[$uid]['ISOcode'] = $sys_language_rec['language_isocode'];
1503 } elseif ($sys_language_rec['static_lang_isocode'] && ExtensionManagementUtility::isLoaded('static_info_tables')) {
1504 GeneralUtility::deprecationLog('Usage of the field "static_lang_isocode" is discouraged, and will stop working with CMS 8. Use the built-in language field "language_isocode" in your sys_language records.');
1505 $staticLangRow = BackendUtility::getRecord('static_languages', $sys_language_rec['static_lang_isocode'], 'lg_iso_2');
1506 if ($staticLangRow['lg_iso_2']) {
1507 $additionalPreviewLanguages[$uid]['ISOcode'] = $staticLangRow['lg_iso_2'];
1508 }
1509 }
1510 }
1511 }
1512 }
1513 $this->additionalPreviewLanguages = $additionalPreviewLanguages;
1514 }
1515
1516 /**
1517 * @return BackendUserAuthentication
1518 */
1519 protected function getBackendUserAuthentication() {
1520 return $GLOBALS['BE_USER'];
1521 }
1522
1523 /**
1524 * @return DocumentTemplate
1525 */
1526 protected function getControllerDocumentTemplate() {
1527 // $GLOBALS['SOBE'] might be any kind of PHP class (controller most of the times)
1528 // These class do not inherit from any common class, but they all seem to have a "doc" member
1529 return $GLOBALS['SOBE']->doc;
1530 }
1531
1532 /**
1533 * @return LanguageService
1534 */
1535 protected function getLanguageService() {
1536 return $GLOBALS['LANG'];
1537 }
1538
1539 /**
1540 * Wrapper for access to the current page renderer object
1541 *
1542 * @return \TYPO3\CMS\Core\Page\PageRenderer
1543 */
1544 protected function getPageRenderer() {
1545 return $this->getControllerDocumentTemplate()->getPageRenderer();
1546 }
1547
1548 }