EditDocumentController.php 63.2 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

Nicole Cordes's avatar
Nicole Cordes committed
17
18
19
20
use TYPO3\CMS\Backend\Form\FormEngine;
use TYPO3\CMS\Backend\Utility\BackendUtility;
use TYPO3\CMS\Backend\Utility\IconUtility;
use TYPO3\CMS\Core\Html\HtmlParser;
21
22
use TYPO3\CMS\Core\Type\Bitmask\JsConfirmation;
use TYPO3\CMS\Core\Type\Bitmask\Permission;
Nicole Cordes's avatar
Nicole Cordes committed
23
24
25
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\HttpUtility;
use TYPO3\CMS\Core\Utility\MathUtility;
26
use TYPO3\CMS\Frontend\Page\PageRepository;
Christian Kuhn's avatar
Christian Kuhn committed
27
use TYPO3\CMS\Backend\Form\Utility\FormEngineUtility;
28
29
30
31
32
use TYPO3\CMS\Extbase\SignalSlot\Dispatcher;
use TYPO3\CMS\Core\DataHandling\DataHandler;
use TYPO3\CMS\Backend\Form\DataPreprocessor;
use TYPO3\CMS\Core\Messaging\FlashMessage;
use TYPO3\CMS\Core\Messaging\FlashMessageService;
Nicole Cordes's avatar
Nicole Cordes committed
33

34
35
36
37
38
39
40
41
/**
 * 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
 *
 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
 */
class EditDocumentController {

42
43
44
45
46
47
48
	/**
	 * 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
	 */
49
50
	public $editconf;

51
52
53
54
55
56
57
	/**
	 * 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
	 */
58
59
	public $columnsOnly;

60
61
62
63
64
65
	/**
	 * Default values for fields (array with tablenames, fields etc. as keys).
	 * Can be seen modified internally.
	 *
	 * @var array
	 */
66
67
	public $defVals;

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

76
77
78
79
80
81
	/**
	 * 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
	 */
82
83
	public $returnUrl;

84
85
86
87
88
	/**
	 * Close-document command. Not really sure of all options...
	 *
	 * @var int
	 */
89
90
	public $closeDoc;

91
92
93
94
95
96
97
	/**
	 * 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
	 */
98
99
	public $doSave;

100
101
102
103
104
	/**
	 * The data array from which the data comes...
	 *
	 * @var array
	 */
105
106
	public $data;

107
108
109
110
111
	/**
	 * @var string
	 */
	public $cmd;

112
113
114
	/**
	 * @var array
	 */
115
116
	public $mirror;

117
118
119
120
121
	/**
	 * Clear-cache cmd.
	 *
	 * @var string
	 */
122
123
	public $cacheCmd;

124
125
126
127
128
	/**
	 * Redirect (not used???)
	 *
	 * @var string
	 */
129
130
	public $redirect;

131
132
133
134
135
136
	/**
	 * 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
	 */
137
138
	public $returnNewPageId;

139
140
141
	/**
	 * @var string
	 */
142
143
	public $vC;

144
145
146
147
148
	/**
	 * update BE_USER->uc
	 *
	 * @var array
	 */
149
150
	public $uc;

151
152
153
154
155
	/**
	 * ID for displaying the page in the frontend (used for SAVE/VIEW operations)
	 *
	 * @var int
	 */
156
157
	public $popViewId;

158
159
160
161
162
	/**
	 * Additional GET vars for the link, eg. "&L=xxx"
	 *
	 * @var string
	 */
163
164
	public $popViewId_addParams;

165
166
167
168
169
	/**
	 * Alternative URL for viewing the frontend pages.
	 *
	 * @var string
	 */
170
171
	public $viewUrl;

172
173
174
175
176
	/**
	 * 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
177
	 * @deprecated since TYPO3 CMS 7, will be removed with TYPO3 CMS 8
178
	 */
179
180
	public $editRegularContentFromId;

181
182
183
184
185
	/**
	 * Alternative title for the document handler.
	 *
	 * @var string
	 */
186
187
	public $recTitle;

188
189
190
191
192
	/**
	 * If set, then no SAVE/VIEW button is printed
	 *
	 * @var bool
	 */
193
194
	public $noView;

195
196
197
198
199
	/**
	 * @var string
	 */
	public $perms_clause;

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

208
209
210
211
212
	/**
	 * localization mode for TCEforms (eg. "text")
	 *
	 * @var string
	 */
213
214
	public $localizationMode;

215
216
217
218
219
220
221
	/**
	 * Workspace used for the editing action.
	 *
	 * @var NULL|integer
	 */
	protected $workspace;

222
223
224
	/**
	 * document template object
	 *
225
	 * @var \TYPO3\CMS\Backend\Template\DocumentTemplate
226
227
228
	 */
	public $doc;

229
230
231
232
233
	/**
	 * a static HTML template, usually in templates/alt_doc.html
	 *
	 * @var string
	 */
234
235
	public $template;

236
237
238
239
240
	/**
	 * Content accumulation
	 *
	 * @var string
	 */
241
242
	public $content;

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

252
253
254
255
256
257
258
	/**
	 * 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
	 */
259
260
	public $R_URL_parts;

261
262
263
264
265
266
	/**
	 * 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
	 */
267
268
	public $R_URL_getvars;

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

276
277
278
279
280
281
282
283
284
285
	/**
	 * @var array
	 */
	public $MCONF;

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

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

294
295
296
297
298
299
	/**
	 * 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
	 */
300
301
	public $storeArray;

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

309
310
311
312
313
	/**
	 * Hashed value of storeURL (see compileStoreDat())
	 *
	 * @var string
	 */
314
315
	public $storeUrlMd5;

316
317
318
319
320
	/**
	 * Module session data
	 *
	 * @var array
	 */
321
322
	public $docDat;

323
324
325
326
327
328
329
330
	/**
	 * 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
	 */
331
332
	public $docHandler;

333
334
335
336
337
	/**
	 * Array of the elements to create edit forms for.
	 *
	 * @var array
	 */
338
339
	public $elementsData;

340
341
342
343
344
	/**
	 * Pointer to the first element in $elementsData
	 *
	 * @var array
	 */
345
346
	public $firstEl;

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

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

361
362
363
364
365
366
	/**
	 * 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
	 */
367
368
	public $viewId;

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

376
377
378
379
380
	/**
	 * Module TSconfig, loaded from main() based on the page id value of viewId
	 *
	 * @var array
	 */
381
382
383
384
385
386
387
388
389
	public $modTSconfig;

