8c6493c04efd15da84e02b4ce20f07d6d20ff70f
[Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Classes / Controller / FormInlineAjaxController.php
1 <?php
2 namespace TYPO3\CMS\Backend\Controller;
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 Psr\Http\Message\ResponseInterface;
18 use Psr\Http\Message\ServerRequestInterface;
19 use TYPO3\CMS\Backend\Form\FormDataCompiler;
20 use TYPO3\CMS\Backend\Form\FormDataGroup\InlineParentRecord;
21 use TYPO3\CMS\Backend\Form\FormDataGroup\TcaDatabaseRecord;
22 use TYPO3\CMS\Backend\Form\InlineStackProcessor;
23 use TYPO3\CMS\Backend\Form\NodeFactory;
24 use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
25 use TYPO3\CMS\Core\DataHandling\DataHandler;
26 use TYPO3\CMS\Core\Utility\GeneralUtility;
27 use TYPO3\CMS\Core\Utility\MathUtility;
28
29 /**
30 * Handle FormEngine inline ajax calls
31 */
32 class FormInlineAjaxController
33 {
34 /**
35 * Create a new inline child via AJAX.
36 *
37 * @param ServerRequestInterface $request
38 * @param ResponseInterface $response
39 * @return ResponseInterface
40 */
41 public function createAction(ServerRequestInterface $request, ResponseInterface $response)
42 {
43 $ajaxArguments = isset($request->getParsedBody()['ajax']) ? $request->getParsedBody()['ajax'] : $request->getQueryParams()['ajax'];
44
45 $domObjectId = $ajaxArguments[0];
46 $inlineFirstPid = $this->getInlineFirstPidFromDomObjectId($domObjectId);
47 $childChildUid = null;
48 if (isset($ajaxArguments[1]) && MathUtility::canBeInterpretedAsInteger($ajaxArguments[1])) {
49 $childChildUid = (int)$ajaxArguments[1];
50 }
51
52 // Parse the DOM identifier, add the levels to the structure stack
53 /** @var InlineStackProcessor $inlineStackProcessor */
54 $inlineStackProcessor = GeneralUtility::makeInstance(InlineStackProcessor::class);
55 $inlineStackProcessor->initializeByParsingDomObjectIdString($domObjectId);
56 $inlineStackProcessor->injectAjaxConfiguration($ajaxArguments['context']);
57
58 // Parent, this table embeds the child table
59 $parent = $inlineStackProcessor->getStructureLevel(-1);
60 $parentFieldName = $parent['field'];
61
62 if (MathUtility::canBeInterpretedAsInteger($parent['uid'])) {
63 $command = 'edit';
64 $vanillaUid = (int)$parent['uid'];
65 $databaseRow = [
66 // TcaInlineExpandCollapseState needs the record uid
67 'uid' => (int)$parent['uid'],
68 ];
69 } else {
70 $command = 'new';
71 $databaseRow = [];
72 $vanillaUid = (int)$inlineFirstPid;
73 }
74 $formDataCompilerInputForParent = [
75 'vanillaUid' => $vanillaUid,
76 'command' => $command,
77 'tableName' => $parent['table'],
78 'databaseRow' => $databaseRow,
79 'inlineFirstPid' => $inlineFirstPid,
80 'columnsToProcess' => [
81 $parentFieldName
82 ],
83 // Do not resolve existing children, we don't need them now
84 'inlineResolveExistingChildren' => false,
85 ];
86 /** @var TcaDatabaseRecord $formDataGroup */
87 $formDataGroup = GeneralUtility::makeInstance(InlineParentRecord::class);
88 /** @var FormDataCompiler $formDataCompiler */
89 $formDataCompiler = GeneralUtility::makeInstance(FormDataCompiler::class, $formDataGroup);
90 $parentData = $formDataCompiler->compile($formDataCompilerInputForParent);
91 $parentConfig = $parentData['processedTca']['columns'][$parentFieldName]['config'];
92
93 // Child, a record from this table should be rendered
94 $child = $inlineStackProcessor->getUnstableStructure();
95 if (MathUtility::canBeInterpretedAsInteger($child['uid'])) {
96 // If uid comes in, it is the id of the record neighbor record "create after"
97 $childVanillaUid = -1 * abs((int)$child['uid']);
98 } else {
99 // Else inline first Pid is the storage pid of new inline records
100 $childVanillaUid = (int)$inlineFirstPid;
101 }
102
103 if ($parentConfig['type'] === 'flex') {
104 $parentConfig = $this->getParentConfigFromFlexForm($parentConfig, $domObjectId);
105 }
106 $childTableName = $parentConfig['foreign_table'];
107
108 /** @var TcaDatabaseRecord $formDataGroup */
109 $formDataGroup = GeneralUtility::makeInstance(TcaDatabaseRecord::class);
110 /** @var FormDataCompiler $formDataCompiler */
111 $formDataCompiler = GeneralUtility::makeInstance(FormDataCompiler::class, $formDataGroup);
112 $formDataCompilerInput = [
113 'command' => 'new',
114 'tableName' => $childTableName,
115 'vanillaUid' => $childVanillaUid,
116 'isInlineChild' => true,
117 'inlineStructure' => $inlineStackProcessor->getStructure(),
118 'inlineFirstPid' => $inlineFirstPid,
119 'inlineParentUid' => $parent['uid'],
120 'inlineParentTableName' => $parent['table'],
121 'inlineParentFieldName' => $parent['field'],
122 'inlineParentConfig' => $parentConfig,
123 ];
124 if ($childChildUid) {
125 $formDataCompilerInput['inlineChildChildUid'] = $childChildUid;
126 }
127 $childData = $formDataCompiler->compile($formDataCompilerInput);
128
129 // Set language of new child record to the language of the parent record:
130 // @todo: To my understanding, the below case can't happen: With localizationMode select, lang overlays
131 // @todo: of children are only created with the "synchronize" button that will trigger a different ajax action.
132 // @todo: The edge case of new page overlay together with localized media field, this code won't kick in either.
133 /**
134 if ($parent['localizationMode'] === 'select' && MathUtility::canBeInterpretedAsInteger($parent['uid'])) {
135 $parentRecord = $inlineRelatedRecordResolver->getRecord($parent['table'], $parent['uid']);
136 $parentLanguageField = $GLOBALS['TCA'][$parent['table']]['ctrl']['languageField'];
137 $childLanguageField = $GLOBALS['TCA'][$child['table']]['ctrl']['languageField'];
138 if ($parentRecord[$parentLanguageField] > 0) {
139 $record[$childLanguageField] = $parentRecord[$parentLanguageField];
140 }
141 }
142 */
143 if ($parentConfig['foreign_selector'] && $parentConfig['appearance']['useCombination']) {
144 // We have a foreign_selector. So, we just created a new record on an intermediate table in $mainChild.
145 // Now, if a valid id is given as second ajax parameter, the intermediate row should be connected to an
146 // existing record of the child-child table specified by the given uid. If there is no such id, user
147 // clicked on "created new" and a new child-child should be created, too.
148 if ($childChildUid) {
149 // Fetch existing child child
150 $childData['databaseRow'][$parentConfig['foreign_selector']] = [
151 $childChildUid,
152 ];
153 $childData['combinationChild'] = $this->compileCombinationChild($childData, $parentConfig);
154 } else {
155 /** @var TcaDatabaseRecord $formDataGroup */
156 $formDataGroup = GeneralUtility::makeInstance(TcaDatabaseRecord::class);
157 /** @var FormDataCompiler $formDataCompiler */
158 $formDataCompiler = GeneralUtility::makeInstance(FormDataCompiler::class, $formDataGroup);
159 $formDataCompilerInput = [
160 'command' => 'new',
161 'tableName' => $childData['processedTca']['columns'][$parentConfig['foreign_selector']]['config']['foreign_table'],
162 'vanillaUid' => (int)$inlineFirstPid,
163 'inlineFirstPid' => (int)$inlineFirstPid,
164 ];
165 $childData['combinationChild'] = $formDataCompiler->compile($formDataCompilerInput);
166 }
167 }
168
169 $childData['inlineParentUid'] = (int)$parent['uid'];
170 $childData['renderType'] = 'inlineRecordContainer';
171 $nodeFactory = GeneralUtility::makeInstance(NodeFactory::class);
172 $childResult = $nodeFactory->create($childData)->render();
173
174 $jsonArray = [
175 'data' => '',
176 'stylesheetFiles' => [],
177 'scriptCall' => [],
178 ];
179
180 // The HTML-object-id's prefix of the dynamically created record
181 $objectName = $inlineStackProcessor->getCurrentStructureDomObjectIdPrefix($inlineFirstPid);
182 $objectPrefix = $objectName . '-' . $child['table'];
183 $objectId = $objectPrefix . '-' . $childData['databaseRow']['uid'];
184 $expandSingle = $parentConfig['appearance']['expandSingle'];
185 if (!$child['uid']) {
186 $jsonArray['scriptCall'][] = 'inline.domAddNewRecord(\'bottom\',' . GeneralUtility::quoteJSvalue($objectName . '_records') . ',' . GeneralUtility::quoteJSvalue($objectPrefix) . ',json.data);';
187 $jsonArray['scriptCall'][] = 'inline.memorizeAddRecord(' . GeneralUtility::quoteJSvalue($objectPrefix) . ',' . GeneralUtility::quoteJSvalue($childData['databaseRow']['uid']) . ',null,' . GeneralUtility::quoteJSvalue($childChildUid) . ');';
188 } else {
189 $jsonArray['scriptCall'][] = 'inline.domAddNewRecord(\'after\',' . GeneralUtility::quoteJSvalue($domObjectId . '_div') . ',' . GeneralUtility::quoteJSvalue($objectPrefix) . ',json.data);';
190 $jsonArray['scriptCall'][] = 'inline.memorizeAddRecord(' . GeneralUtility::quoteJSvalue($objectPrefix) . ',' . GeneralUtility::quoteJSvalue($childData['databaseRow']['uid']) . ',' . GeneralUtility::quoteJSvalue($child['uid']) . ',' . GeneralUtility::quoteJSvalue($childChildUid) . ');';
191 }
192 $jsonArray = $this->mergeChildResultIntoJsonResult($jsonArray, $childResult);
193 if ($parentConfig['appearance']['useSortable']) {
194 $inlineObjectName = $inlineStackProcessor->getCurrentStructureDomObjectIdPrefix($inlineFirstPid);
195 $jsonArray['scriptCall'][] = 'inline.createDragAndDropSorting(' . GeneralUtility::quoteJSvalue($inlineObjectName . '_records') . ');';
196 }
197 if (!$parentConfig['appearance']['collapseAll'] && $expandSingle) {
198 $jsonArray['scriptCall'][] = 'inline.collapseAllRecords(' . GeneralUtility::quoteJSvalue($objectId) . ',' . GeneralUtility::quoteJSvalue($objectPrefix) . ',' . GeneralUtility::quoteJSvalue($childData['databaseRow']['uid']) . ');';
199 }
200 // Fade out and fade in the new record in the browser view to catch the user's eye
201 $jsonArray['scriptCall'][] = 'inline.fadeOutFadeIn(' . GeneralUtility::quoteJSvalue($objectId . '_div') . ');';
202
203 $response->getBody()->write(json_encode($jsonArray));
204
205 return $response;
206 }
207
208 /**
209 * Show the details of a child record.
210 *
211 * @param ServerRequestInterface $request
212 * @param ResponseInterface $response
213 * @return ResponseInterface
214 */
215 public function detailsAction(ServerRequestInterface $request, ResponseInterface $response)
216 {
217 $ajaxArguments = isset($request->getParsedBody()['ajax']) ? $request->getParsedBody()['ajax'] : $request->getQueryParams()['ajax'];
218
219 $domObjectId = $ajaxArguments[0];
220 $inlineFirstPid = $this->getInlineFirstPidFromDomObjectId($domObjectId);
221
222 // Parse the DOM identifier, add the levels to the structure stack
223 /** @var InlineStackProcessor $inlineStackProcessor */
224 $inlineStackProcessor = GeneralUtility::makeInstance(InlineStackProcessor::class);
225 $inlineStackProcessor->initializeByParsingDomObjectIdString($domObjectId);
226 $inlineStackProcessor->injectAjaxConfiguration($ajaxArguments['context']);
227
228 // Parent, this table embeds the child table
229 $parent = $inlineStackProcessor->getStructureLevel(-1);
230 $parentFieldName = $parent['field'];
231
232 $formDataCompilerInputForParent = [
233 'vanillaUid' => (int)$parent['uid'],
234 'command' => 'edit',
235 'tableName' => $parent['table'],
236 'databaseRow' => [
237 // TcaInlineExpandCollapseState needs this
238 'uid' => (int)$parent['uid'],
239 ],
240 'inlineFirstPid' => $inlineFirstPid,
241 'columnsToProcess' => [
242 $parentFieldName
243 ],
244 // @todo: still needed?
245 'inlineStructure' => $inlineStackProcessor->getStructure(),
246 // Do not resolve existing children, we don't need them now
247 'inlineResolveExistingChildren' => false,
248 ];
249 /** @var TcaDatabaseRecord $formDataGroup */
250 $formDataGroup = GeneralUtility::makeInstance(InlineParentRecord::class);
251 /** @var FormDataCompiler $formDataCompiler */
252 $formDataCompiler = GeneralUtility::makeInstance(FormDataCompiler::class, $formDataGroup);
253 $parentData = $formDataCompiler->compile($formDataCompilerInputForParent);
254 // Set flag in config so that only the fields are rendered
255 // @todo: Solve differently / rename / whatever
256 $parentData['processedTca']['columns'][$parentFieldName]['config']['renderFieldsOnly'] = true;
257 $parentConfig = $parentData['processedTca']['columns'][$parentFieldName]['config'];
258
259 // Child, a record from this table should be rendered
260 $child = $inlineStackProcessor->getUnstableStructure();
261
262 $childData = $this->compileChild($parentData, $parentFieldName, (int)$child['uid'], $inlineStackProcessor->getStructure());
263
264 $childData['inlineParentUid'] = (int)$parent['uid'];
265 $childData['renderType'] = 'inlineRecordContainer';
266 $nodeFactory = GeneralUtility::makeInstance(NodeFactory::class);
267 $childResult = $nodeFactory->create($childData)->render();
268
269 $jsonArray = [
270 'data' => '',
271 'stylesheetFiles' => [],
272 'scriptCall' => [],
273 ];
274
275 // The HTML-object-id's prefix of the dynamically created record
276 $objectPrefix = $inlineStackProcessor->getCurrentStructureDomObjectIdPrefix($inlineFirstPid) . '-' . $child['table'];
277 $objectId = $objectPrefix . '-' . (int)$child['uid'];
278 $expandSingle = $parentConfig['appearance']['expandSingle'];
279 $jsonArray['scriptCall'][] = 'inline.domAddRecordDetails(' . GeneralUtility::quoteJSvalue($domObjectId) . ',' . GeneralUtility::quoteJSvalue($objectPrefix) . ',' . ($expandSingle ? '1' : '0') . ',json.data);';
280 if ($parentConfig['foreign_unique']) {
281 $jsonArray['scriptCall'][] = 'inline.removeUsed(' . GeneralUtility::quoteJSvalue($objectPrefix) . ',\'' . (int)$child['uid'] . '\');';
282 }
283 $jsonArray = $this->mergeChildResultIntoJsonResult($jsonArray, $childResult);
284 if ($parentConfig['appearance']['useSortable']) {
285 $inlineObjectName = $inlineStackProcessor->getCurrentStructureDomObjectIdPrefix($inlineFirstPid);
286 $jsonArray['scriptCall'][] = 'inline.createDragAndDropSorting(' . GeneralUtility::quoteJSvalue($inlineObjectName . '_records') . ');';
287 }
288 if (!$parentConfig['appearance']['collapseAll'] && $expandSingle) {
289 $jsonArray['scriptCall'][] = 'inline.collapseAllRecords(' . GeneralUtility::quoteJSvalue($objectId) . ',' . GeneralUtility::quoteJSvalue($objectPrefix) . ',\'' . (int)$child['uid'] . '\');';
290 }
291
292 $response->getBody()->write(json_encode($jsonArray));
293
294 return $response;
295 }
296
297 /**
298 * Adds localizations or synchronizes the locations of all child records.
299 * Handle AJAX calls to localize all records of a parent, localize a single record or to synchronize with the original language parent.
300 *
301 * @param ServerRequestInterface $request the incoming request
302 * @param ResponseInterface $response the empty response
303 * @return ResponseInterface the filled response
304 */
305 public function synchronizeLocalizeAction(ServerRequestInterface $request, ResponseInterface $response)
306 {
307 $ajaxArguments = isset($request->getParsedBody()['ajax']) ? $request->getParsedBody()['ajax'] : $request->getQueryParams()['ajax'];
308 $domObjectId = $ajaxArguments[0];
309 $type = $ajaxArguments[1];
310
311 /** @var InlineStackProcessor $inlineStackProcessor */
312 $inlineStackProcessor = GeneralUtility::makeInstance(InlineStackProcessor::class);
313 // Parse the DOM identifier (string), add the levels to the structure stack (array), load the TCA config:
314 $inlineStackProcessor->initializeByParsingDomObjectIdString($domObjectId);
315 $inlineStackProcessor->injectAjaxConfiguration($ajaxArguments['context']);
316 $inlineFirstPid = $this->getInlineFirstPidFromDomObjectId($domObjectId);
317
318 $jsonArray = false;
319 if ($type === 'localize' || $type === 'synchronize' || MathUtility::canBeInterpretedAsInteger($type)) {
320 // Parent, this table embeds the child table
321 $parent = $inlineStackProcessor->getStructureLevel(-1);
322 $parentFieldName = $parent['field'];
323
324 // Child, a record from this table should be rendered
325 $child = $inlineStackProcessor->getUnstableStructure();
326
327 $formDataCompilerInputForParent = [
328 'vanillaUid' => (int)$parent['uid'],
329 'command' => 'edit',
330 'tableName' => $parent['table'],
331 'databaseRow' => [
332 // TcaInlineExpandCollapseState needs this
333 'uid' => (int)$parent['uid'],
334 ],
335 'inlineFirstPid' => $inlineFirstPid,
336 'columnsToProcess' => [
337 $parentFieldName
338 ],
339 // @todo: still needed? NO!
340 'inlineStructure' => $inlineStackProcessor->getStructure(),
341 // Do not compile existing children, we don't need them now
342 'inlineCompileExistingChildren' => false,
343 ];
344 // Full TcaDatabaseRecord is required here to have the list of connected uids $oldItemList
345 /** @var TcaDatabaseRecord $formDataGroup */
346 $formDataGroup = GeneralUtility::makeInstance(TcaDatabaseRecord::class);
347 /** @var FormDataCompiler $formDataCompiler */
348 $formDataCompiler = GeneralUtility::makeInstance(FormDataCompiler::class, $formDataGroup);
349 $parentData = $formDataCompiler->compile($formDataCompilerInputForParent);
350 $parentConfig = $parentData['processedTca']['columns'][$parentFieldName]['config'];
351 $oldItemList = $parentData['databaseRow'][$parentFieldName];
352
353 $cmd = array();
354 $cmd[$parent['table']][$parent['uid']]['inlineLocalizeSynchronize'] = $parent['field'] . ',' . $type;
355 /** @var $tce DataHandler */
356 $tce = GeneralUtility::makeInstance(DataHandler::class);
357 $tce->stripslashes_values = false;
358 $tce->start(array(), $cmd);
359 $tce->process_cmdmap();
360
361 $newItemList = $tce->registerDBList[$parent['table']][$parent['uid']][$parentFieldName];
362
363 $jsonArray = array(
364 'data' => '',
365 'stylesheetFiles' => [],
366 'scriptCall' => [],
367 );
368 $nameObject = $inlineStackProcessor->getCurrentStructureDomObjectIdPrefix($inlineFirstPid);
369 $nameObjectForeignTable = $nameObject . '-' . $child['table'];
370
371 $oldItems = $this->getInlineRelatedRecordsUidArray($oldItemList);
372 $newItems = $this->getInlineRelatedRecordsUidArray($newItemList);
373
374 // Set the items that should be removed in the forms view:
375 $removedItems = array_diff($oldItems, $newItems);
376 foreach ($removedItems as $childUid) {
377 $jsonArray['scriptCall'][] = 'inline.deleteRecord(' . GeneralUtility::quoteJSvalue($nameObjectForeignTable . '-' . $childUid) . ', {forceDirectRemoval: true});';
378 }
379
380 $localizedItems = array_diff($newItems, $oldItems);
381 foreach ($localizedItems as $childUid) {
382 $childData = $this->compileChild($parentData, $parentFieldName, (int)$childUid, $inlineStackProcessor->getStructure());
383
384 $childData['inlineParentUid'] = (int)$parent['uid'];
385 $childData['renderType'] = 'inlineRecordContainer';
386 $nodeFactory = GeneralUtility::makeInstance(NodeFactory::class);
387 $childResult = $nodeFactory->create($childData)->render();
388
389 $jsonArray = $this->mergeChildResultIntoJsonResult($jsonArray, $childResult);
390
391 // Get the name of the field used as foreign selector (if any):
392 $foreignSelector = isset($parentConfig['foreign_selector']) && $parentConfig['foreign_selector'] ? $parentConfig['foreign_selector'] : false;
393 $selectedValue = $foreignSelector ? GeneralUtility::quoteJSvalue($childData['databaseRow'][$foreignSelector]) : 'null';
394 if (is_array($selectedValue)) {
395 $selectedValue = $selectedValue[0];
396 }
397 $jsonArray['scriptCall'][] = 'inline.memorizeAddRecord(' . GeneralUtility::quoteJSvalue($nameObjectForeignTable) . ', ' . GeneralUtility::quoteJSvalue($childUid) . ', null, ' . $selectedValue . ');';
398 // Remove possible virtual records in the form which showed that a child records could be localized:
399 $transOrigPointerFieldName = $childData['processedTca']['ctrl']['transOrigPointerField'];
400 if (isset($childData['databaseRow'][$transOrigPointerFieldName]) && $childData['databaseRow'][$transOrigPointerFieldName]) {
401 $transOrigPointerField = $childData['databaseRow'][$transOrigPointerFieldName];
402 if (is_array($transOrigPointerField)) {
403 $transOrigPointerField = $transOrigPointerField[0];
404 }
405 $jsonArray['scriptCall'][] = 'inline.fadeAndRemove(' . GeneralUtility::quoteJSvalue($nameObjectForeignTable . '-' . $transOrigPointerField . '_div') . ');';
406 }
407 }
408 // Tell JS to add new HTML of one or multiple (localize all) records to DOM
409 if (!empty($jsonArray['data'])) {
410 array_push(
411 $jsonArray['scriptCall'],
412 'inline.domAddNewRecord(\'bottom\', ' . GeneralUtility::quoteJSvalue($nameObject . '_records')
413 . ', ' . GeneralUtility::quoteJSvalue($nameObjectForeignTable)
414 . ', json.data);'
415 );
416 }
417 }
418
419 $response->getBody()->write(json_encode($jsonArray));
420
421 return $response;
422 }
423
424 /**
425 * Adds localizations or synchronizes the locations of all child records.
426 *
427 * @param ServerRequestInterface $request the incoming request
428 * @param ResponseInterface $response the empty response
429 * @return ResponseInterface the filled response
430 */
431 public function expandOrCollapseAction(ServerRequestInterface $request, ResponseInterface $response)
432 {
433 $ajaxArguments = isset($request->getParsedBody()['ajax']) ? $request->getParsedBody()['ajax'] : $request->getQueryParams()['ajax'];
434 $domObjectId = $ajaxArguments[0];
435
436 /** @var InlineStackProcessor $inlineStackProcessor */
437 $inlineStackProcessor = GeneralUtility::makeInstance(InlineStackProcessor::class);
438 // Parse the DOM identifier (string), add the levels to the structure stack (array), don't load TCA config
439 $inlineStackProcessor->initializeByParsingDomObjectIdString($domObjectId);
440 $expand = $ajaxArguments[1];
441 $collapse = $ajaxArguments[2];
442
443 $backendUser = $this->getBackendUserAuthentication();
444 // The current table - for this table we should add/import records
445 $currentTable = $inlineStackProcessor->getUnstableStructure();
446 $currentTable = $currentTable['table'];
447 // The top parent table - this table embeds the current table
448 $top = $inlineStackProcessor->getStructureLevel(0);
449 $topTable = $top['table'];
450 $topUid = $top['uid'];
451 $inlineView = $this->getInlineExpandCollapseStateArray();
452 // Only do some action if the top record and the current record were saved before
453 if (MathUtility::canBeInterpretedAsInteger($topUid)) {
454 $expandUids = GeneralUtility::trimExplode(',', $expand);
455 $collapseUids = GeneralUtility::trimExplode(',', $collapse);
456 // Set records to be expanded
457 foreach ($expandUids as $uid) {
458 $inlineView[$topTable][$topUid][$currentTable][] = $uid;
459 }
460 // Set records to be collapsed
461 foreach ($collapseUids as $uid) {
462 $inlineView[$topTable][$topUid][$currentTable] = $this->removeFromArray($uid, $inlineView[$topTable][$topUid][$currentTable]);
463 }
464 // Save states back to database
465 if (is_array($inlineView[$topTable][$topUid][$currentTable])) {
466 $inlineView[$topTable][$topUid][$currentTable] = array_unique($inlineView[$topTable][$topUid][$currentTable]);
467 $backendUser->uc['inlineView'] = serialize($inlineView);
468 $backendUser->writeUC();
469 }
470 }
471
472 $response->getBody()->write(json_encode(array()));
473 return $response;
474 }
475
476 /**
477 * Compile a full child record
478 *
479 * @param array $parentData Result array of parent
480 * @param string $parentFieldName Name of parent field
481 * @param int $childUid Uid of child to compile
482 * @param array $inlineStructure Current inline structure
483 * @return array Full result array
484 *
485 * @todo: This clones methods compileChild and compileCombinationChild from TcaInline Provider.
486 * @todo: Find something around that, eg. some option to force TcaInline provider to calculate a
487 * @todo: specific forced-open element only :)
488 */
489 protected function compileChild(array $parentData, $parentFieldName, $childUid, array $inlineStructure)
490 {
491 $parentConfig = $parentData['processedTca']['columns'][$parentFieldName]['config'];
492
493 /** @var InlineStackProcessor $inlineStackProcessor */
494 $inlineStackProcessor = GeneralUtility::makeInstance(InlineStackProcessor::class);
495 $inlineStackProcessor->initializeByGivenStructure($inlineStructure);
496 $inlineTopMostParent = $inlineStackProcessor->getStructureLevel(0);
497
498 // @todo: do not use stack processor here ...
499 $child = $inlineStackProcessor->getUnstableStructure();
500 $childTableName = $child['table'];
501
502 /** @var TcaDatabaseRecord $formDataGroup */
503 $formDataGroup = GeneralUtility::makeInstance(TcaDatabaseRecord::class);
504 /** @var FormDataCompiler $formDataCompiler */
505 $formDataCompiler = GeneralUtility::makeInstance(FormDataCompiler::class, $formDataGroup);
506 $formDataCompilerInput = [
507 'command' => 'edit',
508 'tableName' => $childTableName,
509 'vanillaUid' => (int)$childUid,
510 'isInlineChild' => true,
511 'inlineStructure' => $inlineStructure,
512 'inlineFirstPid' => $parentData['inlineFirstPid'],
513 'inlineParentConfig' => $parentConfig,
514 'isInlineAjaxOpeningContext' => true,
515
516 // values of the current parent element
517 // it is always a string either an id or new...
518 'inlineParentUid' => $parentData['databaseRow']['uid'],
519 'inlineParentTableName' => $parentData['tableName'],
520 'inlineParentFieldName' => $parentFieldName,
521
522 // values of the top most parent element set on first level and not overridden on following levels
523 'inlineTopMostParentUid' => $parentData['inlineTopMostParentUid'] ?: $inlineTopMostParent['uid'],
524 'inlineTopMostParentTableName' => $parentData['inlineTopMostParentTableName'] ?: $inlineTopMostParent['table'],
525 'inlineTopMostParentFieldName' => $parentData['inlineTopMostParentFieldName'] ?: $inlineTopMostParent['field'],
526 ];
527 // For foreign_selector with useCombination $mainChild is the mm record
528 // and $combinationChild is the child-child. For "normal" relations, $mainChild
529 // is just the normal child record and $combinationChild is empty.
530 $mainChild = $formDataCompiler->compile($formDataCompilerInput);
531 if ($parentConfig['foreign_selector'] && $parentConfig['appearance']['useCombination']) {
532 $mainChild['combinationChild'] = $this->compileCombinationChild($mainChild, $parentConfig, $inlineStructure);
533 }
534 return $mainChild;
535 }
536
537 /**
538 * With useCombination set, not only content of the intermediate table, but also
539 * the connected child should be rendered in one go. Prepare this here.
540 *
541 * @param array $intermediate Full data array of "mm" record
542 * @param array $parentConfig TCA configuration of "parent"
543 * @param array $inlineStructure Current inline structure
544 * @return array Full data array of child
545 */
546 protected function compileCombinationChild(array $intermediate, array $parentConfig, array $inlineStructure)
547 {
548 // foreign_selector on intermediate is probably type=select, so data provider of this table resolved that to the uid already
549 $intermediateUid = $intermediate['databaseRow'][$parentConfig['foreign_selector']][0];
550 $combinationChild = $this->compileChild($intermediate, $parentConfig['foreign_selector'], $intermediateUid, $inlineStructure);
551 return $combinationChild;
552 }
553
554 /**
555 * Merge stuff from child array into json array.
556 * This method is needed since ajax handling methods currently need to put scriptCalls before and after child code.
557 *
558 * @param array $jsonResult Given json result
559 * @param array $childResult Given child result
560 * @return array Merged json array
561 */
562 protected function mergeChildResultIntoJsonResult(array $jsonResult, array $childResult)
563 {
564 $jsonResult['data'] .= $childResult['html'];
565 $jsonResult['stylesheetFiles'] = $childResult['stylesheetFiles'];
566 if (!empty($childResult['inlineData'])) {
567 $jsonResult['scriptCall'][] = 'inline.addToDataArray(' . json_encode($childResult['inlineData']) . ');';
568 }
569 if (!empty($childResult['additionalJavaScriptSubmit'])) {
570 $additionalJavaScriptSubmit = implode('', $childResult['additionalJavaScriptSubmit']);
571 $additionalJavaScriptSubmit = str_replace(array(CR, LF), '', $additionalJavaScriptSubmit);
572 $jsonResult['scriptCall'][] = 'TBE_EDITOR.addActionChecks("submit", "' . addslashes($additionalJavaScriptSubmit) . '");';
573 }
574 foreach ($childResult['additionalJavaScriptPost'] as $singleAdditionalJavaScriptPost) {
575 $jsonResult['scriptCall'][] = $singleAdditionalJavaScriptPost;
576 }
577 $jsonResult['scriptCall'][] = $childResult['extJSCODE'];
578 if (!empty($childResult['requireJsModules'])) {
579 foreach ($childResult['requireJsModules'] as $module) {
580 $moduleName = null;
581 $callback = null;
582 if (is_string($module)) {
583 // if $module is a string, no callback
584 $moduleName = $module;
585 $callback = null;
586 } elseif (is_array($module)) {
587 // if $module is an array, callback is possible
588 foreach ($module as $key => $value) {
589 $moduleName = $key;
590 $callback = $value;
591 break;
592 }
593 }
594 if ($moduleName !== null) {
595 $inlineCodeKey = $moduleName;
596 $javaScriptCode = 'require(["' . $moduleName . '"]';
597 if ($callback !== null) {
598 $inlineCodeKey .= sha1($callback);
599 $javaScriptCode .= ', ' . $callback;
600 }
601 $javaScriptCode .= ');';
602 $jsonResult['scriptCall'][] = '/*RequireJS-Module-' . $inlineCodeKey . '*/' . LF . $javaScriptCode;
603 }
604 }
605 }
606 return $jsonResult;
607 }
608
609 /**
610 * Gets an array with the uids of related records out of a list of items.
611 * This list could contain more information than required. This methods just
612 * extracts the uids.
613 *
614 * @param string $itemList The list of related child records
615 * @return array An array with uids
616 */
617 protected function getInlineRelatedRecordsUidArray($itemList)
618 {
619 $itemArray = GeneralUtility::trimExplode(',', $itemList, true);
620 // Perform modification of the selected items array:
621 foreach ($itemArray as &$value) {
622 $parts = explode('|', $value, 2);
623 $value = $parts[0];
624 }
625 unset($value);
626 return $itemArray;
627 }
628
629 /**
630 * Checks if a record selector may select a certain file type
631 *
632 * @param array $selectorConfiguration
633 * @param array $fileRecord
634 * @return bool
635 * @todo: check this ...
636 */
637 protected function checkInlineFileTypeAccessForField(array $selectorConfiguration, array $fileRecord)
638 {
639 if (!empty($selectorConfiguration['PA']['fieldConf']['config']['appearance']['elementBrowserAllowed'])) {
640 $allowedFileExtensions = GeneralUtility::trimExplode(
641 ',',
642 $selectorConfiguration['PA']['fieldConf']['config']['appearance']['elementBrowserAllowed'],
643 true
644 );
645 if (!in_array(strtolower($fileRecord['extension']), $allowedFileExtensions, true)) {
646 return false;
647 }
648 }
649 return true;
650 }
651
652 /**
653 * Return expand / collapse state array for a given table / uid combination
654 *
655 * @param string $table Handled table
656 * @param int $uid Handled uid
657 * @return array
658 */
659 protected function getInlineExpandCollapseStateArrayForTableUid($table, $uid)
660 {
661 $inlineView = $this->getInlineExpandCollapseStateArray();
662 $result = array();
663 if (MathUtility::canBeInterpretedAsInteger($uid)) {
664 if (!empty($inlineView[$table][$uid])) {
665 $result = $inlineView[$table][$uid];
666 }
667 }
668 return $result;
669 }
670
671 /**
672 * Get expand / collapse state of inline items
673 *
674 * @return array
675 */
676 protected function getInlineExpandCollapseStateArray()
677 {
678 $backendUser = $this->getBackendUserAuthentication();
679 $inlineView = unserialize($backendUser->uc['inlineView']);
680 if (!is_array($inlineView)) {
681 $inlineView = array();
682 }
683 return $inlineView;
684 }
685
686 /**
687 * Remove an element from an array.
688 *
689 * @param mixed $needle The element to be removed.
690 * @param array $haystack The array the element should be removed from.
691 * @param mixed $strict Search elements strictly.
692 * @return array The array $haystack without the $needle
693 */
694 protected function removeFromArray($needle, $haystack, $strict = null)
695 {
696 $pos = array_search($needle, $haystack, $strict);
697 if ($pos !== false) {
698 unset($haystack[$pos]);
699 }
700 return $haystack;
701 }
702
703 /**
704 * Generates an error message that transferred as JSON for AJAX calls
705 *
706 * @param string $message The error message to be shown
707 * @return array The error message in a JSON array
708 */
709 protected function getErrorMessageForAJAX($message)
710 {
711 return [
712 'data' => $message,
713 'scriptCall' => [
714 'alert("' . $message . '");'
715 ],
716 ];
717 }
718
719 /**
720 * Get inlineFirstPid from a given objectId string
721 *
722 * @param string $domObjectId The id attribute of an element
723 * @return int|NULL Pid or null
724 */
725 protected function getInlineFirstPidFromDomObjectId($domObjectId)
726 {
727 // Substitute FlexForm addition and make parsing a bit easier
728 $domObjectId = str_replace('---', ':', $domObjectId);
729 // The starting pattern of an object identifier (e.g. "data-<firstPidValue>-<anything>)
730 $pattern = '/^data' . '-' . '(.+?)' . '-' . '(.+)$/';
731 if (preg_match($pattern, $domObjectId, $match)) {
732 return $match[1];
733 }
734 return null;
735 }
736
737 /**
738 * @return BackendUserAuthentication
739 */
740 protected function getBackendUserAuthentication()
741 {
742 return $GLOBALS['BE_USER'];
743 }
744
745 /**
746 * Extract the inline child table configuration from the flexform data structure
747 * using the the domObjectId to traverse the XML structure.
748 *
749 * domObjectId parsing has been copied from InlineStackProcessor::initializeByDomObjectId
750 *
751 * @param array $parentConfig
752 * @param string $domObjectId
753 * @return array
754 */
755 protected function getParentConfigFromFlexForm(array $parentConfig, $domObjectId)
756 {
757 // Substitute FlexForm addition and make parsing a bit easier
758 $domObjectId = str_replace('---', ':', $domObjectId);
759 // The starting pattern of an object identifier (e.g. "data-<firstPidValue>-<anything>)
760 $pattern = '/^data' . '-' . '(?<firstPidValue>.+?)' . '-' . '(?<anything>.+)$/';
761
762 $flexFormPath = [];
763
764 if (preg_match($pattern, $domObjectId, $match)) {
765 $parts = explode('-', $match['anything']);
766
767 if (!isset($parts[2]) || strpos($parts[2], ':') === false) {
768 throw new \UnexpectedValueException(
769 'DOM Object ID' . $domObjectId . 'does not contain required information '
770 . 'to extract inline field configuration.',
771 1446996136
772 );
773 }
774
775 $fieldParts = GeneralUtility::trimExplode(':', $parts[2]);
776
777 // FlexForm parts start with data:
778 if (empty($fieldParts) || !isset($fieldParts[1]) || $fieldParts[1] !== 'data') {
779 throw new \UnexpectedValueException(
780 'Malformed flexform identifier: ' . $parts[2],
781 1446996254
782 );
783 }
784
785 $flexFormPath = array_slice($fieldParts, 2);
786 }
787
788 $childConfig = $parentConfig['ds']['sheets'];
789
790 foreach ($flexFormPath as $flexFormNode) {
791 // We are dealing with configuration information from a flexform,
792 // not value storage, identifiers that the reference language or
793 // value nodes must be skipped.
794 if (!isset($childConfig[$flexFormNode]) && preg_match('/^[lv][[:alpha:]]+$/', $flexFormNode)) {
795 continue;
796 }
797 $childConfig = $childConfig[$flexFormNode];
798
799 // Skip to the field configuration of a sheet
800 if (isset($childConfig['ROOT']) && $childConfig['ROOT']['type'] == 'array') {
801 $childConfig = $childConfig['ROOT']['el'];
802 }
803 }
804
805 if (!isset($childConfig['config'])
806 || !is_array($childConfig['config'])
807 || $childConfig['config']['type'] !== 'inline'
808 ) {
809 throw new \UnexpectedValueException(
810 'Configuration retrieved from FlexForm is incomplete or not of type "inline".',
811 1446996319
812 );
813 }
814 return $childConfig['config'];
815 }
816 }