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