-
Notifications
You must be signed in to change notification settings - Fork 27
/
BackendTemplateMappingController.php
2729 lines (2433 loc) · 133 KB
/
BackendTemplateMappingController.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 Ppi\TemplaVoilaPlus\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\Template\Components\ButtonBar;
use TYPO3\CMS\Backend\Utility\BackendUtility;
use TYPO3\CMS\Core\Imaging\Icon;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use Ppi\TemplaVoilaPlus\Utility\TemplaVoilaUtility;
$GLOBALS['LANG']->includeLLFile(
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('templavoilaplus') . 'Resources/Private/Language/BackendTemplateMapping.xlf'
);
/**
* Class for controlling the TemplaVoila module.
*
* @author Kasper Skaarhoj <kasperYYYY@typo3.com>
* @co-author Robert Lemke <robert@typo3.org>
*/
class BackendTemplateMappingController extends \TYPO3\CMS\Backend\Module\BaseScriptClass
{
/**
* @var string
*/
protected $DS_element_DELETE;
/**
* @var string
*/
protected $sessionKey;
/**
* @var array
*/
public $head_markUpTags = [
// Block elements:
'title' => [],
'script' => [],
'style' => [],
// Single elements:
'link' => ['single' => 1],
'meta' => ['single' => 1],
];
/**
* Extension key of this module
*
* @var string
*/
public $extKey = 'templavoilaplus';
/**
* The name of the module
*
* @var string
*/
protected $moduleName = 'templavoilaplus_mapping';
/**
* @var array
*/
public $dsTypes;
/**
* Used to store the name of the file to mark up with a given path.
*
* @var string
*/
public $markupFile = '';
/**
* @var \Ppi\TemplaVoilaPlus\Domain\Model\HtmlMarkup
*/
public $markupObj;
/**
* @var array
*/
public $elNames = [];
/**
* Setting whether we are editing a data structure or not.
*
* @var integer
*/
public $editDataStruct = 0;
/**
* Storage folders as key(uid) / value (title) pairs.
*
* @var array
*/
public $storageFolders = [];
/**
* The storageFolders pids imploded to a comma list including "0"
*
* @var integer
*/
public $storageFolders_pidList = 0;
/**
* Looking for "&mode", which defines if we draw a frameset (default), the module (mod) or display (display)
*
* @var string
*/
public $mode;
/**
* (GPvar "file", shared with DISPLAY mode!) The file to display, if file is referenced directly from filelist module. Takes precedence over displayTable/displayUid
*
* @var string
*/
public $displayFile = '';
/**
* (GPvar "table") The table from which to display element (Data Structure object [tx_templavoilaplus_datastructure], template object [tx_templavoilaplus_tmplobj])
*
* @var string
*/
public $displayTable = '';
/**
* (GPvar "uid") The UID to display (from ->displayTable)
*
* @var string
*/
public $displayUid = '';
/**
* (GPvar "htmlPath") The "HTML-path" to display from the current file
*
* @var string
*/
public $displayPath = '';
/**
* (GPvar "returnUrl") Return URL if the script is supplied with that.
*
* @var string
*/
public $returnUrl = ''; //
/**
* @var boolean
*/
public $_preview;
/**
* @var string
*/
public $mapElPath;
/**
* @var boolean
*/
public $doMappingOfPath;
/**
* @var boolean
*/
public $showPathOnly;
/**
* @var string
*/
public $mappingToTags;
/**
* @var string
*/
public $DS_element;
/**
* @var string
*/
public $DS_cmd;
/**
* @var string
*/
public $fieldName;
/**
* @var boolean
*/
public $_load_ds_xml_content;
/**
* @var boolean
*/
public $_load_ds_xml_to;
/**
* @var integer
*/
public $_saveDSandTO_TOuid;
/**
* @var string
*/
public $_saveDSandTO_title;
/**
* @var string
*/
public $_saveDSandTO_type;
/**
* @var integer
*/
public $_saveDSandTO_pid;
/**
* instance of class Ppi\TemplaVoilaPlus\Module\Cm1\DsEdit
*
* @var \Ppi\TemplaVoilaPlus\Module\Cm1\DsEdit
*/
public $dsEdit;
/**
* instance of class Ppi\TemplaVoilaPlus\Module\Cm1\ETypes
*
* @var \Ppi\TemplaVoilaPlus\Module\Cm1\ETypes
*/
public $eTypes;
/**
* holds the extconf configuration
*
* @var array
*/
public $extConf;
/**
* Boolean; if true DS records are file based
*
* @var boolean
*/
public $staticDS = false;
/**
* @return void
*/
public function init()
{
parent::init();
$this->moduleTemplate = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Template\ModuleTemplate::class);
$this->iconFactory = $this->moduleTemplate->getIconFactory();
$this->buttonBar = $this->moduleTemplate->getDocHeaderComponent()->getButtonBar();
$this->extConf = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['templavoilaplus']);
}
/**
* Preparing menu content
*
* @return void
*/
public function menuConfig()
{
$this->MOD_MENU = [
'displayMode' => [
'explode' => 'Mode: Exploded Visual',
'source' => 'Mode: HTML Source ',
],
'showDSxml' => ''
];
// page/be_user TSconfig settings and blinding of menu-items
$this->modTSconfig = BackendUtility::getModTSconfig($this->id, 'mod.' . $this->moduleName);
// CLEANSE SETTINGS
$this->MOD_SETTINGS = BackendUtility::getModuleData($this->MOD_MENU, GeneralUtility::_GP('SET'), $this->moduleName);
}
/**
* Returns an abbrevation and a description for a given element-type.
*
* @param array $conf
* @TODO Clean up that array has 2 meanings (container or section!!)
*
* @return array
*/
public function dsTypeInfo($conf)
{
if ($conf['type'] !== null && isset($this->dsTypes[$conf['type']])) {
if ($conf['type'] == 'array') {
if (!$conf['section']) {
return $this->dsTypes['container'];
}
}
return $this->dsTypes[$conf['type']];
}
return $this->dsTypes['element'];
}
/*******************************************
*
* Main functions
*
*******************************************/
/**
* Injects the request object for the current request or subrequest
* As this controller goes only through the main() method, it is rather simple for now
*
* @param ServerRequestInterface $request the current request
* @param ResponseInterface $response
* @return ResponseInterface the response with the content
*/
public function mainAction(ServerRequestInterface $request, ResponseInterface $response)
{
$this->init();
$this->main();
$response->getBody()->write($this->moduleTemplate->renderContent());
return $response;
}
/**
* Main function, distributes the load between the module and display modes.
* "Display" mode is when the exploded template file is shown in an IFRAME
*
* @return void
*/
public function main()
{
// Initialize ds_edit
$this->dsEdit = GeneralUtility::getUserObj(\Ppi\TemplaVoilaPlus\Module\Cm1\DsEdit::class, '');
$this->dsEdit->init($this);
// Initialize eTypes
$this->eTypes = GeneralUtility::getUserObj(\Ppi\TemplaVoilaPlus\Module\Cm1\ETypes::class, '');
$this->eTypes->init($this);
$this->extConf = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['templavoilaplus']);
$this->staticDS = ($this->extConf['staticDS.']['enable']);
// Setting GPvars:
// It can be, that we get a storeg:file link from clickmenu
$this->displayFile = \Ppi\TemplaVoilaPlus\Domain\Model\File::filename(GeneralUtility::_GP('file'));
$this->displayTable = GeneralUtility::_GP('table');
$this->displayUid = GeneralUtility::_GP('uid');
$this->returnUrl = GeneralUtility::sanitizeLocalUrl(GeneralUtility::_GP('returnUrl'));
// Access check!
// The page will show only if there is a valid page and if this page may be viewed by the user
$pageInfoArr = BackendUtility::readPageAccess($this->id, $this->perms_clause);
$access = is_array($pageInfoArr);
if ($access) {
// Add custom styles
$this->getPageRenderer()->addCssFile(\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extRelPath($this->extKey) . 'Resources/Public/StyleSheet/cm1_default.css');
$this->getPageRenderer()->addCssFile(\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extRelPath($this->extKey) . 'Resources/Public/StyleSheet/HtmlMarkup.css');
// Adding classic jumpToUrl function, needed for the function menu.
// And some more functions
$this->moduleTemplate->addJavaScriptCode('templavoilaplus_function', '
script_ended = 0;
function jumpToUrl(URL) { //
document.location = URL;
}
function updPath(inPath) { //
document.location = "' . GeneralUtility::linkThisScript(array('htmlPath' => '', 'doMappingOfPath' => 1)) . '&htmlPath="+top.rawurlencode(inPath);
}
function openValidator(key) {
new Ajax.Request("' . $GLOBALS['BACK_PATH'] . 'ajax.php?ajaxID=Ppi\\TemplaVoilaPlus\Module\\Cm1\\Ajax::getDisplayFileContent&key=" + key, {
onSuccess: function(response) {
var valform = new Element(\'form\',{method: \'post\', target:\'_blank\', action: \'http://validator.w3.org/check#validate_by_input\'});
valform.insert(new Element(\'input\',{name: \'fragment\', value:response.responseText, type: \'hidden\'}));$(document.body).insert(valform);
valform.submit();
}
});
}
');
$this->main_mode();
} else {
$this->moduleTemplate->addFlashMessage(
TemplaVoilaUtility::getLanguageService()->getLL('noaccess'),
TemplaVoilaUtility::getLanguageService()->getLL('title'),
\TYPO3\CMS\Core\Messaging\FlashMessage::INFO
);
}
$title = TemplaVoilaUtility::getLanguageService()->getLL('mappingTitle');
$header = $this->moduleTemplate->header($title);
$this->moduleTemplate->setTitle($title);
$this->moduleTemplate->getDocHeaderComponent()->setMetaInformation($pageInfoArr);
$this->setDocHeaderButtons(!isset($pageInfoArr['uid']));
$this->moduleTemplate->setForm('<form action="' . $this->linkThisScript([]) . '" method="post" name="pageform">');
if ($this->content) {
$this->moduleTemplate->setContent($header . $this->content);
}
}
/**
* Gets the buttons that shall be rendered in the docHeader.
*
* @return array Available buttons for the docHeader
*/
protected function setDocHeaderButtons()
{
$this->addCshButton('');
$this->addShortcutButton();
$this->addBackButton();
}
/**
* Adds csh icon to the right document header button bar
*/
public function addCshButton($fieldName)
{
$contextSensitiveHelpButton = $this->buttonBar->makeHelpButton()
->setModuleName('_MOD_' . $this->moduleName)
->setFieldName($fieldName);
$this->buttonBar->addButton($contextSensitiveHelpButton, ButtonBar::BUTTON_POSITION_RIGHT);
}
/**
* Adds shortcut icon to the right document header button bar
*/
public function addShortcutButton()
{
$shortcutButton = $this->buttonBar->makeShortcutButton()
->setModuleName($this->moduleName)
->setGetVariables(
[
'id',
'uid',
]
)
->setSetVariables(array_keys($this->MOD_MENU));
$this->buttonBar->addButton($shortcutButton, ButtonBar::BUTTON_POSITION_RIGHT);
}
public function addBackButton()
{
if ($this->returnUrl) {
$url = $this->returnUrl;
} else {
// @TODO Go back to ControlCenter if we are on "start page"
$url = BackendUtility::getModuleUrl(
'templavoilaplus_mapping',
[
'id' => $this->id,
'file' => $this->displayFile,
'table' => $this->displayTable,
'uid' => $this->displayUid,
]
);
}
$backButton = $this->buttonBar->makeLinkButton()
->setHref($url)
->setTitle($this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:rm.closeDoc'))
->setIcon($this->iconFactory->getIcon('actions-view-go-back', Icon::SIZE_SMALL));
$this->buttonBar->addButton($backButton, ButtonBar::BUTTON_POSITION_LEFT, 10);
}
/**
* Makes a context-free xml-string from an array.
*
* @param array $array
* @param string $pfx
*
* @return string
*/
public function flattenarray($array, $pfx = '')
{
if (!is_array($array)) {
if (is_string($array)) {
return $array;
} else {
return '';
}
}
return str_replace("<>\n", '', str_replace("</>", '', GeneralUtility::array2xml($array, '', -1, '', 0, array('useCDATA' => 1))));
}
/**
* Makes an array from a context-free xml-string.
*
* @param string $string
*
* @return array
*/
public function unflattenarray($string)
{
if (!is_string($string) || !trim($string)) {
if (is_array($string)) {
return $string;
} else {
return [];
}
}
return GeneralUtility::xml2array('<grouped>' . $string . '</grouped>');
}
/**
* Merges two arrays recursively and "binary safe" (integer keys are overridden as well), overruling similar values in the first array ($arr0) with the values of the second array ($arr1)
* In case of identical keys, ie. keeping the values of the second.
* Usage: 0
*
* @param array $arr0 First array
* @param array $arr1 Second array, overruling the first array
* @param integer $notAddKeys If set, keys that are NOT found in $arr0 (first array) will not be set. Thus only existing value can/will be overruled from second array.
* @param boolean $includeEmtpyValues If set, values from $arr1 will overrule if they are empty or zero. Default: true
* @param boolean $kill If set, anything will override arrays in $arr0
*
* @return array Resulting array where $arr1 values has overruled $arr0 values
*/
public function array_merge_recursive_overrule($arr0, $arr1, $notAddKeys = 0, $includeEmtpyValues = true, $kill = true)
{
foreach ($arr1 as $key => $val) {
if (is_array($arr0[$key])) {
if (is_array($arr1[$key])) {
$arr0[$key] = $this->array_merge_recursive_overrule($arr0[$key], $arr1[$key], $notAddKeys, $includeEmtpyValues, $kill);
} else {
if ($kill) {
if ($includeEmtpyValues || $val) {
$arr0[$key] = $val;
}
}
}
} else {
if ($notAddKeys) {
if (isset($arr0[$key])) {
if ($includeEmtpyValues || $val) {
$arr0[$key] = $val;
}
}
} else {
if ($includeEmtpyValues || $val) {
$arr0[$key] = $val;
}
}
}
}
reset($arr0);
return $arr0;
}
/*****************************************
*
* MODULE mode
*
*****************************************/
/**
* Main function of the MODULE. Write the content to $this->content
* There are three main modes:
* - Based on a file reference, creating/modifying a DS/TO
* - Based on a Template Object uid, remapping
* - Based on a Data Structure uid, selecting a Template Object to map.
*
* @return void
*/
public function main_mode()
{
// General GPvars for module mode:
$this->displayPath = GeneralUtility::_GP('htmlPath');
// GPvars specific to the DS listing/table and mapping features:
$this->_preview = GeneralUtility::_GP('_preview');
$this->mapElPath = GeneralUtility::_GP('mapElPath');
$this->doMappingOfPath = GeneralUtility::_GP('doMappingOfPath');
$this->showPathOnly = GeneralUtility::_GP('showPathOnly');
$this->mappingToTags = GeneralUtility::_GP('mappingToTags');
$this->DS_element = GeneralUtility::_GP('DS_element');
$this->DS_cmd = GeneralUtility::_GP('DS_cmd');
$this->fieldName = GeneralUtility::_GP('fieldName');
// GPvars specific for DS creation from a file.
$this->_load_ds_xml_content = GeneralUtility::_GP('_load_ds_xml_content');
$this->_load_ds_xml_to = GeneralUtility::_GP('_load_ds_xml_to');
$this->_saveDSandTO_TOuid = GeneralUtility::_GP('_saveDSandTO_TOuid');
$this->_saveDSandTO_title = GeneralUtility::_GP('_saveDSandTO_title');
$this->_saveDSandTO_type = GeneralUtility::_GP('_saveDSandTO_type');
$this->_saveDSandTO_pid = GeneralUtility::_GP('_saveDSandTO_pid');
$this->DS_element_DELETE = GeneralUtility::_GP('DS_element_DELETE');
// Finding Storage folder:
$this->findingStorageFolderIds();
// dsType configuration
// @TODO Clean up that type array can have 2 meanings!
$this->dsTypes = [
'section' => [
'id' => 'sc',
'title' => TemplaVoilaUtility::getLanguageService()->getLL('dsTypes_section') . ': ',
],
'array' => [
'id' => 'sc',
'title' => TemplaVoilaUtility::getLanguageService()->getLL('dsTypes_section') . ': ',
],
'container' => [
'id' => 'co',
'title' => TemplaVoilaUtility::getLanguageService()->getLL('dsTypes_container') . ': ',
],
'attr' => [
'id' => 'at',
'title' => TemplaVoilaUtility::getLanguageService()->getLL('dsTypes_attribute') . ': ',
],
'element' => [
'id' => 'el',
'title' => TemplaVoilaUtility::getLanguageService()->getLL('dsTypes_element') . ': ',
],
'no_map' => [
'id' => 'no',
'title' => TemplaVoilaUtility::getLanguageService()->getLL('dsTypes_notmapped') . ': ',
],
];
// Render content, depending on input values:
if ($this->displayFile) { // Browsing file directly, possibly creating a template/data object records.
$this->renderFile();
} elseif ($this->displayTable == 'tx_templavoilaplus_datastructure') { // Data source display
$this->renderDSO();
} elseif ($this->displayTable == 'tx_templavoilaplus_tmplobj') { // Data source display
$this->renderTO();
}
}
/**
* Renders the display of DS/TO creation directly from a file
*
* @return void
*/
public function renderFile()
{
if (@is_file($this->displayFile) && GeneralUtility::getFileAbsFileName($this->displayFile)) {
// Converting GPvars into a "cmd" value:
$cmd = '';
if (GeneralUtility::_GP('_load_ds_xml')) { // Loading DS from XML or TO uid
$cmd = 'load_ds_xml';
} elseif (GeneralUtility::_GP('_clear')) { // Resetting mapping/DS
$cmd = 'clear';
} elseif (GeneralUtility::_GP('_saveDSandTO')) { // Saving DS and TO to records.
if (!strlen(trim($this->_saveDSandTO_title))) {
$cmd = 'saveScreen';
$this->moduleTemplate->addFlashMessage(
TemplaVoilaUtility::getLanguageService()->getLL('errorNoToTitleDefined'),
TemplaVoilaUtility::getLanguageService()->getLL('error'),
\TYPO3\CMS\Core\Messaging\FlashMessage::ERROR
);
} else {
$cmd = 'saveDSandTO';
}
} elseif (GeneralUtility::_GP('_updateDSandTO')) { // Updating DS and TO
$cmd = 'updateDSandTO';
} elseif (GeneralUtility::_GP('_showXMLDS')) { // Showing current DS as XML
$cmd = 'showXMLDS';
} elseif (GeneralUtility::_GP('_preview')) { // Previewing mappings
$cmd = 'preview';
} elseif (GeneralUtility::_GP('_save_data_mapping')) { // Saving mapping to Session
$cmd = 'save_data_mapping';
} elseif (GeneralUtility::_GP('_updateDS')) {
$cmd = 'updateDS';
} elseif (GeneralUtility::_GP('DS_element_DELETE')) {
$cmd = 'DS_element_DELETE';
} elseif (GeneralUtility::_GP('_saveScreen')) {
$cmd = 'saveScreen';
} elseif (GeneralUtility::_GP('_loadScreen')) {
$cmd = 'loadScreen';
} elseif (GeneralUtility::_GP('_save')) {
$cmd = 'saveUpdatedDSandTO';
} elseif (GeneralUtility::_GP('_saveExit')) {
$cmd = 'saveUpdatedDSandTOandExit';
}
// Init settings:
$this->editDataStruct = 1; // Edit DS...
$content = '';
// Checking Storage Folder PID:
if (!count($this->storageFolders)) {
$this->moduleTemplate->addFlashMessage(
TemplaVoilaUtility::getLanguageService()->getLL('errorNoStorageFolder'),
TemplaVoilaUtility::getLanguageService()->getLL('error'),
\TYPO3\CMS\Core\Messaging\FlashMessage::ERROR
);
}
// Session data
$this->sessionKey = $this->MCONF['name'] . '_mappingInfo:' . $this->_load_ds_xml_to;
if ($cmd == 'clear') { // Reset session data:
$sesDat = array('displayFile' => $this->displayFile, 'TO' => $this->_load_ds_xml_to, 'DS' => $this->displayUid);
TemplaVoilaUtility::getBackendUser()->setAndSaveSessionData($this->sessionKey, $sesDat);
} else { // Get session data:
$sesDat = TemplaVoilaUtility::getBackendUser()->getSessionData($this->sessionKey);
}
if ($this->_load_ds_xml_to) {
$toREC = BackendUtility::getRecordWSOL('tx_templavoilaplus_tmplobj', $this->_load_ds_xml_to);
if ($this->staticDS) {
$dsREC['dataprot'] = GeneralUtility::getURL(GeneralUtility::getFileAbsFileName($toREC['datastructure']));
} else {
$dsREC = BackendUtility::getRecordWSOL('tx_templavoilaplus_datastructure', $toREC['datastructure']);
}
}
// Loading DS from either XML or a Template Object (containing reference to DS)
if ($cmd == 'load_ds_xml' && ($this->_load_ds_xml_content || $this->_load_ds_xml_to)) {
$to_uid = $this->_load_ds_xml_to;
if ($to_uid) {
$tM = unserialize($toREC['templatemapping']);
$sesDat = array('displayFile' => $this->displayFile, 'TO' => $this->_load_ds_xml_to, 'DS' => $this->displayUid);
$sesDat['currentMappingInfo'] = $tM['MappingInfo'];
$sesDat['currentMappingInfo_head'] = $tM['MappingInfo_head'];
$ds = GeneralUtility::xml2array($dsREC['dataprot']);
$sesDat['dataStruct'] = $sesDat['autoDS'] = $ds; // Just set $ds, not only its ROOT! Otherwise <meta> will be lost.
TemplaVoilaUtility::getBackendUser()->setAndSaveSessionData($this->sessionKey, $sesDat);
} else {
$ds = GeneralUtility::xml2array($this->_load_ds_xml_content);
$sesDat = array('displayFile' => $this->displayFile, 'TO' => $this->_load_ds_xml_to, 'DS' => $this->displayUid);
$sesDat['dataStruct'] = $sesDat['autoDS'] = $ds;
TemplaVoilaUtility::getBackendUser()->setAndSaveSessionData($this->sessionKey, $sesDat);
}
}
// Setting Data Structure to value from session data - unless it does not exist in which case a default structure is created.
$dataStruct = is_array($sesDat['autoDS']) ? $sesDat['autoDS'] : array(
'meta' => array(
'langDisable' => '1',
),
'ROOT' => array(
'tx_templavoilaplus' => array(
'title' => 'ROOT',
'description' => TemplaVoilaUtility::getLanguageService()->getLL('rootDescription'),
),
'type' => 'array',
'el' => array()
)
);
// Setting Current Mapping information to session variable content OR blank if none exists.
$currentMappingInfo = is_array($sesDat['currentMappingInfo']) ? $sesDat['currentMappingInfo'] : [];
$this->cleanUpMappingInfoAccordingToDS($currentMappingInfo, $dataStruct); // This will clean up the Current Mapping info to match the Data Structure.
// CMD switch:
switch ($cmd) {
// Saving incoming Mapping Data to session data:
case 'save_data_mapping':
$inputData = GeneralUtility::_GP('dataMappingForm', 1);
if (is_array($inputData)) {
$sesDat['currentMappingInfo'] = $currentMappingInfo = $this->array_merge_recursive_overrule($currentMappingInfo, $inputData);
$sesDat['dataStruct'] = $dataStruct;
TemplaVoilaUtility::getBackendUser()->setAndSaveSessionData($this->sessionKey, $sesDat);
}
break;
// Saving incoming Data Structure settings to session data:
case 'updateDS':
$inDS = GeneralUtility::_GP('autoDS', 1);
if (is_array($inDS)) {
$sesDat['dataStruct'] = $sesDat['autoDS'] = $dataStruct = $this->array_merge_recursive_overrule($dataStruct, $inDS);
TemplaVoilaUtility::getBackendUser()->setAndSaveSessionData($this->sessionKey, $sesDat);
}
break;
// If DS element is requested for deletion, remove it and update session data:
case 'DS_element_DELETE':
$ref = explode('][', substr($this->DS_element_DELETE, 1, -1));
$this->unsetArrayPath($dataStruct, $ref);
$sesDat['dataStruct'] = $sesDat['autoDS'] = $dataStruct;
TemplaVoilaUtility::getBackendUser()->setAndSaveSessionData($this->sessionKey, $sesDat);
break;
}
// Creating $templatemapping array with cached mapping content:
if (GeneralUtility::inList('showXMLDS,saveDSandTO,updateDSandTO,saveUpdatedDSandTO,saveUpdatedDSandTOandExit', $cmd)) {
// Template mapping prepared:
$templatemapping = [];
$templatemapping['MappingInfo'] = $currentMappingInfo;
if (isset($sesDat['currentMappingInfo_head'])) {
$templatemapping['MappingInfo_head'] = $sesDat['currentMappingInfo_head'];
}
// Getting cached data:
reset($dataStruct);
$fileContent = GeneralUtility::getUrl($this->displayFile);
$relPathFix = dirname(substr($this->displayFile, strlen(PATH_site))) . '/';
// @TODO We have this init multiple in this class => BAD
// @TODO We have this loading 3 times in this class => BAD
// Init mark up object.
$this->markupObj = GeneralUtility::makeInstance(\Ppi\TemplaVoilaPlus\Domain\Model\HtmlMarkup::class);
$this->markupObj->init();
$fileContent = $this->markupObj->htmlParse->prefixResourcePath($relPathFix, $fileContent);
$contentSplittedByMapping = $this->markupObj->splitContentToMappingInfo($fileContent, $currentMappingInfo);
$templatemapping['MappingData_cached'] = $contentSplittedByMapping['sub']['ROOT'];
// Get <head>...</head> from template:
$splitByHeader = $this->markupObj->htmlParse->splitIntoBlock('head', $fileContent);
// There should be only one head tag
$html_header = $this->markupObj->htmlParse->removeFirstAndLastTag($splitByHeader[1]);
$this->markupObj->tags = $this->head_markUpTags; // Set up the markupObject to process only header-section tags:
if (isset($templatemapping['MappingInfo_head'])) {
$h_currentMappingInfo = [];
$currentMappingInfo_head = $templatemapping['MappingInfo_head'];
if (is_array($currentMappingInfo_head['headElementPaths'])) {
foreach ($currentMappingInfo_head['headElementPaths'] as $kk => $vv) {
$h_currentMappingInfo['el_' . $kk]['MAP_EL'] = $vv;
}
}
$contentSplittedByMapping = $this->markupObj->splitContentToMappingInfo($html_header, $h_currentMappingInfo);
$templatemapping['MappingData_head_cached'] = $contentSplittedByMapping;
// Get <body> tag:
$reg = '';
preg_match('/<body[^>]*>/i', $fileContent, $reg);
$templatemapping['BodyTag_cached'] = $currentMappingInfo_head['addBodyTag'] ? $reg[0] : '';
}
if ($cmd != 'showXMLDS') {
// Set default flags to <meta> tag
if (!isset($dataStruct['meta'])) {
// Make sure <meta> goes at the beginning of data structure.
// This is not critical for typo3 but simply convinient to
// people who used to see it at the beginning.
$dataStruct = array_merge(array('meta' => array()), $dataStruct);
}
if ($this->_saveDSandTO_type == 1) {
// If we save a page template, set langDisable to 1 as per localization guide
if (!isset($dataStruct['meta']['langDisable'])) {
$dataStruct['meta']['langDisable'] = '1';
}
} else {
// FCE defaults to inheritance
if (!isset($dataStruct['meta']['langDisable'])) {
$dataStruct['meta']['langDisable'] = '0';
$dataStruct['meta']['langChildren'] = '1';
}
}
}
}
// CMD switch:
switch ($cmd) {
// If it is requested to save the current DS and mapping information to a DS and TO record, then...:
case 'saveDSandTO':
// Init TCEmain object and store:
$tce = GeneralUtility::makeInstance(\TYPO3\CMS\Core\DataHandling\DataHandler::class);
$tce->stripslashes_values = 0;
// DS:
// Modifying data structure with conversion of preset values for field types to actual settings:
$storeDataStruct = $dataStruct;
if (is_array($storeDataStruct['ROOT']['el'])) {
$this->eTypes->substEtypeWithRealStuff($storeDataStruct['ROOT']['el'], $contentSplittedByMapping['sub']['ROOT'], $dataArr['tx_templavoilaplus_datastructure']['NEW']['scope']);
}
$dataProtXML = GeneralUtility::array2xml_cs($storeDataStruct, 'T3DataStructure', array('useCDATA' => 1));
if ($this->staticDS) {
$title = preg_replace('|[/,\."\']+|', '_', $this->_saveDSandTO_title) . ' (' . ($this->_saveDSandTO_type == 1 ? 'page' : 'fce') . ').xml';
$path = GeneralUtility::getFileAbsFileName($this->_saveDSandTO_type == 2 ? $this->extConf['staticDS.']['path_fce'] : $this->extConf['staticDS.']['path_page']) . $title;
GeneralUtility::writeFile($path, $dataProtXML);
$newID = substr($path, strlen(PATH_site));
} else {
$dataArr = [];
$dataArr['tx_templavoilaplus_datastructure']['NEW']['pid'] = (int)$this->_saveDSandTO_pid;
$dataArr['tx_templavoilaplus_datastructure']['NEW']['title'] = $this->_saveDSandTO_title;
$dataArr['tx_templavoilaplus_datastructure']['NEW']['scope'] = $this->_saveDSandTO_type;
$dataArr['tx_templavoilaplus_datastructure']['NEW']['dataprot'] = $dataProtXML;
// start data processing
$tce->start($dataArr, array());
$tce->process_datamap();
$newID = (int)$tce->substNEWwithIDs['NEW'];
}
// If that succeeded, create the TO as well:
if ($newID) {
$dataArr = [];
$dataArr['tx_templavoilaplus_tmplobj']['NEW']['pid'] = (int)$this->_saveDSandTO_pid;
$dataArr['tx_templavoilaplus_tmplobj']['NEW']['title'] = $this->_saveDSandTO_title . ' [Template]';
$dataArr['tx_templavoilaplus_tmplobj']['NEW']['datastructure'] = $newID;
$dataArr['tx_templavoilaplus_tmplobj']['NEW']['fileref'] = substr($this->displayFile, strlen(PATH_site));
$dataArr['tx_templavoilaplus_tmplobj']['NEW']['templatemapping'] = serialize($templatemapping);
$dataArr['tx_templavoilaplus_tmplobj']['NEW']['fileref_mtime'] = @filemtime($this->displayFile);
$dataArr['tx_templavoilaplus_tmplobj']['NEW']['fileref_md5'] = @md5_file($this->displayFile);
// Init TCEmain object and store:
$tce->start($dataArr, array());
$tce->process_datamap();
$newToID = (int)$tce->substNEWwithIDs['NEW'];
if ($newToID) {
$this->moduleTemplate->addFlashMessage(
sprintf(
TemplaVoilaUtility::getLanguageService()->getLL('msgDSTOSaved'),
$dataArr['tx_templavoilaplus_tmplobj']['NEW']['datastructure'],
$tce->substNEWwithIDs['NEW'],
$this->_saveDSandTO_pid
),
'',
\TYPO3\CMS\Core\Messaging\FlashMessage::OK
);
} else {
$this->moduleTemplate->addFlashMessage(
sprintf(
TemplaVoilaUtility::getLanguageService()->getLL('errorTONotSaved'),
$dataArr['tx_templavoilaplus_tmplobj']['NEW']['datastructure']
),
TemplaVoilaUtility::getLanguageService()->getLL('error'),
\TYPO3\CMS\Core\Messaging\FlashMessage::ERROR
);
}
} else {
$this->moduleTemplate->addFlashMessage(
TemplaVoilaUtility::getLanguageService()->getLL('errorTONotCreated'),
TemplaVoilaUtility::getLanguageService()->getLL('error'),
\TYPO3\CMS\Core\Messaging\FlashMessage::ERROR
);
}
unset($tce);
if ($newID && $newToID) {
//redirect to edit view
$this->redirectToModifyDSTO($newToID, $newID);
exit;
} else {
// Clear cached header info because saveDSandTO always resets headers
$sesDat['currentMappingInfo_head'] = '';
TemplaVoilaUtility::getBackendUser()->setAndSaveSessionData($this->sessionKey, $sesDat);
}
break;
// Updating DS and TO records:
case 'updateDSandTO':
case 'saveUpdatedDSandTO':
case 'saveUpdatedDSandTOandExit':
if ($cmd == 'updateDSandTO') {
// Looking up the records by their uids:
$toREC = BackendUtility::getRecordWSOL('tx_templavoilaplus_tmplobj', $this->_saveDSandTO_TOuid);
} else {
$toREC = BackendUtility::getRecordWSOL('tx_templavoilaplus_tmplobj', $this->_load_ds_xml_to);
}
if ($this->staticDS) {
$dsREC['uid'] = $toREC['datastructure'];
} else {
$dsREC = BackendUtility::getRecordWSOL('tx_templavoilaplus_datastructure', $toREC['datastructure']);
}
// If they are found, continue:
if ($toREC['uid'] && $dsREC['uid']) {
// Init TCEmain object and store:
$tce = GeneralUtility::makeInstance(\TYPO3\CMS\Core\DataHandling\DataHandler::class);
$tce->stripslashes_values = 0;
// Modifying data structure with conversion of preset values for field types to actual settings:
$storeDataStruct = $dataStruct;
if (is_array($storeDataStruct['ROOT']['el'])) {
$this->eTypes->substEtypeWithRealStuff($storeDataStruct['ROOT']['el'], $contentSplittedByMapping['sub']['ROOT'], $dsREC['scope']);
}
$dataProtXML = GeneralUtility::array2xml_cs($storeDataStruct, 'T3DataStructure', array('useCDATA' => 1));
// DS:
if ($this->staticDS) {
$path = PATH_site . $dsREC['uid'];
GeneralUtility::writeFile($path, $dataProtXML);
} else {
$dataArr = [];
$dataArr['tx_templavoilaplus_datastructure'][$dsREC['uid']]['dataprot'] = $dataProtXML;
// process data
$tce->start($dataArr, array());
$tce->process_datamap();
}
// TO:
$TOuid = BackendUtility::wsMapId('tx_templavoilaplus_tmplobj', $toREC['uid']);