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