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