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