	/**
	 * instance of TCEforms class
	 *
	 * @var \TYPO3\CMS\Backend\Form\FormEngine
	 */
	public $tceforms;

390
391
392
393
394
	/**
	 * Contains the root-line path of the currently edited record(s) - for display.
	 *
	 * @var string
	 */
395
396
	public $generalPathOfForm;

397
398
399
400
401
	/**
	 * Used internally to disable the storage of the document reference (eg. new records)
	 *
	 * @var bool
	 */
402
403
	public $dontStoreDocumentRef;

404
405
406
407
408
	/**
	 * @var \TYPO3\CMS\Extbase\SignalSlot\Dispatcher
	 */
	protected $signalSlotDispatcher;

409
410
411
412
413
414
415
	/**
	 * Stores information needed to preview the currently saved record
	 *
	 * @var array
	 */
	protected $previewData = [];

416
417
418
419
420
	/**
	 * Constructor
	 */
	public function __construct() {
		$GLOBALS['SOBE'] = $this;
421
		$this->getLanguageService()->includeLLFile('EXT:lang/locallang_alt_doc.xml');
422
423
	}

424
425
426
427
428
429
430
	/**
	 * Get the SignalSlot dispatcher
	 *
	 * @return \TYPO3\CMS\Extbase\SignalSlot\Dispatcher
	 */
	protected function getSignalSlotDispatcher() {
		if (!isset($this->signalSlotDispatcher)) {
431
			$this->signalSlotDispatcher = GeneralUtility::makeInstance(Dispatcher::class);
432
433
434
435
		}
		return $this->signalSlotDispatcher;
	}

436
437
438
439
440
441
442
443
444
	/**
	 * Emits a signal after a function was executed
	 *
	 * @param string $signalName
	 */
	protected function emitFunctionAfterSignal($signalName) {
		$this->getSignalSlotDispatcher()->dispatch(__CLASS__, $signalName . 'After', array($this));
	}

445
446
447
448
449
450
	/**
	 * First initialization.
	 *
	 * @return void
	 */
	public function preInit() {
Nicole Cordes's avatar
Nicole Cordes committed
451
452
		if (GeneralUtility::_GP('justLocalized')) {
			$this->localizationRedirect(GeneralUtility::_GP('justLocalized'));
453
454
		}
		// Setting GPvars:
Nicole Cordes's avatar
Nicole Cordes committed
455
456
457
458
459
460
461
462
463
		$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');
464
		$this->workspace = GeneralUtility::_GP('workspace');
Nicole Cordes's avatar
Nicole Cordes committed
465
		$this->uc = GeneralUtility::_GP('uc');
466
467
468
469
470
		// 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
471
		$this->retUrl = $this->returnUrl ?: BackendUtility::getModuleUrl('dummy');
472
473
474
		// 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
475
476
		$this->R_URL_parts = parse_url(GeneralUtility::getIndpEnv('REQUEST_URI'));
		$this->R_URL_getvars = GeneralUtility::_GET();
477
478
479
480
481
482
483
		$this->R_URL_getvars['edit'] = $this->editconf;
		// MAKE url for storing
		$this->compileStoreDat();
		// Initialize more variables.
		$this->dontStoreDocumentRef = 0;
		$this->storeTitle = '';
		// Get session data for the module:
484
		$this->docDat = $this->getBackendUser()->getModuleData('FormEngine', 'ses');
485
486
487
488
489
490
491
492
		$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...
493
		if (is_array($this->R_URL_getvars) && count($this->R_URL_getvars) < 2 && !is_array($this->editconf)) {
494
495
			$this->setDocument($this->docDat[1]);
		}
496
497
498
499
500

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

502
		$this->emitFunctionAfterSignal(__FUNCTION__);
503
504
505
506
507
	}

