EditDocumentController.php 62.3 KB
Newer Older
1
2
3
<?php
namespace TYPO3\CMS\Backend\Controller;

4
/*
5
 * This file is part of the TYPO3 CMS project.
6
 *
7
8
9
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
10
 *
11
12
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
13
 *
14
15
 * The TYPO3 project - inspiring people to share!
 */
16

17
use Psr\Http\Message\ServerRequestInterface;
18
19
use TYPO3\CMS\Backend\Form\Exception\AccessDeniedException;
use TYPO3\CMS\Backend\Form\FormResultCompiler;
20
use TYPO3\CMS\Backend\Form\Utility\FormEngineUtility;
Nicole Cordes's avatar
Nicole Cordes committed
21
22
use TYPO3\CMS\Backend\Utility\BackendUtility;
use TYPO3\CMS\Backend\Utility\IconUtility;
23
use TYPO3\CMS\Core\DataHandling\DataHandler;
24
use TYPO3\CMS\Core\Http\Response;
25
26
use TYPO3\CMS\Core\Imaging\Icon;
use TYPO3\CMS\Core\Imaging\IconFactory;
27
28
29
use TYPO3\CMS\Core\Messaging\FlashMessage;
use TYPO3\CMS\Core\Messaging\FlashMessageService;
use TYPO3\CMS\Core\Page\PageRenderer;
30
use TYPO3\CMS\Core\Type\Bitmask\Permission;
Nicole Cordes's avatar
Nicole Cordes committed
31
32
33
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\HttpUtility;
use TYPO3\CMS\Core\Utility\MathUtility;
34
use TYPO3\CMS\Extbase\SignalSlot\Dispatcher;
35
use TYPO3\CMS\Frontend\Page\PageRepository;
36
37
38
use TYPO3\CMS\Backend\Form\FormDataCompiler;
use TYPO3\CMS\Backend\Form\NodeFactory;
use TYPO3\CMS\Backend\Form\FormDataGroup\TcaDatabaseRecord;
Nicole Cordes's avatar
Nicole Cordes committed
39

40
41
42
43
/**
 * Script Class: Drawing the editing form for editing records in TYPO3.
 * Notice: It does NOT use tce_db.php to submit data to, rather it handles submissions itself
 */
