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