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