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