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