44
class EditDocumentController implements \TYPO3\CMS\Core\Http\ControllerInterface {
45

46
47
48
49
50
51
52
	/**
	 * GPvar "edit": Is an array looking approx like [tablename][list-of-ids]=command, eg.
	 * "&edit[pages][123]=edit". See \TYPO3\CMS\Backend\Utility\BackendUtility::editOnClick(). Value can be seen modified
	 * internally (converting NEW keyword to id, workspace/versioning etc).
	 *
	 * @var array
	 */
53
54
	public $editconf;

55
56
57
58
59
60
61
	/**
	 * Commalist of fieldnames to edit. The point is IF you specify this list, only those
	 * fields will be rendered in the form. Otherwise all (available) fields in the record
	 * is shown according to the types configuration in $GLOBALS['TCA']
	 *
	 * @var bool
	 */
62
63
	public $columnsOnly;

64
65
66
67
68
69
	/**
	 * Default values for fields (array with tablenames, fields etc. as keys).
	 * Can be seen modified internally.
	 *
	 * @var array
	 */
70
71
	public $defVals;

72
73
74
75
76
77
	/**
	 * Array of values to force being set (as hidden fields). Will be set as $this->defVals
	 * IF defVals does not exist.
	 *
	 * @var array
	 */
78
79
	public $overrideVals;

80
81
82
83
84
85
	/**
	 * If set, this value will be set in $this->retUrl (which is used quite many places
	 * as the return URL). If not set, "dummy.php" will be set in $this->retUrl
	 *
	 * @var string
	 */
86
87
	public $returnUrl;

88
89
90
91
92
	/**
	 * Close-document command. Not really sure of all options...
	 *
	 * @var int
	 */
93
94
	public $closeDoc;

95
96
97
98
99
100
101
	/**
	 * Quite simply, if this variable is set, then the processing of incoming data will be performed
	 * as if a save-button is pressed. Used in the forms as a hidden field which can be set through
	 * JavaScript if the form is somehow submitted by JavaScript).
	 *
	 * @var bool
	 */
102
103
	public $doSave;

104
105
106
107
108
	/**
	 * The data array from which the data comes...
	 *
	 * @var array
	 */
109
110
	public $data;

111
112
113
114
115
	/**
	 * @var string
	 */
	public $cmd;

116
117
118
	/**
	 * @var array
	 */
119
120
	public $mirror;

121
122
123
124
125
	/**
	 * Clear-cache cmd.
	 *
	 * @var string
	 */
126
127
	public $cacheCmd;

128
129
130
131
132
	/**
	 * Redirect (not used???)
	 *
	 * @var string
	 */
133
134
	public $redirect;

135
136
137
138
139
140
	/**
	 * Boolean: If set, then the GET var "&id=" will be added to the
	 * retUrl string so that the NEW id of something is returned to the script calling the form.
	 *
	 * @var bool
	 */
141
142
	public $returnNewPageId;

143
144
145
	/**
	 * @var string
	 */
146
147
	public $vC;

148
149
150
151
152
	/**
	 * update BE_USER->uc
	 *
	 * @var array
	 */
153
154
	public $uc;

155
156
157
158
159
	/**
	 * ID for displaying the page in the frontend (used for SAVE/VIEW operations)
	 *
	 * @var int
	 */
160
161
	public $popViewId;

162
163
164
165
166
	/**
	 * Additional GET vars for the link, eg. "&L=xxx"
	 *
	 * @var string
	 */
167
168
	public $popViewId_addParams;

169
170
171
172
173
	/**
	 * Alternative URL for viewing the frontend pages.
	 *
	 * @var string
	 */
174
175
	public $viewUrl;

176
177
178
179
180
	/**
	 * If this is pointing to a page id it will automatically load all content elements
	 * (NORMAL column/default language) from that page into the form!
	 *
	 * @var int
181
	 * @deprecated since TYPO3 CMS 7, will be removed with TYPO3 CMS 8
182
	 */
183
184
	public $editRegularContentFromId;

185
186
187
188
189
	/**
	 * Alternative title for the document handler.
	 *
	 * @var string
	 */
190
191
	public $recTitle;

192
193
194
195
196
	/**
	 * If set, then no SAVE/VIEW button is printed
	 *
	 * @var bool
	 */
197
198
	public $noView;

199
200
201
202
203
	/**
	 * @var string
	 */
	public $perms_clause;

204
205
206
207
208
209
	/**
	 * If set, the $this->editconf array is returned to the calling script
	 * (used by wizard_add.php for instance)
	 *
	 * @var bool
	 */
210
211
	public $returnEditConf;

212
213
214
215
216
217
218
	/**
	 * Workspace used for the editing action.
	 *
	 * @var NULL|integer
	 */
	protected $workspace;

219
220
221
	/**
	 * document template object
	 *
222
	 * @var \TYPO3\CMS\Backend\Template\DocumentTemplate
223
224
225
	 */
	public $doc;

226
227
228
229
230
	/**
	 * a static HTML template, usually in templates/alt_doc.html
	 *
	 * @var string
	 */
231
232
	public $template;

233
234
235
236
237
	/**
	 * Content accumulation
	 *
	 * @var string
	 */
238
239
	public $content;

240
241
	/**
	 * Return URL script, processed. This contains the script (if any) that we should
242
	 * RETURN TO from the FormEngine script IF we press the close button. Thus this
243
244
245
246
	 * variable is normally passed along from the calling script so we can properly return if needed.
	 *
	 * @var string
	 */
247
248
	public $retUrl;

249
250
251
252
253
254
255
	/**
	 * Contains the parts of the REQUEST_URI (current url). By parts we mean the result of resolving
	 * REQUEST_URI (current url) by the parse_url() function. The result is an array where eg. "path"
	 * is the script path and "query" is the parameters...
	 *
	 * @var array
	 */
256
257
	public $R_URL_parts;

258
259
260
261
262
263
	/**
	 * Contains the current GET vars array; More specifically this array is the foundation for creating
	 * the R_URI internal var (which becomes the "url of this script" to which we submit the forms etc.)
	 *
	 * @var array
	 */
264
265
	public $R_URL_getvars;

266
267
268
269
270
	/**
	 * Set to the URL of this script including variables which is needed to re-display the form. See main()
	 *
	 * @var string
	 */
271
272
	public $R_URI;

273
274
275
276
277
278
279
280
281
282
	/**
	 * @var array
	 */
	public $MCONF;

	/**
	 * @var array
	 */
	public $pageinfo;

283
284
285
286
287
288
	/**
	 * Is loaded with the "title" of the currently "open document" - this is used in the
	 * Document Selector box. (see makeDocSel())
	 *
	 * @var string
	 */
289
	public $storeTitle = '';
290

291
292
293
294
295
296
	/**
	 * Contains an array with key/value pairs of GET parameters needed to reach the
	 * current document displayed - used in the Document Selector box. (see compileStoreDat())
	 *
	 * @var array
	 */
297
298
	public $storeArray;

299
300
301
302
303
	/**
	 * Contains storeArray, but imploded into a GET parameter string (see compileStoreDat())
	 *
	 * @var string
	 */
304
305
	public $storeUrl;

306
307
308
309
310
	/**
	 * Hashed value of storeURL (see compileStoreDat())
	 *
	 * @var string
	 */
311
312
	public $storeUrlMd5;

313
314
315
316
317
	/**
	 * Module session data
	 *
	 * @var array
	 */
318
319
	public $docDat;

320
321
322
323
324
325
326
327
	/**
	 * An array of the "open documents" - keys are md5 hashes (see $storeUrlMd5) identifying
	 * the various documents on the GET parameter list needed to open it. The values are
	 * arrays with 0,1,2 keys with information about the document (see compileStoreDat()).
	 * The docHandler variable is stored in the $docDat session data, key "0".
	 *
	 * @var array
	 */
328
329
	public $docHandler;

330
331
332
333
334
	/**
	 * Array of the elements to create edit forms for.
	 *
	 * @var array
	 */
335
336
	public $elementsData;

337
338
339
340
341
	/**
	 * Pointer to the first element in $elementsData
	 *
	 * @var array
	 */
342
343
	public $firstEl;

344
345
346
347
348
	/**
	 * Counter, used to count the number of errors (when users do not have edit permissions)
	 *
	 * @var int
	 */
349
350
	public $errorC;

351
352
353
354
355
	/**
	 * Counter, used to count the number of new record forms displayed
	 *
	 * @var int
	 */
356
357
	public $newC;

358
359
360
361
362
363
	/**
	 * Is set to the pid value of the last shown record - thus indicating which page to
	 * show when clicking the SAVE/VIEW button
	 *
	 * @var int
	 */
364
365
	public $viewId;

366
367
368
369
370
	/**
	 * Is set to additional parameters (like "&L=xxx") if the record supports it.
	 *
	 * @var string
	 */
371
372
	public $viewId_addParams;

373
374
375
376
377
	/**
	 * Module TSconfig, loaded from main() based on the page id value of viewId
	 *
	 * @var array
	 */
378
379
380
	public $modTSconfig;

