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