[TASK] Add override values to record information
[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 if (is_array($this->overrideVals) && is_array($this->overrideVals[$table])) {
951 $formDataCompilerInput['overrideValues'] = $this->overrideVals[$table];
952 }
953
954 $formData = $formDataCompiler->compile($formDataCompilerInput);
955
956 // Set this->viewId if possible
957 if ($command === 'new' && $table !== 'pages' && !empty($formData['parentPageRow']['uid'])) {
958 $this->viewId = $formData['parentPageRow']['uid'];
959 } else {
960 if ($table == 'pages') {
961 $this->viewId = $formData['databaseRow']['uid'];
962 } elseif (!empty($formData['parentPageRow']['uid'])) {
963 $this->viewId = $formData['parentPageRow']['uid'];
964 // Adding "&L=xx" if the record being edited has a languageField with a value larger than zero!
965 if (!empty($formData['vanillaTableTca']['ctrl']['languageField'])
966 && is_array($formData['databaseRow'][$formData['vanillaTableTca']['ctrl']['languageField']])
967 && $formData['databaseRow'][$formData['vanillaTableTca']['ctrl']['languageField']][0] > 0
968 ) {
969 $this->viewId_addParams = '&L=' . $formData['databaseRow'][$formData['vanillaTableTca']['ctrl']['languageField']][0];
970 }
971 }
972 }
973
974 // Determine if delete button can be shown
975 $deleteAccess = FALSE;
976 if ($command === 'edit') {
977 $permission = $formData['userPermissionOnPage'];
978 if ($formData['tableName'] === 'pages') {
979 $deleteAccess = $permission & Permission::PAGE_DELETE ? TRUE : FALSE;
980 } else {
981 $deleteAccess = $permission & Permission::CONTENT_EDIT ? TRUE : FALSE;
982 }
983 }
984
985 // Display "is-locked" message:
986 if ($command === 'edit') {
987 $lockInfo = BackendUtility::isRecordLocked($table, $formData['databaseRow']['uid']);
988 if ($lockInfo) {
989 /** @var $flashMessage \TYPO3\CMS\Core\Messaging\FlashMessage */
990 $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, htmlspecialchars($lockInfo['msg']), '', FlashMessage::WARNING);
991 /** @var $flashMessageService \TYPO3\CMS\Core\Messaging\FlashMessageService */
992 $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
993 /** @var $defaultFlashMessageQueue \TYPO3\CMS\Core\Messaging\FlashMessageQueue */
994 $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
995 $defaultFlashMessageQueue->enqueue($flashMessage);
996 }
997 }
998
999 // Record title
1000 if (!$this->storeTitle) {
1001 $this->storeTitle = $this->recTitle
1002 ? htmlspecialchars($this->recTitle)
1003 : BackendUtility::getRecordTitle($table, FormEngineUtility::databaseRowCompatibility($formData['databaseRow']), TRUE);
1004 }
1005
1006 $this->elementsData[] = array(
1007 'table' => $table,
1008 'uid' => $formData['databaseRow']['uid'],
1009 'pid' => $formData['databaseRow']['pid'],
1010 'cmd' => $command,
1011 'deleteAccess' => $deleteAccess
1012 );
1013
1014 if ($command !== 'new') {
1015 BackendUtility::lockRecords($table, $formData['databaseRow']['uid'], $table === 'tt_content' ? $formData['databaseRow']['pid'] : 0);
1016 }
1017
1018 // Set list if only specific fields should be rendered. This will trigger
1019 // ListOfFieldsContainer instead of FullRecordContainer in OuterWrapContainer
1020 if ($this->columnsOnly) {
1021 if (is_array($this->columnsOnly)) {
1022 $formData['fieldListToRender'] = $this->columnsOnly[$table];
1023 } else {
1024 $formData['fieldListToRender'] = $this->columnsOnly;
1025 }
1026 }
1027
1028 $formData['renderType'] = 'outerWrapContainer';
1029 $formResult = $nodeFactory->create($formData)->render();
1030
1031 $html = $formResult['html'];
1032
1033 $formResult['html'] = '';
1034 $formResult['doSaveFieldName'] = 'doSave';
1035
1036 // @todo: Put all the stuff into FormEngine as final "compiler" class
1037 // @todo: This is done here for now to not rewrite JStop()
1038 // @todo: and printNeededJSFunctions() now
1039 $this->formResultCompiler->mergeResult($formResult);
1040
1041 // Seems the pid is set as hidden field (again) at end?!
1042 if ($command == 'new') {
1043 // @todo: looks ugly
1044 $html .= LF
1045 . '<input type="hidden"'
1046 . ' name="data[' . $table . '][' . $formData['databaseRow']['uid'] . '][pid]"'
1047 . ' value="' . $formData['databaseRow']['pid'] . '" />';
1048 $this->newC++;
1049 }
1050
1051 $editForm .= $html;
1052
1053 } catch (AccessDeniedException $e) {
1054 $this->errorC++;
1055 // Try to fetch error message from "recordInternals" be user object
1056 // @todo: This construct should be logged and localized and de-uglified
1057 $message = $beUser->errorMsg;
1058 if (empty($message)) {
1059 // Create message from exception.
1060 $message = $e->getMessage() . ' ' . $e->getCode();
1061 }
1062 $editForm .= $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:labels.noEditPermission', TRUE)
1063 . '<br /><br />' . htmlspecialchars($message) . '<br /><br />';
1064 }
1065 } // End of for each uid
1066 }
1067 }
1068 }
1069 }
1070 return $editForm;
1071 }
1072
1073 /**
1074 * Create the panel of buttons for submitting the form or otherwise perform operations.
1075 *
1076 * @return array All available buttons as an assoc. array
1077 */
1078 protected function getButtons() {
1079 $lang = $this->getLanguageService();
1080 $buttons = array(
1081 'save' => '',
1082 'save_view' => '',
1083 'save_new' => '',
1084 'save_close' => '',
1085 'close' => '',
1086 'delete' => '',
1087 'undo' => '',
1088 'history' => '',
1089 'columns_only' => '',
1090 'csh' => '',
1091 'translation_save' => '',
1092 'translation_saveclear' => ''
1093 );
1094 /** @var IconFactory $iconFactory */
1095 $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
1096 // Render SAVE type buttons:
1097 // The action of each button is decided by its name attribute. (See doProcessData())
1098 if (!$this->errorC && !$GLOBALS['TCA'][$this->firstEl['table']]['ctrl']['readOnly']) {
1099 // SAVE button:
1100 $buttons['save'] = '<button name="_savedok" class="c-inputButton" value="1" title="' . $lang->sL('LLL:EXT:lang/locallang_core.xlf:rm.saveDoc', TRUE) . '">'
1101 . $iconFactory->getIcon('actions-document-save', Icon::SIZE_SMALL)
1102 . '</button>';
1103 // SAVE / VIEW button:
1104 if ($this->viewId && !$this->noView && $this->getNewIconMode($this->firstEl['table'], 'saveDocView')) {
1105 $pagesTSconfig = BackendUtility::getPagesTSconfig($this->pageinfo['uid']);
1106 if (isset($pagesTSconfig['TCEMAIN.']['preview.']['disableButtonForDokType'])) {
1107 $excludeDokTypes = GeneralUtility::intExplode(',', $pagesTSconfig['TCEMAIN.']['preview.']['disableButtonForDokType'], TRUE);
1108 } else {
1109 // exclude sysfolders, spacers and recycler by default
1110 $excludeDokTypes = array(PageRepository::DOKTYPE_RECYCLER, PageRepository::DOKTYPE_SYSFOLDER, PageRepository::DOKTYPE_SPACER);
1111 }
1112 if (!in_array((int)$this->pageinfo['doktype'], $excludeDokTypes, TRUE) || isset($pagesTSconfig['TCEMAIN.']['preview.'][$this->firstEl['table'].'.']['previewPageId'])) {
1113 $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\');">'
1114 . $iconFactory->getIcon('actions-document-save-view', Icon::SIZE_SMALL)
1115 . '</button>';
1116 }
1117 }
1118 // SAVE / NEW button:
1119 if (count($this->elementsData) === 1 && $this->getNewIconMode($this->firstEl['table'])) {
1120 $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) . '">'
1121 . $iconFactory->getIcon('actions-document-save-new', Icon::SIZE_SMALL)
1122 . '</button>';
1123 }
1124 // SAVE / CLOSE
1125 $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) . '">'
1126 . $iconFactory->getIcon('actions-document-save-close', Icon::SIZE_SMALL)
1127 . '</button>';
1128 // FINISH TRANSLATION / SAVE / CLOSE
1129 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['explicitConfirmationOfTranslation']) {
1130 $buttons['translation_save'] = '<button name="_translation_savedok" class="c-inputButton" value="1" title="' . $lang->sL('LLL:EXT:lang/locallang_core.xlf:rm.translationSaveDoc', TRUE) . '">'
1131 . $iconFactory->getIcon('actions-document-save-translation', Icon::SIZE_SMALL)
1132 . '</button>';
1133 $buttons['translation_saveclear'] = '<button name="_translation_savedokclear" class="c-inputButton" value="1" title="' . $lang->sL('LLL:EXT:lang/locallang_core.xlf:rm.translationSaveDocClear', TRUE) . '">'
1134 . $iconFactory->getIcon('actions-document-save-cleartranslationcache', Icon::SIZE_SMALL)
1135 . '</button>';
1136 }
1137 }
1138 // CLOSE button:
1139 $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>';
1140 // DELETE + UNDO buttons:
1141 if (!$this->errorC && !$GLOBALS['TCA'][$this->firstEl['table']]['ctrl']['readOnly'] && count($this->elementsData) === 1) {
1142 if ($this->firstEl['cmd'] != 'new' && MathUtility::canBeInterpretedAsInteger($this->firstEl['uid'])) {
1143 // Delete:
1144 if ($this->firstEl['deleteAccess'] && !$GLOBALS['TCA'][$this->firstEl['table']]['ctrl']['readOnly'] && !$this->getNewIconMode($this->firstEl['table'], 'disableDelete')) {
1145 $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>';
1146 }
1147 // Undo:
1148 $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');
1149 if ($undoButtonR = $this->getDatabaseConnection()->sql_fetch_assoc($undoRes)) {
1150 $aOnClick = 'window.location.href=' .
1151 GeneralUtility::quoteJSvalue(
1152 BackendUtility::getModuleUrl(
1153 'record_history',
1154 array(
1155 'element' => $this->firstEl['table'] . ':' . $this->firstEl['uid'],
1156 'revert' => 'ALL_FIELDS',
1157 'sumUp' => -1,
1158 'returnUrl' => $this->R_URI,
1159 )
1160 )
1161 ) . '; return false;';
1162 $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>';
1163 }
1164 if ($this->getNewIconMode($this->firstEl['table'], 'showHistory')) {
1165 $aOnClick = 'window.location.href=' .
1166 GeneralUtility::quoteJSvalue(
1167 BackendUtility::getModuleUrl(
1168 'record_history',
1169 array(
1170 'element' => $this->firstEl['table'] . ':' . $this->firstEl['uid'],
1171 'returnUrl' => $this->R_URI,
1172 )
1173 )
1174 ) . '; return false;';
1175 $buttons['history'] = '<a href="#" onclick="' . htmlspecialchars($aOnClick) . '">' . $this->iconFactory->getIcon('actions-document-history-open', Icon::SIZE_SMALL) . '</a>';
1176 }
1177 // If only SOME fields are shown in the form, this will link the user to the FULL form:
1178 if ($this->columnsOnly) {
1179 $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>';
1180 }
1181 }
1182 }
1183 // add the CSH icon
1184 $buttons['csh'] = BackendUtility::cshItem('xMOD_csh_corebe', 'TCEforms');
1185 $buttons['shortcut'] = $this->shortCutLink();
1186 $buttons['open_in_new_window'] = $this->openInNewWindowLink();
1187
1188 return $buttons;
1189 }
1190
1191 /**
1192 * Returns the language switch/selector for editing,
1193 * show only when a single record is edited
1194 * - multiple records are too confusing
1195 *
1196 * @return string The HTML
1197 */
1198 public function langSelector() {
1199 $langSelector = '';
1200 if (count($this->elementsData) === 1) {
1201 $langSelector = $this->languageSwitch($this->firstEl['table'], $this->firstEl['uid'], $this->firstEl['pid']);
1202 }
1203 return $langSelector;
1204 }
1205
1206 /**
1207 * Put together the various elements (buttons, selectors, form) into a table
1208 *
1209 * @param string $editForm HTML form.
1210 * @return string Composite HTML
1211 */
1212 public function compileForm($editForm) {
1213 $formContent = '
1214 <!-- EDITING FORM -->
1215 ' . $editForm . '
1216
1217 <input type="hidden" name="returnUrl" value="' . htmlspecialchars($this->retUrl) . '" />
1218 <input type="hidden" name="viewUrl" value="' . htmlspecialchars($this->viewUrl) . '" />';
1219 if ($this->returnNewPageId) {
1220 $formContent .= '<input type="hidden" name="returnNewPageId" value="1" />';
1221 }
1222 $formContent .= '<input type="hidden" name="popViewId" value="' . htmlspecialchars($this->viewId) . '" />';
1223 if ($this->viewId_addParams) {
1224 $formContent .= '<input type="hidden" name="popViewId_addParams" value="' . htmlspecialchars($this->viewId_addParams) . '" />';
1225 }
1226 $formContent .= '
1227 <input type="hidden" name="closeDoc" value="0" />
1228 <input type="hidden" name="doSave" value="0" />
1229 <input type="hidden" name="_serialNumber" value="' . md5(microtime()) . '" />
1230 <input type="hidden" name="_scrollPosition" value="" />';
1231 return $formContent;
1232 }
1233
1234 /**
1235 * Create shortcut icon
1236 *
1237 * @return string
1238 */
1239 public function shortCutLink() {
1240 if ($this->returnUrl === 'sysext/backend/Resources/Private/Templates/Close.html' || !$this->getBackendUser()->mayMakeShortcut()) {
1241 return '';
1242 }
1243 return $this->doc->makeShortcutIcon('returnUrl,edit,defVals,overrideVals,columnsOnly,returnNewPageId,editRegularContentFromId,noView', '', $this->MCONF['name'], 1);
1244 }
1245
1246 /**
1247 * Creates open-in-window link
1248 *
1249 * @return string
1250 */
1251 public function openInNewWindowLink() {
1252 if ($this->returnUrl === 'sysext/backend/Resources/Private/Templates/Close.html') {
1253 return '';
1254 }
1255 $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;';
1256 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>';
1257 }
1258
1259 /***************************
1260 *
1261 * Localization stuff
1262 *
1263 ***************************/
1264 /**
1265 * Make selector box for creating new translation for a record or switching to edit the record in an existing language.
1266 * Displays only languages which are available for the current page.
1267 *
1268 * @param string $table Table name
1269 * @param int $uid Uid for which to create a new language
1270 * @param int $pid Pid of the record
1271 * @return string <select> HTML element (if there were items for the box anyways...)
1272 */
1273 public function languageSwitch($table, $uid, $pid = NULL) {
1274 $content = '';
1275 $languageField = $GLOBALS['TCA'][$table]['ctrl']['languageField'];
1276 $transOrigPointerField = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
1277 // Table editable and activated for languages?
1278 if ($this->getBackendUser()->check('tables_modify', $table) && $languageField && $transOrigPointerField && !$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerTable']) {
1279 if (is_null($pid)) {
1280 $row = BackendUtility::getRecord($table, $uid, 'pid');
1281 $pid = $row['pid'];
1282 }
1283 // Get all avalibale languages for the page
1284 $langRows = $this->getLanguages($pid);
1285 // Page available in other languages than default language?
1286 if (is_array($langRows) && count($langRows) > 1) {
1287 $rowsByLang = array();
1288 $fetchFields = 'uid,' . $languageField . ',' . $transOrigPointerField;
1289 // Get record in current language
1290 $rowCurrent = BackendUtility::getLiveVersionOfRecord($table, $uid, $fetchFields);
1291 if (!is_array($rowCurrent)) {
1292 $rowCurrent = BackendUtility::getRecord($table, $uid, $fetchFields);
1293 }
1294 $currentLanguage = $rowCurrent[$languageField];
1295 // Disabled for records with [all] language!
1296 if ($currentLanguage > -1) {
1297 // Get record in default language if needed
1298 if ($currentLanguage && $rowCurrent[$transOrigPointerField]) {
1299 $rowsByLang[0] = BackendUtility::getLiveVersionOfRecord($table, $rowCurrent[$transOrigPointerField], $fetchFields);
1300 if (!is_array($rowsByLang[0])) {
1301 $rowsByLang[0] = BackendUtility::getRecord($table, $rowCurrent[$transOrigPointerField], $fetchFields);
1302 }
1303 } else {
1304 $rowsByLang[$rowCurrent[$languageField]] = $rowCurrent;
1305 }
1306 if ($rowCurrent[$transOrigPointerField] || $currentLanguage === '0') {
1307 // Get record in other languages to see what's already available
1308 $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));
1309 foreach ($translations as $row) {
1310 $rowsByLang[$row[$languageField]] = $row;
1311 }
1312 }
1313 $langSelItems = array();
1314 foreach ($langRows as $lang) {
1315 if ($this->getBackendUser()->checkLanguageAccess($lang['uid'])) {
1316 $newTranslation = isset($rowsByLang[$lang['uid']]) ? '' : ' [' . $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:labels.new', TRUE) . ']';
1317 // Create url for creating a localized record
1318 if ($newTranslation) {
1319 $redirectUrl = BackendUtility::getModuleUrl('record_edit', array(
1320 'justLocalized' => $table . ':' . $rowsByLang[0]['uid'] . ':' . $lang['uid'],
1321 'returnUrl' => $this->retUrl
1322 ));
1323 $href = $this->doc->issueCommand('&cmd[' . $table . '][' . $rowsByLang[0]['uid'] . '][localize]=' . $lang['uid'], $redirectUrl);
1324 } else {
1325 $href = BackendUtility::getModuleUrl('record_edit', array(
1326 'edit[' . $table . '][' . $rowsByLang[$lang['uid']]['uid'] . ']' => 'edit',
1327 'returnUrl' => $this->retUrl
1328 ));
1329 }
1330 $langSelItems[$lang['uid']] = '
1331 <option value="' . htmlspecialchars($href) . '"' . ($currentLanguage == $lang['uid'] ? ' selected="selected"' : '') . '>' . htmlspecialchars(($lang['title'] . $newTranslation)) . '</option>';
1332 }
1333 }
1334 // If any languages are left, make selector:
1335 if (count($langSelItems) > 1) {
1336 $onChange = 'if(this.options[this.selectedIndex].value){window.location.href=(this.options[this.selectedIndex].value);}';
1337 $content = $this->getLanguageService()->sL('LLL:EXT:lang/locallang_general.xlf:LGL.language', TRUE) . ' <select name="_langSelector" onchange="' . htmlspecialchars($onChange) . '">
1338 ' . implode('', $langSelItems) . '
1339 </select>';
1340 }
1341 }
1342 }
1343 }
1344 return $content;
1345 }
1346
1347 /**
1348 * Redirects to FormEngine with new parameters to edit a just created localized record
1349 *
1350 * @param string $justLocalized String passed by GET &justLocalized=
1351 * @return void
1352 */
1353 public function localizationRedirect($justLocalized) {
1354 list($table, $orig_uid, $language) = explode(':', $justLocalized);
1355 if ($GLOBALS['TCA'][$table] && $GLOBALS['TCA'][$table]['ctrl']['languageField'] && $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']) {
1356 $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));
1357 if (is_array($localizedRecord)) {
1358 // Create parameters and finally run the classic page module for creating a new page translation
1359 $location = BackendUtility::getModuleUrl('record_edit', array(
1360 'edit[' . $table . '][' . $localizedRecord['uid'] . ']' => 'edit',
1361 'returnUrl' => GeneralUtility::sanitizeLocalUrl(GeneralUtility::_GP('returnUrl'))
1362 ));
1363 HttpUtility::redirect($location);
1364 }
1365 }
1366 }
1367
1368 /**
1369 * Returns sys_language records available for record translations on given page.
1370 *
1371 * @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)
1372 * @return array Language records including faked record for default language
1373 */
1374 public function getLanguages($id) {
1375 $modSharedTSconfig = BackendUtility::getModTSconfig($id, 'mod.SHARED');
1376 // Fallback non sprite-configuration
1377 if (preg_match('/\\.gif$/', $modSharedTSconfig['properties']['defaultLanguageFlag'])) {
1378 $modSharedTSconfig['properties']['defaultLanguageFlag'] = str_replace('.gif', '', $modSharedTSconfig['properties']['defaultLanguageFlag']);
1379 }
1380 $languages = array(
1381 0 => array(
1382 'uid' => 0,
1383 'pid' => 0,
1384 'hidden' => 0,
1385 'title' => $modSharedTSconfig['properties']['defaultLanguageLabel'] !== ''
1386 ? $modSharedTSconfig['properties']['defaultLanguageLabel'] . ' (' . $this->getLanguageService()->sl('LLL:EXT:lang/locallang_mod_web_list.xlf:defaultLanguage') . ')'
1387 : $this->getLanguageService()->sl('LLL:EXT:lang/locallang_mod_web_list.xlf:defaultLanguage'),
1388 'flag' => $modSharedTSconfig['properties']['defaultLanguageFlag']
1389 )
1390 );
1391 $exQ = $this->getBackendUser()->isAdmin() ? '' : ' AND sys_language.hidden=0';
1392 if ($id) {
1393 $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');
1394 } else {
1395 $rows = $this->getDatabaseConnection()->exec_SELECTgetRows('sys_language.*', 'sys_language', 'sys_language.hidden=0', '', 'sys_language.title');
1396 }
1397 if ($rows) {
1398 foreach ($rows as $row) {
1399 $languages[$row['uid']] = $row;
1400 }
1401 }
1402 return $languages;
1403 }
1404
1405 /***************************
1406 *
1407 * Other functions
1408 *
1409 ***************************/
1410 /**
1411 * Fix $this->editconf if versioning applies to any of the records
1412 *
1413 * @param array|bool $mapArray Mapping between old and new ids if auto-versioning has been performed.
1414 * @return void
1415 */
1416 public function fixWSversioningInEditConf($mapArray = FALSE) {
1417 // Traverse the editConf array
1418 if (is_array($this->editconf)) {
1419 // Tables:
1420 foreach ($this->editconf as $table => $conf) {
1421 if (is_array($conf) && $GLOBALS['TCA'][$table]) {
1422 // Traverse the keys/comments of each table (keys can be a commalist of uids)
1423 $newConf = array();
1424 foreach ($conf as $cKey => $cmd) {
1425 if ($cmd == 'edit') {
1426 // Traverse the ids:
1427 $ids = GeneralUtility::trimExplode(',', $cKey, TRUE);
1428 foreach ($ids as $idKey => $theUid) {
1429 if (is_array($mapArray)) {
1430 if ($mapArray[$table][$theUid]) {
1431 $ids[$idKey] = $mapArray[$table][$theUid];
1432 }
1433 } else {
1434 // Default, look for versions in workspace for record:
1435 $calcPRec = $this->getRecordForEdit($table, $theUid);
1436 if (is_array($calcPRec)) {
1437 // Setting UID again if it had changed, eg. due to workspace versioning.
1438 $ids[$idKey] = $calcPRec['uid'];
1439 }
1440 }
1441 }
1442 // Add the possibly manipulated IDs to the new-build newConf array:
1443 $newConf[implode(',', $ids)] = $cmd;
1444 } else {
1445 $newConf[$cKey] = $cmd;
1446 }
1447 }
1448 // Store the new conf array:
1449 $this->editconf[$table] = $newConf;
1450 }
1451 }
1452 }
1453 }
1454
1455 /**
1456 * Get record for editing.
1457 *
1458 * @param string $table Table name
1459 * @param int $theUid Record UID
1460 * @return array Returns record to edit, FALSE if none
1461 */
1462 public function getRecordForEdit($table, $theUid) {
1463 // Fetch requested record:
1464 $reqRecord = BackendUtility::getRecord($table, $theUid, 'uid,pid');
1465 if (is_array($reqRecord)) {
1466 // If workspace is OFFLINE:
1467 if ($this->getBackendUser()->workspace != 0) {
1468 // Check for versioning support of the table:
1469 if ($GLOBALS['TCA'][$table] && $GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
1470 // If the record is already a version of "something" pass it by.
1471 if ($reqRecord['pid'] == -1) {
1472 // (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)
1473 return $reqRecord;
1474 } else {
1475 // The input record was online and an offline version must be found or made:
1476 // Look for version of this workspace:
1477 $versionRec = BackendUtility::getWorkspaceVersionOfRecord($this->getBackendUser()->workspace, $table, $reqRecord['uid'], 'uid,pid,t3ver_oid');
1478 return is_array($versionRec) ? $versionRec : $reqRecord;
1479 }
1480 } else {
1481 // This means that editing cannot occur on this record because it was not supporting versioning which is required inside an offline workspace.
1482 return FALSE;
1483 }
1484 } else {
1485 // In ONLINE workspace, just return the originally requested record:
1486 return $reqRecord;
1487 }
1488 } else {
1489 // Return FALSE because the table/uid was not found anyway.
1490 return FALSE;
1491 }
1492 }
1493
1494 /**
1495 * 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
1496 *
1497 * @return void
1498 * @deprecated since TYPO3 CMS 7, will be removed with TYPO3 CMS 8
1499 */
1500 public function editRegularContentFromId() {
1501 GeneralUtility::logDeprecatedFunction();
1502 $dbConnection = $this->getDatabaseConnection();
1503 $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');
1504 if ($dbConnection->sql_num_rows($res)) {
1505 $ecUids = array();
1506 while ($ecRec = $dbConnection->sql_fetch_assoc($res)) {
1507 $ecUids[] = $ecRec['uid'];
1508 }
1509 $this->editconf['tt_content'][implode(',', $ecUids)] = 'edit';
1510 }
1511 $dbConnection->sql_free_result($res);
1512 }
1513
1514 /**
1515 * Populates the variables $this->storeArray, $this->storeUrl, $this->storeUrlMd5
1516 *
1517 * @return void
1518 * @see makeDocSel()
1519 */
1520 public function compileStoreDat() {
1521 $this->storeArray = GeneralUtility::compileSelectedGetVarsFromArray('edit,defVals,overrideVals,columnsOnly,noView,editRegularContentFromId,workspace', $this->R_URL_getvars);
1522 $this->storeUrl = GeneralUtility::implodeArrayForUrl('', $this->storeArray);
1523 $this->storeUrlMd5 = md5($this->storeUrl);
1524 }
1525
1526 /**
1527 * Function used to look for configuration of buttons in the form: Fx. disabling buttons or showing them at various positions.
1528 *
1529 * @param string $table The table for which the configuration may be specific
1530 * @param string $key The option for look for. Default is checking if the saveDocNew button should be displayed.
1531 * @return string Return value fetched from USER TSconfig
1532 */
1533 public function getNewIconMode($table, $key = 'saveDocNew') {
1534 $TSconfig = $this->getBackendUser()->getTSConfig('options.' . $key);
1535 $output = trim(isset($TSconfig['properties'][$table]) ? $TSconfig['properties'][$table] : $TSconfig['value']);
1536 return $output;
1537 }
1538
1539 /**
1540 * Handling the closing of a document
1541 *
1542 * @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
1543 * @return void
1544 */
1545 public function closeDocument($code = 0) {
1546 // If current document is found in docHandler,
1547 // then unset it, possibly unset it ALL and finally, write it to the session data
1548 if (isset($this->docHandler[$this->storeUrlMd5])) {
1549 // add the closing document to the recent documents
1550 $recentDocs = $this->getBackendUser()->getModuleData('opendocs::recent');
1551 if (!is_array($recentDocs)) {
1552 $recentDocs = array();
1553 }
1554 $closedDoc = $this->docHandler[$this->storeUrlMd5];
1555 $recentDocs = array_merge(array($this->storeUrlMd5 => $closedDoc), $recentDocs);
1556 if (count($recentDocs) > 8) {
1557 $recentDocs = array_slice($recentDocs, 0, 8);
1558 }
1559 // remove it from the list of the open documents
1560 unset($this->docHandler[$this->storeUrlMd5]);
1561 if ($code == '3') {
1562 $recentDocs = array_merge($this->docHandler, $recentDocs);
1563 $this->docHandler = array();
1564 }
1565 $this->getBackendUser()->pushModuleData('opendocs::recent', $recentDocs);
1566 $this->getBackendUser()->pushModuleData('FormEngine', array($this->docHandler, $this->docDat[1]));
1567 BackendUtility::setUpdateSignal('OpendocsController::updateNumber', count($this->docHandler));
1568 }
1569 // 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...)
1570 if ($this->returnEditConf && $this->retUrl != BackendUtility::getModuleUrl('dummy')) {
1571 $this->retUrl .= '&returnEditConf=' . rawurlencode(json_encode($this->editconf));
1572 }
1573 // If code is NOT set OR set to 1, then make a header location redirect to $this->retUrl
1574 if (!$code || $code == 1) {
1575 HttpUtility::redirect($this->retUrl);
1576 } else {
1577 $this->setDocument('', $this->retUrl);
1578 }
1579 }
1580
1581 /**
1582 * Redirects to the document pointed to by $currentDocFromHandlerMD5 OR $retUrl (depending on some internal calculations).
1583 * Most likely you will get a header-location redirect from this function.
1584 *
1585 * @param string $currentDocFromHandlerMD5 Pointer to the document in the docHandler array
1586 * @param string $retUrl Alternative/Default retUrl
1587 * @return void
1588 */
1589 public function setDocument($currentDocFromHandlerMD5 = '', $retUrl = '') {
1590 if ($retUrl === '') {
1591 return;
1592 }
1593 if (!$this->modTSconfig['properties']['disableDocSelector'] && is_array($this->docHandler) && !empty($this->docHandler)) {
1594 if (isset($this->docHandler[$currentDocFromHandlerMD5])) {
1595 $setupArr = $this->docHandler[$currentDocFromHandlerMD5];
1596 } else {
1597 $setupArr = reset($this->docHandler);
1598 }
1599 if ($setupArr[2]) {
1600 $sParts = parse_url(GeneralUtility::getIndpEnv('REQUEST_URI'));
1601 $retUrl = $sParts['path'] . '?' . $setupArr[2] . '&returnUrl=' . rawurlencode($retUrl);
1602 }
1603 }
1604 HttpUtility::redirect($retUrl);
1605 }
1606
1607 /**
1608 * Injects the request object for the current request or subrequest
1609 *
1610 * @param ServerRequestInterface $request the current request
1611 * @param ResponseInterface $response
1612 * @return ResponseInterface the response with the content
1613 */
1614 public function mainAction(ServerRequestInterface $request, ResponseInterface $response) {
1615 BackendUtility::lockRecords();
1616
1617 // Preprocessing, storing data if submitted to
1618 $this->preInit();
1619
1620 // Checks, if a save button has been clicked (or the doSave variable is sent)
1621 if ($this->doProcessData()) {
1622 $this->processData();
1623 }
1624
1625 $this->init();
1626 $this->main();
1627
1628 $response->getBody()->write($this->content);
1629 return $response;
1630 }
1631
1632 /**
1633 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
1634 */
1635 protected function getBackendUser() {
1636 return $GLOBALS['BE_USER'];
1637 }
1638
1639 /**
1640 * Returns LanguageService
1641 *
1642 * @return \TYPO3\CMS\Lang\LanguageService
1643 */
1644 protected function getLanguageService() {
1645 return $GLOBALS['LANG'];
1646 }
1647
1648 /**
1649 * Returns the database connection
1650 *
1651 * @return \TYPO3\CMS\Core\Database\DatabaseConnection
1652 */
1653 protected function getDatabaseConnection() {
1654 return $GLOBALS['TYPO3_DB'];
1655 }
1656
1657 }