	/**
	 * Detects, if a save command has been triggered.
	 *
508
	 * @return bool TRUE, then save the document (data submitted)
509
510
	 */
	public function doProcessData() {
511
		$out = $this->doSave || isset($_POST['_savedok_x']) || isset($_POST['_saveandclosedok_x']) || isset($_POST['_savedokview_x']) || isset($_POST['_savedoknew_x']) || isset($_POST['_translation_savedok_x']) || isset($_POST['_translation_savedokclear_x']);
512
513
514
515
516
517
518
519
520
		return $out;
	}

	/**
	 * Do processing of data, submitting it to TCEmain.
	 *
	 * @return void
	 */
	public function processData() {
521
		$beUser = $this->getBackendUser();
522
		// GPvars specifically for processing:
Nicole Cordes's avatar
Nicole Cordes committed
523
524
525
526
527
528
529
530
		$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');
531
532
		// See tce_db.php for relevate options here:
		// Only options related to $this->data submission are included here.
533
		/** @var $tce \TYPO3\CMS\Core\DataHandling\DataHandler */
534
535
		$tce = GeneralUtility::makeInstance(DataHandler::class);
		$tce->stripslashes_values = FALSE;
536
537
538
539

		if (!empty($control)) {
			$tce->setControl($control);
		}
540
541
542
543
544
545
546
547
		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:
548
		$TCAdefaultOverride = $beUser->getTSConfigProp('TCAdefaults');
549
550
551
552
		if (is_array($TCAdefaultOverride)) {
			$tce->setDefaultsFromUserTS($TCAdefaultOverride);
		}
		// Setting internal vars:
553
		if ($beUser->uc['neverHideAtCopy']) {
554
555
556
557
558
559
560
561
			$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
562
563
		$refInfo = parse_url(GeneralUtility::getIndpEnv('HTTP_REFERER'));
		$httpHost = GeneralUtility::getIndpEnv('TYPO3_HOST_ONLY');
564
		if ($httpHost != $refInfo['host'] && $this->vC != $beUser->veriCode() && !$GLOBALS['TYPO3_CONF_VARS']['SYS']['doNotCheckReferer']) {
565
566
567
568
569
570
571
			$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();
572
			// If pages are being edited, we set an instruction about updating the page tree after this operation.
573
			if ($tce->pagetreeNeedsRefresh && (isset($this->data['pages']) || $beUser->workspace != 0 && !empty($this->data))) {
574
575
				BackendUtility::setUpdateSignal('updatePageTree');
			}
576
			// If there was saved any new items, load them:
577
			if (!empty($tce->substNEWwithIDs_table)) {
578
				// save the expanded/collapsed states for new inline records, if any
Christian Kuhn's avatar
Christian Kuhn committed
579
				FormEngineUtility::updateInlineView($this->uc, $tce);
580
581
582
				$newEditConf = array();
				foreach ($this->editconf as $tableName => $tableCmds) {
					$keys = array_keys($tce->substNEWwithIDs_table, $tableName);
583
					if (!empty($keys)) {
584
585
586
587
588
						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:
589
								if ($versionRec = BackendUtility::getWorkspaceVersionOfRecord($beUser->workspace, $tableName, $editId, 'uid')) {
590
591
592
593
594
									$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!
595
							if ($tableName == 'pages' && $this->retUrl != BackendUtility::getModuleUrl('dummy') && $this->returnNewPageId) {
596
597
598
599
600
601
602
603
								$this->retUrl .= '&id=' . $tce->substNEWwithIDs[$key];
							}
						}
					} else {
						$newEditConf[$tableName] = $tableCmds;
					}
				}
				// Resetting editconf if newEditConf has values:
604
				if (!empty($newEditConf)) {
605
606
607
608
609
610
611
612
613
614
					$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?
615
			if (!empty($tce->autoVersionIdMap)) {
616
617
618
619
620
621
622
623
624
625
				$this->fixWSversioningInEditConf($tce->autoVersionIdMap);
			}
			// If a document is saved and a new one is created right after.
			if (isset($_POST['_savedoknew_x']) && is_array($this->editconf)) {
				// 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
626
				$nRec = BackendUtility::getRecord($nTable, $nUid, 'pid,uid');
627
628
629
630
631
632
633
634
635
636
637
638
				// 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();
			}
639
640
641
642
643
644
645
646
647
648
649
650
			// If a preview is requested
			if (isset($_POST['_savedokview_x'])) {
				// 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;
			}
Nicole Cordes's avatar
Nicole Cordes committed
651
			$tce->printLogErrorMessages(isset($_POST['_saveandclosedok_x']) || isset($_POST['_translation_savedok_x']) ? $this->retUrl : $this->R_URL_parts['path'] . '?' . GeneralUtility::implodeArrayForUrl('', $this->R_URL_getvars));
652
653
654
		}
		//  || 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!
655
		if (isset($_POST['_saveandclosedok_x']) || isset($_POST['_translation_savedok_x']) || $this->closeDoc < 0) {
656
657
658
659
660
661
662
663
664
665
			$this->closeDocument(abs($this->closeDoc));
		}
	}

	/**
	 * Initialize the normal module operation
	 *
	 * @return void
	 */
	public function init() {
666
		$beUser = $this->getBackendUser();
667
		// Setting more GPvars:
Nicole Cordes's avatar
Nicole Cordes committed
668
669
670
671
672
673
		$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');
674
		$this->perms_clause = $beUser->getPagePermsClause(1);
675
676
		// Set other internal variables:
		$this->R_URL_getvars['returnUrl'] = $this->retUrl;
677
		$this->R_URI = $this->R_URL_parts['path'] . '?' . ltrim(GeneralUtility::implodeArrayForUrl('', $this->R_URL_getvars), '&');
678
679
680
681
		// Setting virtual document name
		$this->MCONF['name'] = 'xMOD_alt_doc.php';
		// Create an instance of the document template object
		$this->doc = $GLOBALS['TBE_TEMPLATE'];
682
		$this->doc->getPageRenderer()->addInlineLanguageLabelFile('EXT:lang/locallang_alt_doc.xml');
683
		$this->doc->backPath = $GLOBALS['BACK_PATH'];
684
		$this->doc->setModuleTemplate('EXT:backend/Resources/Private/Templates/alt_doc.html');
685
		$this->doc->form = '<form action="' . htmlspecialchars($this->R_URI) . '" method="post" enctype="' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['form_enctype'] . '" name="editform" onsubmit="document.editform._scrollPosition.value=(document.documentElement.scrollTop || document.body.scrollTop); return TBE_EDITOR.checkSubmit(1);">';
686
		$this->doc->getPageRenderer()->loadPrototype();
687
688
689
		// override the default jumpToUrl
		$this->doc->JScodeArray['jumpToUrl'] = '
			function jumpToUrl(URL,formEl) {
690
691
692
693
694
695
				if (!TBE_EDITOR.isFormChanged()) {
					window.location.href = URL;
				} else if (formEl && formEl.type=="checkbox") {
					formEl.checked = formEl.checked ? 0 : 1;
				}
			}
696
';
697
698
699
		// define the window size of the element browser
		$popupWindowWidth  = 700;
		$popupWindowHeight = 750;
700
		$popupWindowSize = trim($beUser->getTSConfigVal('options.popupWindowSize'));
701
702
703
704
705
706
707
708
709
		if (!empty($popupWindowSize)) {
			list($popupWindowWidth, $popupWindowHeight) = GeneralUtility::intExplode('x', $popupWindowSize);
		}
		$t3Configuration = array(
			'PopupWindow' => array(
				'width' => $popupWindowWidth,
				'height' => $popupWindowHeight
			),
		);
710
711
712
713
714
		$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
715
716
717
			function typoSetup() {	//
				this.uniqueID = "";
				this.passwordDummy = "********";
718
				this.PATH_typo3 = "";
719
720
721
722
723
724
725
726
				this.decimalSign = ".";
			}
			var TS = new typoSetup();

				// Info view:
			function launchView(table,uid,bP) {	//
				var backPath= bP ? bP : "";
				var thePreviewWindow="";
727
				thePreviewWindow = window.open(backPath+' . GeneralUtility::quoteJSvalue(BackendUtility::getModuleUrl('show_item', array(), '') . '&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");
728
729
730
731
732
733
				if (thePreviewWindow && thePreviewWindow.focus) {
					thePreviewWindow.focus();
				}
			}
			function deleteRecord(table,id,url) {	//
				if (
734
					' . ($beUser->jsConfirmation(JsConfirmation::DELETE) ? 'confirm(' . GeneralUtility::quoteJSvalue($this->getLanguageService()->getLL('deleteWarning')) . ')' : '1==1') . '
735
				)	{
736
					window.location.href = ' . GeneralUtility::quoteJSvalue(BackendUtility::getModuleUrl('tce_db') . '&cmd[') . '+table+"]["+id+"][delete]=1' . BackendUtility::getUrlToken('tceAction') . '&redirect="+escape(url)+"&vC=' . $beUser->veriCode() . '&prErr=1&uPT=1";
737
738
739
				}
				return false;
			}
740
741
742
743
744
		';

		$previewCode = isset($_POST['_savedokview_x']) && $this->popViewId ? $this->generatePreviewCode() : '';

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

749
		$this->emitFunctionAfterSignal(__FUNCTION__);
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
838
839
840
841
842
843
844
845
846
847
848
	/**
	 * @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)
			. '
				}';
	}

849
850
851
852
853
854
	/**
	 * Main module operation
	 *
	 * @return void
	 */
	public function main() {
855
		$body = '';
856
857
858
		// Begin edit:
		if (is_array($this->editconf)) {
			// Initialize TCEforms (rendering the forms)
859
			$this->tceforms = GeneralUtility::makeInstance(FormEngine::class);
860
			$this->tceforms->doSaveFieldName = 'doSave';
Nicole Cordes's avatar
Nicole Cordes committed
861
			$this->tceforms->localizationMode = GeneralUtility::inList('text,media', $this->localizationMode) ? $this->localizationMode : '';
862
863
864
865
866
867
868
869
870
871
			// text,media is keywords defined in TYPO3 Core API..., see "l10n_cat"
			$this->tceforms->returnUrl = $this->R_URI;
			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:
872
				if (($this->docDat[1] !== $this->storeUrlMd5 || !isset($this->docHandler[$this->storeUrlMd5])) && !$this->dontStoreDocumentRef) {
873
					$this->docHandler[$this->storeUrlMd5] = array($this->storeTitle, $this->storeArray, $this->storeUrl, $this->firstEl);
874
					$this->getBackendUser()->pushModuleData('FormEngine', array($this->docHandler, $this->storeUrlMd5));
Nicole Cordes's avatar
Nicole Cordes committed
875
					BackendUtility::setUpdateSignal('OpendocsController::updateNumber', count($this->docHandler));
876
877
				}
				// Module configuration
Nicole Cordes's avatar
Nicole Cordes committed
878
				$this->modTSconfig = $this->viewId ? BackendUtility::getModTSconfig($this->viewId, 'mod.xMOD_alt_doc') : array();
879
				$body = $this->tceforms->printNeededJSFunctions_top();
880
881
882
883
884
885
				$body .= $this->compileForm($editForm);
				$body .= $this->tceforms->printNeededJSFunctions();
			}
		}
		// 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
886
		$this->pageinfo = BackendUtility::readPageAccess($this->viewId, $this->perms_clause);
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
		// Setting up the buttons and markers for docheader
		$docHeaderButtons = $this->getButtons();
		$markers = array(
			'LANGSELECTOR' => $this->langSelector(),
			'EXTRAHEADER' => $this->extraFormHeaders(),
			'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
	 */
	public function printContent() {
		echo $this->content;
	}

	/***************************
	 *
	 * Sub-content functions, rendering specific parts of the module content.
	 *
	 ***************************/
	/**
	 * Creates the editing form with TCEforms, based on the input from GPvars.
	 *
	 * @return string HTML form elements wrapped in tables
	 */
	public function makeEditForm() {
		// Initialize variables:
		$this->elementsData = array();
		$this->errorC = 0;
		$this->newC = 0;
		$thePrevUid = '';
		$editForm = '';
		$trData = NULL;
929
		$beUser = $this->getBackendUser();
930
931
932
		// Traverse the GPvar edit array
		// Tables:
		foreach ($this->editconf as $table => $conf) {
933
			if (is_array($conf) && $GLOBALS['TCA'][$table] && $beUser->check('tables_modify', $table)) {
934
935
936
937
				// Traverse the keys/comments of each table (keys can be a commalist of uids)
				foreach ($conf as $cKey => $cmd) {
					if ($cmd == 'edit' || $cmd == 'new') {
						// Get the ids:
938
						$ids = GeneralUtility::trimExplode(',', $cKey, TRUE);
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
						// Traverse the ids:
						foreach ($ids as $theUid) {
							// Checking if the user has permissions? (Only working as a precaution,
							// because the final permission check is always down in TCE. But it's
							// good to notify the user on beforehand...)
							// First, resetting flags.
							$hasAccess = 1;
							$deniedAccessReason = '';
							$deleteAccess = 0;
							$this->viewId = 0;
							// If the command is to create a NEW record...:
							if ($cmd == 'new') {
								// NOTICE: the id values in this case points to the page uid onto which the
								// record should be create OR (if the id is negativ) to a record from the
								// same table AFTER which to create the record.
954
								if ((int)$theUid) {
955
956
957
									// Find parent page on which the new record reside
									// Less than zero - find parent page
									if ($theUid < 0) {
Nicole Cordes's avatar
Nicole Cordes committed
958
959
										$calcPRec = BackendUtility::getRecord($table, abs($theUid));
										$calcPRec = BackendUtility::getRecord('pages', $calcPRec['pid']);
960
961
									} else {
										// always a page
Nicole Cordes's avatar
Nicole Cordes committed
962
										$calcPRec = BackendUtility::getRecord('pages', abs($theUid));
963
964
965
966
									}
									// Now, calculate whether the user has access to creating new records on this position:
									if (is_array($calcPRec)) {
										// Permissions for the parent page
967
										$CALC_PERMS = $beUser->calcPerms($calcPRec);
968
969
										if ($table == 'pages') {
											// If pages:
970
											$hasAccess = $CALC_PERMS & Permission::PAGE_NEW ? 1 : 0;
971
972
											$this->viewId = 0;
										} else {
973
											$hasAccess = $CALC_PERMS & Permission::CONTENT_EDIT ? 1 : 0;
974
975
976
977
978
979
980
981
											$this->viewId = $calcPRec['uid'];
										}
									}
								}
								// Don't save this document title in the document selector if the document is new.
								$this->dontStoreDocumentRef = 1;
							} else {
								// Edit:
Nicole Cordes's avatar
Nicole Cordes committed
982
983
								$calcPRec = BackendUtility::getRecord($table, $theUid);
								BackendUtility::fixVersioningPid($table, $calcPRec);
984
								if (is_array($calcPRec)) {
985
									if ($table == 'pages') { // If pages:
986
										$CALC_PERMS = $beUser->calcPerms($calcPRec);
987
988
										$hasAccess = $CALC_PERMS & Permission::PAGE_EDIT ? 1 : 0;
										$deleteAccess = $CALC_PERMS & Permission::PAGE_DELETE ? 1 : 0;
989
990
991
										$this->viewId = $calcPRec['uid'];
									} else {
										// Fetching pid-record first
992
										$CALC_PERMS = $beUser->calcPerms(BackendUtility::getRecord('pages', $calcPRec['pid']));
993
994
										$hasAccess = $CALC_PERMS & Permission::CONTENT_EDIT ? 1 : 0;
										$deleteAccess = $CALC_PERMS & Permission::CONTENT_EDIT ? 1 : 0;
995
996
997
998
999
1000
										$this->viewId = $calcPRec['pid'];
										// Adding "&L=xx" if the record being edited has a languageField with a value larger than zero!
										if ($GLOBALS['TCA'][$table]['ctrl']['languageField'] && $calcPRec[$GLOBALS['TCA'][$table]['ctrl']['languageField']] > 0) {
											$this->viewId_addParams = '&L=' . $calcPRec[$GLOBALS['TCA'][$table]['ctrl']['languageField']];
										}
									}