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