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