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