	/**
381
	 * @var FormResultCompiler
382
	 */
383
	protected $formResultCompiler;
384

385
386
387
388
389
	/**
	 * Used internally to disable the storage of the document reference (eg. new records)
	 *
	 * @var bool
	 */
390
	public $dontStoreDocumentRef = 0;
391

392
393
394
395
396
	/**
	 * @var \TYPO3\CMS\Extbase\SignalSlot\Dispatcher
	 */
	protected $signalSlotDispatcher;

397
398
399
400
401
402
403
	/**
	 * Stores information needed to preview the currently saved record
	 *
	 * @var array
	 */
	protected $previewData = [];

404
405
406
407
408
	/**
	 * @var IconFactory
	 */
	protected $iconFactory;

409
410
411
412
413
	/**
	 * Constructor
	 */
	public function __construct() {
		$GLOBALS['SOBE'] = $this;
414
		$this->getLanguageService()->includeLLFile('EXT:lang/locallang_alt_doc.xlf');
415
		$this->iconFactory = GeneralUtility::makeInstance(IconFactory::class);
416
417
	}

418
419
420
421
422
423
424
	/**
	 * Get the SignalSlot dispatcher
	 *
	 * @return \TYPO3\CMS\Extbase\SignalSlot\Dispatcher
	 */
	protected function getSignalSlotDispatcher() {
		if (!isset($this->signalSlotDispatcher)) {
425
			$this->signalSlotDispatcher = GeneralUtility::makeInstance(Dispatcher::class);
426
427
428
429
		}
		return $this->signalSlotDispatcher;
	}

430
431
432
433
434
435
436
437
438
	/**
	 * Emits a signal after a function was executed
	 *
	 * @param string $signalName
	 */
	protected function emitFunctionAfterSignal($signalName) {
		$this->getSignalSlotDispatcher()->dispatch(__CLASS__, $signalName . 'After', array($this));
	}

439
440
441
442
443
444
	/**
	 * First initialization.
	 *
	 * @return void
	 */
	public function preInit() {
Nicole Cordes's avatar
Nicole Cordes committed
445
446
		if (GeneralUtility::_GP('justLocalized')) {
			$this->localizationRedirect(GeneralUtility::_GP('justLocalized'));
447
448
		}
		// Setting GPvars:
Nicole Cordes's avatar
Nicole Cordes committed
449
450
451
452
453
454
455
456
457
		$this->editconf = GeneralUtility::_GP('edit');
		$this->defVals = GeneralUtility::_GP('defVals');
		$this->overrideVals = GeneralUtility::_GP('overrideVals');
		$this->columnsOnly = GeneralUtility::_GP('columnsOnly');
		$this->returnUrl = GeneralUtility::sanitizeLocalUrl(GeneralUtility::_GP('returnUrl'));
		$this->closeDoc = GeneralUtility::_GP('closeDoc');
		$this->doSave = GeneralUtility::_GP('doSave');
		$this->returnEditConf = GeneralUtility::_GP('returnEditConf');
		$this->localizationMode = GeneralUtility::_GP('localizationMode');
458
		$this->workspace = GeneralUtility::_GP('workspace');
Nicole Cordes's avatar
Nicole Cordes committed
459
		$this->uc = GeneralUtility::_GP('uc');
460
461
462
463
464
		// Setting override values as default if defVals does not exist.
		if (!is_array($this->defVals) && is_array($this->overrideVals)) {
			$this->defVals = $this->overrideVals;
		}
		// Setting return URL
465
		$this->retUrl = $this->returnUrl ?: BackendUtility::getModuleUrl('dummy');
466
467
468
		// Fix $this->editconf if versioning applies to any of the records
		$this->fixWSversioningInEditConf();
		// Make R_URL (request url) based on input GETvars:
Nicole Cordes's avatar
Nicole Cordes committed
469
470
		$this->R_URL_parts = parse_url(GeneralUtility::getIndpEnv('REQUEST_URI'));
		$this->R_URL_getvars = GeneralUtility::_GET();
471
472
473
474
		$this->R_URL_getvars['edit'] = $this->editconf;
		// MAKE url for storing
		$this->compileStoreDat();
		// Get session data for the module:
475
		$this->docDat = $this->getBackendUser()->getModuleData('FormEngine', 'ses');
476
477
478
479
480
481
482
483
		$this->docHandler = $this->docDat[0];
		// If a request for closing the document has been sent, act accordingly:
		if ($this->closeDoc > 0) {
			$this->closeDocument($this->closeDoc);
		}
		// If NO vars are sent to the script, try to read first document:
		// Added !is_array($this->editconf) because editConf must not be set either.
		// Anyways I can't figure out when this situation here will apply...
484
		if (is_array($this->R_URL_getvars) && count($this->R_URL_getvars) < 2 && !is_array($this->editconf)) {
485
486
			$this->setDocument($this->docDat[1]);
		}
487
488
489
490
491

		// Sets a temporary workspace, this request is based on
		if ($this->workspace !== NULL) {
			$this->getBackendUser()->setTemporaryWorkspace($this->workspace);
		}
492

493
		$this->emitFunctionAfterSignal(__FUNCTION__);
494
495
496
497
498
	}

