[TASK] Remove global option BACK_PATH
[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) { //
780 var thePreviewWindow = window.open(
781 ' . GeneralUtility::quoteJSvalue(BackendUtility::getModuleUrl('show_item') . '&table=') . ' + encodeURIComponent(table) + "&uid=" + encodeURIComponent(uid),
782 "ShowItem" + TS.uniqueID,
783 "height=300,width=410,status=0,menubar=0,resizable=0,location=0,directories=0,scrollbars=1,toolbar=0"
784 );
785 if (thePreviewWindow && thePreviewWindow.focus) {
786 thePreviewWindow.focus();
787 }
788 }
789 function deleteRecord(table,id,url) { //
790 window.location.href = ' . GeneralUtility::quoteJSvalue(BackendUtility::getModuleUrl('tce_db') . '&cmd[') . '+table+"]["+id+"][delete]=1&redirect="+escape(url)+"&vC=' . $beUser->veriCode() . '&prErr=1&uPT=1";
791 }
792 ';
793
794 $previewCode = isset($_POST['_savedokview']) && $this->popViewId ? $this->generatePreviewCode() : '';
795 $this->moduleTemplate->addJavaScriptCode(
796 'PreviewCode',
797 $javascript . $previewCode
798 );
799 // Setting up the context sensitive menu:
800 $this->moduleTemplate->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Backend/ClickMenu');
801
802 $this->emitFunctionAfterSignal(__FUNCTION__);
803 }
804
805 /**
806 * @return string
807 */
808 protected function generatePreviewCode()
809 {
810 $currentPageId = MathUtility::convertToPositiveInteger($this->popViewId);
811 $table = $this->previewData['table'];
812 $recordId = $this->previewData['id'];
813
814 $pageTsConfig = BackendUtility::getPagesTSconfig($currentPageId);
815 $previewConfiguration = isset($pageTsConfig['TCEMAIN.']['preview.'][$table . '.'])
816 ? $pageTsConfig['TCEMAIN.']['preview.'][$table . '.']
817 : array();
818
819 $recordArray = BackendUtility::getRecord($table, $recordId);
820
821 // find the right preview page id
822 $previewPageId = 0;
823 if (isset($previewConfiguration['previewPageId'])) {
824 $previewPageId = $previewConfiguration['previewPageId'];
825 }
826 // if no preview page was configured
827 if (!$previewPageId) {
828 $rootPageData = null;
829 $rootLine = BackendUtility::BEgetRootLine($currentPageId);
830 $currentPage = reset($rootLine);
831 if ((int)$currentPage['doktype'] === PageRepository::DOKTYPE_DEFAULT) {
832 // try the current page
833 $previewPageId = $currentPageId;
834 } else {
835 // or search for the root page
836 foreach ($rootLine as $page) {
837 if ($page['is_siteroot']) {
838 $rootPageData = $page;
839 break;
840 }
841 }
842 $previewPageId = isset($rootPageData)
843 ? (int)$rootPageData['uid']
844 : $currentPageId;
845 }
846 }
847
848 $linkParameters = [
849 'no_cache' => 1,
850 ];
851
852 // language handling
853 $languageField = isset($GLOBALS['TCA'][$table]['ctrl']['languageField'])
854 ? $GLOBALS['TCA'][$table]['ctrl']['languageField']
855 : '';
856 if ($languageField && !empty($recordArray[$languageField])) {
857 $l18nPointer = isset($GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'])
858 ? $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']
859 : '';
860 if ($l18nPointer && !empty($recordArray[$l18nPointer])
861 && isset($previewConfiguration['useDefaultLanguageRecord'])
862 && !$previewConfiguration['useDefaultLanguageRecord']
863 ) {
864 // use parent record
865 $recordId = $recordArray[$l18nPointer];
866 }
867 $linkParameters['L'] = $recordArray[$languageField];
868 }
869
870 // map record data to GET parameters
871 if (isset($previewConfiguration['fieldToParameterMap.'])) {
872 foreach ($previewConfiguration['fieldToParameterMap.'] as $field => $parameterName) {
873 $value = $recordArray[$field];
874 if ($field === 'uid') {
875 $value = $recordId;
876 }
877 $linkParameters[$parameterName] = $value;
878 }
879 }
880
881 // add/override parameters by configuration
882 if (isset($previewConfiguration['additionalGetParameters.'])) {
883 $additionalGetParameters = [];
884 $this->parseAdditionalGetParameters(
885 $additionalGetParameters,
886 $previewConfiguration['additionalGetParameters.']
887 );
888 $linkParameters = array_replace($linkParameters, $additionalGetParameters);
889 }
890
891 $this->popViewId = $previewPageId;
892 $this->popViewId_addParams = GeneralUtility::implodeArrayForUrl('', $linkParameters, '', false, true);
893
894 $previewPageRootline = BackendUtility::BEgetRootLine($this->popViewId);
895 return '
896 if (window.opener) {
897 '
898 . BackendUtility::viewOnClick(
899 $this->popViewId,
900 '',
901 $previewPageRootline,
902 '',
903 $this->viewUrl,
904 $this->popViewId_addParams,
905 false
906 )
907 . '
908 } else {
909 '
910 . BackendUtility::viewOnClick(
911 $this->popViewId,
912 '',
913 $previewPageRootline,
914 '',
915 $this->viewUrl,
916 $this->popViewId_addParams
917 )
918 . '
919 }';
920 }
921
922 /**
923 * Migrates a set of (possibly nested) GET parameters in TypoScript syntax to a plain array
924 *
925 * This basically removes the trailing dots of sub-array keys in TypoScript.
926 * The result can be used to create a query string with GeneralUtility::implodeArrayForUrl().
927 *
928 * @param array $parameters Should be an empty array by default
929 * @param array $typoScript The TypoScript configuration
930 */
931 protected function parseAdditionalGetParameters(array &$parameters, array $typoScript)
932 {
933 foreach ($typoScript as $key => $value) {
934 if (is_array($value)) {
935 $key = rtrim($key, '.');
936 $parameters[$key] = [];
937 $this->parseAdditionalGetParameters($parameters[$key], $value);
938 } else {
939 $parameters[$key] = $value;
940 }
941 }
942 }
943
944 /**
945 * Main module operation
946 *
947 * @return void
948 */
949 public function main()
950 {
951 $body = '';
952 // Begin edit:
953 if (is_array($this->editconf)) {
954 /** @var FormResultCompiler formResultCompiler */
955 $this->formResultCompiler = GeneralUtility::makeInstance(FormResultCompiler::class);
956
957 // Creating the editing form, wrap it with buttons, document selector etc.
958 $editForm = $this->makeEditForm();
959 if ($editForm) {
960 $this->firstEl = reset($this->elementsData);
961 // Checking if the currently open document is stored in the list of "open documents" - if not, add it:
962 if (($this->docDat[1] !== $this->storeUrlMd5
963 || !isset($this->docHandler[$this->storeUrlMd5]))
964 && !$this->dontStoreDocumentRef
965 ) {
966 $this->docHandler[$this->storeUrlMd5] = array(
967 $this->storeTitle,
968 $this->storeArray,
969 $this->storeUrl,
970 $this->firstEl
971 );
972 $this->getBackendUser()->pushModuleData('FormEngine', array($this->docHandler, $this->storeUrlMd5));
973 BackendUtility::setUpdateSignal('OpendocsController::updateNumber', count($this->docHandler));
974 }
975 // Module configuration
976 $this->modTSconfig = $this->viewId ? BackendUtility::getModTSconfig(
977 $this->viewId,
978 'mod.xMOD_alt_doc'
979 ) : array();
980 $body = $this->formResultCompiler->JStop();
981 $body .= $this->compileForm($editForm);
982 $body .= $this->formResultCompiler->printNeededJSFunctions();
983 $body .= '</form>';
984 }
985 }
986 // Access check...
987 // The page will show only if there is a valid page and if this page may be viewed by the user
988 $this->pageinfo = BackendUtility::readPageAccess($this->viewId, $this->perms_clause);
989 if ($this->pageinfo) {
990 $this->moduleTemplate->getDocHeaderComponent()->setMetaInformation($this->pageinfo);
991 }
992 // Setting up the buttons and markers for docheader
993 $this->getButtons();
994 $this->languageSwitch($this->firstEl['table'], $this->firstEl['uid'], $this->firstEl['pid']);
995 $this->moduleTemplate->setContent($body);
996 }
997
998 /***************************
999 *
1000 * Sub-content functions, rendering specific parts of the module content.
1001 *
1002 ***************************/
1003 /**
1004 * Creates the editing form with FormEnigne, based on the input from GPvars.
1005 *
1006 * @return string HTML form elements wrapped in tables
1007 */
1008 public function makeEditForm()
1009 {
1010 // Initialize variables:
1011 $this->elementsData = array();
1012 $this->errorC = 0;
1013 $this->newC = 0;
1014 $editForm = '';
1015 $trData = null;
1016 $beUser = $this->getBackendUser();
1017 // Traverse the GPvar edit array
1018 // Tables:
1019 foreach ($this->editconf as $table => $conf) {
1020 if (is_array($conf) && $GLOBALS['TCA'][$table] && $beUser->check('tables_modify', $table)) {
1021 // Traverse the keys/comments of each table (keys can be a commalist of uids)
1022 foreach ($conf as $cKey => $command) {
1023 if ($command == 'edit' || $command == 'new') {
1024 // Get the ids:
1025 $ids = GeneralUtility::trimExplode(',', $cKey, true);
1026 // Traverse the ids:
1027 foreach ($ids as $theUid) {
1028 // Don't save this document title in the document selector if the document is new.
1029 if ($command === 'new') {
1030 $this->dontStoreDocumentRef = 1;
1031 }
1032
1033 /** @var TcaDatabaseRecord $formDataGroup */
1034 $formDataGroup = GeneralUtility::makeInstance(TcaDatabaseRecord::class);
1035 /** @var FormDataCompiler $formDataCompiler */
1036 $formDataCompiler = GeneralUtility::makeInstance(FormDataCompiler::class, $formDataGroup);
1037 /** @var NodeFactory $nodeFactory */
1038 $nodeFactory = GeneralUtility::makeInstance(NodeFactory::class);
1039
1040 try {
1041 // Reset viewId - it should hold data of last entry only
1042 $this->viewId = 0;
1043 $this->viewId_addParams = '';
1044
1045 $formDataCompilerInput = [
1046 'tableName' => $table,
1047 'vanillaUid' => (int)$theUid,
1048 'command' => $command,
1049 'returnUrl' => $this->R_URI,
1050 ];
1051 if (is_array($this->overrideVals) && is_array($this->overrideVals[$table])) {
1052 $formDataCompilerInput['overrideValues'] = $this->overrideVals[$table];
1053 }
1054
1055 $formData = $formDataCompiler->compile($formDataCompilerInput);
1056
1057 // Set this->viewId if possible
1058 if ($command === 'new'
1059 && $table !== 'pages'
1060 && !empty($formData['parentPageRow']['uid'])
1061 ) {
1062 $this->viewId = $formData['parentPageRow']['uid'];
1063 } else {
1064 if ($table == 'pages') {
1065 $this->viewId = $formData['databaseRow']['uid'];
1066 } elseif (!empty($formData['parentPageRow']['uid'])) {
1067 $this->viewId = $formData['parentPageRow']['uid'];
1068 // Adding "&L=xx" if the record being edited has a languageField with a value larger than zero!
1069 if (!empty($formData['processedTca']['ctrl']['languageField'])
1070 && is_array($formData['databaseRow'][$formData['processedTca']['ctrl']['languageField']])
1071 && $formData['databaseRow'][$formData['processedTca']['ctrl']['languageField']][0] > 0
1072 ) {
1073 $this->viewId_addParams = '&L=' . $formData['databaseRow'][$formData['processedTca']['ctrl']['languageField']][0];
1074 }
1075 }
1076 }
1077
1078 // Determine if delete button can be shown
1079 $deleteAccess = false;
1080 if ($command === 'edit') {
1081 $permission = $formData['userPermissionOnPage'];
1082 if ($formData['tableName'] === 'pages') {
1083 $deleteAccess = $permission & Permission::PAGE_DELETE ? true : false;
1084 } else {
1085 $deleteAccess = $permission & Permission::CONTENT_EDIT ? true : false;
1086 }
1087 }
1088
1089 // Display "is-locked" message:
1090 if ($command === 'edit') {
1091 $lockInfo = BackendUtility::isRecordLocked($table, $formData['databaseRow']['uid']);
1092 if ($lockInfo) {
1093 /** @var $flashMessage \TYPO3\CMS\Core\Messaging\FlashMessage */
1094 $flashMessage = GeneralUtility::makeInstance(
1095 FlashMessage::class,
1096 htmlspecialchars($lockInfo['msg']),
1097 '',
1098 FlashMessage::WARNING
1099 );
1100 /** @var $flashMessageService \TYPO3\CMS\Core\Messaging\FlashMessageService */
1101 $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
1102 /** @var $defaultFlashMessageQueue FlashMessageQueue */
1103 $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
1104 $defaultFlashMessageQueue->enqueue($flashMessage);
1105 }
1106 }
1107
1108 // Record title
1109 if (!$this->storeTitle) {
1110 $this->storeTitle = $this->recTitle
1111 ? htmlspecialchars($this->recTitle)
1112 : BackendUtility::getRecordTitle($table, FormEngineUtility::databaseRowCompatibility($formData['databaseRow']), true);
1113 }
1114
1115 $this->elementsData[] = array(
1116 'table' => $table,
1117 'uid' => $formData['databaseRow']['uid'],
1118 'pid' => $formData['databaseRow']['pid'],
1119 'cmd' => $command,
1120 'deleteAccess' => $deleteAccess
1121 );
1122
1123 if ($command !== 'new') {
1124 BackendUtility::lockRecords($table, $formData['databaseRow']['uid'], $table === 'tt_content' ? $formData['databaseRow']['pid'] : 0);
1125 }
1126
1127 // Set list if only specific fields should be rendered. This will trigger
1128 // ListOfFieldsContainer instead of FullRecordContainer in OuterWrapContainer
1129 if ($this->columnsOnly) {
1130 if (is_array($this->columnsOnly)) {
1131 $formData['fieldListToRender'] = $this->columnsOnly[$table];
1132 } else {
1133 $formData['fieldListToRender'] = $this->columnsOnly;
1134 }
1135 }
1136
1137 $formData['renderType'] = 'outerWrapContainer';
1138 $formResult = $nodeFactory->create($formData)->render();
1139
1140 $html = $formResult['html'];
1141
1142 $formResult['html'] = '';
1143 $formResult['doSaveFieldName'] = 'doSave';
1144
1145 // @todo: Put all the stuff into FormEngine as final "compiler" class
1146 // @todo: This is done here for now to not rewrite JStop()
1147 // @todo: and printNeededJSFunctions() now
1148 $this->formResultCompiler->mergeResult($formResult);
1149
1150 // Seems the pid is set as hidden field (again) at end?!
1151 if ($command == 'new') {
1152 // @todo: looks ugly
1153 $html .= LF
1154 . '<input type="hidden"'
1155 . ' name="data[' . htmlspecialchars($table) . '][' . htmlspecialchars($formData['databaseRow']['uid']) . '][pid]"'
1156 . ' value="' . (int)$formData['databaseRow']['pid'] . '" />';
1157 $this->newC++;
1158 }
1159
1160 $editForm .= $html;
1161 } catch (AccessDeniedException $e) {
1162 $this->errorC++;
1163 // Try to fetch error message from "recordInternals" be user object
1164 // @todo: This construct should be logged and localized and de-uglified
1165 $message = $beUser->errorMsg;
1166 if (empty($message)) {
1167 // Create message from exception.
1168 $message = $e->getMessage() . ' ' . $e->getCode();
1169 }
1170 $editForm .= $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:labels.noEditPermission', true)
1171 . '<br /><br />' . htmlspecialchars($message) . '<br /><br />';
1172 }
1173 } // End of for each uid
1174 }
1175 }
1176 }
1177 }
1178 return $editForm;
1179 }
1180
1181 /**
1182 * Create the panel of buttons for submitting the form or otherwise perform operations.
1183 *
1184 * @return array All available buttons as an assoc. array
1185 */
1186 protected function getButtons()
1187 {
1188 $lang = $this->getLanguageService();
1189 // Render SAVE type buttons:
1190 // The action of each button is decided by its name attribute. (See doProcessData())
1191 $buttonBar = $this->moduleTemplate->getDocHeaderComponent()->getButtonBar();
1192 if (!$this->errorC && !$GLOBALS['TCA'][$this->firstEl['table']]['ctrl']['readOnly']) {
1193 $saveSplitButton = $buttonBar->makeSplitButton();
1194 // SAVE button:
1195 $saveButton = $buttonBar->makeInputButton()
1196 ->setTitle($lang->sL('LLL:EXT:lang/locallang_core.xlf:rm.saveDoc'))
1197 ->setName('_savedok')
1198 ->setValue('1')
1199 ->setForm('EditDocumentController')
1200 ->setIcon($this->moduleTemplate->getIconFactory()->getIcon('actions-document-save', Icon::SIZE_SMALL));
1201 $saveSplitButton->addItem($saveButton, true);
1202
1203 // SAVE / VIEW button:
1204 if ($this->viewId && !$this->noView && $this->getNewIconMode($this->firstEl['table'], 'saveDocView')) {
1205 $pagesTSconfig = BackendUtility::getPagesTSconfig($this->pageinfo['uid']);
1206 if (isset($pagesTSconfig['TCEMAIN.']['preview.']['disableButtonForDokType'])) {
1207 $excludeDokTypes = GeneralUtility::intExplode(
1208 ',',
1209 $pagesTSconfig['TCEMAIN.']['preview.']['disableButtonForDokType'],
1210 true
1211 );
1212 } else {
1213 // exclude sysfolders, spacers and recycler by default
1214 $excludeDokTypes = array(
1215 PageRepository::DOKTYPE_RECYCLER,
1216 PageRepository::DOKTYPE_SYSFOLDER,
1217 PageRepository::DOKTYPE_SPACER
1218 );
1219 }
1220 if (!in_array((int)$this->pageinfo['doktype'], $excludeDokTypes, true)
1221 || isset($pagesTSconfig['TCEMAIN.']['preview.'][$this->firstEl['table'] . '.']['previewPageId'])
1222 ) {
1223 $saveAndOpenButton = $buttonBar->makeInputButton()
1224 ->setTitle($lang->sL('LLL:EXT:lang/locallang_core.xlf:rm.saveDocShow'))
1225 ->setName('_savedokview')
1226 ->setValue('1')
1227 ->setForm('EditDocumentController')
1228 ->setOnClick("window.open('', 'newTYPO3frontendWindow');")
1229 ->setIcon($this->moduleTemplate->getIconFactory()->getIcon(
1230 'actions-document-save-view',
1231 Icon::SIZE_SMALL
1232 ));
1233 $saveSplitButton->addItem($saveAndOpenButton);
1234 }
1235 }
1236 // SAVE / NEW button:
1237 if (count($this->elementsData) === 1 && $this->getNewIconMode($this->firstEl['table'])) {
1238 $saveAndNewButton = $buttonBar->makeInputButton()
1239 ->setName('_savedoknew')
1240 ->setClasses('t3js-editform-submitButton')
1241 ->setValue('1')
1242 ->setForm('EditDocumentController')
1243 ->setTitle($lang->sL('LLL:EXT:lang/locallang_core.xlf:rm.saveNewDoc'))
1244 ->setIcon($this->moduleTemplate->getIconFactory()->getIcon(
1245 'actions-document-save-new',
1246 Icon::SIZE_SMALL
1247 ));
1248 $saveSplitButton->addItem($saveAndNewButton);
1249 }
1250 // SAVE / CLOSE
1251 $saveAndCloseButton = $buttonBar->makeInputButton()
1252 ->setName('_saveandclosedok')
1253 ->setClasses('t3js-editform-submitButton')
1254 ->setValue('1')
1255 ->setForm('EditDocumentController')
1256 ->setTitle($lang->sL('LLL:EXT:lang/locallang_core.xlf:rm.saveCloseDoc'))
1257 ->setIcon($this->moduleTemplate->getIconFactory()->getIcon(
1258 'actions-document-save-close',
1259 Icon::SIZE_SMALL
1260 ));
1261 $saveSplitButton->addItem($saveAndCloseButton);
1262 // FINISH TRANSLATION / SAVE / CLOSE
1263 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['explicitConfirmationOfTranslation']) {
1264 $saveTranslationButton = $buttonBar->makeInputButton()
1265 ->setName('_translation_savedok')
1266 ->setValue('1')
1267 ->setForm('EditDocumentController')
1268 ->setTitle($lang->sL('LLL:EXT:lang/locallang_core.xlf:rm.translationSaveDoc'))
1269 ->setIcon($this->moduleTemplate->getIconFactory()->getIcon(
1270 'actions-document-save-cleartranslationcache',
1271 Icon::SIZE_SMALL
1272 ));
1273 $saveSplitButton->addItem($saveTranslationButton);
1274 $saveAndClearTranslationButton = $buttonBar->makeInputButton()
1275 ->setName('_translation_savedokclear')
1276 ->setValue('1')
1277 ->setForm('EditDocumentController')
1278 ->setTitle($lang->sL('LLL:EXT:lang/locallang_core.xlf:rm.translationSaveDocClear'))
1279 ->setIcon($this->moduleTemplate->getIconFactory()->getIcon(
1280 'actions-document-save-cleartranslationcache',
1281 Icon::SIZE_SMALL
1282 ));
1283 $saveSplitButton->addItem($saveAndClearTranslationButton);
1284 }
1285 $buttonBar->addButton($saveSplitButton, ButtonBar::BUTTON_POSITION_LEFT, 2);
1286 }
1287 // CLOSE button:
1288 $closeButton = $buttonBar->makeLinkButton()
1289 ->setHref('#')
1290 ->setClasses('t3js-editform-close')
1291 ->setTitle($lang->sL('LLL:EXT:lang/locallang_core.xlf:rm.closeDoc'))
1292 ->setIcon($this->moduleTemplate->getIconFactory()->getIcon(
1293 'actions-document-close',
1294 Icon::SIZE_SMALL
1295 ));
1296 $buttonBar->addButton($closeButton);
1297 // DELETE + UNDO buttons:
1298 if (!$this->errorC
1299 && !$GLOBALS['TCA'][$this->firstEl['table']]['ctrl']['readOnly']
1300 && count($this->elementsData) === 1
1301 ) {
1302 if ($this->firstEl['cmd'] !== 'new' && MathUtility::canBeInterpretedAsInteger($this->firstEl['uid'])) {
1303 // Delete:
1304 if ($this->firstEl['deleteAccess']
1305 && !$GLOBALS['TCA'][$this->firstEl['table']]['ctrl']['readOnly']
1306 && !$this->getNewIconMode($this->firstEl['table'], 'disableDelete')
1307 ) {
1308 $returnUrl = $this->retUrl;
1309 if ($this->firstEl['table'] === 'pages') {
1310 parse_str((string)parse_url($returnUrl, PHP_URL_QUERY), $queryParams);
1311 if (isset($queryParams['M'])
1312 && isset($queryParams['id'])
1313 && (string)$this->firstEl['uid'] === (string)$queryParams['id']
1314 ) {
1315 // TODO: Use the page's pid instead of 0, this requires a clean API to manipulate the page
1316 // tree from the outside to be able to mark the pid as active
1317 $returnUrl = BackendUtility::getModuleUrl($queryParams['M'], ['id' => 0]);
1318 }
1319 }
1320 $deleteButton = $buttonBar->makeLinkButton()
1321 ->setHref('#')
1322 ->setClasses('t3js-editform-delete-record')
1323 ->setTitle($lang->getLL('deleteItem'))
1324 ->setIcon($this->moduleTemplate->getIconFactory()->getIcon(
1325 'actions-edit-delete',
1326 Icon::SIZE_SMALL
1327 ))
1328 ->setDataAttributes([
1329 'return-url' => $returnUrl,
1330 'uid' => $this->firstEl['uid'],
1331 'table' => $this->firstEl['table']
1332 ]);
1333 $buttonBar->addButton($deleteButton, ButtonBar::BUTTON_POSITION_LEFT, 3);
1334 }
1335 // Undo:
1336 $undoRes = $this->getDatabaseConnection()->exec_SELECTquery(
1337 'tstamp',
1338 'sys_history',
1339 'tablename='
1340 . $this->getDatabaseConnection()->fullQuoteStr($this->firstEl['table'], 'sys_history')
1341 . ' AND recuid='
1342 . (int)$this->firstEl['uid'],
1343 '',
1344 'tstamp DESC',
1345 '1'
1346 );
1347 if ($undoButtonR = $this->getDatabaseConnection()->sql_fetch_assoc($undoRes)) {
1348 $aOnClick = 'window.location.href=' .
1349 GeneralUtility::quoteJSvalue(
1350 BackendUtility::getModuleUrl(
1351 'record_history',
1352 array(
1353 'element' => $this->firstEl['table'] . ':' . $this->firstEl['uid'],
1354 'revert' => 'ALL_FIELDS',
1355 'sumUp' => -1,
1356 'returnUrl' => $this->R_URI,
1357 )
1358 )
1359 ) . '; return false;';
1360
1361 $undoButton = $buttonBar->makeLinkButton()
1362 ->setHref('#')
1363 ->setOnClick($aOnClick)
1364 ->setTitle(
1365 sprintf(
1366 $lang->getLL('undoLastChange'),
1367 BackendUtility::calcAge(
1368 ($GLOBALS['EXEC_TIME'] - $undoButtonR['tstamp']),
1369 $lang->sL('LLL:EXT:lang/locallang_core.xlf:labels.minutesHoursDaysYears')
1370 )
1371 )
1372 )
1373 ->setIcon($this->moduleTemplate->getIconFactory()->getIcon(
1374 'actions-edit-undo',
1375 Icon::SIZE_SMALL
1376 ));
1377 $buttonBar->addButton($undoButton, ButtonBar::BUTTON_POSITION_LEFT, 3);
1378 }
1379 if ($this->getNewIconMode($this->firstEl['table'], 'showHistory')) {
1380 $aOnClick = 'window.location.href=' .
1381 GeneralUtility::quoteJSvalue(
1382 BackendUtility::getModuleUrl(
1383 'record_history',
1384 array(
1385 'element' => $this->firstEl['table'] . ':' . $this->firstEl['uid'],
1386 'returnUrl' => $this->R_URI,
1387 )
1388 )
1389 ) . '; return false;';
1390
1391 $historyButton = $buttonBar->makeLinkButton()
1392 ->setHref('#')
1393 ->setOnClick($aOnClick)
1394 ->setTitle('Open history of this record')
1395 ->setIcon($this->moduleTemplate->getIconFactory()->getIcon(
1396 'actions-document-history-open',
1397 Icon::SIZE_SMALL
1398 ));
1399 $buttonBar->addButton($historyButton, ButtonBar::BUTTON_POSITION_LEFT, 3);
1400 }
1401 // If only SOME fields are shown in the form, this will link the user to the FULL form:
1402 if ($this->columnsOnly) {
1403 $columnsOnlyButton = $buttonBar->makeLinkButton()
1404 ->setHref($this->R_URI . '&columnsOnly=')
1405 ->setTitle($lang->getLL('editWholeRecord'))
1406 ->setIcon($this->moduleTemplate->getIconFactory()->getIcon(
1407 'actions-document-open',
1408 Icon::SIZE_SMALL
1409 ));
1410 $buttonBar->addButton($columnsOnlyButton, ButtonBar::BUTTON_POSITION_LEFT, 3);
1411 }
1412 }
1413 }
1414 $cshButton = $buttonBar->makeHelpButton()->setModuleName('xMOD_csh_corebe')->setFieldName('TCEforms');
1415 $buttonBar->addButton($cshButton);
1416 $this->shortCutLink();
1417 $this->openInNewWindowLink();
1418 }
1419
1420 /**
1421 * Put together the various elements (buttons, selectors, form) into a table
1422 *
1423 * @param string $editForm HTML form.
1424 * @return string Composite HTML
1425 */
1426 public function compileForm($editForm)
1427 {
1428 $formContent = '
1429 <!-- EDITING FORM -->
1430 <form
1431 action="' . htmlspecialchars($this->R_URI) . '"
1432 method="post"
1433 enctype="multipart/form-data"
1434 name="editform"
1435 id="EditDocumentController"
1436 onsubmit="TBE_EDITOR.checkAndDoSubmit(1); return false;">
1437 ' . $editForm . '
1438
1439 <input type="hidden" name="returnUrl" value="' . htmlspecialchars($this->retUrl) . '" />
1440 <input type="hidden" name="viewUrl" value="' . htmlspecialchars($this->viewUrl) . '" />';
1441 if ($this->returnNewPageId) {
1442 $formContent .= '<input type="hidden" name="returnNewPageId" value="1" />';
1443 }
1444 $formContent .= '<input type="hidden" name="popViewId" value="' . htmlspecialchars($this->viewId) . '" />';
1445 if ($this->viewId_addParams) {
1446 $formContent .= '<input type="hidden" name="popViewId_addParams" value="' . htmlspecialchars($this->viewId_addParams) . '" />';
1447 }
1448 $formContent .= '
1449 <input type="hidden" name="closeDoc" value="0" />
1450 <input type="hidden" name="doSave" value="0" />
1451 <input type="hidden" name="_serialNumber" value="' . md5(microtime()) . '" />
1452 <input type="hidden" name="_scrollPosition" value="" />';
1453 return $formContent;
1454 }
1455
1456 /**
1457 * Create shortcut icon
1458 */
1459 public function shortCutLink()
1460 {
1461 if ($this->returnUrl !== 'sysext/backend/Resources/Private/Templates/Close.html') {
1462 $shortCutButton = $this->moduleTemplate->getDocHeaderComponent()->getButtonBar()->makeShortcutButton();
1463 $shortCutButton->setModuleName($this->MCONF['name'])
1464 ->setGetVariables([
1465 'returnUrl',
1466 'edit',
1467 'defVals',
1468 'overrideVals',
1469 'columnsOnly',
1470 'returnNewPageId',
1471 'noView']);
1472 $this->moduleTemplate->getDocHeaderComponent()->getButtonBar()->addButton($shortCutButton);
1473 }
1474 }
1475
1476 /**
1477 * Creates open-in-window link
1478 */
1479 public function openInNewWindowLink()
1480 {
1481 if ($this->returnUrl !== 'sysext/backend/Resources/Private/Templates/Close.html') {
1482 $aOnClick = 'vHWin=window.open(' . GeneralUtility::quoteJSvalue(GeneralUtility::linkThisScript(
1483 array('returnUrl' => 'sysext/backend/Resources/Private/Templates/Close.html')
1484 ))
1485 . ','
1486 . GeneralUtility::quoteJSvalue(md5($this->R_URI))
1487 . ',\'width=670,height=500,status=0,menubar=0,scrollbars=1,resizable=1\');vHWin.focus();return false;';
1488 $openInNewWindowButton = $this->moduleTemplate->getDocHeaderComponent()->getButtonBar()
1489 ->makeLinkButton()
1490 ->setHref('#')
1491 ->setTitle($this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:labels.openInNewWindow'))
1492 ->setIcon($this->moduleTemplate->getIconFactory()->getIcon('actions-window-open', Icon::SIZE_SMALL))
1493 ->setOnClick($aOnClick);
1494 $this->moduleTemplate->getDocHeaderComponent()->getButtonBar()->addButton(
1495 $openInNewWindowButton,
1496 ButtonBar::BUTTON_POSITION_RIGHT
1497 );
1498 }
1499 }
1500
1501 /***************************
1502 *
1503 * Localization stuff
1504 *
1505 ***************************/
1506 /**
1507 * Make selector box for creating new translation for a record or switching to edit the record in an existing
1508 * language.
1509 * Displays only languages which are available for the current page.
1510 *
1511 * @param string $table Table name
1512 * @param int $uid Uid for which to create a new language
1513 * @param int $pid Pid of the record
1514 */
1515 public function languageSwitch($table, $uid, $pid = null)
1516 {
1517 $languageField = $GLOBALS['TCA'][$table]['ctrl']['languageField'];
1518 $transOrigPointerField = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
1519 // Table editable and activated for languages?
1520 if ($this->getBackendUser()->check('tables_modify', $table)
1521 && $languageField
1522 && $transOrigPointerField && !$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerTable']
1523 ) {
1524 if (is_null($pid)) {
1525 $row = BackendUtility::getRecord($table, $uid, 'pid');
1526 $pid = $row['pid'];
1527 }
1528 // Get all available languages for the page
1529 $langRows = $this->getLanguages($pid);
1530 // Page available in other languages than default language?
1531 if (is_array($langRows) && count($langRows) > 1) {
1532 $rowsByLang = array();
1533 $fetchFields = 'uid,' . $languageField . ',' . $transOrigPointerField;
1534 // Get record in current language
1535 $rowCurrent = BackendUtility::getLiveVersionOfRecord($table, $uid, $fetchFields);
1536 if (!is_array($rowCurrent)) {
1537 $rowCurrent = BackendUtility::getRecord($table, $uid, $fetchFields);
1538 }
1539 $currentLanguage = (int)$rowCurrent[$languageField];
1540 // Disabled for records with [all] language!
1541 if ($currentLanguage > -1) {
1542 // Get record in default language if needed
1543 if ($currentLanguage && $rowCurrent[$transOrigPointerField]) {
1544 $rowsByLang[0] = BackendUtility::getLiveVersionOfRecord(
1545 $table,
1546 $rowCurrent[$transOrigPointerField],
1547 $fetchFields
1548 );
1549 if (!is_array($rowsByLang[0])) {
1550 $rowsByLang[0] = BackendUtility::getRecord(
1551 $table,
1552 $rowCurrent[$transOrigPointerField],
1553 $fetchFields
1554 );
1555 }
1556 } else {
1557 $rowsByLang[$rowCurrent[$languageField]] = $rowCurrent;
1558 }
1559 if ($rowCurrent[$transOrigPointerField] || $currentLanguage === 0) {
1560 // Get record in other languages to see what's already available
1561 $translations = $this->getDatabaseConnection()->exec_SELECTgetRows(
1562 $fetchFields,
1563 $table,
1564 'pid=' . (int)$pid . ' AND ' . $languageField . '>0' . ' AND ' . $transOrigPointerField . '=' . (int)$rowsByLang[0]['uid'] . BackendUtility::deleteClause($table) . BackendUtility::versioningPlaceholderClause($table)
1565 );
1566 foreach ($translations as $row) {
1567 $rowsByLang[$row[$languageField]] = $row;
1568 }
1569 }
1570 $languageMenu = $this->moduleTemplate->getDocHeaderComponent()->getMenuRegistry()->makeMenu();
1571 $languageMenu->setIdentifier('_langSelector');
1572 $languageMenu->setLabel($this->getLanguageService()->sL(
1573 'LLL:EXT:lang/locallang_general.xlf:LGL.language',
1574 true
1575 ));
1576 foreach ($langRows as $lang) {
1577 if ($this->getBackendUser()->checkLanguageAccess($lang['uid'])) {
1578 $newTranslation = isset($rowsByLang[$lang['uid']]) ? '' : ' [' . $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:labels.new', true) . ']';
1579 // Create url for creating a localized record
1580 if ($newTranslation) {
1581 $redirectUrl = BackendUtility::getModuleUrl('record_edit', array(
1582 'justLocalized' => $table . ':' . $rowsByLang[0]['uid'] . ':' . $lang['uid'],
1583 'returnUrl' => $this->retUrl
1584 ));
1585 $href = BackendUtility::getLinkToDataHandlerAction(
1586 '&cmd[' . $table . '][' . $rowsByLang[0]['uid'] . '][localize]=' . $lang['uid'],
1587 $redirectUrl
1588 );
1589 } else {
1590 $href = BackendUtility::getModuleUrl('record_edit', array(
1591 'edit[' . $table . '][' . $rowsByLang[$lang['uid']]['uid'] . ']' => 'edit',
1592 'returnUrl' => $this->retUrl
1593 ));
1594 }
1595 $menuItem = $languageMenu->makeMenuItem()
1596 ->setTitle($lang['title'] . $newTranslation)
1597 ->setHref($href);
1598 if ((int)$lang['uid'] === $currentLanguage) {
1599 $menuItem->setActive(true);
1600 }
1601 $languageMenu->addMenuItem($menuItem);
1602 }
1603 }
1604 $this->moduleTemplate->getDocHeaderComponent()->getMenuRegistry()->addMenu($languageMenu);
1605 }
1606 }
1607 }
1608 }
1609
1610 /**
1611 * Redirects to FormEngine with new parameters to edit a just created localized record
1612 *
1613 * @param string $justLocalized String passed by GET &justLocalized=
1614 * @return void
1615 */
1616 public function localizationRedirect($justLocalized)
1617 {
1618 list($table, $orig_uid, $language) = explode(':', $justLocalized);
1619 if ($GLOBALS['TCA'][$table]
1620 && $GLOBALS['TCA'][$table]['ctrl']['languageField']
1621 && $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']
1622 ) {
1623 $localizedRecord = $this->getDatabaseConnection()->exec_SELECTgetSingleRow(
1624 'uid',
1625 $table,
1626 $GLOBALS['TCA'][$table]['ctrl']['languageField'] . '=' . (int)$language . ' AND '
1627 . $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'] . '=' . (int)$orig_uid
1628 . BackendUtility::deleteClause($table) . BackendUtility::versioningPlaceholderClause($table)
1629 );
1630 if (is_array($localizedRecord)) {
1631 // Create parameters and finally run the classic page module for creating a new page translation
1632 $location = BackendUtility::getModuleUrl('record_edit', array(
1633 'edit[' . $table . '][' . $localizedRecord['uid'] . ']' => 'edit',
1634 'returnUrl' => GeneralUtility::sanitizeLocalUrl(GeneralUtility::_GP('returnUrl'))
1635 ));
1636 HttpUtility::redirect($location);
1637 }
1638 }
1639 }
1640
1641 /**
1642 * Returns sys_language records available for record translations on given page.
1643 *
1644 * @param int $id Page id: If zero, the query will select all sys_language records from root level which are NOT
1645 * hidden. If set to another value, the query will select all sys_language records that has a
1646 * pages_language_overlay record on that page (and is not hidden, unless you are admin user)
1647 * @return array Language records including faked record for default language
1648 */
1649 public function getLanguages($id)
1650 {
1651 $modSharedTSconfig = BackendUtility::getModTSconfig($id, 'mod.SHARED');
1652 // Fallback non sprite-configuration
1653 if (preg_match('/\\.gif$/', $modSharedTSconfig['properties']['defaultLanguageFlag'])) {
1654 $modSharedTSconfig['properties']['defaultLanguageFlag'] = str_replace(
1655 '.gif',
1656 '',
1657 $modSharedTSconfig['properties']['defaultLanguageFlag']
1658 );
1659 }
1660 $languages = array(
1661 0 => array(
1662 'uid' => 0,
1663 'pid' => 0,
1664 'hidden' => 0,
1665 'title' => $modSharedTSconfig['properties']['defaultLanguageLabel'] !== ''
1666 ? $modSharedTSconfig['properties']['defaultLanguageLabel'] . ' (' . $this->getLanguageService()->sL('LLL:EXT:lang/locallang_mod_web_list.xlf:defaultLanguage') . ')'
1667 : $this->getLanguageService()->sL('LLL:EXT:lang/locallang_mod_web_list.xlf:defaultLanguage'),
1668 'flag' => $modSharedTSconfig['properties']['defaultLanguageFlag']
1669 )
1670 );
1671 $exQ = $this->getBackendUser()->isAdmin() ? '' : ' AND sys_language.hidden=0';
1672 if ($id) {
1673 $rows = $this->getDatabaseConnection()->exec_SELECTgetRows(
1674 'sys_language.*',
1675 'pages_language_overlay,sys_language',
1676 'pages_language_overlay.sys_language_uid=sys_language.uid
1677 AND pages_language_overlay.pid=' . (int)$id . BackendUtility::deleteClause('pages_language_overlay')
1678 . $exQ,
1679 'pages_language_overlay.sys_language_uid,
1680 sys_language.uid,
1681 sys_language.pid,
1682 sys_language.tstamp,
1683 sys_language.hidden,
1684 sys_language.title,
1685 sys_language.language_isocode,
1686 sys_language.static_lang_isocode,
1687 sys_language.flag',
1688 'sys_language.title'
1689 );
1690 } else {
1691 $rows = $this->getDatabaseConnection()->exec_SELECTgetRows(
1692 'sys_language.*',
1693 'sys_language',
1694 'sys_language.hidden=0',
1695 '',
1696 'sys_language.title'
1697 );
1698 }
1699 if ($rows) {
1700 foreach ($rows as $row) {
1701 $languages[$row['uid']] = $row;
1702 }
1703 }
1704 return $languages;
1705 }
1706
1707 /***************************
1708 *
1709 * Other functions
1710 *
1711 ***************************/
1712 /**
1713 * Fix $this->editconf if versioning applies to any of the records
1714 *
1715 * @param array|bool $mapArray Mapping between old and new ids if auto-versioning has been performed.
1716 * @return void
1717 */
1718 public function fixWSversioningInEditConf($mapArray = false)
1719 {
1720 // Traverse the editConf array
1721 if (is_array($this->editconf)) {
1722 // Tables:
1723 foreach ($this->editconf as $table => $conf) {
1724 if (is_array($conf) && $GLOBALS['TCA'][$table]) {
1725 // Traverse the keys/comments of each table (keys can be a commalist of uids)
1726 $newConf = array();
1727 foreach ($conf as $cKey => $cmd) {
1728 if ($cmd == 'edit') {
1729 // Traverse the ids:
1730 $ids = GeneralUtility::trimExplode(',', $cKey, true);
1731 foreach ($ids as $idKey => $theUid) {
1732 if (is_array($mapArray)) {
1733 if ($mapArray[$table][$theUid]) {
1734 $ids[$idKey] = $mapArray[$table][$theUid];
1735 }
1736 } else {
1737 // Default, look for versions in workspace for record:
1738 $calcPRec = $this->getRecordForEdit($table, $theUid);
1739 if (is_array($calcPRec)) {
1740 // Setting UID again if it had changed, eg. due to workspace versioning.
1741 $ids[$idKey] = $calcPRec['uid'];
1742 }
1743 }
1744 }
1745 // Add the possibly manipulated IDs to the new-build newConf array:
1746 $newConf[implode(',', $ids)] = $cmd;
1747 } else {
1748 $newConf[$cKey] = $cmd;
1749 }
1750 }
1751 // Store the new conf array:
1752 $this->editconf[$table] = $newConf;
1753 }
1754 }
1755 }
1756 }
1757
1758 /**
1759 * Get record for editing.
1760 *
1761 * @param string $table Table name
1762 * @param int $theUid Record UID
1763 * @return array Returns record to edit, FALSE if none
1764 */
1765 public function getRecordForEdit($table, $theUid)
1766 {
1767 // Fetch requested record:
1768 $reqRecord = BackendUtility::getRecord($table, $theUid, 'uid,pid');
1769 if (is_array($reqRecord)) {
1770 // If workspace is OFFLINE:
1771 if ($this->getBackendUser()->workspace != 0) {
1772 // Check for versioning support of the table:
1773 if ($GLOBALS['TCA'][$table] && $GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
1774 // If the record is already a version of "something" pass it by.
1775 if ($reqRecord['pid'] == -1) {
1776 // (If it turns out not to be a version of the current workspace there will be trouble, but
1777 // that is handled inside TCEmain then and in the interface it would clearly be an error of
1778 // links if the user accesses such a scenario)
1779 return $reqRecord;
1780 } else {
1781 // The input record was online and an offline version must be found or made:
1782 // Look for version of this workspace:
1783 $versionRec = BackendUtility::getWorkspaceVersionOfRecord(
1784 $this->getBackendUser()->workspace,
1785 $table,
1786 $reqRecord['uid'],
1787 'uid,pid,t3ver_oid'
1788 );
1789 return is_array($versionRec) ? $versionRec : $reqRecord;
1790 }
1791 } else {
1792 // This means that editing cannot occur on this record because it was not supporting versioning
1793 // which is required inside an offline workspace.
1794 return false;
1795 }
1796 } else {
1797 // In ONLINE workspace, just return the originally requested record:
1798 return $reqRecord;
1799 }
1800 } else {
1801 // Return FALSE because the table/uid was not found anyway.
1802 return false;
1803 }
1804 }
1805
1806 /**
1807 * Populates the variables $this->storeArray, $this->storeUrl, $this->storeUrlMd5
1808 *
1809 * @return void
1810 * @see makeDocSel()
1811 */
1812 public function compileStoreDat()
1813 {
1814 $this->storeArray = GeneralUtility::compileSelectedGetVarsFromArray(
1815 'edit,defVals,overrideVals,columnsOnly,noView,workspace',
1816 $this->R_URL_getvars
1817 );
1818 $this->storeUrl = GeneralUtility::implodeArrayForUrl('', $this->storeArray);
1819 $this->storeUrlMd5 = md5($this->storeUrl);
1820 }
1821
1822 /**
1823 * Function used to look for configuration of buttons in the form: Fx. disabling buttons or showing them at various
1824 * positions.
1825 *
1826 * @param string $table The table for which the configuration may be specific
1827 * @param string $key The option for look for. Default is checking if the saveDocNew button should be displayed.
1828 * @return string Return value fetched from USER TSconfig
1829 */
1830 public function getNewIconMode($table, $key = 'saveDocNew')
1831 {
1832 $TSconfig = $this->getBackendUser()->getTSConfig('options.' . $key);
1833 $output = trim(isset($TSconfig['properties'][$table]) ? $TSconfig['properties'][$table] : $TSconfig['value']);
1834 return $output;
1835 }
1836
1837 /**
1838 * Handling the closing of a document
1839 *
1840 * @param int $code Close code: 0/1 will redirect to $this->retUrl, 3 will clear the docHandler (thus closing all
1841 * documents) and other values will call setDocument with ->retUrl
1842 * @return void
1843 */
1844 public function closeDocument($code = 0)
1845 {
1846 // If current document is found in docHandler,
1847 // then unset it, possibly unset it ALL and finally, write it to the session data
1848 if (isset($this->docHandler[$this->storeUrlMd5])) {
1849 // add the closing document to the recent documents
1850 $recentDocs = $this->getBackendUser()->getModuleData('opendocs::recent');
1851 if (!is_array($recentDocs)) {
1852 $recentDocs = array();
1853 }
1854 $closedDoc = $this->docHandler[$this->storeUrlMd5];
1855 $recentDocs = array_merge(array($this->storeUrlMd5 => $closedDoc), $recentDocs);
1856 if (count($recentDocs) > 8) {
1857 $recentDocs = array_slice($recentDocs, 0, 8);
1858 }
1859 // remove it from the list of the open documents
1860 unset($this->docHandler[$this->storeUrlMd5]);
1861 if ($code == '3') {
1862 $recentDocs = array_merge($this->docHandler, $recentDocs);
1863 $this->docHandler = array();
1864 }
1865 $this->getBackendUser()->pushModuleData('opendocs::recent', $recentDocs);
1866 $this->getBackendUser()->pushModuleData('FormEngine', array($this->docHandler, $this->docDat[1]));
1867 BackendUtility::setUpdateSignal('OpendocsController::updateNumber', count($this->docHandler));
1868 }
1869 // If ->returnEditConf is set, then add the current content of editconf to the ->retUrl variable: (used by
1870 // other scripts, like wizard_add, to know which records was created or so...)
1871 if ($this->returnEditConf && $this->retUrl != BackendUtility::getModuleUrl('dummy')) {
1872 $this->retUrl .= '&returnEditConf=' . rawurlencode(json_encode($this->editconf));
1873 }
1874 // If code is NOT set OR set to 1, then make a header location redirect to $this->retUrl
1875 if (!$code || $code == 1) {
1876 HttpUtility::redirect($this->retUrl);
1877 } else {
1878 $this->setDocument('', $this->retUrl);
1879 }
1880 }
1881
1882 /**
1883 * Redirects to the document pointed to by $currentDocFromHandlerMD5 OR $retUrl (depending on some internal
1884 * calculations).
1885 * Most likely you will get a header-location redirect from this function.
1886 *
1887 * @param string $currentDocFromHandlerMD5 Pointer to the document in the docHandler array
1888 * @param string $retUrl Alternative/Default retUrl
1889 * @return void
1890 */
1891 public function setDocument($currentDocFromHandlerMD5 = '', $retUrl = '')
1892 {
1893 if ($retUrl === '') {
1894 return;
1895 }
1896 if (!$this->modTSconfig['properties']['disableDocSelector']
1897 && is_array($this->docHandler)
1898 && !empty($this->docHandler)
1899 ) {
1900 if (isset($this->docHandler[$currentDocFromHandlerMD5])) {
1901 $setupArr = $this->docHandler[$currentDocFromHandlerMD5];
1902 } else {
1903 $setupArr = reset($this->docHandler);
1904 }
1905 if ($setupArr[2]) {
1906 $sParts = parse_url(GeneralUtility::getIndpEnv('REQUEST_URI'));
1907 $retUrl = $sParts['path'] . '?' . $setupArr[2] . '&returnUrl=' . rawurlencode($retUrl);
1908 }
1909 }
1910 HttpUtility::redirect($retUrl);
1911 }
1912
1913 /**
1914 * Injects the request object for the current request or subrequest
1915 *
1916 * @param ServerRequestInterface $request the current request
1917 * @param ResponseInterface $response
1918 * @return ResponseInterface the response with the content
1919 */
1920 public function mainAction(ServerRequestInterface $request, ResponseInterface $response)
1921 {
1922 BackendUtility::lockRecords();
1923
1924 // Preprocessing, storing data if submitted to
1925 $this->preInit();
1926
1927 // Checks, if a save button has been clicked (or the doSave variable is sent)
1928 if ($this->doProcessData()) {
1929 $this->processData();
1930 }
1931
1932 $this->init();
1933 $this->main();
1934
1935 $response->getBody()->write($this->moduleTemplate->renderContent());
1936 return $response;
1937 }
1938
1939 /**
1940 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
1941 */
1942 protected function getBackendUser()
1943 {
1944 return $GLOBALS['BE_USER'];
1945 }
1946
1947 /**
1948 * Returns LanguageService
1949 *
1950 * @return \TYPO3\CMS\Lang\LanguageService
1951 */
1952 protected function getLanguageService()
1953 {
1954 return $GLOBALS['LANG'];
1955 }
1956
1957 /**
1958 * Returns the database connection
1959 *
1960 * @return \TYPO3\CMS\Core\Database\DatabaseConnection
1961 */
1962 protected function getDatabaseConnection()
1963 {
1964 return $GLOBALS['TYPO3_DB'];
1965 }
1966 }