[TASK] Use ServerRequestInterface in EditDocumentController
[Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Classes / Controller / EditDocumentController.php
1 <?php
2 declare(strict_types = 1);
3 namespace TYPO3\CMS\Backend\Controller;
4
5 /*
6 * This file is part of the TYPO3 CMS project.
7 *
8 * It is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU General Public License, either version 2
10 * of the License, or any later version.
11 *
12 * For the full copyright and license information, please read the
13 * LICENSE.txt file that was distributed with this source code.
14 *
15 * The TYPO3 project - inspiring people to share!
16 */
17
18 use Psr\Http\Message\ResponseInterface;
19 use Psr\Http\Message\ServerRequestInterface;
20 use TYPO3\CMS\Backend\Form\Exception\AccessDeniedException;
21 use TYPO3\CMS\Backend\Form\Exception\DatabaseRecordException;
22 use TYPO3\CMS\Backend\Form\FormDataCompiler;
23 use TYPO3\CMS\Backend\Form\FormDataGroup\TcaDatabaseRecord;
24 use TYPO3\CMS\Backend\Form\FormResultCompiler;
25 use TYPO3\CMS\Backend\Form\NodeFactory;
26 use TYPO3\CMS\Backend\Form\Utility\FormEngineUtility;
27 use TYPO3\CMS\Backend\Routing\UriBuilder;
28 use TYPO3\CMS\Backend\Template\Components\ButtonBar;
29 use TYPO3\CMS\Backend\Template\ModuleTemplate;
30 use TYPO3\CMS\Backend\Utility\BackendUtility;
31 use TYPO3\CMS\Core\Compatibility\PublicPropertyDeprecationTrait;
32 use TYPO3\CMS\Core\Database\ConnectionPool;
33 use TYPO3\CMS\Core\Database\Query\Restriction\BackendWorkspaceRestriction;
34 use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
35 use TYPO3\CMS\Core\Database\Query\Restriction\HiddenRestriction;
36 use TYPO3\CMS\Core\DataHandling\DataHandler;
37 use TYPO3\CMS\Core\Http\HtmlResponse;
38 use TYPO3\CMS\Core\Http\RedirectResponse;
39 use TYPO3\CMS\Core\Imaging\Icon;
40 use TYPO3\CMS\Core\Messaging\FlashMessage;
41 use TYPO3\CMS\Core\Messaging\FlashMessageService;
42 use TYPO3\CMS\Core\Page\PageRenderer;
43 use TYPO3\CMS\Core\Type\Bitmask\Permission;
44 use TYPO3\CMS\Core\Utility\GeneralUtility;
45 use TYPO3\CMS\Core\Utility\HttpUtility;
46 use TYPO3\CMS\Core\Utility\MathUtility;
47 use TYPO3\CMS\Core\Utility\PathUtility;
48 use TYPO3\CMS\Extbase\SignalSlot\Dispatcher;
49 use TYPO3\CMS\Frontend\Page\CacheHashCalculator;
50 use TYPO3\CMS\Frontend\Page\PageRepository;
51
52 /**
53 * Main backend controller almost always used if some database record is edited in the backend.
54 *
55 * Main job of this controller is to evaluate and sanitize $request parameters,
56 * call the DataHandler if records should be created or updated and
57 * execute FormEngine for record rendering.
58 */
59 class EditDocumentController
60 {
61 use PublicPropertyDeprecationTrait;
62
63 /**
64 * @deprecated since v9. These constants will be set to protected in v10
65 */
66 public const DOCUMENT_CLOSE_MODE_DEFAULT = 0;
67 public const DOCUMENT_CLOSE_MODE_REDIRECT = 1; // works like DOCUMENT_CLOSE_MODE_DEFAULT
68 public const DOCUMENT_CLOSE_MODE_CLEAR_ALL = 3;
69 public const DOCUMENT_CLOSE_MODE_NO_REDIRECT = 4;
70
71 /**
72 * Properties which have been moved to protected status from public
73 *
74 * @var array
75 */
76 protected $deprecatedPublicProperties = [
77 'editconf' => 'Using $editconf of class EditDocumentTemplate from the outside is discouraged, as this variable is only used for internal storage.',
78 'defVals' => 'Using $defVals of class EditDocumentTemplate from the outside is discouraged, as this variable is only used for internal storage.',
79 'overrideVals' => 'Using $overrideVals of class EditDocumentTemplate from the outside is discouraged, as this variable is only used for internal storage.',
80 'columnsOnly' => 'Using $columnsOnly of class EditDocumentTemplate from the outside is discouraged, as this variable is only used for internal storage.',
81 'returnUrl' => 'Using $returnUrl of class EditDocumentTemplate from the outside is discouraged, as this variable is only used for internal storage.',
82 'closeDoc' => 'Using $closeDoc of class EditDocumentTemplate from the outside is discouraged, as this variable is only used for internal storage.',
83 'doSave' => 'Using $doSave of class EditDocumentTemplate from the outside is discouraged, as this variable is only used for internal storage.',
84 'returnEditConf' => 'Using $returnEditConf of class EditDocumentTemplate from the outside is discouraged, as this variable is only used for internal storage.',
85 'uc' => 'Using $uc of class EditDocumentTemplate from the outside is discouraged, as this variable is only used for internal storage.',
86 'retUrl' => 'Using $retUrl of class EditDocumentTemplate from the outside is discouraged, as this variable is only used for internal storage.',
87 'R_URL_parts' => 'Using $R_URL_parts of class EditDocumentTemplate from the outside is discouraged, as this variable is only used for internal storage.',
88 'R_URL_getvars' => 'Using $R_URL_getvars of class EditDocumentTemplate from the outside is discouraged, as this variable is only used for internal storage.',
89 'storeArray' => 'Using $storeArray of class EditDocumentTemplate from the outside is discouraged, as this variable is only used for internal storage.',
90 'storeUrl' => 'Using $storeUrl of class EditDocumentTemplate from the outside is discouraged, as this variable is only used for internal storage.',
91 'storeUrlMd5' => 'Using $storeUrlMd5 of class EditDocumentTemplate from the outside is discouraged, as this variable is only used for internal storage.',
92 'docDat' => 'Using $docDat of class EditDocumentTemplate from the outside is discouraged, as this variable is only used for internal storage.',
93 'docHandler' => 'Using $docHandler of class EditDocumentTemplate from the outside is discouraged, as this variable is only used for internal storage.',
94 'cmd' => 'Using $cmd of class EditDocumentTemplate from the outside is discouraged, as this variable is only used for internal storage.',
95 'mirror' => 'Using $mirror of class EditDocumentTemplate from the outside is discouraged, as this variable is only used for internal storage.',
96 'cacheCmd' => 'Using $cacheCmd of class EditDocumentTemplate from the outside is discouraged, the variable will be removed.',
97 'redirect' => 'Using $redirect of class EditDocumentTemplate from the outside is discouraged, the variable will be removed.',
98 'returnNewPageId' => 'Using $returnNewPageId of class EditDocumentTemplate from the outside is discouraged, as this variable is only used for internal storage.',
99 'popViewId' => 'Using $popViewId of class EditDocumentTemplate from the outside is discouraged, as this variable is only used for internal storage.',
100 'popViewId_addParams' => 'Using $popViewId_addParams of class EditDocumentTemplate from the outside is discouraged, the variable will be removed.',
101 'viewUrl' => 'Using $viewUrl of class EditDocumentTemplate from the outside is discouraged, as this variable is only used for internal storage.',
102 'recTitle' => 'Using $recTitle of class EditDocumentTemplate from the outside is discouraged, as this variable is only used for internal storage.',
103 'noView' => 'Using $noView of class EditDocumentTemplate from the outside is discouraged, as this variable is only used for internal storage.',
104 'MCONF' => 'Using $MCONF of class EditDocumentTemplate from the outside is discouraged, the variable will be removed.',
105 'doc' => 'Using $doc of class EditDocumentTemplate from the outside is discouraged, the variable will be removed.',
106 'perms_clause' => 'Using $perms_clause of class EditDocumentTemplate from the outside is discouraged, as this variable is only used for internal storage.',
107 'template' => 'Using $template of class EditDocumentTemplate from the outside is discouraged, the variable will be removed.',
108 'content' => 'Using $content of class EditDocumentTemplate from the outside is discouraged, the variable will be removed.',
109 'R_URI' => 'Using $R_URI of class EditDocumentTemplate from the outside is discouraged, as this variable is only used for internal storage.',
110 'pageinfo' => 'Using $pageinfo of class EditDocumentTemplate from the outside is discouraged, as this variable is only used for internal storage.',
111 'storeTitle' => 'Using $storeTitle of class EditDocumentTemplate from the outside is discouraged, as this variable is only used for internal storage.',
112 'firstEl' => 'Using $firstEl of class EditDocumentTemplate from the outside is discouraged, as this variable is only used for internal storage.',
113 'errorC' => 'Using $errorC of class EditDocumentTemplate from the outside is discouraged, as this variable is only used for internal storage.',
114 'newC' => 'Using $newC of class EditDocumentTemplate from the outside is discouraged, as this variable is only used for internal storage.',
115 'viewId' => 'Using $viewId of class EditDocumentTemplate from the outside is discouraged, as this variable is only used for internal storage.',
116 'viewId_addParams' => 'Using $viewId_addParams of class EditDocumentTemplate from the outside is discouraged, as this variable is only used for internal storage.',
117 'modTSconfig' => 'Using $modTSconfig of class EditDocumentTemplate from the outside is discouraged, as this variable is only used for internal storage.',
118 'dontStoreDocumentRef' => 'Using $dontStoreDocumentRef of class EditDocumentTemplate from the outside is discouraged, as this variable is only used for internal storage.',
119 ];
120
121 /**
122 * An array looking approx like [tablename][list-of-ids]=command, eg. "&edit[pages][123]=edit".
123 *
124 * @see \TYPO3\CMS\Backend\Utility\BackendUtility::editOnClick()
125 * @var array
126 */
127 protected $editconf = [];
128
129 /**
130 * Comma list of field names to edit. If specified, only those fields will be rendered.
131 * Otherwise all (available) fields in the record are shown according to the TCA type.
132 *
133 * @var string|null
134 */
135 protected $columnsOnly;
136
137 /**
138 * Default values for fields
139 *
140 * @var array|null [table][field]
141 */
142 protected $defVals;
143
144 /**
145 * Array of values to force being set as hidden fields in FormEngine
146 *
147 * @var array|null [table][field]
148 */
149 protected $overrideVals;
150
151 /**
152 * If set, this value will be set in $this->retUrl as "returnUrl", if not,
153 * $this->retUrl will link to dummy controller
154 *
155 * @var string|null
156 */
157 protected $returnUrl;
158
159 /**
160 * Prepared return URL. Contains the URL that we should return to from FormEngine if
161 * close button is clicked. Usually passed along as 'returnUrl', but falls back to
162 * "dummy" controller.
163 *
164 * @var string
165 */
166 protected $retUrl;
167
168 /**
169 * Close document command. One of the DOCUMENT_CLOSE_MODE_* constants above
170 *
171 * @var int
172 */
173 protected $closeDoc;
174
175 /**
176 * If true, the processing of incoming data will be performed as if a save-button is pressed.
177 * Used in the forms as a hidden field which can be set through
178 * JavaScript if the form is somehow submitted by JavaScript.
179 *
180 * @var bool
181 */
182 protected $doSave;
183
184 /**
185 * Main DataHandler datamap array
186 *
187 * @var array
188 * @todo: Will be set protected later, still used by ConditionMatcher
189 * @internal Will be removed / protected in v10 without further notice
190 */
191 public $data;
192
193 /**
194 * Main DataHandler cmdmap array
195 *
196 * @var array
197 */
198 protected $cmd;
199
200 /**
201 * DataHandler 'mirror' input
202 *
203 * @var array
204 */
205 protected $mirror;
206
207 /**
208 * @var string
209 * @deprecated since v9, will be removed in v10, unused
210 */
211 protected $cacheCmd;
212
213 /**
214 * @var string
215 * @deprecated since v9, will be removed in v10, unused
216 */
217 protected $redirect;
218
219 /**
220 * Boolean: If set, then the GET var "&id=" will be added to the
221 * retUrl string so that the NEW id of something is returned to the script calling the form.
222 *
223 * @var bool
224 */
225 protected $returnNewPageId = false;
226
227 /**
228 * Updated values for backendUser->uc. Used for new inline records to mark them
229 * as expanded: uc[inlineView][...]
230 *
231 * @var array|null
232 */
233 protected $uc;
234
235 /**
236 * ID for displaying the page in the frontend, "save and view"
237 *
238 * @var int
239 */
240 protected $popViewId;
241
242 /**
243 * @var string
244 * @deprecated since v9, will be removed in v10, unused
245 */
246 protected $popViewId_addParams;
247
248 /**
249 * Alternative URL for viewing the frontend pages.
250 *
251 * @var string
252 */
253 protected $viewUrl;
254
255 /**
256 * Alternative title for the document handler.
257 *
258 * @var string
259 */
260 protected $recTitle;
261
262 /**
263 * If set, then no save & view button is printed
264 *
265 * @var bool
266 */
267 protected $noView;
268
269 /**
270 * @var string
271 */
272 protected $perms_clause;
273
274 /**
275 * If true, $this->editconf array is added a redirect response, used by Wizard/AddController
276 *
277 * @var bool
278 */
279 protected $returnEditConf;
280
281 /**
282 * Workspace used for the editing action.
283 *
284 * @var string|null
285 */
286 protected $workspace;
287
288 /**
289 * @var \TYPO3\CMS\Backend\Template\DocumentTemplate
290 * @deprecated since v9, will be removed in v10, unused
291 */
292 protected $doc;
293
294 /**
295 * @deprecated since v9, will be removed in v10, unused
296 */
297 protected $template;
298
299 /**
300 * @deprecated since v9, will be removed in v10, unused
301 */
302 protected $content;
303
304 /**
305 * parse_url() of current requested URI, contains ['path'] and ['query'] parts.
306 *
307 * @var array
308 */
309 protected $R_URL_parts;
310
311 /**
312 * Contains $request query parameters. This array is the foundation for creating
313 * the R_URI internal var which becomes the url to which forms are submitted
314 *
315 * @var array
316 */
317 protected $R_URL_getvars;
318
319 /**
320 * Set to the URL of this script including variables which is needed to re-display the form.
321 *
322 * @var string
323 */
324 protected $R_URI;
325
326 /**
327 * @var array
328 * @deprecated since v9, will be removed in v10, unused
329 */
330 protected $MCONF;
331
332 /**
333 * @var array
334 */
335 protected $pageinfo;
336
337 /**
338 * Is loaded with the "title" of the currently "open document"
339 * used for the open document toolbar
340 *
341 * @var string
342 */
343 protected $storeTitle = '';
344
345 /**
346 * Contains an array with key/value pairs of GET parameters needed to reach the
347 * current document displayed - used in the 'open documents' toolbar.
348 *
349 * @var array
350 */
351 protected $storeArray;
352
353 /**
354 * $this->storeArray imploded to url
355 *
356 * @var string
357 */
358 protected $storeUrl;
359
360 /**
361 * md5 hash of storeURL, used to identify a single open document in backend user uc
362 *
363 * @var string
364 */
365 protected $storeUrlMd5;
366
367 /**
368 * Backend user session data of this module
369 *
370 * @var array
371 */
372 protected $docDat;
373
374 /**
375 * An array of the "open documents" - keys are md5 hashes (see $storeUrlMd5) identifying
376 * the various documents on the GET parameter list needed to open it. The values are
377 * arrays with 0,1,2 keys with information about the document (see compileStoreData()).
378 * The docHandler variable is stored in the $docDat session data, key "0".
379 *
380 * @var array
381 */
382 protected $docHandler;
383
384 /**
385 * Array of the elements to create edit forms for.
386 *
387 * @var array
388 * @todo: Will be set protected later, still used by ConditionMatcher
389 * @internal Will be removed / protected in v10 without further notice
390 */
391 public $elementsData;
392
393 /**
394 * Pointer to the first element in $elementsData
395 *
396 * @var array
397 */
398 protected $firstEl;
399
400 /**
401 * Counter, used to count the number of errors (when users do not have edit permissions)
402 *
403 * @var int
404 */
405 protected $errorC;
406
407 /**
408 * Counter, used to count the number of new record forms displayed
409 *
410 * @var int
411 */
412 protected $newC;
413
414 /**
415 * Is set to the pid value of the last shown record - thus indicating which page to
416 * show when clicking the SAVE/VIEW button
417 *
418 * @var int
419 */
420 protected $viewId;
421
422 /**
423 * Is set to additional parameters (like "&L=xxx") if the record supports it.
424 *
425 * @var string
426 */
427 protected $viewId_addParams;
428
429 /**
430 * Module TSconfig, loaded from main() based on the page id value of viewId
431 *
432 * @var array
433 */
434 protected $modTSconfig;
435
436 /**
437 * @var FormResultCompiler
438 */
439 protected $formResultCompiler;
440
441 /**
442 * Used internally to disable the storage of the document reference (eg. new records)
443 *
444 * @var bool
445 */
446 protected $dontStoreDocumentRef = 0;
447
448 /**
449 * @var \TYPO3\CMS\Extbase\SignalSlot\Dispatcher
450 */
451 protected $signalSlotDispatcher;
452
453 /**
454 * Stores information needed to preview the currently saved record
455 *
456 * @var array
457 */
458 protected $previewData = [];
459
460 /**
461 * ModuleTemplate object
462 *
463 * @var ModuleTemplate
464 */
465 protected $moduleTemplate;
466
467 /**
468 * Constructor
469 */
470 public function __construct()
471 {
472 $this->moduleTemplate = GeneralUtility::makeInstance(ModuleTemplate::class);
473 $this->moduleTemplate->setUiBlock(true);
474 // @todo Used by TYPO3\CMS\Backend\Configuration\TypoScript\ConditionMatching
475 $GLOBALS['SOBE'] = $this;
476 $this->getLanguageService()->includeLLFile('EXT:lang/Resources/Private/Language/locallang_alt_doc.xlf');
477 }
478
479 /**
480 * Main dispatcher entry method registered as "record_edit" end point
481 *
482 * @param ServerRequestInterface $request the current request
483 * @return ResponseInterface the response with the content
484 */
485 public function mainAction(ServerRequestInterface $request): ResponseInterface
486 {
487 // Unlock all locked records
488 BackendUtility::lockRecords();
489 if ($response = $this->preInit($request)) {
490 return $response;
491 }
492
493 // Process incoming data via DataHandler?
494 $parsedBody = $request->getParsedBody();
495 if ($this->doSave
496 || isset($parsedBody['_savedok'])
497 || isset($parsedBody['_saveandclosedok'])
498 || isset($parsedBody['_savedokview'])
499 || isset($parsedBody['_savedoknew'])
500 || isset($parsedBody['_duplicatedoc'])
501 || isset($parsedBody['_translation_savedok'])
502 || isset($parsedBody['_translation_savedokclear'])
503 ) {
504 if ($response = $this->processData($request)) {
505 return $response;
506 }
507 }
508
509 $this->init($request);
510 $this->main($request);
511
512 return new HtmlResponse($this->moduleTemplate->renderContent());
513 }
514
515 /**
516 * First initialization, always called, even before processData() executes DataHandler processing.
517 *
518 * @param ServerRequestInterface $request
519 * @return ResponseInterface|null Possible redirect response
520 */
521 public function preInit(ServerRequestInterface $request = null): ?ResponseInterface
522 {
523 if ($request === null) {
524 // Missing argument? This method must have been called from outside.
525 // Method will be protected and $request mandatory in v10, giving core freedom to move stuff around
526 // New v10 signature: "protected function preInit(ServerRequestInterface $request): ?ResponseInterface"
527 // @deprecated since TYPO3 v9, method argument $request will be set to mandatory
528 trigger_error('Method preInit() will be set to protected in v10. Do not call from other extension', E_USER_DEPRECATED);
529 $request = $GLOBALS['TYPO3_REQUEST'];
530 }
531
532 if ($response = $this->localizationRedirect($request)) {
533 return $response;
534 }
535
536 $parsedBody = $request->getParsedBody();
537 $queryParams = $request->getQueryParams();
538
539 $this->editconf = $parsedBody['edit'] ?? $queryParams['edit'] ?? [];
540 $this->defVals = $parsedBody['defVals'] ?? $queryParams['defVals'] ?? null;
541 $this->overrideVals = $parsedBody['overrideVals'] ?? $queryParams['overrideVals'] ?? null;
542 $this->columnsOnly = $parsedBody['columnsOnly'] ?? $queryParams['columnsOnly'] ?? null;
543 $this->returnUrl = GeneralUtility::sanitizeLocalUrl($parsedBody['returnUrl'] ?? $queryParams['returnUrl'] ?? null);
544 $this->closeDoc = (int)($parsedBody['closeDoc'] ?? $queryParams['closeDoc'] ?? self::DOCUMENT_CLOSE_MODE_DEFAULT);
545 $this->doSave = (bool)($parsedBody['doSave'] ?? $queryParams['doSave'] ?? false);
546 $this->returnEditConf = (bool)($parsedBody['returnEditConf'] ?? $queryParams['returnEditConf'] ?? false);
547 $this->workspace = $parsedBody['workspace'] ?? $queryParams['workspace'] ?? null;
548 $this->uc = $parsedBody['uc'] ?? $queryParams['uc'] ?? null;
549
550 // Set overrideVals as default values if defVals does not exist.
551 if (!is_array($this->defVals) && is_array($this->overrideVals)) {
552 $this->defVals = $this->overrideVals;
553 }
554
555 // Set final return URL
556 $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
557 $this->retUrl = $this->returnUrl ?: (string)$uriBuilder->buildUriFromRoute('dummy');
558
559 // Change $this->editconf if versioning applies to any of the records
560 $this->fixWSversioningInEditConf();
561
562 // Prepare R_URL (request url)
563 $this->R_URL_parts = parse_url($request->getAttribute('normalizedParams')->getRequestUri());
564 $this->R_URL_getvars = $queryParams;
565 $this->R_URL_getvars['edit'] = $this->editconf;
566
567 // Prepare 'open documents' url, this is later modified again various times
568 $this->compileStoreData();
569 // Backend user session data of this module
570 $this->docDat = $this->getBackendUser()->getModuleData('FormEngine', 'ses');
571 $this->docHandler = $this->docDat[0];
572
573 // Close document if a request for closing the document has been sent
574 if ((int)$this->closeDoc > self::DOCUMENT_CLOSE_MODE_DEFAULT) {
575 if ($response = $this->closeDocument($this->closeDoc, $request)) {
576 return $response;
577 }
578 }
579
580 // Sets a temporary workspace, this request is based on
581 if ($this->workspace !== null) {
582 $this->getBackendUser()->setTemporaryWorkspace($this->workspace);
583 }
584
585 $this->emitFunctionAfterSignal('preInit', $request);
586
587 return null;
588 }
589
590 /**
591 * Detects, if a save command has been triggered.
592 *
593 * @return bool TRUE, then save the document (data submitted)
594 * @deprecated since TYPO3 v9, will be removed in TYPO3 v10
595 */
596 public function doProcessData()
597 {
598 trigger_error('This method will be removed in TYPO3 v10.', E_USER_DEPRECATED);
599
600 $out = $this->doSave
601 || isset($_POST['_savedok'])
602 || isset($_POST['_saveandclosedok'])
603 || isset($_POST['_savedokview'])
604 || isset($_POST['_savedoknew'])
605 || isset($_POST['_duplicatedoc'])
606 || isset($_POST['_translation_savedok'])
607 || isset($_POST['_translation_savedokclear']);
608 return $out;
609 }
610
611 /**
612 * Do processing of data, submitting it to DataHandler. May return a RedirectResponse
613 *
614 * @param $request ServerRequestInterface
615 * @return ResponseInterface|null
616 */
617 public function processData(ServerRequestInterface $request = null): ?ResponseInterface
618 {
619 // @deprecated Variable can be removed in v10
620 $deprecatedCaller = false;
621 if ($request === null) {
622 // Missing argument? This method must have been called from outside.
623 // Method will be protected and $request mandatory in v10, giving core freedom to move stuff around
624 // New v10 signature: "protected function processData(ServerRequestInterface $request): ?ResponseInterface"
625 // @deprecated since TYPO3 v9, method argument $request will be set to mandatory
626 trigger_error('Method processData() will be set to protected in v10. Do not call from other extension', E_USER_DEPRECATED);
627 $request = $GLOBALS['TYPO3_REQUEST'];
628 $deprecatedCaller = true;
629 }
630
631 $parsedBody = $request->getParsedBody();
632 $queryParams = $request->getQueryParams();
633
634 $beUser = $this->getBackendUser();
635
636 // Processing related GET / POST vars
637 $this->data = $parsedBody['data'] ?? $queryParams['data'] ?? [];
638 $this->cmd = $parsedBody['cmd'] ?? $queryParams['cmd'] ?? [];
639 $this->mirror = $parsedBody['mirror'] ?? $queryParams['mirror'] ?? [];
640 // @deprecated property cacheCmd is unused and can be removed in v10
641 $this->cacheCmd = $parsedBody['cacheCmd'] ?? $queryParams['cacheCmd'] ?? null;
642 // @deprecated property redirect is unused and can be removed in v10
643 $this->redirect = $parsedBody['redirect'] ?? $queryParams['redirect'] ?? null;
644 $this->returnNewPageId = (bool)($parsedBody['returnNewPageId'] ?? $queryParams['returnNewPageId'] ?? false);
645
646 // Only options related to $this->data submission are included here
647 $tce = GeneralUtility::makeInstance(DataHandler::class);
648
649 $tce->setControl($parsedBody['control'] ?? $queryParams['control'] ?? []);
650
651 if (isset($parsedBody['_translation_savedok'])) {
652 $tce->updateModeL10NdiffData = 'FORCE_FFUPD';
653 }
654 if (isset($parsedBody['_translation_savedokclear'])) {
655 $tce->updateModeL10NdiffData = 'FORCE_FFUPD';
656 $tce->updateModeL10NdiffDataClear = true;
657 }
658 // Set default values specific for the user
659 $TCAdefaultOverride = $beUser->getTSConfigProp('TCAdefaults');
660 if (is_array($TCAdefaultOverride)) {
661 $tce->setDefaultsFromUserTS($TCAdefaultOverride);
662 }
663 // Set internal vars
664 if (isset($beUser->uc['neverHideAtCopy']) && $beUser->uc['neverHideAtCopy']) {
665 $tce->neverHideAtCopy = 1;
666 }
667 // Load DataHandler with data
668 $tce->start($this->data, $this->cmd);
669 if (is_array($this->mirror)) {
670 $tce->setMirror($this->mirror);
671 }
672
673 // Perform the saving operation with DataHandler:
674 if ($this->doSave === true) {
675 // @todo: Make DataHandler understand UploadedFileInterface and submit $request->getUploadedFiles() instead of $_FILES here
676 $tce->process_uploads($_FILES);
677 $tce->process_datamap();
678 $tce->process_cmdmap();
679 }
680 // If pages are being edited, we set an instruction about updating the page tree after this operation.
681 if ($tce->pagetreeNeedsRefresh
682 && (isset($this->data['pages']) || $beUser->workspace != 0 && !empty($this->data))
683 ) {
684 BackendUtility::setUpdateSignal('updatePageTree');
685 }
686 // If there was saved any new items, load them:
687 if (!empty($tce->substNEWwithIDs_table)) {
688 // Save the expanded/collapsed states for new inline records, if any
689 FormEngineUtility::updateInlineView($this->uc, $tce);
690 $newEditConf = [];
691 foreach ($this->editconf as $tableName => $tableCmds) {
692 $keys = array_keys($tce->substNEWwithIDs_table, $tableName);
693 if (!empty($keys)) {
694 foreach ($keys as $key) {
695 $editId = $tce->substNEWwithIDs[$key];
696 // Check if the $editId isn't a child record of an IRRE action
697 if (!(is_array($tce->newRelatedIDs[$tableName])
698 && in_array($editId, $tce->newRelatedIDs[$tableName]))
699 ) {
700 // Translate new id to the workspace version
701 if ($versionRec = BackendUtility::getWorkspaceVersionOfRecord(
702 $beUser->workspace,
703 $tableName,
704 $editId,
705 'uid'
706 )) {
707 $editId = $versionRec['uid'];
708 }
709 $newEditConf[$tableName][$editId] = 'edit';
710 }
711 $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
712 // Traverse all new records and forge the content of ->editconf so we can continue to edit these records!
713 if ($tableName === 'pages'
714 && $this->retUrl != (string)$uriBuilder->buildUriFromRoute('dummy')
715 && $this->returnNewPageId
716 ) {
717 $this->retUrl .= '&id=' . $tce->substNEWwithIDs[$key];
718 }
719 }
720 } else {
721 $newEditConf[$tableName] = $tableCmds;
722 }
723 }
724 // Reset editconf if newEditConf has values
725 if (!empty($newEditConf)) {
726 $this->editconf = $newEditConf;
727 }
728 // Finally, set the editconf array in the "getvars" so they will be passed along in URLs as needed.
729 $this->R_URL_getvars['edit'] = $this->editconf;
730 // Unset default values since we don't need them anymore.
731 unset($this->R_URL_getvars['defVals']);
732 // Recompile the store* values since editconf changed
733 $this->compileStoreData();
734 }
735 // See if any records was auto-created as new versions?
736 if (!empty($tce->autoVersionIdMap)) {
737 $this->fixWSversioningInEditConf($tce->autoVersionIdMap);
738 }
739 // If a document is saved and a new one is created right after.
740 if (isset($parsedBody['_savedoknew']) && is_array($this->editconf)) {
741 if ($redirect = $this->closeDocument(self::DOCUMENT_CLOSE_MODE_NO_REDIRECT, $request)) {
742 return $redirect;
743 }
744 // Find the current table
745 reset($this->editconf);
746 $nTable = key($this->editconf);
747 // Finding the first id, getting the records pid+uid
748 reset($this->editconf[$nTable]);
749 $nUid = key($this->editconf[$nTable]);
750 $recordFields = 'pid,uid';
751 if (!empty($GLOBALS['TCA'][$nTable]['ctrl']['versioningWS'])) {
752 $recordFields .= ',t3ver_oid';
753 }
754 $nRec = BackendUtility::getRecord($nTable, $nUid, $recordFields);
755 // Determine insertion mode: 'top' is self-explaining,
756 // otherwise new elements are inserted after one using a negative uid
757 $insertRecordOnTop = ($this->getTsConfigOption($nTable, 'saveDocNew') === 'top');
758 // Setting a blank editconf array for a new record:
759 $this->editconf = [];
760 // Determine related page ID for regular live context
761 if ($nRec['pid'] != -1) {
762 if ($insertRecordOnTop) {
763 $relatedPageId = $nRec['pid'];
764 } else {
765 $relatedPageId = -$nRec['uid'];
766 }
767 } else {
768 // Determine related page ID for workspace context
769 if ($insertRecordOnTop) {
770 // Fetch live version of workspace version since the pid value is always -1 in workspaces
771 $liveRecord = BackendUtility::getRecord($nTable, $nRec['t3ver_oid'], $recordFields);
772 $relatedPageId = $liveRecord['pid'];
773 } else {
774 // Use uid of live version of workspace version
775 $relatedPageId = -$nRec['t3ver_oid'];
776 }
777 }
778 $this->editconf[$nTable][$relatedPageId] = 'new';
779 // Finally, set the editconf array in the "getvars" so they will be passed along in URLs as needed.
780 $this->R_URL_getvars['edit'] = $this->editconf;
781 // Recompile the store* values since editconf changed...
782 $this->compileStoreData();
783 }
784 // If a document should be duplicated.
785 if (isset($parsedBody['_duplicatedoc']) && is_array($this->editconf)) {
786 $this->closeDocument(self::DOCUMENT_CLOSE_MODE_NO_REDIRECT, $request);
787 // Find current table
788 reset($this->editconf);
789 $nTable = key($this->editconf);
790 // Find the first id, getting the records pid+uid
791 reset($this->editconf[$nTable]);
792 $nUid = key($this->editconf[$nTable]);
793 if (!MathUtility::canBeInterpretedAsInteger($nUid)) {
794 $nUid = $tce->substNEWwithIDs[$nUid];
795 }
796
797 $recordFields = 'pid,uid';
798 if (!empty($GLOBALS['TCA'][$nTable]['ctrl']['versioningWS'])) {
799 $recordFields .= ',t3ver_oid';
800 }
801 $nRec = BackendUtility::getRecord($nTable, $nUid, $recordFields);
802
803 // Setting a blank editconf array for a new record:
804 $this->editconf = [];
805
806 if ($nRec['pid'] != -1) {
807 $relatedPageId = -$nRec['uid'];
808 } else {
809 $relatedPageId = -$nRec['t3ver_oid'];
810 }
811
812 /** @var $duplicateTce \TYPO3\CMS\Core\DataHandling\DataHandler */
813 $duplicateTce = GeneralUtility::makeInstance(DataHandler::class);
814
815 $duplicateCmd = [
816 $nTable => [
817 $nUid => [
818 'copy' => $relatedPageId
819 ]
820 ]
821 ];
822
823 $duplicateTce->start([], $duplicateCmd);
824 $duplicateTce->process_cmdmap();
825
826 $duplicateMappingArray = $duplicateTce->copyMappingArray;
827 $duplicateUid = $duplicateMappingArray[$nTable][$nUid];
828
829 if ($nTable === 'pages') {
830 BackendUtility::setUpdateSignal('updatePageTree');
831 }
832
833 $this->editconf[$nTable][$duplicateUid] = 'edit';
834 // Finally, set the editconf array in the "getvars" so they will be passed along in URLs as needed.
835 $this->R_URL_getvars['edit'] = $this->editconf;
836 // Recompile the store* values since editconf changed...
837 $this->compileStoreData();
838
839 // Inform the user of the duplication
840 $flashMessage = GeneralUtility::makeInstance(
841 FlashMessage::class,
842 $this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.recordDuplicated'),
843 '',
844 FlashMessage::OK
845 );
846 $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
847 $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
848 $defaultFlashMessageQueue->enqueue($flashMessage);
849 }
850 // If a preview is requested
851 if (isset($parsedBody['_savedokview'])) {
852 // Get the first table and id of the data array from DataHandler
853 $table = reset(array_keys($this->data));
854 $id = reset(array_keys($this->data[$table]));
855 if (!MathUtility::canBeInterpretedAsInteger($id)) {
856 $id = $tce->substNEWwithIDs[$id];
857 }
858 // Store this information for later use
859 $this->previewData['table'] = $table;
860 $this->previewData['id'] = $id;
861 }
862 $tce->printLogErrorMessages();
863
864 if ((int)$this->closeDoc < self::DOCUMENT_CLOSE_MODE_DEFAULT
865 || isset($parsedBody['_saveandclosedok'])
866 || isset($parsedBody['_translation_savedok'])
867 ) {
868 // Redirect if element should be closed after save
869 $possibleRedirect = $this->closeDocument(abs($this->closeDoc), $request);
870 if ($deprecatedCaller && $possibleRedirect) {
871 // @deprecated fall back if method has been called from outside. This if can be removed in v10
872 HttpUtility::redirect($possibleRedirect->getHeaders()['location'][0]);
873 }
874 return $possibleRedirect;
875 }
876 return null;
877 }
878
879 /**
880 * Initialize the view part of the controller logic.
881 *
882 * @param $request ServerRequestInterface
883 */
884 public function init(ServerRequestInterface $request = null): void
885 {
886 if ($request === null) {
887 // Missing argument? This method must have been called from outside.
888 // Method will be protected and $request mandatory in v10, giving core freedom to move stuff around
889 // New v10 signature: "protected function init(ServerRequestInterface $request): void
890 // @deprecated since TYPO3 v9, method argument $request will be set to mandatory
891 trigger_error('Method init() will be set to protected in v10. Do not call from other extension', E_USER_DEPRECATED);
892 $request = $GLOBALS['TYPO3_REQUEST'];
893 }
894
895 $parsedBody = $request->getParsedBody();
896 $queryParams = $request->getQueryParams();
897
898 $beUser = $this->getBackendUser();
899
900 // @deprecated since v9, will be removed in v10, unused, remove call in v10
901 $this->popViewId_addParams = $parsedBody['popViewId_addParams'] ?? $queryParams['popViewId_addParams'] ?? '';
902
903 $this->popViewId = (int)($parsedBody['popViewId'] ?? $queryParams['popViewId'] ?? 0);
904 $this->viewUrl = (string)($parsedBody['viewUrl'] ?? $queryParams['viewUrl'] ?? '');
905 $this->recTitle = (string)($parsedBody['recTitle'] ?? $queryParams['recTitle'] ?? '');
906 $this->noView = (bool)($parsedBody['noView'] ?? $queryParams['noView'] ?? false);
907 $this->perms_clause = $beUser->getPagePermsClause(Permission::PAGE_SHOW);
908 // Set other internal variables:
909 $this->R_URL_getvars['returnUrl'] = $this->retUrl;
910 $this->R_URI = $this->R_URL_parts['path'] . '?' . ltrim(GeneralUtility::implodeArrayForUrl(
911 '',
912 $this->R_URL_getvars
913 ), '&');
914
915 // @deprecated since v9, will be removed in v10, unused
916 $this->MCONF['name'] = 'xMOD_alt_doc.php';
917 // @deprecated since v9, will be removed in v10, unused
918 $this->doc = $GLOBALS['TBE_TEMPLATE'];
919
920 $pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
921 $pageRenderer->addInlineLanguageLabelFile('EXT:lang/Resources/Private/Language/locallang_alt_doc.xlf');
922
923 $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
924 // override the default jumpToUrl
925 $this->moduleTemplate->addJavaScriptCode(
926 'jumpToUrl',
927 '
928 function jumpToUrl(URL,formEl) {
929 if (!TBE_EDITOR.isFormChanged()) {
930 window.location.href = URL;
931 } else if (formEl && formEl.type=="checkbox") {
932 formEl.checked = formEl.checked ? 0 : 1;
933 }
934 }
935 // Info view:
936 function launchView(table,uid) {
937 console.warn(\'Calling launchView() has been deprecated in v9 and will be removed in v10.0\');
938 var thePreviewWindow = window.open(
939 ' . GeneralUtility::quoteJSvalue((string)$uriBuilder->buildUriFromRoute('show_item') . '&table=') . ' + encodeURIComponent(table) + "&uid=" + encodeURIComponent(uid),
940 "ShowItem" + Math.random().toString(16).slice(2),
941 "height=300,width=410,status=0,menubar=0,resizable=0,location=0,directories=0,scrollbars=1,toolbar=0"
942 );
943 if (thePreviewWindow && thePreviewWindow.focus) {
944 thePreviewWindow.focus();
945 }
946 }
947 function deleteRecord(table,id,url) {
948 window.location.href = ' . GeneralUtility::quoteJSvalue((string)$uriBuilder->buildUriFromRoute('tce_db') . '&cmd[') . '+table+"]["+id+"][delete]=1&redirect="+escape(url);
949 }
950 ' . (isset($parsedBody['_savedokview']) && $this->popViewId ? $this->generatePreviewCode() : '')
951 );
952 // Set context sensitive menu
953 $this->moduleTemplate->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Backend/ContextMenu');
954
955 $this->emitFunctionAfterSignal('init', $request);
956 }
957
958 /**
959 * @return string
960 */
961 protected function generatePreviewCode(): string
962 {
963 $table = $this->previewData['table'];
964 $recordId = $this->previewData['id'];
965
966 if ($table === 'pages') {
967 $currentPageId = $recordId;
968 } else {
969 $currentPageId = MathUtility::convertToPositiveInteger($this->popViewId);
970 }
971
972 $pageTsConfig = BackendUtility::getPagesTSconfig($currentPageId);
973 $previewConfiguration = $pageTsConfig['TCEMAIN.']['preview.'][$table . '.'] ?? [];
974
975 $recordArray = BackendUtility::getRecord($table, $recordId);
976
977 // find the right preview page id
978 $previewPageId = 0;
979 if (isset($previewConfiguration['previewPageId'])) {
980 $previewPageId = $previewConfiguration['previewPageId'];
981 }
982 // if no preview page was configured
983 if (!$previewPageId) {
984 $rootPageData = null;
985 $rootLine = BackendUtility::BEgetRootLine($currentPageId);
986 $currentPage = reset($rootLine);
987 // Allow all doktypes below 200
988 // This makes custom doktype work as well with opening a frontend page.
989 if ((int)$currentPage['doktype'] <= PageRepository::DOKTYPE_SPACER) {
990 // try the current page
991 $previewPageId = $currentPageId;
992 } else {
993 // or search for the root page
994 foreach ($rootLine as $page) {
995 if ($page['is_siteroot']) {
996 $rootPageData = $page;
997 break;
998 }
999 }
1000 $previewPageId = isset($rootPageData)
1001 ? (int)$rootPageData['uid']
1002 : $currentPageId;
1003 }
1004 }
1005
1006 $linkParameters = [];
1007
1008 // language handling
1009 $languageField = $GLOBALS['TCA'][$table]['ctrl']['languageField'] ?? '';
1010 if ($languageField && !empty($recordArray[$languageField])) {
1011 $l18nPointer = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'] ?? '';
1012 if ($l18nPointer && !empty($recordArray[$l18nPointer])
1013 && isset($previewConfiguration['useDefaultLanguageRecord'])
1014 && !$previewConfiguration['useDefaultLanguageRecord']
1015 ) {
1016 // use parent record
1017 $recordId = $recordArray[$l18nPointer];
1018 }
1019 $linkParameters['L'] = $recordArray[$languageField];
1020 }
1021
1022 // map record data to GET parameters
1023 if (isset($previewConfiguration['fieldToParameterMap.'])) {
1024 foreach ($previewConfiguration['fieldToParameterMap.'] as $field => $parameterName) {
1025 $value = $recordArray[$field];
1026 if ($field === 'uid') {
1027 $value = $recordId;
1028 }
1029 $linkParameters[$parameterName] = $value;
1030 }
1031 }
1032
1033 // add/override parameters by configuration
1034 if (isset($previewConfiguration['additionalGetParameters.'])) {
1035 $additionalGetParameters = [];
1036 $this->parseAdditionalGetParameters(
1037 $additionalGetParameters,
1038 $previewConfiguration['additionalGetParameters.']
1039 );
1040 $linkParameters = array_replace($linkParameters, $additionalGetParameters);
1041 }
1042
1043 if (!empty($previewConfiguration['useCacheHash'])) {
1044 $cacheHashCalculator = GeneralUtility::makeInstance(CacheHashCalculator::class);
1045 $fullLinkParameters = GeneralUtility::implodeArrayForUrl('', array_merge($linkParameters, ['id' => $previewPageId]));
1046 $cacheHashParameters = $cacheHashCalculator->getRelevantParameters($fullLinkParameters);
1047 $linkParameters['cHash'] = $cacheHashCalculator->calculateCacheHash($cacheHashParameters);
1048 } else {
1049 $linkParameters['no_cache'] = 1;
1050 }
1051
1052 $this->popViewId = $previewPageId;
1053 $popViewId_addParams = GeneralUtility::implodeArrayForUrl('', $linkParameters, '', false, true);
1054 $anchorSection = $table === 'tt_content' ? '#c' . $recordId : '';
1055
1056 $previewPageRootLine = BackendUtility::BEgetRootLine($this->popViewId);
1057 return '
1058 if (window.opener) {
1059 '
1060 . BackendUtility::viewOnClick(
1061 $this->popViewId,
1062 '',
1063 $previewPageRootLine,
1064 $anchorSection,
1065 $this->viewUrl,
1066 $popViewId_addParams,
1067 false
1068 )
1069 . '
1070 } else {
1071 '
1072 . BackendUtility::viewOnClick(
1073 $this->popViewId,
1074 '',
1075 $previewPageRootLine,
1076 $anchorSection,
1077 $this->viewUrl,
1078 $popViewId_addParams
1079 )
1080 . '
1081 }';
1082 }
1083
1084 /**
1085 * Migrates a set of (possibly nested) GET parameters in TypoScript syntax to a plain array
1086 *
1087 * This basically removes the trailing dots of sub-array keys in TypoScript.
1088 * The result can be used to create a query string with GeneralUtility::implodeArrayForUrl().
1089 *
1090 * @param array $parameters Should be an empty array by default
1091 * @param array $typoScript The TypoScript configuration
1092 */
1093 protected function parseAdditionalGetParameters(array &$parameters, array $typoScript)
1094 {
1095 foreach ($typoScript as $key => $value) {
1096 if (is_array($value)) {
1097 $key = rtrim($key, '.');
1098 $parameters[$key] = [];
1099 $this->parseAdditionalGetParameters($parameters[$key], $value);
1100 } else {
1101 $parameters[$key] = $value;
1102 }
1103 }
1104 }
1105
1106 /**
1107 * Main module operation
1108 *
1109 * @param $request ServerRequestInterface
1110 */
1111 public function main(ServerRequestInterface $request = null): void
1112 {
1113 if ($request === null) {
1114 // Set method signature in v10 to: "protected function main(ServerRequestInterface $request): void"
1115 trigger_error('@deprecated since v9, this method will be set to protected in v10', E_USER_DEPRECATED);
1116 $request = $GLOBALS['TYPO3_REQUEST'];
1117 }
1118
1119 $body = '';
1120 // Begin edit
1121 if (is_array($this->editconf)) {
1122 $this->formResultCompiler = GeneralUtility::makeInstance(FormResultCompiler::class);
1123
1124 // Creating the editing form, wrap it with buttons, document selector etc.
1125 $editForm = $this->makeEditForm();
1126 if ($editForm) {
1127 $this->firstEl = reset($this->elementsData);
1128 // Checking if the currently open document is stored in the list of "open documents" - if not, add it:
1129 if (($this->docDat[1] !== $this->storeUrlMd5 || !isset($this->docHandler[$this->storeUrlMd5]))
1130 && !$this->dontStoreDocumentRef
1131 ) {
1132 $this->docHandler[$this->storeUrlMd5] = [
1133 $this->storeTitle,
1134 $this->storeArray,
1135 $this->storeUrl,
1136 $this->firstEl
1137 ];
1138 $this->getBackendUser()->pushModuleData('FormEngine', [$this->docHandler, $this->storeUrlMd5]);
1139 BackendUtility::setUpdateSignal('OpendocsController::updateNumber', count($this->docHandler));
1140 }
1141 // Module configuration
1142 $this->modTSconfig = $this->viewId
1143 ? BackendUtility::getModTSconfig(
1144 $this->viewId,
1145 'mod.xMOD_alt_doc'
1146 )
1147 : [];
1148 $body = $this->formResultCompiler->addCssFiles();
1149 $body .= $this->compileForm($editForm);
1150 $body .= $this->formResultCompiler->printNeededJSFunctions();
1151 $body .= '</form>';
1152 }
1153 }
1154 // Access check...
1155 // The page will show only if there is a valid page and if this page may be viewed by the user
1156 $this->pageinfo = BackendUtility::readPageAccess($this->viewId, $this->perms_clause);
1157 if ($this->pageinfo) {
1158 $this->moduleTemplate->getDocHeaderComponent()->setMetaInformation($this->pageinfo);
1159 }
1160 // Setting up the buttons and markers for doc header
1161 $this->getButtons($request);
1162 $this->languageSwitch(
1163 (string)($this->firstEl['table'] ?? ''),
1164 (int)($this->firstEl['uid'] ?? 0),
1165 isset($this->firstEl['pid']) ? (int)$this->firstEl['pid'] : null
1166 );
1167 $this->moduleTemplate->setContent($body);
1168 }
1169
1170 /**
1171 * Creates the editing form with FormEngine, based on the input from GPvars.
1172 *
1173 * @return string HTML form elements wrapped in tables
1174 */
1175 public function makeEditForm(): string
1176 {
1177 // Foreign class call? Method will be protected in v10, giving core freedom to move stuff around
1178 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
1179 if (end($backtrace)['class'] !== __CLASS__) {
1180 // @deprecated since TYPO3 v9, this method will be set to protected in v10
1181 trigger_error('Method makeEditForm() will be set to protected in v10. Do not call from other extension', E_USER_DEPRECATED);
1182 }
1183
1184 // Initialize variables
1185 $this->elementsData = [];
1186 $this->errorC = 0;
1187 $this->newC = 0;
1188 $editForm = '';
1189 $trData = null;
1190 $beUser = $this->getBackendUser();
1191 // Traverse the GPvar edit array tables
1192 foreach ($this->editconf as $table => $conf) {
1193 if (is_array($conf) && $GLOBALS['TCA'][$table] && $beUser->check('tables_modify', $table)) {
1194 // Traverse the keys/comments of each table (keys can be a comma list of uids)
1195 foreach ($conf as $cKey => $command) {
1196 if ($command === 'edit' || $command === 'new') {
1197 // Get the ids:
1198 $ids = GeneralUtility::trimExplode(',', $cKey, true);
1199 // Traverse the ids:
1200 foreach ($ids as $theUid) {
1201 // Don't save this document title in the document selector if the document is new.
1202 if ($command === 'new') {
1203 $this->dontStoreDocumentRef = 1;
1204 }
1205
1206 try {
1207 $formDataGroup = GeneralUtility::makeInstance(TcaDatabaseRecord::class);
1208 $formDataCompiler = GeneralUtility::makeInstance(FormDataCompiler::class, $formDataGroup);
1209 $nodeFactory = GeneralUtility::makeInstance(NodeFactory::class);
1210
1211 // Reset viewId - it should hold data of last entry only
1212 $this->viewId = 0;
1213 $this->viewId_addParams = '';
1214
1215 $formDataCompilerInput = [
1216 'tableName' => $table,
1217 'vanillaUid' => (int)$theUid,
1218 'command' => $command,
1219 'returnUrl' => $this->R_URI,
1220 ];
1221 if (is_array($this->overrideVals) && is_array($this->overrideVals[$table])) {
1222 $formDataCompilerInput['overrideValues'] = $this->overrideVals[$table];
1223 }
1224
1225 $formData = $formDataCompiler->compile($formDataCompilerInput);
1226
1227 // Set this->viewId if possible
1228 if ($command === 'new'
1229 && $table !== 'pages'
1230 && !empty($formData['parentPageRow']['uid'])
1231 ) {
1232 $this->viewId = $formData['parentPageRow']['uid'];
1233 } else {
1234 if ($table === 'pages') {
1235 $this->viewId = $formData['databaseRow']['uid'];
1236 } elseif (!empty($formData['parentPageRow']['uid'])) {
1237 $this->viewId = $formData['parentPageRow']['uid'];
1238 // Adding "&L=xx" if the record being edited has a languageField with a value larger than zero!
1239 if (!empty($formData['processedTca']['ctrl']['languageField'])
1240 && is_array($formData['databaseRow'][$formData['processedTca']['ctrl']['languageField']])
1241 && $formData['databaseRow'][$formData['processedTca']['ctrl']['languageField']][0] > 0
1242 ) {
1243 $this->viewId_addParams = '&L=' . $formData['databaseRow'][$formData['processedTca']['ctrl']['languageField']][0];
1244 }
1245 }
1246 }
1247
1248 // Determine if delete button can be shown
1249 $deleteAccess = false;
1250 if ($command === 'edit') {
1251 $permission = $formData['userPermissionOnPage'];
1252 if ($formData['tableName'] === 'pages') {
1253 $deleteAccess = $permission & Permission::PAGE_DELETE ? true : false;
1254 } else {
1255 $deleteAccess = $permission & Permission::CONTENT_EDIT ? true : false;
1256 }
1257 }
1258
1259 // Display "is-locked" message
1260 if ($command === 'edit') {
1261 $lockInfo = BackendUtility::isRecordLocked($table, $formData['databaseRow']['uid']);
1262 if ($lockInfo) {
1263 $flashMessage = GeneralUtility::makeInstance(
1264 FlashMessage::class,
1265 $lockInfo['msg'],
1266 '',
1267 FlashMessage::WARNING
1268 );
1269 $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
1270 $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
1271 $defaultFlashMessageQueue->enqueue($flashMessage);
1272 }
1273 }
1274
1275 // Record title
1276 if (!$this->storeTitle) {
1277 $this->storeTitle = $this->recTitle
1278 ? htmlspecialchars($this->recTitle)
1279 : BackendUtility::getRecordTitle($table, FormEngineUtility::databaseRowCompatibility($formData['databaseRow']), true);
1280 }
1281
1282 $this->elementsData[] = [
1283 'table' => $table,
1284 'uid' => $formData['databaseRow']['uid'],
1285 'pid' => $formData['databaseRow']['pid'],
1286 'cmd' => $command,
1287 'deleteAccess' => $deleteAccess
1288 ];
1289
1290 if ($command !== 'new') {
1291 BackendUtility::lockRecords($table, $formData['databaseRow']['uid'], $table === 'tt_content' ? $formData['databaseRow']['pid'] : 0);
1292 }
1293
1294 // Set list if only specific fields should be rendered. This will trigger
1295 // ListOfFieldsContainer instead of FullRecordContainer in OuterWrapContainer
1296 if ($this->columnsOnly) {
1297 if (is_array($this->columnsOnly)) {
1298 $formData['fieldListToRender'] = $this->columnsOnly[$table];
1299 } else {
1300 $formData['fieldListToRender'] = $this->columnsOnly;
1301 }
1302 }
1303
1304 $formData['renderType'] = 'outerWrapContainer';
1305 $formResult = $nodeFactory->create($formData)->render();
1306
1307 $html = $formResult['html'];
1308
1309 $formResult['html'] = '';
1310 $formResult['doSaveFieldName'] = 'doSave';
1311
1312 // @todo: Put all the stuff into FormEngine as final "compiler" class
1313 // @todo: This is done here for now to not rewrite addCssFiles()
1314 // @todo: and printNeededJSFunctions() now
1315 $this->formResultCompiler->mergeResult($formResult);
1316
1317 // Seems the pid is set as hidden field (again) at end?!
1318 if ($command === 'new') {
1319 // @todo: looks ugly
1320 $html .= LF
1321 . '<input type="hidden"'
1322 . ' name="data[' . htmlspecialchars($table) . '][' . htmlspecialchars($formData['databaseRow']['uid']) . '][pid]"'
1323 . ' value="' . (int)$formData['databaseRow']['pid'] . '" />';
1324 $this->newC++;
1325 }
1326
1327 $editForm .= $html;
1328 } catch (AccessDeniedException $e) {
1329 $this->errorC++;
1330 // Try to fetch error message from "recordInternals" be user object
1331 // @todo: This construct should be logged and localized and de-uglified
1332 $message = $beUser->errorMsg;
1333 if (empty($message)) {
1334 // Create message from exception.
1335 $message = $e->getMessage() . ' ' . $e->getCode();
1336 }
1337 $editForm .= htmlspecialchars($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.noEditPermission'))
1338 . '<br /><br />' . htmlspecialchars($message) . '<br /><br />';
1339 } catch (DatabaseRecordException $e) {
1340 $editForm = '<div class="alert alert-warning">' . htmlspecialchars($e->getMessage()) . '</div>';
1341 }
1342 } // End of for each uid
1343 }
1344 }
1345 }
1346 }
1347 return $editForm;
1348 }
1349
1350 /**
1351 * Create the panel of buttons for submitting the form or otherwise perform operations.
1352 *
1353 * @param $request ServerRequestInterface
1354 */
1355 protected function getButtons(ServerRequestInterface $request): void
1356 {
1357 $lang = $this->getLanguageService();
1358 /** @var UriBuilder $uriBuilder */
1359 $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
1360 // Render SAVE type buttons:
1361 // The action of each button is decided by its name attribute.
1362 $buttonBar = $this->moduleTemplate->getDocHeaderComponent()->getButtonBar();
1363 if (!$this->errorC && !$GLOBALS['TCA'][$this->firstEl['table']]['ctrl']['readOnly']) {
1364 $saveSplitButton = $buttonBar->makeSplitButton();
1365 // SAVE button:
1366 $saveButton = $buttonBar->makeInputButton()
1367 ->setTitle($lang->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:rm.saveDoc'))
1368 ->setName('_savedok')
1369 ->setValue('1')
1370 ->setForm('EditDocumentController')
1371 ->setIcon($this->moduleTemplate->getIconFactory()->getIcon('actions-document-save', Icon::SIZE_SMALL));
1372 $saveSplitButton->addItem($saveButton, true);
1373
1374 // SAVE / VIEW button:
1375 if ($this->viewId && !$this->noView && !empty($this->firstEl['table']) && $this->getTsConfigOption($this->firstEl['table'], 'saveDocView')) {
1376 $pagesTSconfig = BackendUtility::getPagesTSconfig($this->pageinfo['uid']);
1377 if (isset($pagesTSconfig['TCEMAIN.']['preview.']['disableButtonForDokType'])) {
1378 $excludeDokTypes = GeneralUtility::intExplode(
1379 ',',
1380 $pagesTSconfig['TCEMAIN.']['preview.']['disableButtonForDokType'],
1381 true
1382 );
1383 } else {
1384 // exclude sysfolders, spacers and recycler by default
1385 $excludeDokTypes = [
1386 PageRepository::DOKTYPE_RECYCLER,
1387 PageRepository::DOKTYPE_SYSFOLDER,
1388 PageRepository::DOKTYPE_SPACER
1389 ];
1390 }
1391 if (!in_array((int)$this->pageinfo['doktype'], $excludeDokTypes, true)
1392 || isset($pagesTSconfig['TCEMAIN.']['preview.'][$this->firstEl['table'] . '.']['previewPageId'])
1393 ) {
1394 $saveAndOpenButton = $buttonBar->makeInputButton()
1395 ->setTitle($lang->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:rm.saveDocShow'))
1396 ->setName('_savedokview')
1397 ->setValue('1')
1398 ->setForm('EditDocumentController')
1399 ->setOnClick("window.open('', 'newTYPO3frontendWindow');")
1400 ->setIcon($this->moduleTemplate->getIconFactory()->getIcon(
1401 'actions-document-save-view',
1402 Icon::SIZE_SMALL
1403 ));
1404 $saveSplitButton->addItem($saveAndOpenButton);
1405 }
1406 }
1407 // SAVE / NEW button:
1408 if (count($this->elementsData) === 1 && !empty($this->firstEl['table']) && $this->getTsConfigOption($this->firstEl['table'], 'saveDocNew')) {
1409 $saveAndNewButton = $buttonBar->makeInputButton()
1410 ->setName('_savedoknew')
1411 ->setClasses('t3js-editform-submitButton')
1412 ->setValue('1')
1413 ->setForm('EditDocumentController')
1414 ->setTitle($lang->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:rm.saveNewDoc'))
1415 ->setIcon($this->moduleTemplate->getIconFactory()->getIcon(
1416 'actions-document-save-new',
1417 Icon::SIZE_SMALL
1418 ));
1419 $saveSplitButton->addItem($saveAndNewButton);
1420 }
1421 // SAVE / CLOSE
1422 $saveAndCloseButton = $buttonBar->makeInputButton()
1423 ->setName('_saveandclosedok')
1424 ->setClasses('t3js-editform-submitButton')
1425 ->setValue('1')
1426 ->setForm('EditDocumentController')
1427 ->setTitle($lang->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:rm.saveCloseDoc'))
1428 ->setIcon($this->moduleTemplate->getIconFactory()->getIcon(
1429 'actions-document-save-close',
1430 Icon::SIZE_SMALL
1431 ));
1432 $saveSplitButton->addItem($saveAndCloseButton);
1433 // FINISH TRANSLATION / SAVE / CLOSE
1434 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['explicitConfirmationOfTranslation']) {
1435 $saveTranslationButton = $buttonBar->makeInputButton()
1436 ->setName('_translation_savedok')
1437 ->setValue('1')
1438 ->setForm('EditDocumentController')
1439 ->setTitle($lang->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:rm.translationSaveDoc'))
1440 ->setIcon($this->moduleTemplate->getIconFactory()->getIcon(
1441 'actions-document-save-cleartranslationcache',
1442 Icon::SIZE_SMALL
1443 ));
1444 $saveSplitButton->addItem($saveTranslationButton);
1445 $saveAndClearTranslationButton = $buttonBar->makeInputButton()
1446 ->setName('_translation_savedokclear')
1447 ->setValue('1')
1448 ->setForm('EditDocumentController')
1449 ->setTitle($lang->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:rm.translationSaveDocClear'))
1450 ->setIcon($this->moduleTemplate->getIconFactory()->getIcon(
1451 'actions-document-save-cleartranslationcache',
1452 Icon::SIZE_SMALL
1453 ));
1454 $saveSplitButton->addItem($saveAndClearTranslationButton);
1455 }
1456 $buttonBar->addButton($saveSplitButton, ButtonBar::BUTTON_POSITION_LEFT, 2);
1457 }
1458 // CLOSE button:
1459 $closeButton = $buttonBar->makeLinkButton()
1460 ->setHref('#')
1461 ->setClasses('t3js-editform-close')
1462 ->setTitle($lang->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:rm.closeDoc'))
1463 ->setIcon($this->moduleTemplate->getIconFactory()->getIcon(
1464 'actions-close',
1465 Icon::SIZE_SMALL
1466 ));
1467 $buttonBar->addButton($closeButton);
1468 // DUPLICATE button:
1469 $record = BackendUtility::getRecord($this->firstEl['table'], $this->firstEl['uid']);
1470 $TCActrl = $GLOBALS['TCA'][$this->firstEl['table']]['ctrl'];
1471 $l18nParent = isset($TCActrl['transOrigPointerField'], $record[$TCActrl['transOrigPointerField']])
1472 ? (int)$record[$TCActrl['transOrigPointerField']]
1473 : 0;
1474 $sysLanguageUid = isset($TCActrl['languageField'], $record[$TCActrl['languageField']])
1475 ? (int)$record[$TCActrl['languageField']]
1476 : 0;
1477 $showDuplicateButton = false;
1478 if ($this->firstEl['cmd'] !== 'new' && MathUtility::canBeInterpretedAsInteger($this->firstEl['uid'])) {
1479 if ($sysLanguageUid === 0) {
1480 // show button, if record is in default language
1481 $showDuplicateButton = true;
1482 } else {
1483 // show button, if record is NOT in default language AND has no parent
1484 $showDuplicateButton = $l18nParent === 0;
1485 }
1486 }
1487 if ($showDuplicateButton) {
1488 $duplicateButton = $buttonBar->makeLinkButton()
1489 ->setHref('#')
1490 ->setClasses('t3js-editform-duplicate')
1491 ->setShowLabelText(true)
1492 ->setTitle($lang->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:rm.duplicateDoc'))
1493 ->setIcon($this->moduleTemplate->getIconFactory()->getIcon(
1494 'actions-document-duplicates-select',
1495 Icon::SIZE_SMALL
1496 ));
1497 $buttonBar->addButton($duplicateButton, ButtonBar::BUTTON_POSITION_LEFT, 3);
1498 }
1499 // DELETE + UNDO buttons:
1500 if (!$this->errorC
1501 && !$GLOBALS['TCA'][$this->firstEl['table']]['ctrl']['readOnly']
1502 && count($this->elementsData) === 1
1503 ) {
1504 if ($this->firstEl['cmd'] !== 'new' && MathUtility::canBeInterpretedAsInteger($this->firstEl['uid'])) {
1505 // Delete:
1506 if ($this->firstEl['deleteAccess']
1507 && !$GLOBALS['TCA'][$this->firstEl['table']]['ctrl']['readOnly']
1508 && !$this->getDisableDelete()
1509 ) {
1510 $returnUrl = $this->retUrl;
1511 if ($this->firstEl['table'] === 'pages') {
1512 parse_str((string)parse_url($returnUrl, PHP_URL_QUERY), $queryParams);
1513 if (isset($queryParams['route'])
1514 && isset($queryParams['id'])
1515 && (string)$this->firstEl['uid'] === (string)$queryParams['id']
1516 ) {
1517 // TODO: Use the page's pid instead of 0, this requires a clean API to manipulate the page
1518 // tree from the outside to be able to mark the pid as active
1519 $returnUrl = (string)$uriBuilder->buildUriFromRoutePath($queryParams['route'], ['id' => 0]);
1520 }
1521 }
1522 $deleteButton = $buttonBar->makeLinkButton()
1523 ->setHref('#')
1524 ->setClasses('t3js-editform-delete-record')
1525 ->setTitle($lang->getLL('deleteItem'))
1526 ->setIcon($this->moduleTemplate->getIconFactory()->getIcon(
1527 'actions-edit-delete',
1528 Icon::SIZE_SMALL
1529 ))
1530 ->setDataAttributes([
1531 'return-url' => $returnUrl,
1532 'uid' => $this->firstEl['uid'],
1533 'table' => $this->firstEl['table']
1534 ]);
1535 $buttonBar->addButton($deleteButton, ButtonBar::BUTTON_POSITION_LEFT, 4);
1536 }
1537 // Undo:
1538 if (!empty($this->firstEl['table']) && $this->getTsConfigOption($this->firstEl['table'], 'showHistory')) {
1539 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1540 ->getQueryBuilderForTable('sys_history');
1541 $undoButtonR = $queryBuilder->select('tstamp')
1542 ->from('sys_history')
1543 ->where(
1544 $queryBuilder->expr()->eq(
1545 'tablename',
1546 $queryBuilder->createNamedParameter($this->firstEl['table'], \PDO::PARAM_STR)
1547 ),
1548 $queryBuilder->expr()->eq(
1549 'recuid',
1550 $queryBuilder->createNamedParameter($this->firstEl['uid'], \PDO::PARAM_INT)
1551 )
1552 )
1553 ->orderBy('tstamp', 'DESC')
1554 ->setMaxResults(1)
1555 ->execute()
1556 ->fetch();
1557 if ($undoButtonR !== false) {
1558 $aOnClick = 'window.location.href=' .
1559 GeneralUtility::quoteJSvalue(
1560 (string)$uriBuilder->buildUriFromRoute(
1561 'record_history',
1562 [
1563 'element' => $this->firstEl['table'] . ':' . $this->firstEl['uid'],
1564 'revert' => 'ALL_FIELDS',
1565 'returnUrl' => $this->R_URI,
1566 ]
1567 )
1568 ) . '; return false;';
1569
1570 $undoButton = $buttonBar->makeLinkButton()
1571 ->setHref('#')
1572 ->setOnClick($aOnClick)
1573 ->setTitle(
1574 sprintf(
1575 $lang->getLL('undoLastChange'),
1576 BackendUtility::calcAge(
1577 $GLOBALS['EXEC_TIME'] - $undoButtonR['tstamp'],
1578 $lang->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.minutesHoursDaysYears')
1579 )
1580 )
1581 )
1582 ->setIcon($this->moduleTemplate->getIconFactory()->getIcon(
1583 'actions-document-history-open',
1584 Icon::SIZE_SMALL
1585 ));
1586 $buttonBar->addButton($undoButton, ButtonBar::BUTTON_POSITION_LEFT, 3);
1587 }
1588 }
1589 if (!empty($this->firstEl['table']) && $this->getTsConfigOption($this->firstEl['table'], 'showHistory')) {
1590 $aOnClick = 'window.location.href=' .
1591 GeneralUtility::quoteJSvalue(
1592 (string)$uriBuilder->buildUriFromRoute(
1593 'record_history',
1594 [
1595 'element' => $this->firstEl['table'] . ':' . $this->firstEl['uid'],
1596 'returnUrl' => $this->R_URI,
1597 ]
1598 )
1599 ) . '; return false;';
1600
1601 $historyButton = $buttonBar->makeLinkButton()
1602 ->setHref('#')
1603 ->setOnClick($aOnClick)
1604 ->setTitle('Open history of this record')
1605 ->setIcon($this->moduleTemplate->getIconFactory()->getIcon(
1606 'actions-document-history-open',
1607 Icon::SIZE_SMALL
1608 ));
1609 $buttonBar->addButton($historyButton, ButtonBar::BUTTON_POSITION_LEFT, 3);
1610 }
1611 // If only SOME fields are shown in the form, this will link the user to the FULL form:
1612 if ($this->columnsOnly) {
1613 $columnsOnlyButton = $buttonBar->makeLinkButton()
1614 ->setHref($this->R_URI . '&columnsOnly=')
1615 ->setTitle($lang->getLL('editWholeRecord'))
1616 ->setIcon($this->moduleTemplate->getIconFactory()->getIcon(
1617 'actions-open',
1618 Icon::SIZE_SMALL
1619 ));
1620 $buttonBar->addButton($columnsOnlyButton, ButtonBar::BUTTON_POSITION_LEFT, 3);
1621 }
1622 }
1623 }
1624 $cshButton = $buttonBar->makeHelpButton()->setModuleName('xMOD_csh_corebe')->setFieldName('TCEforms');
1625 $buttonBar->addButton($cshButton);
1626
1627 if ($this->returnUrl !== $this->getCloseUrl()) {
1628 $shortCutButton = $this->moduleTemplate->getDocHeaderComponent()->getButtonBar()->makeShortcutButton();
1629 $shortCutButton->setModuleName('xMOD_alt_doc.php')
1630 ->setGetVariables([
1631 'returnUrl',
1632 'edit',
1633 'defVals',
1634 'overrideVals',
1635 'columnsOnly',
1636 'returnNewPageId',
1637 'noView']);
1638 $this->moduleTemplate->getDocHeaderComponent()->getButtonBar()->addButton($shortCutButton);
1639 }
1640
1641 $closeUrl = $this->getCloseUrl();
1642 if ($this->returnUrl !== $closeUrl) {
1643 $scriptName = $request->getAttribute('normalizedParams')->getScriptName();
1644 $aOnClick = 'vHWin=window.open('
1645 . GeneralUtility::quoteJSvalue($scriptName . '?returnUrl=' . $closeUrl) . ','
1646 . GeneralUtility::quoteJSvalue(md5($this->R_URI))
1647 . ',\'width=670,height=500,status=0,menubar=0,scrollbars=1,resizable=1\');vHWin.focus();return false;';
1648 $openInNewWindowButton = $this->moduleTemplate->getDocHeaderComponent()->getButtonBar()
1649 ->makeLinkButton()
1650 ->setHref('#')
1651 ->setTitle($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.openInNewWindow'))
1652 ->setIcon($this->moduleTemplate->getIconFactory()->getIcon('actions-window-open', Icon::SIZE_SMALL))
1653 ->setOnClick($aOnClick);
1654 $this->moduleTemplate->getDocHeaderComponent()->getButtonBar()->addButton(
1655 $openInNewWindowButton,
1656 ButtonBar::BUTTON_POSITION_RIGHT
1657 );
1658 }
1659 }
1660
1661 /**
1662 * Put together the various elements (buttons, selectors, form) into a table
1663 *
1664 * @param string $editForm HTML form.
1665 * @return string Composite HTML
1666 */
1667 public function compileForm(string $editForm): string
1668 {
1669 // Foreign class call? Method will be protected in v10, giving core freedom to move stuff around
1670 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
1671 if (end($backtrace)['class'] !== __CLASS__) {
1672 // @deprecated since TYPO3 v9, this method will be set to protected in v10
1673 trigger_error('Method compileForm() will be set to protected in v10. Do not call from other extension', E_USER_DEPRECATED);
1674 }
1675
1676 $formContent = '
1677 <form
1678 action="' . htmlspecialchars($this->R_URI) . '"
1679 method="post"
1680 enctype="multipart/form-data"
1681 name="editform"
1682 id="EditDocumentController"
1683 onsubmit="TBE_EDITOR.checkAndDoSubmit(1); return false;"
1684 >
1685 ' . $editForm . '
1686 <input type="hidden" name="returnUrl" value="' . htmlspecialchars($this->retUrl) . '" />
1687 <input type="hidden" name="viewUrl" value="' . htmlspecialchars($this->viewUrl) . '" />
1688 <input type="hidden" name="popViewId" value="' . htmlspecialchars((string)$this->viewId) . '" />
1689 <input type="hidden" name="closeDoc" value="0" />
1690 <input type="hidden" name="doSave" value="0" />
1691 <input type="hidden" name="_serialNumber" value="' . md5(microtime()) . '" />
1692 <input type="hidden" name="_scrollPosition" value="" />';
1693 if ($this->returnNewPageId) {
1694 $formContent .= '<input type="hidden" name="returnNewPageId" value="1" />';
1695 }
1696 if ($this->viewId_addParams) {
1697 $formContent .= '<input type="hidden" name="popViewId_addParams" value="' . htmlspecialchars($this->viewId_addParams) . '" />';
1698 }
1699 return $formContent;
1700 }
1701
1702 /**
1703 * Create shortcut icon
1704 *
1705 * @deprecated since TYPO3 v9, will be removed in TYPO3 v10
1706 */
1707 public function shortCutLink()
1708 {
1709 trigger_error('Method shortCutLink() will be removed in v10', E_USER_DEPRECATED);
1710
1711 if ($this->returnUrl !== $this->getCloseUrl()) {
1712 $shortCutButton = $this->moduleTemplate->getDocHeaderComponent()->getButtonBar()->makeShortcutButton();
1713 $shortCutButton->setModuleName('xMOD_alt_doc.php')
1714 ->setGetVariables([
1715 'returnUrl',
1716 'edit',
1717 'defVals',
1718 'overrideVals',
1719 'columnsOnly',
1720 'returnNewPageId',
1721 'noView']);
1722 $this->moduleTemplate->getDocHeaderComponent()->getButtonBar()->addButton($shortCutButton);
1723 }
1724 }
1725
1726 /**
1727 * Creates open-in-window link
1728 *
1729 * @deprecated since TYPO3 v9, will be removed in TYPO3 v10
1730 */
1731 public function openInNewWindowLink()
1732 {
1733 trigger_error('Method openInNewWindowLink() will be removed in v10', E_USER_DEPRECATED);
1734
1735 $closeUrl = $this->getCloseUrl();
1736 if ($this->returnUrl !== $closeUrl) {
1737 $aOnClick = 'vHWin=window.open(' . GeneralUtility::quoteJSvalue(GeneralUtility::linkThisScript(
1738 ['returnUrl' => $closeUrl]
1739 ))
1740 . ','
1741 . GeneralUtility::quoteJSvalue(md5($this->R_URI))
1742 . ',\'width=670,height=500,status=0,menubar=0,scrollbars=1,resizable=1\');vHWin.focus();return false;';
1743 $openInNewWindowButton = $this->moduleTemplate->getDocHeaderComponent()->getButtonBar()
1744 ->makeLinkButton()
1745 ->setHref('#')
1746 ->setTitle($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.openInNewWindow'))
1747 ->setIcon($this->moduleTemplate->getIconFactory()->getIcon('actions-window-open', Icon::SIZE_SMALL))
1748 ->setOnClick($aOnClick);
1749 $this->moduleTemplate->getDocHeaderComponent()->getButtonBar()->addButton(
1750 $openInNewWindowButton,
1751 ButtonBar::BUTTON_POSITION_RIGHT
1752 );
1753 }
1754 }
1755
1756 /**
1757 * Returns if delete for the current table is disabled by configuration.
1758 * For sys_file_metadata in default language delete is always disabled.
1759 *
1760 * @return bool
1761 */
1762 protected function getDisableDelete(): bool
1763 {
1764 $disableDelete = false;
1765 if ($this->firstEl['table'] === 'sys_file_metadata') {
1766 $row = BackendUtility::getRecord('sys_file_metadata', $this->firstEl['uid'], 'sys_language_uid');
1767 $languageUid = $row['sys_language_uid'];
1768 if ($languageUid === 0) {
1769 $disableDelete = true;
1770 }
1771 } else {
1772 $disableDelete = (bool)$this->getTsConfigOption($this->firstEl['table'] ?? '', 'disableDelete');
1773 }
1774 return $disableDelete;
1775 }
1776
1777 /**
1778 * Returns the URL (usually for the "returnUrl") which closes the current window.
1779 * Used when editing a record in a popup.
1780 *
1781 * @return string
1782 */
1783 protected function getCloseUrl(): string
1784 {
1785 $closeUrl = GeneralUtility::getFileAbsFileName('EXT:backend/Resources/Public/Html/Close.html');
1786 return PathUtility::getAbsoluteWebPath($closeUrl);
1787 }
1788
1789 /***************************
1790 *
1791 * Localization stuff
1792 *
1793 ***************************/
1794 /**
1795 * Make selector box for creating new translation for a record or switching to edit the record in an existing
1796 * language.
1797 * Displays only languages which are available for the current page.
1798 *
1799 * @param string $table Table name
1800 * @param int $uid Uid for which to create a new language
1801 * @param int $pid|null Pid of the record
1802 */
1803 public function languageSwitch(string $table, int $uid, $pid = null)
1804 {
1805 // Foreign class call? Method will be protected in v10, giving core freedom to move stuff around
1806 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
1807 if (end($backtrace)['class'] !== __CLASS__) {
1808 // @deprecated since TYPO3 v9, this method will be set to protected in v10
1809 trigger_error('Method fixWSversioningInEditConf() will be set to protected in v10. Do not call from other extension', E_USER_DEPRECATED);
1810 }
1811
1812 $languageField = $GLOBALS['TCA'][$table]['ctrl']['languageField'];
1813 $transOrigPointerField = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
1814 /** @var UriBuilder $uriBuilder */
1815 $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
1816
1817 // Table editable and activated for languages?
1818 if ($this->getBackendUser()->check('tables_modify', $table)
1819 && $languageField
1820 && $transOrigPointerField
1821 ) {
1822 if ($pid === null) {
1823 $row = BackendUtility::getRecord($table, $uid, 'pid');
1824 $pid = $row['pid'];
1825 }
1826 // Get all available languages for the page
1827 // If editing a page, the translations of the current UID need to be fetched
1828 if ($table === 'pages') {
1829 $row = BackendUtility::getRecord($table, $uid, $GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField']);
1830 // Ensure the check is always done against the default language page
1831 $langRows = $this->getLanguages((int)($row[$GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField']] ?: $uid));
1832 } else {
1833 $langRows = $this->getLanguages((int)$pid);
1834 }
1835 // Page available in other languages than default language?
1836 if (is_array($langRows) && count($langRows) > 1) {
1837 $rowsByLang = [];
1838 $fetchFields = 'uid,' . $languageField . ',' . $transOrigPointerField;
1839 // Get record in current language
1840 $rowCurrent = BackendUtility::getLiveVersionOfRecord($table, $uid, $fetchFields);
1841 if (!is_array($rowCurrent)) {
1842 $rowCurrent = BackendUtility::getRecord($table, $uid, $fetchFields);
1843 }
1844 $currentLanguage = (int)$rowCurrent[$languageField];
1845 // Disabled for records with [all] language!
1846 if ($currentLanguage > -1) {
1847 // Get record in default language if needed
1848 if ($currentLanguage && $rowCurrent[$transOrigPointerField]) {
1849 $rowsByLang[0] = BackendUtility::getLiveVersionOfRecord(
1850 $table,
1851 $rowCurrent[$transOrigPointerField],
1852 $fetchFields
1853 );
1854 if (!is_array($rowsByLang[0])) {
1855 $rowsByLang[0] = BackendUtility::getRecord(
1856 $table,
1857 $rowCurrent[$transOrigPointerField],
1858 $fetchFields
1859 );
1860 }
1861 } else {
1862 $rowsByLang[$rowCurrent[$languageField]] = $rowCurrent;
1863 }
1864 if ($rowCurrent[$transOrigPointerField] || $currentLanguage === 0) {
1865 // Get record in other languages to see what's already available
1866
1867 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1868 ->getQueryBuilderForTable($table);
1869
1870 $queryBuilder->getRestrictions()
1871 ->removeAll()
1872 ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
1873 ->add(GeneralUtility::makeInstance(BackendWorkspaceRestriction::class));
1874
1875 $result = $queryBuilder->select(...GeneralUtility::trimExplode(',', $fetchFields, true))
1876 ->from($table)
1877 ->where(
1878 $queryBuilder->expr()->eq(
1879 'pid',
1880 $queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT)
1881 ),
1882 $queryBuilder->expr()->gt(
1883 $languageField,
1884 $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
1885 ),
1886 $queryBuilder->expr()->eq(
1887 $transOrigPointerField,
1888 $queryBuilder->createNamedParameter($rowsByLang[0]['uid'], \PDO::PARAM_INT)
1889 )
1890 )
1891 ->execute();
1892
1893 while ($row = $result->fetch()) {
1894 $rowsByLang[$row[$languageField]] = $row;
1895 }
1896 }
1897 $languageMenu = $this->moduleTemplate->getDocHeaderComponent()->getMenuRegistry()->makeMenu();
1898 $languageMenu->setIdentifier('_langSelector');
1899 foreach ($langRows as $lang) {
1900 if ($this->getBackendUser()->checkLanguageAccess($lang['uid'])) {
1901 $newTranslation = isset($rowsByLang[$lang['uid']]) ? '' : ' [' . htmlspecialchars($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.new')) . ']';
1902 // Create url for creating a localized record
1903 $addOption = true;
1904 $href = '';
1905 if ($newTranslation) {
1906 $redirectUrl = (string)$uriBuilder->buildUriFromRoute('record_edit', [
1907 'justLocalized' => $table . ':' . $rowsByLang[0]['uid'] . ':' . $lang['uid'],
1908 'returnUrl' => $this->retUrl
1909 ]);
1910
1911 if (array_key_exists(0, $rowsByLang)) {
1912 $href = BackendUtility::getLinkToDataHandlerAction(
1913 '&cmd[' . $table . '][' . $rowsByLang[0]['uid'] . '][localize]=' . $lang['uid'],
1914 $redirectUrl
1915 );
1916 } else {
1917 $addOption = false;
1918 }
1919 } else {
1920 $href = (string)$uriBuilder->buildUriFromRoute('record_edit', [
1921 'edit[' . $table . '][' . $rowsByLang[$lang['uid']]['uid'] . ']' => 'edit',
1922 'returnUrl' => $this->retUrl
1923 ]);
1924 }
1925 if ($addOption) {
1926 $menuItem = $languageMenu->makeMenuItem()
1927 ->setTitle($lang['title'] . $newTranslation)
1928 ->setHref($href);
1929 if ((int)$lang['uid'] === $currentLanguage) {
1930 $menuItem->setActive(true);
1931 }
1932 $languageMenu->addMenuItem($menuItem);
1933 }
1934 }
1935 }
1936 $this->moduleTemplate->getDocHeaderComponent()->getMenuRegistry()->addMenu($languageMenu);
1937 }
1938 }
1939 }
1940 }
1941
1942 /**
1943 * Redirects to FormEngine with new parameters to edit a just created localized record
1944 *
1945 * @param ServerRequestInterface $request Incoming request object
1946 * @return ResponseInterface|null Possible redirect response
1947 */
1948 public function localizationRedirect(ServerRequestInterface $request = null): ?ResponseInterface
1949 {
1950 $deprecatedCaller = false;
1951 if (!$request instanceof ServerRequestInterface) {
1952 // @deprecated since TYPO3 v9
1953 // Method signature in v10: protected function localizationRedirect(ServerRequestInterface $request): ?ResponseInterface
1954 trigger_error('Method localizationRedirect() will be set to protected in v10. Do not call from other extension', E_USER_DEPRECATED);
1955 $justLocalized = $request;
1956 $request = $GLOBALS['TYPO3_REQUEST'];
1957 $deprecatedCaller = true;
1958 } else {
1959 $justLocalized = $request->getQueryParams()['justLocalized'];
1960 }
1961
1962 if (empty($justLocalized)) {
1963 return null;
1964 }
1965
1966 list($table, $origUid, $language) = explode(':', $justLocalized);
1967
1968 if ($GLOBALS['TCA'][$table]
1969 && $GLOBALS['TCA'][$table]['ctrl']['languageField']
1970 && $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']
1971 ) {
1972 $parsedBody = $request->getParsedBody();
1973 $queryParams = $request->getQueryParams();
1974
1975 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1976 $queryBuilder->getRestrictions()
1977 ->removeAll()
1978 ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
1979 ->add(GeneralUtility::makeInstance(BackendWorkspaceRestriction::class));
1980 $localizedRecord = $queryBuilder->select('uid')
1981 ->from($table)
1982 ->where(
1983 $queryBuilder->expr()->eq(
1984 $GLOBALS['TCA'][$table]['ctrl']['languageField'],
1985 $queryBuilder->createNamedParameter($language, \PDO::PARAM_INT)
1986 ),
1987 $queryBuilder->expr()->eq(
1988 $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'],
1989 $queryBuilder->createNamedParameter($origUid, \PDO::PARAM_INT)
1990 )
1991 )
1992 ->execute()
1993 ->fetch();
1994 $returnUrl = $parsedBody['returnUrl'] ?? $queryParams['returnUrl'] ?? '';
1995 if (is_array($localizedRecord)) {
1996 if ($deprecatedCaller) {
1997 // @deprecated fall back if method has been called from outside. This if can be removed in v10
1998 $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
1999 $location = (string)$uriBuilder->buildUriFromRoute('record_edit', [
2000 'edit[' . $table . '][' . $localizedRecord['uid'] . ']' => 'edit',
2001 'returnUrl' => GeneralUtility::sanitizeLocalUrl($returnUrl)
2002 ]);
2003 HttpUtility::redirect($location);
2004 }
2005 // Create redirect response to self to edit just created record
2006 $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
2007 return new RedirectResponse(
2008 (string)$uriBuilder->buildUriFromRoute(
2009 'record_edit',
2010 [
2011 'edit[' . $table . '][' . $localizedRecord['uid'] . ']' => 'edit',
2012 'returnUrl' => GeneralUtility::sanitizeLocalUrl($returnUrl)
2013 ]
2014 ),
2015 303
2016 );
2017 }
2018 }
2019 return null;
2020 }
2021
2022 /**
2023 * Returns sys_language records available for record translations on given page.
2024 *
2025 * @param int $id Page id: If zero, the query will select all sys_language records from root level which are NOT
2026 * hidden. If set to another value, the query will select all sys_language records that has a
2027 * translation record on that page (and is not hidden, unless you are admin user)
2028 * @return array Language records including faked record for default language
2029 */
2030 public function getLanguages(int $id): array
2031 {
2032 // Foreign class call? Method will be protected in v10, giving core freedom to move stuff around
2033 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
2034 if (end($backtrace)['class'] !== __CLASS__) {
2035 // @deprecated since TYPO3 v9, this method will be set to protected in v10
2036 trigger_error('Method getLanguages() will be set to protected in v10. Do not call from other extension', E_USER_DEPRECATED);
2037 }
2038
2039 $languageService = $this->getLanguageService();
2040 $modSharedTSconfig = BackendUtility::getModTSconfig($id, 'mod.SHARED');
2041 // Fallback non sprite-configuration
2042 if (preg_match('/\\.gif$/', $modSharedTSconfig['properties']['defaultLanguageFlag'] ?? '')) {
2043 $modSharedTSconfig['properties']['defaultLanguageFlag'] = str_replace(
2044 '.gif',
2045 '',
2046 $modSharedTSconfig['properties']['defaultLanguageFlag']
2047 );
2048 }
2049 $languages = [
2050 0 => [
2051 'uid' => 0,
2052 'pid' => 0,
2053 'hidden' => 0,
2054 'title' => $modSharedTSconfig['properties']['defaultLanguageLabel'] !== ''
2055 ? $modSharedTSconfig['properties']['defaultLanguageLabel'] . ' (' . $languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_mod_web_list.xlf:defaultLanguage') . ')'
2056 : $languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_mod_web_list.xlf:defaultLanguage'),
2057 'flag' => $modSharedTSconfig['properties']['defaultLanguageFlag']
2058 ]
2059 ];
2060
2061 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
2062 ->getQueryBuilderForTable('sys_language');
2063
2064 $queryBuilder->select('s.uid', 's.pid', 's.hidden', 's.title', 's.flag')
2065 ->from('sys_language', 's')
2066 ->groupBy('s.uid', 's.pid', 's.hidden', 's.title', 's.flag', 's.sorting')
2067 ->orderBy('s.sorting');
2068
2069 if ($id) {
2070 $queryBuilder->getRestrictions()
2071 ->removeAll()
2072 ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
2073 ->add(GeneralUtility::makeInstance(BackendWorkspaceRestriction::class));
2074
2075 if (!$this->getBackendUser()->isAdmin()) {
2076 $queryBuilder->getRestrictions()->add(GeneralUtility::makeInstance(HiddenRestriction::class));
2077 }
2078
2079 // Add join with pages translations to only show active languages
2080 $queryBuilder->from('pages', 'o')
2081 ->where(
2082 $queryBuilder->expr()->eq('o.' . $GLOBALS['TCA']['pages']['ctrl']['languageField'], $queryBuilder->quoteIdentifier('s.uid')),
2083 $queryBuilder->expr()->eq('o.' . $GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField'], $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT))
2084 );
2085 }
2086
2087 $result = $queryBuilder->execute();
2088 while ($row = $result->fetch()) {
2089 $languages[$row['uid']] = $row;
2090 }
2091
2092 return $languages;
2093 }
2094
2095 /**
2096 * Fix $this->editconf if versioning applies to any of the records
2097 *
2098 * @param array|bool $mapArray Mapping between old and new ids if auto-versioning has been performed.
2099 */
2100 public function fixWSversioningInEditConf($mapArray = false): void
2101 {
2102 // Foreign class call? Method will be protected in v10, giving core freedom to move stuff around
2103 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
2104 if (end($backtrace)['class'] !== __CLASS__) {
2105 // @deprecated since TYPO3 v9, this method will be set to protected in v10
2106 trigger_error('Method fixWSversioningInEditConf() will be set to protected in v10. Do not call from other extension', E_USER_DEPRECATED);
2107 }
2108
2109 // Traverse the editConf array
2110 if (is_array($this->editconf)) {
2111 // Tables:
2112 foreach ($this->editconf as $table => $conf) {
2113 if (is_array($conf) && $GLOBALS['TCA'][$table]) {
2114 // Traverse the keys/comments of each table (keys can be a comma list of uids)
2115 $newConf = [];
2116 foreach ($conf as $cKey => $cmd) {
2117 if ($cmd === 'edit') {
2118 // Traverse the ids:
2119 $ids = GeneralUtility::trimExplode(',', $cKey, true);
2120 foreach ($ids as $idKey => $theUid) {
2121 if (is_array($mapArray)) {
2122 if ($mapArray[$table][$theUid]) {
2123 $ids[$idKey] = $mapArray[$table][$theUid];
2124 }
2125 } else {
2126 // Default, look for versions in workspace for record:
2127 $calcPRec = $this->getRecordForEdit((string)$table, (int)$theUid);
2128 if (is_array($calcPRec)) {
2129 // Setting UID again if it had changed, eg. due to workspace versioning.
2130 $ids[$idKey] = $calcPRec['uid'];
2131 }
2132 }
2133 }
2134 // Add the possibly manipulated IDs to the new-build newConf array:
2135 $newConf[implode(',', $ids)] = $cmd;
2136 } else {
2137 $newConf[$cKey] = $cmd;
2138 }
2139 }
2140 // Store the new conf array:
2141 $this->editconf[$table] = $newConf;
2142 }
2143 }
2144 }
2145 }
2146
2147 /**
2148 * Get record for editing.
2149 *
2150 * @param string $table Table name
2151 * @param int $theUid Record UID
2152 * @return array|false Returns record to edit, false if none
2153 */
2154 public function getRecordForEdit(string $table, int $theUid)
2155 {
2156 // Foreign class call? Method will be protected in v10, giving core freedom to move stuff around
2157 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
2158 if (end($backtrace)['class'] !== __CLASS__) {
2159 // @deprecated since TYPO3 v9, this method will be set to protected in v10
2160 trigger_error('Method getRecordForEdit() will be set to protected in v10. Do not call from other extension', E_USER_DEPRECATED);
2161 }
2162
2163 // Fetch requested record:
2164 $reqRecord = BackendUtility::getRecord($table, $theUid, 'uid,pid');
2165 if (is_array($reqRecord)) {
2166 // If workspace is OFFLINE:
2167 if ($this->getBackendUser()->workspace != 0) {
2168 // Check for versioning support of the table:
2169 if ($GLOBALS['TCA'][$table] && $GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
2170 // If the record is already a version of "something" pass it by.
2171 if ($reqRecord['pid'] == -1) {
2172 // (If it turns out not to be a version of the current workspace there will be trouble, but
2173 // that is handled inside DataHandler then and in the interface it would clearly be an error of
2174 // links if the user accesses such a scenario)
2175 return $reqRecord;
2176 }
2177 // The input record was online and an offline version must be found or made:
2178 // Look for version of this workspace:
2179 $versionRec = BackendUtility::getWorkspaceVersionOfRecord(
2180 $this->getBackendUser()->workspace,
2181 $table,
2182 $reqRecord['uid'],
2183 'uid,pid,t3ver_oid'
2184 );
2185 return is_array($versionRec) ? $versionRec : $reqRecord;
2186 }
2187 // This means that editing cannot occur on this record because it was not supporting versioning
2188 // which is required inside an offline workspace.
2189 return false;
2190 }
2191 // In ONLINE workspace, just return the originally requested record:
2192 return $reqRecord;
2193 }
2194 // Return FALSE because the table/uid was not found anyway.
2195 return false;
2196 }
2197
2198 /**
2199 * Populates the variables $this->storeArray, $this->storeUrl, $this->storeUrlMd5
2200 *
2201 * @deprecated since TYPO3 v9, will be removed in TYPO3 v10
2202 */
2203 public function compileStoreDat()
2204 {
2205 trigger_error('Method compileStoreDat() will be removed in TYPO3 v10.', E_USER_DEPRECATED);
2206 $this->compileStoreData();
2207 }
2208
2209 /**
2210 * Populates the variables $this->storeArray, $this->storeUrl, $this->storeUrlMd5
2211 * to prepare 'open documents' urls
2212 */
2213 protected function compileStoreData(): void
2214 {
2215 // @todo: Refactor in v10: This GeneralUtility method fiddles with _GP()
2216 $this->storeArray = GeneralUtility::compileSelectedGetVarsFromArray(
2217 'edit,defVals,overrideVals,columnsOnly,noView,workspace',
2218 $this->R_URL_getvars
2219 );
2220 $this->storeUrl = GeneralUtility::implodeArrayForUrl('', $this->storeArray);
2221 $this->storeUrlMd5 = md5($this->storeUrl);
2222 }
2223
2224 /**
2225 * Function used to look for configuration of buttons in the form: Fx. disabling buttons or showing them at various
2226 * positions.
2227 *
2228 * @param string $table The table for which the configuration may be specific
2229 * @param string $key The option for look for. Default is checking if the saveDocNew button should be displayed.
2230 * @return string Return value fetched from USER TSconfig
2231 * @deprecated since TYPO3 v9, will be removed in TYPO3 v10
2232 */
2233 public function getNewIconMode($table, $key = 'saveDocNew')
2234 {
2235 trigger_error('Method getNewIconMode() will be removed in TYPO3 v10.', E_USER_DEPRECATED);
2236 return $this->getTsConfigOption($table, $key);
2237 }
2238
2239 /**
2240 * Get a TSConfig 'option.' array, possibly for a specific table.
2241 *
2242 * @param string $table Table name
2243 * @param string $key Options key
2244 * @return string
2245 */
2246 protected function getTsConfigOption(string $table, string $key): string
2247 {
2248 $TsConfig = $this->getBackendUser()->getTSConfig('options.' . $key);
2249 return trim((string)($TsConfig['properties'][$table] ?? $TsConfig['value']));
2250 }
2251
2252 /**
2253 * Handling the closing of a document
2254 * The argument $mode can be one of this values:
2255 * - 0/1 will redirect to $this->retUrl [self::DOCUMENT_CLOSE_MODE_DEFAULT || self::DOCUMENT_CLOSE_MODE_REDIRECT]
2256 * - 3 will clear the docHandler (thus closing all documents) [self::DOCUMENT_CLOSE_MODE_CLEAR_ALL]
2257 * - 4 will do no redirect [self::DOCUMENT_CLOSE_MODE_NO_REDIRECT]
2258 * - other values will call setDocument with ->retUrl
2259 *
2260 * @param int $mode the close mode: one of self::DOCUMENT_CLOSE_MODE_*
2261 * @param $request ServerRequestInterface Incoming request
2262 * @return ResponseInterface|null Redirect response if needed
2263 */
2264 public function closeDocument($mode = self::DOCUMENT_CLOSE_MODE_DEFAULT, ServerRequestInterface $request = null): ?ResponseInterface
2265 {
2266 // Foreign class call or missing argument? Method will be protected and $request mandatory in v10, giving core freedom to move stuff around
2267 $deprecatedCaller = false;
2268 if ($request === null) {
2269 // Set method signature in v10 to: "protected function closeDocument($mode, ServerRequestInterface $request): ?ResponseInterface"
2270 trigger_error('@deprecated since v9, this method will be set to protected in v10', E_USER_DEPRECATED);
2271 $request = $GLOBALS['TYPO3_REQUEST'];
2272 $deprecatedCaller = true;
2273 }
2274
2275 $mode = (int)$mode;
2276 // If current document is found in docHandler,
2277 // then unset it, possibly unset it ALL and finally, write it to the session data
2278 if (isset($this->docHandler[$this->storeUrlMd5])) {
2279 // add the closing document to the recent documents
2280 $recentDocs = $this->getBackendUser()->getModuleData('opendocs::recent');
2281 if (!is_array($recentDocs)) {
2282 $recentDocs = [];
2283 }
2284 $closedDoc = $this->docHandler[$this->storeUrlMd5];
2285 $recentDocs = array_merge([$this->storeUrlMd5 => $closedDoc], $recentDocs);
2286 if (count($recentDocs) > 8) {
2287 $recentDocs = array_slice($recentDocs, 0, 8);
2288 }
2289 // remove it from the list of the open documents
2290 unset($this->docHandler[$this->storeUrlMd5]);
2291 if ($mode === self::DOCUMENT_CLOSE_MODE_CLEAR_ALL) {
2292 $recentDocs = array_merge($this->docHandler, $recentDocs);
2293 $this->docHandler = [];
2294 }
2295 $this->getBackendUser()->pushModuleData('opendocs::recent', $recentDocs);
2296 $this->getBackendUser()->pushModuleData('FormEngine', [$this->docHandler, $this->docDat[1]]);
2297 BackendUtility::setUpdateSignal('OpendocsController::updateNumber', count($this->docHandler));
2298 }
2299 if ($mode === self::DOCUMENT_CLOSE_MODE_NO_REDIRECT) {
2300 return null;
2301 }
2302 $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
2303 // If ->returnEditConf is set, then add the current content of editconf to the ->retUrl variable: used by
2304 // other scripts, like wizard_add, to know which records was created or so...
2305 if ($this->returnEditConf && $this->retUrl != (string)$uriBuilder->buildUriFromRoute('dummy')) {
2306 $this->retUrl .= '&returnEditConf=' . rawurlencode(json_encode($this->editconf));
2307 }
2308 // If mode is NOT set (means 0) OR set to 1, then make a header location redirect to $this->retUrl
2309 if ($mode === self::DOCUMENT_CLOSE_MODE_DEFAULT || $mode === self::DOCUMENT_CLOSE_MODE_REDIRECT) {
2310 if ($deprecatedCaller) {
2311 // @deprecated fall back if method has been called from outside. This if can be removed in v10
2312 HttpUtility::redirect($this->retUrl);
2313 }
2314 return new RedirectResponse($this->returnUrl, 303);
2315 }
2316 if ($this->retUrl === '') {
2317 return null;
2318 }
2319 $retUrl = $this->returnUrl;
2320 if (is_array($this->docHandler) && !empty($this->docHandler)) {
2321 if (!empty($setupArr[2])) {
2322 $sParts = parse_url($request->getAttribute('normalizedParams')->getRequestUri());
2323 $retUrl = $sParts['path'] . '?' . $setupArr[2] . '&returnUrl=' . rawurlencode($retUrl);
2324 }
2325 }
2326 if ($deprecatedCaller) {
2327 // @deprecated fall back if method has been called from outside. This if can be removed in v10
2328 HttpUtility::redirect($retUrl);
2329 }
2330 return new RedirectResponse($retUrl, 303);
2331 }
2332
2333 /**
2334 * Redirects to the document pointed to by $currentDocFromHandlerMD5 OR $retUrl,
2335 * depending on some internal calculations.
2336 *
2337 * @param string $currentDocFromHandlerMD5 Pointer to the document in the docHandler array
2338 * @param string $retUrl Alternative/Default retUrl
2339 * @deprecated since TYPO3 v9, will be removed in TYPO3 v10
2340 */
2341 public function setDocument($currentDocFromHandlerMD5 = '', $retUrl = '')
2342 {
2343 trigger_error('This method will be removed in TYPO3 v10.', E_USER_DEPRECATED);
2344 if ($retUrl === '') {
2345 return;
2346 }
2347 if (is_array($this->docHandler) && !empty($this->docHandler)) {
2348 if (isset($this->docHandler[$currentDocFromHandlerMD5])) {
2349 $setupArr = $this->docHandler[$currentDocFromHandlerMD5];
2350 } else {
2351 $setupArr = reset($this->docHandler);
2352 }
2353 if ($setupArr[2]) {
2354 $sParts = parse_url(GeneralUtility::getIndpEnv('REQUEST_URI'));
2355 $retUrl = $sParts['path'] . '?' . $setupArr[2] . '&returnUrl=' . rawurlencode($retUrl);
2356 }
2357 }
2358 HttpUtility::redirect($retUrl);
2359 }
2360
2361 /**
2362 * Emits a signal after a function was executed
2363 *
2364 * @param string $signalName
2365 * @param ServerRequestInterface $request
2366 */
2367 protected function emitFunctionAfterSignal($signalName, ServerRequestInterface $request): void
2368 {
2369 $this->getSignalSlotDispatcher()->dispatch(__CLASS__, $signalName . 'After', [$this, 'request' => $request]);
2370 }
2371
2372 /**
2373 * Get the SignalSlot dispatcher
2374 *
2375 * @return \TYPO3\CMS\Extbase\SignalSlot\Dispatcher
2376 */
2377 protected function getSignalSlotDispatcher()
2378 {
2379 if (!isset($this->signalSlotDispatcher)) {
2380 $this->signalSlotDispatcher = GeneralUtility::makeInstance(Dispatcher::class);
2381 }
2382 return $this->signalSlotDispatcher;
2383 }
2384
2385 /**
2386 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
2387 */
2388 protected function getBackendUser()
2389 {
2390 return $GLOBALS['BE_USER'];
2391 }
2392
2393 /**
2394 * Returns LanguageService
2395 *
2396 * @return \TYPO3\CMS\Core\Localization\LanguageService
2397 */
2398 protected function getLanguageService()
2399 {
2400 return $GLOBALS['LANG'];
2401 }
2402 }