	/**
	 * Detects, if a save command has been triggered.
	 *
499
	 * @return bool TRUE, then save the document (data submitted)
500
501
	 */
	public function doProcessData() {
502
		$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']);
503
504
505
506
507
508
509
510
511
		return $out;
	}

	/**
	 * Do processing of data, submitting it to TCEmain.
	 *
	 * @return void
	 */
	public function processData() {
512
		$beUser = $this->getBackendUser();
513
		// GPvars specifically for processing:
Nicole Cordes's avatar
Nicole Cordes committed
514
515
516
517
518
519
520
521
		$control = GeneralUtility::_GP('control');
		$this->data = GeneralUtility::_GP('data');
		$this->cmd = GeneralUtility::_GP('cmd');
		$this->mirror = GeneralUtility::_GP('mirror');
		$this->cacheCmd = GeneralUtility::_GP('cacheCmd');
		$this->redirect = GeneralUtility::_GP('redirect');
		$this->returnNewPageId = GeneralUtility::_GP('returnNewPageId');
		$this->vC = GeneralUtility::_GP('vC');
522
523
		// See tce_db.php for relevate options here:
		// Only options related to $this->data submission are included here.
524
		/** @var $tce \TYPO3\CMS\Core\DataHandling\DataHandler */
525
526
		$tce = GeneralUtility::makeInstance(DataHandler::class);
		$tce->stripslashes_values = FALSE;
527
528
529
530

		if (!empty($control)) {
			$tce->setControl($control);
		}
531
532
533
534
535
536
537
538
		if (isset($_POST['_translation_savedok_x'])) {
			$tce->updateModeL10NdiffData = 'FORCE_FFUPD';
		}
		if (isset($_POST['_translation_savedokclear_x'])) {
			$tce->updateModeL10NdiffData = 'FORCE_FFUPD';
			$tce->updateModeL10NdiffDataClear = TRUE;
		}
		// Setting default values specific for the user:
539
		$TCAdefaultOverride = $beUser->getTSConfigProp('TCAdefaults');
540
541
542
543
		if (is_array($TCAdefaultOverride)) {
			$tce->setDefaultsFromUserTS($TCAdefaultOverride);
		}
		// Setting internal vars:
544
		if ($beUser->uc['neverHideAtCopy']) {
545
546
547
548
549
550
551
552
			$tce->neverHideAtCopy = 1;
		}
		// Loading TCEmain with data:
		$tce->start($this->data, $this->cmd);
		if (is_array($this->mirror)) {
			$tce->setMirror($this->mirror);
		}
		// Checking referer / executing
Nicole Cordes's avatar
Nicole Cordes committed
553
554
		$refInfo = parse_url(GeneralUtility::getIndpEnv('HTTP_REFERER'));
		$httpHost = GeneralUtility::getIndpEnv('TYPO3_HOST_ONLY');
555
		if ($httpHost != $refInfo['host'] && $this->vC != $beUser->veriCode() && !$GLOBALS['TYPO3_CONF_VARS']['SYS']['doNotCheckReferer']) {
556
557
558
559
560
561
562
			$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));
			debug('Error: Referer host did not match with server host.');
		} else {
			// Perform the saving operation with TCEmain:
			$tce->process_uploads($_FILES);
			$tce->process_datamap();
			$tce->process_cmdmap();
563
			// If pages are being edited, we set an instruction about updating the page tree after this operation.
564
			if ($tce->pagetreeNeedsRefresh && (isset($this->data['pages']) || $beUser->workspace != 0 && !empty($this->data))) {
565
566
				BackendUtility::setUpdateSignal('updatePageTree');
			}
567
			// If there was saved any new items, load them:
568
			if (!empty($tce->substNEWwithIDs_table)) {
569
				// save the expanded/collapsed states for new inline records, if any
Christian Kuhn's avatar
Christian Kuhn committed
570
				FormEngineUtility::updateInlineView($this->uc, $tce);
571
572
573
				$newEditConf = array();
				foreach ($this->editconf as $tableName => $tableCmds) {
					$keys = array_keys($tce->substNEWwithIDs_table, $tableName);
574
					if (!empty($keys)) {
575
576
577
578
579
						foreach ($keys as $key) {
							$editId = $tce->substNEWwithIDs[$key];
							// Check if the $editId isn't a child record of an IRRE action
							if (!(is_array($tce->newRelatedIDs[$tableName]) && in_array($editId, $tce->newRelatedIDs[$tableName]))) {
								// Translate new id to the workspace version:
580
								if ($versionRec = BackendUtility::getWorkspaceVersionOfRecord($beUser->workspace, $tableName, $editId, 'uid')) {
581
582
583
584
585
									$editId = $versionRec['uid'];
								}
								$newEditConf[$tableName][$editId] = 'edit';
							}
							// Traverse all new records and forge the content of ->editconf so we can continue to EDIT these records!
586
							if ($tableName == 'pages' && $this->retUrl != BackendUtility::getModuleUrl('dummy') && $this->returnNewPageId) {
587
588
589
590
591
592
593
594
								$this->retUrl .= '&id=' . $tce->substNEWwithIDs[$key];
							}
						}
					} else {
						$newEditConf[$tableName] = $tableCmds;
					}
				}
				// Resetting editconf if newEditConf has values:
595
				if (!empty($newEditConf)) {
596
597
598
599
600
601
602
603
604
605
					$this->editconf = $newEditConf;
				}
				// Finally, set the editconf array in the "getvars" so they will be passed along in URLs as needed.
				$this->R_URL_getvars['edit'] = $this->editconf;
				// Unsetting default values since we don't need them anymore.
				unset($this->R_URL_getvars['defVals']);
				// Re-compile the store* values since editconf changed...
				$this->compileStoreDat();
			}
			// See if any records was auto-created as new versions?
606
			if (!empty($tce->autoVersionIdMap)) {
607
608
609
				$this->fixWSversioningInEditConf($tce->autoVersionIdMap);
			}
			// If a document is saved and a new one is created right after.
610
			if (isset($_POST['_savedoknew']) && is_array($this->editconf)) {
611
612
613
614
615
616
				// Finding the current table:
				reset($this->editconf);
				$nTable = key($this->editconf);
				// Finding the first id, getting the records pid+uid
				reset($this->editconf[$nTable]);
				$nUid = key($this->editconf[$nTable]);
Nicole Cordes's avatar
Nicole Cordes committed
617
				$nRec = BackendUtility::getRecord($nTable, $nUid, 'pid,uid');
618
619
620
621
622
623
624
625
626
627
628
629
				// Setting a blank editconf array for a new record:
				$this->editconf = array();
				if ($this->getNewIconMode($nTable) == 'top') {
					$this->editconf[$nTable][$nRec['pid']] = 'new';
				} else {
					$this->editconf[$nTable][-$nRec['uid']] = 'new';
				}
				// Finally, set the editconf array in the "getvars" so they will be passed along in URLs as needed.
				$this->R_URL_getvars['edit'] = $this->editconf;
				// Re-compile the store* values since editconf changed...
				$this->compileStoreDat();
			}
630
			// If a preview is requested
631
			if (isset($_POST['_savedokview'])) {
632
633
634
635
636
637
638
639
640
641
				// Get the first table and id of the data array from DataHandler
				$table = reset(array_keys($this->data));
				$id = reset(array_keys($this->data[$table]));
				if (!MathUtility::canBeInterpretedAsInteger($id)) {
					$id = $tce->substNEWwithIDs[$id];
				}
				// Store this information for later use
				$this->previewData['table'] = $table;
				$this->previewData['id'] = $id;
			}
642
			$tce->printLogErrorMessages(isset($_POST['_saveandclosedok']) || isset($_POST['_translation_savedok_x']) ? $this->retUrl : $this->R_URL_parts['path'] . '?' . GeneralUtility::implodeArrayForUrl('', $this->R_URL_getvars));
643
644
645
		}
		//  || count($tce->substNEWwithIDs)... If any new items has been save, the document is CLOSED
		// because if not, we just get that element re-listed as new. And we don't want that!
