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