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