646
		if (isset($_POST['_saveandclosedok']) || isset($_POST['_translation_savedok_x']) || $this->closeDoc < 0) {
647
648
649
650
651
652
653
654
655
656
			$this->closeDocument(abs($this->closeDoc));
		}
	}

	/**
	 * Initialize the normal module operation
	 *
	 * @return void
	 */
	public function init() {
657
		$beUser = $this->getBackendUser();
658
		// Setting more GPvars:
Nicole Cordes's avatar
Nicole Cordes committed
659
660
661
662
663
664
		$this->popViewId = GeneralUtility::_GP('popViewId');
		$this->popViewId_addParams = GeneralUtility::_GP('popViewId_addParams');
		$this->viewUrl = GeneralUtility::_GP('viewUrl');
		$this->editRegularContentFromId = GeneralUtility::_GP('editRegularContentFromId');
		$this->recTitle = GeneralUtility::_GP('recTitle');
		$this->noView = GeneralUtility::_GP('noView');
665
		$this->perms_clause = $beUser->getPagePermsClause(1);
666
667
		// Set other internal variables:
		$this->R_URL_getvars['returnUrl'] = $this->retUrl;
668
		$this->R_URI = $this->R_URL_parts['path'] . '?' . ltrim(GeneralUtility::implodeArrayForUrl('', $this->R_URL_getvars), '&');
669
670
		// Setting virtual document name
		$this->MCONF['name'] = 'xMOD_alt_doc.php';
671

672
673
		// Create an instance of the document template object
		$this->doc = $GLOBALS['TBE_TEMPLATE'];
674
675
		$pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
		$pageRenderer->addInlineLanguageLabelFile('EXT:lang/locallang_alt_doc.xlf');
676
		$this->doc->setModuleTemplate('EXT:backend/Resources/Private/Templates/alt_doc.html');
677
		$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;">';
678
679
680
		// override the default jumpToUrl
		$this->doc->JScodeArray['jumpToUrl'] = '
			function jumpToUrl(URL,formEl) {
681
682
683
684
685
686
				if (!TBE_EDITOR.isFormChanged()) {
					window.location.href = URL;
				} else if (formEl && formEl.type=="checkbox") {
					formEl.checked = formEl.checked ? 0 : 1;
				}
			}
687
';
688
689
690
		// define the window size of the element browser
		$popupWindowWidth  = 700;
		$popupWindowHeight = 750;
691
		$popupWindowSize = trim($beUser->getTSConfigVal('options.popupWindowSize'));
692
693
694
695
696
697
698
699
700
		if (!empty($popupWindowSize)) {
			list($popupWindowWidth, $popupWindowHeight) = GeneralUtility::intExplode('x', $popupWindowSize);
		}
		$t3Configuration = array(
			'PopupWindow' => array(
				'width' => $popupWindowWidth,
				'height' => $popupWindowHeight
			),
		);
701
702
703
704
705
		$javascript = '
			TYPO3.configuration = ' . json_encode($t3Configuration) . ';
			// Object: TS:
			// passwordDummy and decimalSign are used by tbe_editor.js and have to be declared here as
			// TS object overwrites the object declared in tbe_editor.js
706
707
708
			function typoSetup() {	//
				this.uniqueID = "";
				this.passwordDummy = "********";
709
				this.PATH_typo3 = "";
710
711
712
713
714
715
716
				this.decimalSign = ".";
			}
			var TS = new typoSetup();

				// Info view:
			function launchView(table,uid,bP) {	//
				var backPath= bP ? bP : "";
717
718
719
720
721
				var thePreviewWindow = window.open(
					backPath+' . GeneralUtility::quoteJSvalue(BackendUtility::getModuleUrl('show_item') . '&table=') . ' + encodeURIComponent(table) + "&uid=" + encodeURIComponent(uid),
					"ShowItem" + TS.uniqueID,
					"height=300,width=410,status=0,menubar=0,resizable=0,location=0,directories=0,scrollbars=1,toolbar=0"
				);
722
723
724
725
726
				if (thePreviewWindow && thePreviewWindow.focus) {
					thePreviewWindow.focus();
				}
			}
			function deleteRecord(table,id,url) {	//
727
				window.location.href = ' . GeneralUtility::quoteJSvalue(BackendUtility::getModuleUrl('tce_db') . '&cmd[') . '+table+"]["+id+"][delete]=1&redirect="+escape(url)+"&vC=' . $beUser->veriCode() . '&prErr=1&uPT=1";
728
			}
729
730
		';

731
		$previewCode = isset($_POST['_savedokview']) && $this->popViewId ? $this->generatePreviewCode() : '';
732
733

		$this->doc->JScode = $this->doc->wrapScriptTags($javascript . $previewCode);
734
735
		// Setting up the context sensitive menu:
		$this->doc->getContextMenuCode();
Nicole Cordes's avatar
Nicole Cordes committed
736
		$this->doc->bodyTagAdditions = 'onload="window.scrollTo(0,' . MathUtility::forceIntegerInRange(GeneralUtility::_GP('_scrollPosition'), 0, 10000) . ');"';
737

738
		$this->emitFunctionAfterSignal(__FUNCTION__);
739
740
	}

741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
	/**
	 * @return string
	 */
	protected function generatePreviewCode() {
		$currentPageId = MathUtility::convertToPositiveInteger($this->popViewId);
		$table = $this->previewData['table'];
		$recordId = $this->previewData['id'];

		$pageTsConfig = BackendUtility::getPagesTSconfig($currentPageId);
		$previewConfiguration = isset($pageTsConfig['TCEMAIN.']['preview.'][$table . '.'])
			? $pageTsConfig['TCEMAIN.']['preview.'][$table . '.']
			: array();

		$recordArray = BackendUtility::getRecord($table, $recordId);

		// find the right preview page id
		$previewPageId = 0;
		if (isset($previewConfiguration['previewPageId'])) {
			$previewPageId = $previewConfiguration['previewPageId'];
		}
		// if no preview page was configured
		if (!$previewPageId) {
			$rootPageData = NULL;
			$rootLine = BackendUtility::BEgetRootLine($currentPageId);
			$currentPage = reset($rootLine);
			if ((int)$currentPage['doktype'] === PageRepository::DOKTYPE_DEFAULT) {
				// try the current page
				$previewPageId = $currentPageId;
			} else {
				// or search for the root page
				foreach ($rootLine as $page) {
					if ($page['is_siteroot']) {
						$rootPageData = $page;
						break;
					}
				}
				$previewPageId = isset($rootPageData)
					? (int)$rootPageData['uid']
					: $currentPageId;
			}
		}

		$linkParameters = [
			'no_cache' => 1,
		];

		// language handling
		$languageField = isset($GLOBALS['TCA'][$table]['ctrl']['languageField'])
			? $GLOBALS['TCA'][$table]['ctrl']['languageField']
			: '';
		if ($languageField && !empty($recordArray[$languageField])) {
			$l18nPointer = isset($GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'])
				? $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']
				: '';
			if (
				$l18nPointer && !empty($recordArray[$l18nPointer])
				&& isset($previewConfiguration['useDefaultLanguageRecord'])
				&& !$previewConfiguration['useDefaultLanguageRecord']
			) {
				// use parent record
				$recordId = $recordArray[$l18nPointer];
			}
			$linkParameters['L'] = $recordArray[$languageField];
		}

		// map record data to GET parameters
		if (isset($previewConfiguration['fieldToParameterMap.'])) {
			foreach ($previewConfiguration['fieldToParameterMap.'] as $field => $parameterName) {
				$value = $recordArray[$field];
				if ($field === 'uid') {
					$value = $recordId;
				}
				$linkParameters[$parameterName] = $value;
			}
		}

		// add/override parameters by configuration
		if (isset($previewConfiguration['additionalGetParameters.'])) {
			$linkParameters = array_replace($linkParameters, $previewConfiguration['additionalGetParameters.']);
		}

		$this->popViewId = $previewPageId;
		$this->popViewId_addParams = GeneralUtility::implodeArrayForUrl('', $linkParameters, '', FALSE, TRUE);

		$previewPageRootline = BackendUtility::BEgetRootLine($this->popViewId);
		return '
				if (window.opener) {
				'
			. BackendUtility::viewOnClick($this->popViewId, '', $previewPageRootline, '', $this->viewUrl, $this->popViewId_addParams, FALSE)
			. '
				} else {
				'
			. BackendUtility::viewOnClick($this->popViewId, '', $previewPageRootline, '', $this->viewUrl, $this->popViewId_addParams)
			. '
				}';
	}

838
839
840
841
842
843
	/**
	 * Main module operation
	 *
	 * @return void
	 */
	public function main() {
844
		$body = '';
845
846
		// Begin edit:
		if (is_array($this->editconf)) {
847
848
849
			/** @var FormResultCompiler formResultCompiler */
			$this->formResultCompiler = GeneralUtility::makeInstance(FormResultCompiler::class);

850
851
852
853
854
855
856
857
			if ($this->editRegularContentFromId) {
				$this->editRegularContentFromId();
			}
			// Creating the editing form, wrap it with buttons, document selector etc.
			$editForm = $this->makeEditForm();
			if ($editForm) {
				$this->firstEl = reset($this->elementsData);
				// Checking if the currently open document is stored in the list of "open documents" - if not, then add it:
858
				if (($this->docDat[1] !== $this->storeUrlMd5 || !isset($this->docHandler[$this->storeUrlMd5])) && !$this->dontStoreDocumentRef) {
859
					$this->docHandler[$this->storeUrlMd5] = array($this->storeTitle, $this->storeArray, $this->storeUrl, $this->firstEl);
860
					$this->getBackendUser()->pushModuleData('FormEngine', array($this->docHandler, $this->storeUrlMd5));
Nicole Cordes's avatar
Nicole Cordes committed
861
					BackendUtility::setUpdateSignal('OpendocsController::updateNumber', count($this->docHandler));
862
863
				}
				// Module configuration
Nicole Cordes's avatar
Nicole Cordes committed
864
				$this->modTSconfig = $this->viewId ? BackendUtility::getModTSconfig($this->viewId, 'mod.xMOD_alt_doc') : array();
865
				$body = $this->formResultCompiler->JStop();
866
				$body .= $this->compileForm($editForm);
867
				$body .= $this->formResultCompiler->printNeededJSFunctions();
868
869
870
871
			}
		}
		// Access check...
		// The page will show only if there is a valid page and if this page may be viewed by the user
Nicole Cordes's avatar
Nicole Cordes committed
872
		$this->pageinfo = BackendUtility::readPageAccess($this->viewId, $this->perms_clause);
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
		// Setting up the buttons and markers for docheader
		$docHeaderButtons = $this->getButtons();
		$markers = array(
			'LANGSELECTOR' => $this->langSelector(),
			'CSH' => $docHeaderButtons['csh'],
			'CONTENT' => $body
		);
		// Build the <body> for the module
		$this->content = $this->doc->startPage('TYPO3 Edit Document');
		$this->content .= $this->doc->moduleBody($this->pageinfo, $docHeaderButtons, $markers);
		$this->content .= $this->doc->endPage();
		$this->content = $this->doc->insertStylesAndJS($this->content);
	}

	/**
	 * Outputting the accumulated content to screen
	 *
	 * @return void
891
	 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
892
893
	 */
	public function printContent() {
894
		GeneralUtility::logDeprecatedFunction();
895
896
897
898
899
900
901
902
903
		echo $this->content;
	}

	/***************************
	 *
	 * Sub-content functions, rendering specific parts of the module content.
	 *
	 ***************************/
	/**
904
	 * Creates the editing form with FormEnigne, based on the input from GPvars.
905
906
907
908
909
910
911
912
913
914
	 *
	 * @return string HTML form elements wrapped in tables
	 */
	public function makeEditForm() {
		// Initialize variables:
		$this->elementsData = array();
		$this->errorC = 0;
		$this->newC = 0;
		$editForm = '';
		$trData = NULL;
915
		$beUser = $this->getBackendUser();
916
917
918
		// Traverse the GPvar edit array
		// Tables:
		foreach ($this->editconf as $table => $conf) {
919
			if (is_array($conf) && $GLOBALS['TCA'][$table] && $beUser->check('tables_modify', $table)) {
920
				// Traverse the keys/comments of each table (keys can be a commalist of uids)
921
922
				foreach ($conf as $cKey => $command) {
					if ($command == 'edit' || $command == 'new') {
923
						// Get the ids:
924
						$ids = GeneralUtility::trimExplode(',', $cKey, TRUE);
925
926
						// Traverse the ids:
						foreach ($ids as $theUid) {
927
928
929

							// Don't save this document title in the document selector if the document is new.
							if ($command === 'new') {
930
								$this->dontStoreDocumentRef = 1;
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
							}

							/** @var TcaDatabaseRecord $formDataGroup */
							$formDataGroup = GeneralUtility::makeInstance(TcaDatabaseRecord::class);
							/** @var FormDataCompiler $formDataCompiler */
							$formDataCompiler = GeneralUtility::makeInstance(FormDataCompiler::class, $formDataGroup);
							/** @var NodeFactory $nodeFactory */
							$nodeFactory = GeneralUtility::makeInstance(NodeFactory::class);

							try {
								// Reset viewId - it should hold data of last entry only
								$this->viewId = 0;
								$this->viewId_addParams = '';

								$formDataCompilerInput = [
									'tableName' => $table,
									'vanillaUid' => (int)$theUid,
									'command' => $command,
									'returnUrl' => $this->R_URI,
								];
								$formData = $formDataCompiler->compile($formDataCompilerInput);

								// Set this->viewId if possible
								if ($command === 'new' && $table !== 'pages' && !empty($formData['parentPageRow']['uid'])) {
									$this->viewId = $formData['parentPageRow']['uid'];
								} else {
									if ($table == 'pages') {
										$this->viewId = $formData['databaseRow']['uid'];
									} elseif (!empty($formData['parentPageRow']['uid'])) {
										$this->viewId = $formData['parentPageRow']['uid'];
961
										// Adding "&L=xx" if the record being edited has a languageField with a value larger than zero!
962
963
964
965
966
										if (!empty($formData['vanillaTableTca']['ctrl']['languageField'])
											&& is_array($formData['databaseRow'][$formData['vanillaTableTca']['ctrl']['languageField']])
											&& $formData['databaseRow'][$formData['vanillaTableTca']['ctrl']['languageField']][0] > 0
										) {
											$this->viewId_addParams = '&L=' . $formData['databaseRow'][$formData['vanillaTableTca']['ctrl']['languageField']][0];
967
968
969
										}
									}
								}
970
971
972
973
974
975
976

								// Determine if delete button can be shown
								$deleteAccess = FALSE;
								if ($command === 'edit') {
									$permission = $formData['userPermissionOnPage'];
									if ($formData['tableName'] === 'pages') {
										$deleteAccess = $permission & Permission::PAGE_DELETE ? TRUE : FALSE;
977
									} else {
978
										$deleteAccess = $permission & Permission::CONTENT_EDIT ? TRUE : FALSE;
979
									}
980
981
982
983
984
985
								}

								// Display "is-locked" message:
								if ($command === 'edit') {
									$lockInfo = BackendUtility::isRecordLocked($table, $formData['databaseRow']['uid']);
									if ($lockInfo) {
986
987
										/** @var $flashMessage \TYPO3\CMS\Core\Messaging\FlashMessage */
										$flashMessage = GeneralUtility::makeInstance(FlashMessage::class, htmlspecialchars($lockInfo['msg']), '', FlashMessage::WARNING);
988
										/** @var $flashMessageService \TYPO3\CMS\Core\Messaging\FlashMessageService */
989
										$flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
990
991
992
										/** @var $defaultFlashMessageQueue \TYPO3\CMS\Core\Messaging\FlashMessageQueue */
										$defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
										$defaultFlashMessageQueue->enqueue($flashMessage);
993
994
									}
								}
995
996
997
998
999

								// Record title
								if (!$this->storeTitle) {
									$this->storeTitle = $this->recTitle
										? htmlspecialchars($this->recTitle)
1000
										: BackendUtility::getRecordTitle($table, FormEngineUtility::databaseRowCompatibility($formData['databaseRow']), TRUE);