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