-
Notifications
You must be signed in to change notification settings - Fork 638
/
EditDocumentController.php
2029 lines (1888 loc) · 87.2 KB
/
EditDocumentController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
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
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
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
929
930
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
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace TYPO3\CMS\Backend\Controller;
/*
* This file is part of the TYPO3 CMS project.
*
* 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.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use TYPO3\CMS\Backend\Form\Exception\AccessDeniedException;
use TYPO3\CMS\Backend\Form\FormDataCompiler;
use TYPO3\CMS\Backend\Form\FormDataGroup\TcaDatabaseRecord;
use TYPO3\CMS\Backend\Form\FormResultCompiler;
use TYPO3\CMS\Backend\Form\NodeFactory;
use TYPO3\CMS\Backend\Form\Utility\FormEngineUtility;
use TYPO3\CMS\Backend\Template\Components\ButtonBar;
use TYPO3\CMS\Backend\Template\ModuleTemplate;
use TYPO3\CMS\Backend\Utility\BackendUtility;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Database\Query\Restriction\BackendWorkspaceRestriction;
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
use TYPO3\CMS\Core\Database\Query\Restriction\HiddenRestriction;
use TYPO3\CMS\Core\DataHandling\DataHandler;
use TYPO3\CMS\Core\Imaging\Icon;
use TYPO3\CMS\Core\Messaging\FlashMessage;
use TYPO3\CMS\Core\Messaging\FlashMessageQueue;
use TYPO3\CMS\Core\Messaging\FlashMessageService;
use TYPO3\CMS\Core\Page\PageRenderer;
use TYPO3\CMS\Core\Type\Bitmask\Permission;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\HttpUtility;
use TYPO3\CMS\Core\Utility\MathUtility;
use TYPO3\CMS\Core\Utility\PathUtility;
use TYPO3\CMS\Extbase\SignalSlot\Dispatcher;
use TYPO3\CMS\Frontend\Page\CacheHashCalculator;
use TYPO3\CMS\Frontend\Page\PageRepository;
/**
* 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
*/
class EditDocumentController
{
const DOCUMENT_CLOSE_MODE_DEFAULT = 0;
const DOCUMENT_CLOSE_MODE_REDIRECT = 1; // works like DOCUMENT_CLOSE_MODE_DEFAULT
const DOCUMENT_CLOSE_MODE_CLEAR_ALL = 3;
const DOCUMENT_CLOSE_MODE_NO_REDIRECT = 4;
/**
* 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
*/
public $editconf;
/**
* 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
*/
public $columnsOnly;
/**
* Default values for fields (array with tablenames, fields etc. as keys).
* Can be seen modified internally.
*
* @var array
*/
public $defVals;
/**
* Array of values to force being set (as hidden fields). Will be set as $this->defVals
* IF defVals does not exist.
*
* @var array
*/
public $overrideVals;
/**
* 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
*/
public $returnUrl;
/**
* Close-document command. Not really sure of all options...
*
* @var int
*/
public $closeDoc;
/**
* 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
*/
public $doSave;
/**
* The data array from which the data comes...
*
* @var array
*/
public $data;
/**
* @var string
*/
public $cmd;
/**
* @var array
*/
public $mirror;
/**
* Clear-cache cmd.
*
* @var string
*/
public $cacheCmd;
/**
* Redirect (not used???)
*
* @var string
*/
public $redirect;
/**
* 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
*/
public $returnNewPageId;
/**
* update BE_USER->uc
*
* @var array
*/
public $uc;
/**
* ID for displaying the page in the frontend (used for SAVE/VIEW operations)
*
* @var int
*/
public $popViewId;
/**
* Additional GET vars for the link, eg. "&L=xxx"
*
* @var string
*/
public $popViewId_addParams;
/**
* Alternative URL for viewing the frontend pages.
*
* @var string
*/
public $viewUrl;
/**
* Alternative title for the document handler.
*
* @var string
*/
public $recTitle;
/**
* If set, then no SAVE/VIEW button is printed
*
* @var bool
*/
public $noView;
/**
* @var string
*/
public $perms_clause;
/**
* If set, the $this->editconf array is returned to the calling script
* (used by wizard_add.php for instance)
*
* @var bool
*/
public $returnEditConf;
/**
* Workspace used for the editing action.
*
* @var int|null
*/
protected $workspace;
/**
* document template object
*
* @var \TYPO3\CMS\Backend\Template\DocumentTemplate
*/
public $doc;
/**
* a static HTML template, usually in templates/alt_doc.html
*
* @var string
*/
public $template;
/**
* Content accumulation
*
* @var string
*/
public $content;
/**
* Return URL script, processed. This contains the script (if any) that we should
* RETURN TO from the FormEngine script IF we press the close button. Thus this
* variable is normally passed along from the calling script so we can properly return if needed.
*
* @var string
*/
public $retUrl;
/**
* 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
*/
public $R_URL_parts;
/**
* 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
*/
public $R_URL_getvars;
/**
* Set to the URL of this script including variables which is needed to re-display the form. See main()
*
* @var string
*/
public $R_URI;
/**
* @var array
*/
public $MCONF;
/**
* @var array
*/
public $pageinfo;
/**
* Is loaded with the "title" of the currently "open document" - this is used in the
* Document Selector box. (see makeDocSel())
*
* @var string
*/
public $storeTitle = '';
/**
* 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
*/
public $storeArray;
/**
* Contains storeArray, but imploded into a GET parameter string (see compileStoreDat())
*
* @var string
*/
public $storeUrl;
/**
* Hashed value of storeURL (see compileStoreDat())
*
* @var string
*/
public $storeUrlMd5;
/**
* Module session data
*
* @var array
*/
public $docDat;
/**
* 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
*/
public $docHandler;
/**
* Array of the elements to create edit forms for.
*
* @var array
*/
public $elementsData;
/**
* Pointer to the first element in $elementsData
*
* @var array
*/
public $firstEl;
/**
* Counter, used to count the number of errors (when users do not have edit permissions)
*
* @var int
*/
public $errorC;
/**
* Counter, used to count the number of new record forms displayed
*
* @var int
*/
public $newC;
/**
* 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
*/
public $viewId;
/**
* Is set to additional parameters (like "&L=xxx") if the record supports it.
*
* @var string
*/
public $viewId_addParams;
/**
* Module TSconfig, loaded from main() based on the page id value of viewId
*
* @var array
*/
public $modTSconfig;
/**
* @var FormResultCompiler
*/
protected $formResultCompiler;
/**
* Used internally to disable the storage of the document reference (eg. new records)
*
* @var bool
*/
public $dontStoreDocumentRef = 0;
/**
* @var \TYPO3\CMS\Extbase\SignalSlot\Dispatcher
*/
protected $signalSlotDispatcher;
/**
* Stores information needed to preview the currently saved record
*
* @var array
*/
protected $previewData = [];
/**
* ModuleTemplate object
*
* @var ModuleTemplate
*/
protected $moduleTemplate;
/**
* Constructor
*/
public function __construct()
{
$this->moduleTemplate = GeneralUtility::makeInstance(ModuleTemplate::class);
$this->moduleTemplate->setUiBlock(true);
$GLOBALS['SOBE'] = $this;
$this->getLanguageService()->includeLLFile('EXT:lang/Resources/Private/Language/locallang_alt_doc.xlf');
}
/**
* Get the SignalSlot dispatcher
*
* @return \TYPO3\CMS\Extbase\SignalSlot\Dispatcher
*/
protected function getSignalSlotDispatcher()
{
if (!isset($this->signalSlotDispatcher)) {
$this->signalSlotDispatcher = GeneralUtility::makeInstance(Dispatcher::class);
}
return $this->signalSlotDispatcher;
}
/**
* Emits a signal after a function was executed
*
* @param string $signalName
*/
protected function emitFunctionAfterSignal($signalName)
{
$this->getSignalSlotDispatcher()->dispatch(__CLASS__, $signalName . 'After', [$this]);
}
/**
* First initialization.
*/
public function preInit()
{
if (GeneralUtility::_GP('justLocalized')) {
$this->localizationRedirect(GeneralUtility::_GP('justLocalized'));
}
// Setting GPvars:
$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 = (int)GeneralUtility::_GP('closeDoc');
$this->doSave = GeneralUtility::_GP('doSave');
$this->returnEditConf = GeneralUtility::_GP('returnEditConf');
$this->workspace = GeneralUtility::_GP('workspace');
$this->uc = GeneralUtility::_GP('uc');
// Setting override values as default if defVals does not exist.
if (!is_array($this->defVals) && is_array($this->overrideVals)) {
$this->defVals = $this->overrideVals;
}
/** @var \TYPO3\CMS\Backend\Routing\UriBuilder $uriBuilder */
$uriBuilder = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Routing\UriBuilder::class);
// Setting return URL
$this->retUrl = $this->returnUrl ?: (string)$uriBuilder->buildUriFromRoute('dummy');
// Fix $this->editconf if versioning applies to any of the records
$this->fixWSversioningInEditConf();
// Make R_URL (request url) based on input GETvars:
$this->R_URL_parts = parse_url(GeneralUtility::getIndpEnv('REQUEST_URI'));
$this->R_URL_getvars = GeneralUtility::_GET();
$this->R_URL_getvars['edit'] = $this->editconf;
// MAKE url for storing
$this->compileStoreDat();
// Get session data for the module:
$this->docDat = $this->getBackendUser()->getModuleData('FormEngine', 'ses');
$this->docHandler = $this->docDat[0];
// If a request for closing the document has been sent, act accordingly:
if ((int)$this->closeDoc > self::DOCUMENT_CLOSE_MODE_DEFAULT) {
$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...
if (is_array($this->R_URL_getvars) && count($this->R_URL_getvars) < 2 && !is_array($this->editconf)) {
$this->setDocument($this->docDat[1]);
}
// Sets a temporary workspace, this request is based on
if ($this->workspace !== null) {
$this->getBackendUser()->setTemporaryWorkspace($this->workspace);
}
$this->emitFunctionAfterSignal(__FUNCTION__);
}
/**
* Detects, if a save command has been triggered.
*
* @return bool TRUE, then save the document (data submitted)
*/
public function doProcessData()
{
$out = $this->doSave
|| isset($_POST['_savedok'])
|| isset($_POST['_saveandclosedok'])
|| isset($_POST['_savedokview'])
|| isset($_POST['_savedoknew'])
|| isset($_POST['_translation_savedok'])
|| isset($_POST['_translation_savedokclear']);
return $out;
}
/**
* Do processing of data, submitting it to DataHandler.
*/
public function processData()
{
$beUser = $this->getBackendUser();
// GPvars specifically for processing:
$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');
// See tce_db.php for relevate options here:
// Only options related to $this->data submission are included here.
/** @var $tce \TYPO3\CMS\Core\DataHandling\DataHandler */
$tce = GeneralUtility::makeInstance(DataHandler::class);
if (!empty($control)) {
$tce->setControl($control);
}
if (isset($_POST['_translation_savedok'])) {
$tce->updateModeL10NdiffData = 'FORCE_FFUPD';
}
if (isset($_POST['_translation_savedokclear'])) {
$tce->updateModeL10NdiffData = 'FORCE_FFUPD';
$tce->updateModeL10NdiffDataClear = true;
}
// Setting default values specific for the user:
$TCAdefaultOverride = $beUser->getTSConfigProp('TCAdefaults');
if (is_array($TCAdefaultOverride)) {
$tce->setDefaultsFromUserTS($TCAdefaultOverride);
}
// Setting internal vars:
if ($beUser->uc['neverHideAtCopy']) {
$tce->neverHideAtCopy = 1;
}
// Loading DataHandler with data:
$tce->start($this->data, $this->cmd);
if (is_array($this->mirror)) {
$tce->setMirror($this->mirror);
}
// Checking referer / executing
$refInfo = parse_url(GeneralUtility::getIndpEnv('HTTP_REFERER'));
$httpHost = GeneralUtility::getIndpEnv('TYPO3_HOST_ONLY');
if ($httpHost != $refInfo['host']
&& !$GLOBALS['TYPO3_CONF_VARS']['SYS']['doNotCheckReferer']
) {
$tce->log(
'',
0,
0,
0,
1,
'Referer host \'%s\' and server host \'%s\' did not match!',
1,
[$refInfo['host'], $httpHost]
);
debug('Error: Referer host did not match with server host.');
} else {
// Perform the saving operation with DataHandler:
$tce->process_uploads($_FILES);
$tce->process_datamap();
$tce->process_cmdmap();
// If pages are being edited, we set an instruction about updating the page tree after this operation.
if ($tce->pagetreeNeedsRefresh
&& (isset($this->data['pages']) || $beUser->workspace != 0 && !empty($this->data))
) {
BackendUtility::setUpdateSignal('updatePageTree');
}
// If there was saved any new items, load them:
if (!empty($tce->substNEWwithIDs_table)) {
// save the expanded/collapsed states for new inline records, if any
FormEngineUtility::updateInlineView($this->uc, $tce);
$newEditConf = [];
foreach ($this->editconf as $tableName => $tableCmds) {
$keys = array_keys($tce->substNEWwithIDs_table, $tableName);
if (!empty($keys)) {
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:
if ($versionRec = BackendUtility::getWorkspaceVersionOfRecord(
$beUser->workspace,
$tableName,
$editId,
'uid'
)) {
$editId = $versionRec['uid'];
}
$newEditConf[$tableName][$editId] = 'edit';
}
/** @var \TYPO3\CMS\Backend\Routing\UriBuilder $uriBuilder */
$uriBuilder = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Routing\UriBuilder::class);
// Traverse all new records and forge the content of ->editconf so we can continue to EDIT
// these records!
if ($tableName === 'pages'
&& $this->retUrl != (string)$uriBuilder->buildUriFromRoute('dummy')
&& $this->returnNewPageId
) {
$this->retUrl .= '&id=' . $tce->substNEWwithIDs[$key];
}
}
} else {
$newEditConf[$tableName] = $tableCmds;
}
}
// Resetting editconf if newEditConf has values:
if (!empty($newEditConf)) {
$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?
if (!empty($tce->autoVersionIdMap)) {
$this->fixWSversioningInEditConf($tce->autoVersionIdMap);
}
// If a document is saved and a new one is created right after.
if (isset($_POST['_savedoknew']) && is_array($this->editconf)) {
$this->closeDocument(self::DOCUMENT_CLOSE_MODE_NO_REDIRECT);
// 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]);
$recordFields = 'pid,uid';
if (!empty($GLOBALS['TCA'][$nTable]['ctrl']['versioningWS'])) {
$recordFields .= ',t3ver_oid';
}
$nRec = BackendUtility::getRecord($nTable, $nUid, $recordFields);
// Determine insertion mode ('top' is self-explaining,
// otherwise new elements are inserted after one using a negative uid)
$insertRecordOnTop = ($this->getNewIconMode($nTable) === 'top');
// Setting a blank editconf array for a new record:
$this->editconf = [];
// Determine related page ID for regular live context
if ($nRec['pid'] != -1) {
if ($insertRecordOnTop) {
$relatedPageId = $nRec['pid'];
} else {
$relatedPageId = -$nRec['uid'];
}
} else {
// Determine related page ID for workspace context
if ($insertRecordOnTop) {
// Fetch live version of workspace version since the pid value is always -1 in workspaces
$liveRecord = BackendUtility::getRecord($nTable, $nRec['t3ver_oid'], $recordFields);
$relatedPageId = $liveRecord['pid'];
} else {
// Use uid of live version of workspace version
$relatedPageId = -$nRec['t3ver_oid'];
}
}
$this->editconf[$nTable][$relatedPageId] = '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();
}
// If a preview is requested
if (isset($_POST['_savedokview'])) {
// 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;
}
$tce->printLogErrorMessages();
}
// || 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!
if ((int)$this->closeDoc < self::DOCUMENT_CLOSE_MODE_DEFAULT
|| isset($_POST['_saveandclosedok'])
|| isset($_POST['_translation_savedok'])
) {
$this->closeDocument(abs($this->closeDoc));
}
}
/**
* Initialize the normal module operation
*/
public function init()
{
$beUser = $this->getBackendUser();
// Setting more GPvars:
$this->popViewId = GeneralUtility::_GP('popViewId');
$this->popViewId_addParams = GeneralUtility::_GP('popViewId_addParams');
$this->viewUrl = GeneralUtility::_GP('viewUrl');
$this->recTitle = GeneralUtility::_GP('recTitle');
$this->noView = GeneralUtility::_GP('noView');
$this->perms_clause = $beUser->getPagePermsClause(Permission::PAGE_SHOW);
// Set other internal variables:
$this->R_URL_getvars['returnUrl'] = $this->retUrl;
$this->R_URI = $this->R_URL_parts['path'] . '?' . ltrim(GeneralUtility::implodeArrayForUrl(
'',
$this->R_URL_getvars
), '&');
// Setting virtual document name
$this->MCONF['name'] = 'xMOD_alt_doc.php';
// Create an instance of the document template object
$this->doc = $GLOBALS['TBE_TEMPLATE'];
$pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
$pageRenderer->addInlineLanguageLabelFile('EXT:lang/Resources/Private/Language/locallang_alt_doc.xlf');
/** @var \TYPO3\CMS\Backend\Routing\UriBuilder $uriBuilder */
$uriBuilder = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Routing\UriBuilder::class);
// override the default jumpToUrl
$this->moduleTemplate->addJavaScriptCode(
'jumpToUrl',
'
function jumpToUrl(URL,formEl) {
if (!TBE_EDITOR.isFormChanged()) {
window.location.href = URL;
} else if (formEl && formEl.type=="checkbox") {
formEl.checked = formEl.checked ? 0 : 1;
}
}
// Info view:
function launchView(table,uid) {
var thePreviewWindow = window.open(
' . GeneralUtility::quoteJSvalue((string)$uriBuilder->buildUriFromRoute('show_item') . '&table=') . ' + encodeURIComponent(table) + "&uid=" + encodeURIComponent(uid),
"ShowItem" + Math.random().toString(16).slice(2),
"height=300,width=410,status=0,menubar=0,resizable=0,location=0,directories=0,scrollbars=1,toolbar=0"
);
if (thePreviewWindow && thePreviewWindow.focus) {
thePreviewWindow.focus();
}
}
function deleteRecord(table,id,url) {
window.location.href = ' . GeneralUtility::quoteJSvalue((string)$uriBuilder->buildUriFromRoute('tce_db') . '&cmd[') . '+table+"]["+id+"][delete]=1&redirect="+escape(url);
}
' . (isset($_POST['_savedokview']) && $this->popViewId ? $this->generatePreviewCode() : '')
);
// Setting up the context sensitive menu:
$this->moduleTemplate->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Backend/ContextMenu');
$this->emitFunctionAfterSignal(__FUNCTION__);
}
/**
* @return string
*/
protected function generatePreviewCode()
{
$table = $this->previewData['table'];
$recordId = $this->previewData['id'];
if ($table === 'pages') {
$currentPageId = $recordId;
} else {
$currentPageId = MathUtility::convertToPositiveInteger($this->popViewId);
}
$pageTsConfig = BackendUtility::getPagesTSconfig($currentPageId);
$previewConfiguration = $pageTsConfig['TCEMAIN.']['preview.'][$table . '.'] ?? [];
$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);
// Allow all doktypes below 200
// This makes custom doktype work as well with opening a frontend page.
if ((int)$currentPage['doktype'] <= PageRepository::DOKTYPE_SPACER) {
// 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 = [];
// language handling
$languageField = $GLOBALS['TCA'][$table]['ctrl']['languageField'] ?? '';
if ($languageField && !empty($recordArray[$languageField])) {
$l18nPointer = $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.'])) {
$additionalGetParameters = [];
$this->parseAdditionalGetParameters(
$additionalGetParameters,
$previewConfiguration['additionalGetParameters.']
);
$linkParameters = array_replace($linkParameters, $additionalGetParameters);
}
if (!empty($previewConfiguration['useCacheHash'])) {
/** @var CacheHashCalculator */
$cacheHashCalculator = GeneralUtility::makeInstance(CacheHashCalculator::class);
$fullLinkParameters = GeneralUtility::implodeArrayForUrl('', array_merge($linkParameters, ['id' => $previewPageId]));
$cacheHashParameters = $cacheHashCalculator->getRelevantParameters($fullLinkParameters);
$linkParameters['cHash'] = $cacheHashCalculator->calculateCacheHash($cacheHashParameters);
} else {
$linkParameters['no_cache'] = 1;
}
$this->popViewId = $previewPageId;
$this->popViewId_addParams = GeneralUtility::implodeArrayForUrl('', $linkParameters, '', false, true);
$anchorSection = $table === 'tt_content' ? '#c' . $recordId : '';
$previewPageRootline = BackendUtility::BEgetRootLine($this->popViewId);
return '
if (window.opener) {
'
. BackendUtility::viewOnClick(
$this->popViewId,
'',
$previewPageRootline,
$anchorSection,
$this->viewUrl,
$this->popViewId_addParams,
false
)
. '
} else {
'
. BackendUtility::viewOnClick(
$this->popViewId,
'',
$previewPageRootline,
$anchorSection,
$this->viewUrl,
$this->popViewId_addParams
)
. '
}';
}
/**
* Migrates a set of (possibly nested) GET parameters in TypoScript syntax to a plain array
*
* This basically removes the trailing dots of sub-array keys in TypoScript.
* The result can be used to create a query string with GeneralUtility::implodeArrayForUrl().
*
* @param array $parameters Should be an empty array by default
* @param array $typoScript The TypoScript configuration
*/
protected function parseAdditionalGetParameters(array &$parameters, array $typoScript)
{
foreach ($typoScript as $key => $value) {
if (is_array($value)) {
$key = rtrim($key, '.');
$parameters[$key] = [];
$this->parseAdditionalGetParameters($parameters[$key], $value);
} else {
$parameters[$key] = $value;
}
}
}
/**
* Main module operation
*/
public function main()
{
$body = '';
// Begin edit:
if (is_array($this->editconf)) {
/** @var FormResultCompiler formResultCompiler */
$this->formResultCompiler = GeneralUtility::makeInstance(FormResultCompiler::class);
// 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, add it:
if (($this->docDat[1] !== $this->storeUrlMd5
|| !isset($this->docHandler[$this->storeUrlMd5]))
&& !$this->dontStoreDocumentRef
) {
$this->docHandler[$this->storeUrlMd5] = [
$this->storeTitle,
$this->storeArray,
$this->storeUrl,
$this->firstEl
];
$this->getBackendUser()->pushModuleData('FormEngine', [$this->docHandler, $this->storeUrlMd5]);
BackendUtility::setUpdateSignal('OpendocsController::updateNumber', count($this->docHandler));
}
// Module configuration
$this->modTSconfig = $this->viewId ? BackendUtility::getModTSconfig(
$this->viewId,
'mod.xMOD_alt_doc'
) : [];
$body = $this->formResultCompiler->addCssFiles();
$body .= $this->compileForm($editForm);
$body .= $this->formResultCompiler->printNeededJSFunctions();
$body .= '</form>';
}
}
// Access check...
// The page will show only if there is a valid page and if this page may be viewed by the user
$this->pageinfo = BackendUtility::readPageAccess($this->viewId, $this->perms_clause);
if ($this->pageinfo) {
$this->moduleTemplate->getDocHeaderComponent()->setMetaInformation($this->pageinfo);
}
// Setting up the buttons and markers for docheader
$this->getButtons();
$this->languageSwitch($this->firstEl['table'], $this->firstEl['uid'], $this->firstEl['pid']);
$this->moduleTemplate->setContent($body);
}
/***************************
*
* Sub-content functions, rendering specific parts of the module content.
*
***************************/
/**
* Creates the editing form with FormEnigne, based on the input from GPvars.
*
* @return string HTML form elements wrapped in tables
*/
public function makeEditForm()
{
// Initialize variables:
$this->elementsData = [];
$this->errorC = 0;
$this->newC = 0;
$editForm = '';
$trData = null;
$beUser = $this->getBackendUser();
// Traverse the GPvar edit array
// Tables:
foreach ($this->editconf as $table => $conf) {
if (is_array($conf) && $GLOBALS['TCA'][$table] && $beUser->check('tables_modify', $table)) {
// Traverse the keys/comments of each table (keys can be a commalist of uids)
foreach ($conf as $cKey => $command) {
if ($command === 'edit' || $command === 'new') {
// Get the ids:
$ids = GeneralUtility::trimExplode(',', $cKey, true);