-
Notifications
You must be signed in to change notification settings - Fork 994
/
TemplateManifest.php
executable file
·1537 lines (1329 loc) · 63.7 KB
/
TemplateManifest.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
/*
* LimeSurvey
* Copyright (C) 2007-2015 The LimeSurvey Project Team / Carsten Schmitz
* All rights reserved.
* License: GNU/GPL License v2 or later, see LICENSE.php
* LimeSurvey is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*/
/**
* Template Configuration Model
*
* This model retrieves all the data of template configuration from the configuration file
*
* @package LimeSurvey
* @subpackage Backend
*/
class TemplateManifest extends TemplateConfiguration
{
public $templateEditor;
public $sPreviewImgTag;
/* There is no option inheritance on Manifest mode: values from XML are always used. So no: $bUseMagicInherit */
/**
* Public interface specific to TemplateManifest
* They are used in TemplateEditor
*/
/**
* Update the configuration file "last update" node.
* For now, it is called only from template editor
*/
public function actualizeLastUpdate()
{
if (\PHP_VERSION_ID < 80000) {
libxml_disable_entity_loader(false);
}
$config = simplexml_load_file(realpath($this->xmlFile));
$config->metadata->lastUpdate = date("Y-m-d H:i:s");
$config->asXML(realpath($this->xmlFile)); // Belt
touch($this->path); // & Suspenders ;-)
if (\PHP_VERSION_ID < 80000) {
libxml_disable_entity_loader(true);
}
}
/**
* Used from the template editor.
* It returns an array of editable files by screen for a given file type
*
* @param string $sType the type of files (view/css/js)
* @param string $sScreen the screen you want to retrieve the files from. If null: all screens
* @return array array ( [screen name] => array([files]) )
*/
public function getValidScreenFiles($sType = "view", $sScreen = null)
{
$aScreenFiles = array();
if (empty($this->templateEditor)) {
return array();
}
$filesFromXML = (is_null($sScreen)) ? (array) $this->templateEditor->screens->xpath('//file') : $this->templateEditor->screens->xpath('//' . $sScreen . '/file');
foreach ($filesFromXML as $file) {
if ($file->attributes()->type == $sType) {
// prevent accidental linebreaks and empty spaces in xml file string from breaking file path when loading it
$file = trim(str_replace(["\r", "\n"], '', $file));
$aScreenFiles[] = $file;
}
}
$oEvent = new PluginEvent('getValidScreenFiles');
$oEvent->set('type', $sType);
$oEvent->set('screen', $sScreen);
//$oEvent->set('files',$aScreenFiles); // Not needed since we have remove and add event
App()->getPluginManager()->dispatchEvent($oEvent);
$aScreenFiles = array_values(array_diff($aScreenFiles, (array) $oEvent->get('remove')));
$aScreenFiles = array_merge($aScreenFiles, (array)$oEvent->get('add'));
$aScreenFiles = array_unique($aScreenFiles);
return $aScreenFiles;
}
/**
* Returns the complete list of screens, with layout and contents. Used from Twig Command line
* @return array the list of screens, layouts, contents
*/
public function getScreensDetails()
{
$aContent = array();
$oScreensFromXML = $this->templateEditor->xpath('//screens');
foreach ($oScreensFromXML[0] as $sScreen => $oScreen) {
// We reset LayoutName and FileName at each loop to avoid errors
$sLayoutName = "";
$sTitle = "";
foreach ($oScreen as $sKey => $oField) {
if ($oField->attributes()->role == "layout") {
$sLayoutName = (string) $oField;
}
if ($oField->attributes()->role == "content") {
$sFile = (string) $oField;
// From command line, we need to remove the full path for content. It's inside the layout. This could be an option
$aFile = explode("/", $sFile);
$aFileName = explode(".", end($aFile));
$sContent = $aFileName[0];
}
if ($oField->attributes()->role == "title") {
$sTitle = (string) $oField;
if ($oField->attributes()->twig == "on") {
$sTitle = Yii::app()->twigRenderer->convertTwigToHtml($sTitle);
}
}
}
if (!empty($sLayoutName)) {
$aContent[$sScreen]['title'] = $sTitle;
$aContent[$sScreen]['layouts'][$sLayoutName] = $sContent;
}
}
return $aContent;
}
/**
* Returns an array of screens list with their respective titles. Used by Theme Editor to build the screend selection dropdown
* For retro-compatibility purpose, if the array is empty it will use the old default values.
*
* @return array the list of screens with their titles
*/
public function getScreensList()
{
$aScreenList = $this->getScreensDetails();
$aScreens = array();
foreach ($aScreenList as $sScreenName => $aTitleAndLayouts) {
$aScreens[$sScreenName] = $aTitleAndLayouts['title'];
}
// We check there is at least one screen title in the array. Else, the theme manifest is outdated, so we use the default values
$bEmptyTitles = true;
foreach ($aScreens as $sScreenName => $sTitle) {
if (!empty($sTitle)) {
$bEmptyTitles = false;
break;
}
}
if ($bEmptyTitles) {
if (YII_DEBUG) {
Yii::app()->setFlashMessage("Your theme does not implement screen definition in XML. Using the default ones <br> this message will not appear when debug mode is off", 'error');
}
$aScreens['welcome'] = gT('Welcome', 'unescaped');
$aScreens['question'] = gT('Question', 'unescaped');
$aScreens['completed'] = gT('Completed', 'unescaped');
$aScreens['clearall'] = gT('Clear all', 'unescaped');
$aScreens['load'] = gT('Load', 'unescaped');
$aScreens['save'] = gT('Save', 'unescaped');
$aScreens['surveylist'] = gT('Survey list', 'unescaped');
$aScreens['error'] = gT('Error', 'unescaped');
$aScreens['assessments'] = gT('Assessments', 'unescaped');
$aScreens['register'] = gT('Registration', 'unescaped');
$aScreens['printanswers'] = gT('Print answers', 'unescaped');
$aScreens['pdf'] = gT('PDF', 'unescaped');
$aScreens['navigation'] = gT('Navigation', 'unescaped');
$aScreens['misc'] = gT('Miscellaneous files', 'unescaped');
}
return $aScreens;
}
/**
* Return the default datas for theme views.
* This is used when rendering the views outside of the normal survey taking.
* Currently used in two cases: theme editor preview, and twig cache file generation from command line.
*/
public function getDefaultDataForRendering($thissurvey = array())
{
$thissurvey = empty($thissurvey) ? $this->getDefaultCoreDataForRendering() : $thissurvey;
$thissurvey = $this->getDefaultDataForRenderingFromXml($thissurvey);
//$thissurvey['alanguageChanger'] = $this->getDefaultDataForLanguageChanger();
// Redundant values
$thissurvey['surveyls_title'] = $thissurvey['name'];
$thissurvey['surveyls_description'] = $thissurvey['description'];
$thissurvey['surveyls_welcometext'] = $thissurvey['welcome'];
return $thissurvey;
}
public function getDefaultDataForLanguageChanger($thissurvey = array())
{
$thissurvey = empty($thissurvey) ? array() : $thissurvey;
$thissurvey['alanguageChanger']['datas'] = [
'sSelected' => 'en',
//'withForm' => true, // Set to true for no-js functionality.
'aListLang' => [
'en' => gT('English'),
'de' => gT('German')
]
];
}
public function getDefaultDataForRenderingFromXml($thissurvey = array())
{
$thissurvey = empty($thissurvey) ? array() : $thissurvey;
if (empty($this->templateEditor)) {
return $thissurvey;
}
$thissurvey = $this->parseDefaultData('survey', $thissurvey);
$thissurvey['aGroups'][1] = $this->parseDefaultData('group', $thissurvey['aGroups'][1]);
$thissurvey['aGroups'][1]["aQuestions"][1] = $this->parseDefaultData('question_1', $thissurvey['aGroups'][1]["aQuestions"][1]) ;
$thissurvey['aGroups'][1]["aQuestions"][2] = $this->parseDefaultData('question_2', $thissurvey['aGroups'][1]["aQuestions"][2]);
$thissurvey['aAssessments']["datas"]["total"][0] = $this->parseDefaultData('assessments', $thissurvey['aAssessments']["datas"]["total"][0]);
/**
* NOTE: This will allow Theme developer to add their new screens without editing this file.
* It implies they respect the convention :
* $aSurveyData[custom screen name][custom variable] = custom variable value
* Where custom variable value can't be an array.
* TODO: for LS5, refactor all the twig views and theme editor so we use only this convetion.
* Eg: don't use arrays like $thissurvey['aAssessments']["datas"]["total"][0] or $thissurvey['aGroups'][1]["aQuestions"][1]
*/
$thissurvey = $this->getCustomScreenData($thissurvey);
return $thissurvey;
}
/**
* If theme developer created custom screens, they will provide custom data.
* This function will get those custom data to pass them to the preview.
*/
protected function getCustomScreenData($thissurvey = array())
{
$oDataFromXML = $this->templateEditor->xpath("//default_data"); //
foreach ($oDataFromXML[0] as $sScreenName => $oData) {
if ($oData->attributes()->type == "custom") {
$sArrayName = (string) $oData->attributes()->arrayName;
$thissurvey[$sArrayName] = array();
$thissurvey[$sArrayName] = $this->parseDefaultData($sScreenName, $thissurvey[$sArrayName]);
}
}
return $thissurvey;
}
protected function parseDefaultData($sXpath, $aArrayToFeed)
{
$oDataFromXML = $this->templateEditor->default_data->xpath('//' . $sXpath);
$oDataFromXML = end($oDataFromXML);
foreach ($oDataFromXML as $sKey => $oData) {
if (!empty($sKey)) {
$sData = (string) $oData;
if ($oData->attributes()->twig == "on") {
$sData = Yii::app()->twigRenderer->convertTwigToHtml($sData);
}
$aArrayToFeed[$sKey] = $sData;
}
}
return $aArrayToFeed;
}
/**
* Returns all the twig strings inside the current XML. Used from TwigCommand
* NOTE: this not recursive. So it will show only the string of the current XML, not of parent XML. (not needed to generate twig cache from command line since all XML files are parsed)
*
* @param array $items if you already have a list of items and want to use it.
* @return array the list of strings using twig
*/
public function getTwigStrings($items = array())
{
$oDataFromXML = $this->config;
$oElements = $oDataFromXML->xpath('//*[@twig="on"]');
foreach ($oElements as $key => $oELement) {
$items[] = (string) $oELement;
}
return $items;
}
/**
* Hard coded data for theme rendering outside of the normal survey taking.
*
* Currently used in two cases: theme editor preview, and twig cache file generation from command line.
*/
public function getDefaultCoreDataForRendering()
{
$thissurvey = array();
// Values that never change.
$thissurvey['active'] = 'N';
$thissurvey['allowsave'] = "Y";
$thissurvey['active'] = "Y";
$thissurvey['tokenanswerspersistence'] = "Y";
$thissurvey['format'] = "G";
$thissurvey['usecaptcha'] = "A";
$thissurvey['showprogress'] = true;
$thissurvey['aNavigator']['show'] = true;
$thissurvey['aNavigator']['aMoveNext']['show'] = true;
$thissurvey['aNavigator']['aMovePrev']['show'] = true;
$thissurvey['alanguageChanger']['show'] = true;
$thissurvey['alanguageChanger']['datas'] = [
'sSelected' => 'en',
//'withForm' => true, // Set to true for no-js functionality.
'aListLang' => [
'en' => gT('English'),
'de' => gT('German')
]
];
$thissurvey['aQuestionIndex']['bShow'] = true;
$thissurvey['aQuestionIndex']['items'] = [
[
'text' => gT('A group without step status styling')
],
[
'text' => gT('This group is unanswered'),
'stepStatus' => [
'index-item-unanswered' => true
]
],
[
'text' => gT('This group has an error'),
'stepStatus' => [
'index-item-error' => true
]
],
[
'text' => gT('Current group is disabled'),
'stepStatus' => [
'index-item-current' => true
]
]
];
// Show "Clear all".
$thissurvey['bShowClearAll'] = true;
// Show language changer.
$thissurvey['alanguageChanger']['show'] = true;
$thissurvey['alanguageChanger']['datas'] = [
'sSelected' => 'en',
'aListLang' => [
'en' => gT('English'),
'de' => gT('German')
]
];
$thissurvey['aNavigator']['load'] = [
'show' => "Y"
];
$thissurvey['aGroups'][1]["showdescription"] = true;
$thissurvey['aGroups'][1]["aQuestions"][1]["qid"] = "1";
$thissurvey['aGroups'][1]["aQuestions"][1]["mandatory"] = true;
// If called from command line to generate Twig temp, renderPartial doesn't exist in ConsoleApplication
if (method_exists(Yii::app()->getController(), 'renderPartial')) {
$thissurvey['aGroups'][1]["aQuestions"][1]["answer"] = Yii::app()->getController()->renderPartial('/admin/themes/templateeditor_question_answer_view', array(), true);
}
$thissurvey['aGroups'][1]["aQuestions"][1]["help"]["show"] = true;
$thissurvey['aGroups'][1]["aQuestions"][1]["help"]["text"] = gT("This is some helpful text.");
$thissurvey['aGroups'][1]["aQuestions"][1]["class"] = "list-radio mandatory";
$thissurvey['aGroups'][1]["aQuestions"][1]["attributes"] = 'id="question42"';
$thissurvey['aGroups'][1]["aQuestions"][2]["qid"] = "1";
$thissurvey['aGroups'][1]["aQuestions"][2]["mandatory"] = false;
if (method_exists(Yii::app()->getController(), 'renderPartial')) {
$thissurvey['aGroups'][1]["aQuestions"][2]["answer"] = Yii::app()->getController()->renderPartial('/admin/themes/templateeditor_question_answer_view', array('alt' => true), true);
}
$thissurvey['aGroups'][1]["aQuestions"][2]["help"]["show"] = true;
$thissurvey['aGroups'][1]["aQuestions"][2]["help"]["text"] = gT("This is some helpful text.");
$thissurvey['aGroups'][1]["aQuestions"][2]["class"] = "text-long";
$thissurvey['aGroups'][1]["aQuestions"][2]["attributes"] = 'id="question43"';
$thissurvey['aGroups'][1]["aQuestions"][1]['templateeditor'] = true;
$thissurvey['aGroups'][1]["aQuestions"][2]['templateeditor'] = true;
$thissurvey['registration_view'] = 'register_form';
$thissurvey['aCompleted']['showDefault'] = true;
$thissurvey['aCompleted']['aPrintAnswers']['show'] = true;
$thissurvey['aCompleted']['aPublicStatistics']['show'] = true;
$thissurvey['aAssessments']['show'] = true;
$thissurvey['aError']['title'] = '<p class=" text-danger inherit-sizes" role="alert">' . gT("Error title") . '</p>';
$thissurvey['aError']['message'] = '<p class="message-0">' . gT("This is an error message example") . '</p>';
$thissurvey['adminemail'] = 'your-email@example.net';
// Datas for assessments
$thissurvey['aAssessments']["datas"]["total"][0]["name"] = gT("Welcome to the Assessment");
$thissurvey['aAssessments']["datas"]["total"][0]["min"] = "0";
$thissurvey['aAssessments']["datas"]["total"][0]["max"] = "3";
$thissurvey['aAssessments']["datas"]["total"][0]["message"] = gT("You got {TOTAL} points out of 3 possible points.");
$thissurvey['aAssessments']["datas"]["total"]["show"] = true;
$thissurvey['aAssessments']["datas"]["subtotal"]["show"] = true;
$thissurvey['aAssessments']["datas"]["subtotal"]["datas"][2] = 3;
$thissurvey['aAssessments']["datas"]["subtotal_score"][1] = 3;
$thissurvey['aAssessments']["datas"]["total_score"] = 3;
$thissurvey['aLoadForm']['aCaptcha']['show'] = true;
$thissurvey['aLoadForm']['aCaptcha']['sImageUrl'] = Yii::app()->getController()->createUrl('/verification/image', array('sid' => 1));
// Those values can be overwritten by XML
$thissurvey['name'] = gT("Template Sample");
$thissurvey['description'] =
"<p>" . gT('This is a sample survey description. It could be quite long.') . "</p>" .
"<p>" . gT("But this one isn't.") . "<p>";
$thissurvey['welcome'] =
"<p>" . gT('Welcome to this sample survey') . "<p>" .
"<p>" . gT('You should have a great time doing this') . "<p>";
$thissurvey['therearexquestions'] = gT('There is 1 question in this survey');
$thissurvey['surveyls_url'] = "https://www.limesurvey.org/";
$thissurvey['surveyls_urldescription'] = gT("Some URL description");
return $thissurvey;
}
/**
* Returns the layout file name for a given screen
*
* @param string $sScreen the screen you want to retrieve the files from. If null: all screens
* @return string the file name
*/
public function getLayoutForScreen($sScreen)
{
if (empty($this->templateEditor)) {
return false;
}
$filesFromXML = $this->templateEditor->screens->xpath('//' . $sScreen . '/file');
foreach ($filesFromXML as $file) {
if ($file->attributes()->role == "layout") {
return (string) $file;
}
}
return false;
}
/**
* Returns the content file name for a given screen
*
* @param string $sScreen the screen you want to retrieve the files from. If null: all screens
* @return string the file name
*/
public function getContentForScreen($sScreen)
{
if (empty($this->templateEditor)) {
return false;
}
$filesFromXML = $this->templateEditor->screens->xpath('//' . $sScreen . '/file');
foreach ($filesFromXML as $file) {
if ($file->attributes()->role == "content") {
// The path of the file is defined inside the theme itself.
$aExplodedFile = pathinfo((string) $file);
$sFormatedFile = $aExplodedFile['filename'];
return (string) $sFormatedFile;
}
}
return false;
}
/**
* Retreives the absolute path for a file to edit (current template, mother template, etc)
* Also perform few checks (permission to edit? etc)
*
* @param string $sFile relative path to the file to edit
*/
public function getFilePathForEditing($sFile, $aAllowedFiles = null)
{
// Check if the file is allowed for edition ($aAllowedFiles is produced via getValidScreenFiles() )
if (is_array($aAllowedFiles)) {
if (!in_array($sFile, $aAllowedFiles)) {
return false;
}
}
return $this->getFilePath($sFile, $this);
}
/**
* Copy a file from mother template to local directory and edit manifest if needed
*
* @return string template url
*/
public function extendsFile($sFile)
{
if (!file_exists($this->path . $sFile) && !file_exists($this->viewPath . $sFile)) {
// Copy file from mother template to local directory
$sSourceFilePath = $this->getFilePath($sFile, $this);
$sDestinationFilePath = (pathinfo((string) $sFile, PATHINFO_EXTENSION) == 'twig') ? $this->viewPath . $sFile : $this->path . $sFile;
//PHP 7 seems not to create the folder on copy automatically.
@mkdir(dirname($sDestinationFilePath), 0775, true);
copy($sSourceFilePath, $sDestinationFilePath);
// If it's a css or js file from config... must update DB and XML too....
$sExt = pathinfo($sDestinationFilePath, PATHINFO_EXTENSION);
if ($sExt == "css" || $sExt == "js") {
// Check if that CSS/JS file is in DB/XML
$aFiles = $this->getFilesForPackages($sExt, $this);
$sFile = str_replace('./', '', (string) $sFile);
// The CSS/JS file is a configuration one....
if (in_array($sFile, $aFiles)) {
$this->addFileReplacement($sFile, $sExt);
$this->addFileReplacementInDB($sFile, $sExt);
}
}
}
return $this->getFilePath($sFile, $this);
}
/**
* Get the files (css or js) defined in the manifest of a template and its mother templates
*
* @param string $type css|js
* @param string $oRTemplate template from which the recurrence should start
* @return array
*/
public function getFilesForPackages($type, $oRTemplate)
{
$aFiles = array();
while (is_a($oRTemplate, 'TemplateManifest')) {
$aTFiles = isset($oRTemplate->config->files->$type->filename) ? (array) $oRTemplate->config->files->$type->filename : array();
$aFiles = array_merge($aTFiles, $aFiles);
$oRTemplate = $oRTemplate->oMotherTemplate;
}
return $aFiles;
}
/**
* Add a file replacement entry in DB
* In the first place it tries to get the all the configuration entries for this template
* (it can be void if edited from template editor, or they can be numerous if the template has local config at survey/survey group/user level)
* Then, it call $oTemplateConfiguration->addFileReplacement($sFile, $sType) for each one of them.
*
* @param string $sFile the file to replace
* @param string $sType css|js
*/
public function addFileReplacementInDB($sFile, $sType)
{
$oTemplateConfigurationModels = TemplateConfiguration::model()->findAllByAttributes(array('template_name' => $this->sTemplateName));
foreach ($oTemplateConfigurationModels as $oTemplateConfigurationModel) {
$oTemplateConfigurationModel->addFileReplacement($sFile, $sType);
}
}
/**
* Get the list of all the files inside the file folder for a template and its mother templates
* @return array
*/
public function getOtherFiles()
{
$otherfiles = array();
if (!empty($this->oMotherTemplate)) {
$otherfiles = $this->oMotherTemplate->getOtherFiles();
}
if (file_exists($this->filesPath) && $handle = opendir($this->filesPath)) {
while (false !== ($file = readdir($handle))) {
if (!array_search($file, array("DUMMYENTRY", ".", "..", "preview.png"))) {
if (!is_dir($this->viewPath . DIRECTORY_SEPARATOR . $file)) {
$otherfiles[$file] = $this->filesPath . DIRECTORY_SEPARATOR . $file;
}
}
}
closedir($handle);
}
return $otherfiles;
}
/**
* Returns the complete URL path to a given template name
*
* @return string template url
* @throws CException
*/
public function getTemplateURL()
{
Yii::import('application.helpers.SurveyThemeHelper');
// By default, theme folder is always the folder name. @See:TemplateConfig::importManifest().
if (SurveyThemeHelper::isStandardTemplate($this->sTemplateName)) {
return App()->getConfig("standardthemerooturl") . '/' . $this->sTemplateName . '/';
}
return App()->getConfig("userthemerooturl") . '/' . $this->sTemplateName . '/';
}
/**
* Get buttons/actions for the "Available admin themes", not installed
* @return string
* @throws CException
*/
public function getButtons()
{
$sEditorUrl = Yii::app()->getController()->createUrl('admin/themes/sa/view', array("templatename" => $this->sTemplateName));
$sDeleteUrl = Yii::app()->getController()->createUrl('admin/themes/sa/deleteAvailableTheme/');
// TODO: load to DB
$sEditorLink = "<a
id='template_editor_link_" . $this->sTemplateName . "'
href='" . $sEditorUrl . "'
class='btn btn-outline-secondary btn-sm'>
<span class='ri-brush-fill'></span>
" . gT('Theme editor') . "
</a>";
//
// TODO: Installs Theme (maybe rename importManifest to install ?)
$sLoadLink = CHtml::form(
[
"themeOptions/importManifest/"
],
'post',
[
'id' => 'frmínstalltheme',
'name' => 'frmínstalltheme'
]
) .
"<input type='hidden' name='templatename' value='" . $this->sTemplateName . "'>
<button id='template_options_link_" . $this->sTemplateName . "'
class='btn btn-outline-secondary btn-sm w-100'>
<span class='ri-download-fill'></span>
" . gT('Install') . "
</button>
</form>";
$sDeleteLink = '';
// We don't want user to be able to delete standard theme. Must be done via ftp (advanced users only)
Yii::import('application.helpers.SurveyThemeHelper');
if (Permission::model()->hasGlobalPermission('templates', 'delete') && !SurveyThemeHelper::isStandardTemplate($this->sTemplateName)) {
$sDeleteLink = '<a
id="template_delete_link_' . $this->sTemplateName . '"
href="' . $sDeleteUrl . '"
data-post=\'{ "templatename": "' . CHtml::encode($this->sTemplateName) . '" }\'
data-text="' . gT('Are you sure you want to delete this theme? ') . '"
data-button-no="' . gt('Cancel') . '"
data-button-yes="' . gt('Delete') . '"
data-button-type="btn-danger"
title="' . gT('Delete') . '"
class="btn btn-danger btn-sm selector--ConfirmModal">
<span class="ri-delete-bin-fill "></span>
' . gT('Delete') . '
</a>';
}
return '<div class="d-grid gap-2">' . $sEditorLink . $sLoadLink . $sDeleteLink . '</div>';
}
/**
* Installs an available theme
* Create a new entry in {{templates}} and {{template_configuration}} table using the template manifest
* @param string $sTemplateName the name of the template to import
* @return boolean true on success | exception
* @throws Exception
*/
public static function importManifest($sTemplateName, $aDatas = array())
{
$oTemplate = Template::getTemplateConfiguration($sTemplateName, null, null, true);
$aDatas['extends'] = $bExtends = (string) $oTemplate->config->metadata->extends;
if ($bExtends && !Template::model()->findByPk($bExtends)) {
Yii::app()->setFlashMessage(sprintf(gT("You can't import the theme '%s' because '%s' is not installed."), $sTemplateName, $bExtends), 'error');
Yii::app()->getController()->redirect(array("themeOptions/index"));
}
// Metadas is never inherited
$aDatas['api_version'] = (string) $oTemplate->config->metadata->apiVersion;
$aDatas['author_email'] = (string) $oTemplate->config->metadata->authorEmail;
$aDatas['author_url'] = (string) $oTemplate->config->metadata->authorUrl;
$aDatas['copyright'] = (string) $oTemplate->config->metadata->copyright;
$aDatas['version'] = (string) $oTemplate->config->metadata->version;
$aDatas['license'] = (string) $oTemplate->config->metadata->license;
$aDatas['description'] = (string) $oTemplate->config->metadata->description;
$aDatas['title'] = (string) $oTemplate->config->metadata->title;
// Engine, files, and options can be inherited from a moter template
// It means that the while field should always be inherited, not a subfield (eg: all files, not only css add)
$oREngineTemplate = (!empty($bExtends)) ? self::getTemplateForXPath($oTemplate, 'engine') : $oTemplate;
$aDatas['view_folder'] = (string) $oREngineTemplate->config->engine->viewdirectory;
$aDatas['files_folder'] = (string) $oREngineTemplate->config->engine->filesdirectory;
$aDatas['cssframework_name'] = (string) $oREngineTemplate->config->engine->cssframework->name;
$aDatas['cssframework_css'] = self::getAssetsToReplaceFormated($oREngineTemplate->config->engine, 'css'); //self::formatArrayFields($oREngineTemplate, 'engine', 'cssframework_css');
$aDatas['cssframework_js'] = self::formatArrayFields($oREngineTemplate, 'engine', 'cssframework_js');
$aDatas['packages_to_load'] = self::formatArrayFields($oREngineTemplate, 'engine', 'packages');
// If empty in manifest, it should be the field in db, so the Mother Template css/js files will be used...
if (is_object($oTemplate->config->files)) {
$aDatas['files_css'] = self::formatArrayFields($oTemplate, 'files', 'css');
$aDatas['files_js'] = self::formatArrayFields($oTemplate, 'files', 'js');
$aDatas['files_print_css'] = self::formatArrayFields($oTemplate, 'files', 'print_css');
} else {
$aDatas['files_css'] = $aDatas['files_js'] = $aDatas['files_print_css'] = null;
}
$aDatas['aOptions'] = (!empty($oTemplate->config->options[0]) && count($oTemplate->config->options[0]) == 0) ? array() : $oTemplate->config->options[0]; // If template provide empty options, it must be cleaned to avoid crashes
return parent::importManifest($sTemplateName, $aDatas);
}
/**
* Create a new entry in {{template_configuration}} table using the survey theme options from lss export file
* @param $iSurveyId int the id of the survey
* @param $xml SimpleXMLElement
* @return boolean true on success
*/
public static function importManifestLss($iSurveyId = 0, $xml = null)
{
if ((int)$iSurveyId > 0 && !empty($xml)) {
$oTemplateConfiguration = new TemplateConfiguration();
$oTemplateConfiguration->setToInherit();
$oTemplateConfiguration->bJustCreated = true;
$oTemplateConfiguration->isNewRecord = true;
$oTemplateConfiguration->id = null;
$oTemplateConfiguration->template_name = $xml->template_name->__toString();
$oTemplateConfiguration->sid = $iSurveyId;
if (isAssociativeArray((array)$xml->config->options)) {
$oTemplateConfiguration->options = TemplateConfig::convertOptionsToJson($xml->config->options[0]);
}
if ($oTemplateConfiguration->save()) {
return true;
}
}
return false;
}
/**
* @param string $sFieldPath
*/
public static function getTemplateForXPath($oTemplate, $sFieldPath)
{
$oRTemplate = $oTemplate;
while (!is_object($oRTemplate->config->$sFieldPath) || empty($oRTemplate->config->$sFieldPath)) {
$sRTemplateName = (string) $oRTemplate->config->metadata->extends;
if (!empty($sRTemplateName)) {
$oRTemplate = Template::getTemplateConfiguration($sRTemplateName, null, null, true);
if (!is_a($oRTemplate, 'TemplateManifest')) {
// Think about what to do..
throw new Exception("Error: Can't find a template for '$oRTemplate->sTemplateName' in xpath '$sFieldPath'.");
}
} else {
throw new Exception("Error: Can't find a template for '$oRTemplate->sTemplateName' in xpath '$sFieldPath'.");
}
}
return $oRTemplate;
}
/**
* This will prepare an array for the field, so the json_encode will create
* If a field is empty, its value should not be null, but an empty array for the json encoding in DB
*
* @param TemplateManifest $oTemplate
* @param string $sFieldPath path to the field (under config)
* @param string $sFieldName name of the field
* @return array field value | empty array
*/
public static function formatArrayFields($oTemplate, $sFieldPath, $sFieldName)
{
return (empty($oTemplate->config->$sFieldPath->$sFieldName->value) && empty($oTemplate->config->$sFieldPath->$sFieldName)) ? array() : $oTemplate->config->$sFieldPath->$sFieldName;
}
/**
* Get the DOMDocument of the Manifest
* @param string $sConfigPath path where to find the manifest
* @return DOMDocument
*/
public static function getManifestDOM($sConfigPath)
{
// First we get the XML file
$oNewManifest = new DOMDocument();
$oNewManifest->load($sConfigPath . "/config.xml");
return $oNewManifest;
}
/**
* Change the name inside the DOMDocument (will not save it)
* @param DOMDocument $oNewManifest The DOMDOcument of the manifest
* @param string $sName The wanted name
*/
public static function changeNameInDOM($oNewManifest, $sName)
{
$oConfig = $oNewManifest->getElementsByTagName('config')->item(0);
$ometadata = $oConfig->getElementsByTagName('metadata')->item(0);
$oOldNameNode = $ometadata->getElementsByTagName('name')->item(0);
$oNvNameNode = $oNewManifest->createElement('name', $sName);
$ometadata->replaceChild($oNvNameNode, $oOldNameNode);
}
/**
* Change the date inside the DOMDocument
* Used only when copying/extend a survey
* @param DOMDocument $oNewManifest The DOMDOcument of the manifest
* @param string $sDate The wanted date, if empty the current date with config time adjustment will be used
*/
public static function changeDateInDOM($oNewManifest, $sDate = '')
{
$sDate = (empty($sDate)) ? dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig("timeadjust")) : $sDate;
$oConfig = $oNewManifest->getElementsByTagName('config')->item(0);
$ometadata = $oConfig->getElementsByTagName('metadata')->item(0);
if ($ometadata->getElementsByTagName('creationDate')) {
$oOldDateNode = $ometadata->getElementsByTagName('creationDate')->item(0);
}
$oNvDateNode = $oNewManifest->createElement('creationDate', $sDate);
if (empty($oOldDateNode)) {
$ometadata->appendChild($oNvDateNode);
} else {
$ometadata->replaceChild($oNvDateNode, $oOldDateNode);
}
if ($ometadata->getElementsByTagName('lastUpdate')) {
$oOldUpdateNode = $ometadata->getElementsByTagName('lastUpdate')->item(0);
}
$oNvDateNode = $oNewManifest->createElement('lastUpdate', $sDate);
if (empty($oOldUpdateNode)) {
$ometadata->appendChild($oNvDateNode);
} else {
$ometadata->replaceChild($oNvDateNode, $oOldUpdateNode);
}
}
/**
* Change the template name inside the manifest (called from template editor)
* NOTE: all tests (like template exist, etc) are done from template controller.
*
* @param string $sOldName The old name of the template
* @param string $sNewName The newname of the template
*/
public static function rename($sOldName, $sNewName)
{
if (\PHP_VERSION_ID < 80000) {
libxml_disable_entity_loader(false);
}
$sConfigPath = Yii::app()->getConfig('userthemerootdir') . "/" . $sNewName;
$oNewManifest = self::getManifestDOM($sConfigPath);
self::changeNameInDOM($oNewManifest, $sNewName);
self::changeDateInDOM($oNewManifest);
$oNewManifest->save($sConfigPath . "/config.xml");
if (\PHP_VERSION_ID < 80000) {
libxml_disable_entity_loader(true);
}
}
/**
* Delete engine node inside the DOM, except the optionspage configuration
*
* @param DOMDocument $oNewManifest The DOMDOcument of the manifest
*/
public static function deleteEngineInDom($oNewManifest)
{
$oConfig = $oNewManifest->getElementsByTagName('config')->item(0);
// Then we delete the nodes that should be inherit
$aNodesToDelete = array();
//$aNodesToDelete[] = $oConfig->getElementsByTagName('files')->item(0);
$oEngine = $oConfig->getElementsByTagName('engine')->item(0);
$aNodesToDelete[] = $oEngine->childNodes;
foreach ($aNodesToDelete as $node) {
// If extended template already extend another template, it will not have those nodes
// Don't remove 'optionspage' node
if (is_a($node, 'DOMNode') && $node->nodeName != 'optionspage') {
$oEngine->removeChild($node);
}
}
}
/**
* Change author inside the DOM
*
* @param DOMDocument $oNewManifest The DOMDOcument of the manifest
*/
public static function changeAuthorInDom($oNewManifest)
{
$oConfig = $oNewManifest->getElementsByTagName('config')->item(0);
$ometadata = $oConfig->getElementsByTagName('metadata')->item(0);
$oOldAuthorNode = $ometadata->getElementsByTagName('author')->item(0);
$oNvAuthorNode = $oNewManifest->createElement('author', Yii::app()->user->name);
$ometadata->replaceChild($oNvAuthorNode, $oOldAuthorNode);
}
/**
* Change author email inside the DOM
*
* @param DOMDocument $oNewManifest The DOMDOcument of the manifest
*/
public static function changeEmailInDom($oNewManifest)
{
$oConfig = $oNewManifest->getElementsByTagName('config')->item(0);
$ometadata = $oConfig->getElementsByTagName('metadata')->item(0);
$oOldMailNode = $ometadata->getElementsByTagName('authorEmail')->item(0);
$oNvMailNode = $oNewManifest->createElement('authorEmail', htmlspecialchars((string) Yii::app()->getConfig('siteadminemail')));
$ometadata->replaceChild($oNvMailNode, $oOldMailNode);
}
/**
* Change the extends node inside the DOM
* If it doesn't exist, it will create it
* @param DOMDocument $oNewManifest The DOMDOcument of the manifest
* @param string $sToExtends Name of the template to extends
*/
public static function changeExtendsInDom($oNewManifest, $sToExtends)
{
$oExtendsNode = $oNewManifest->createElement('extends', $sToExtends);
$oConfig = $oNewManifest->getElementsByTagName('config')->item(0);
$ometadata = $oConfig->getElementsByTagName('metadata')->item(0);
// We test if mother template already extends another template
if (!empty($ometadata->getElementsByTagName('extends')->item(0))) {
$ometadata->replaceChild($oExtendsNode, $ometadata->getElementsByTagName('extends')->item(0));
} else {
$ometadata->appendChild($oExtendsNode);
}
}
/**
* Update the config file of a given template so that it extends another one
*
* It will:
* 1. Delete files and engine nodes
* 2. Update the name of the template
* 3. Change the creation/modification date to the current date
* 4. Change the autor name to the current logged in user
* 5. Change the author email to the admin email
*
* Used in template editor
* Both templates and configuration files must exist before using this function
*
* It's used when extending a template from template editor
* @param string $sToExtends the name of the template to extend
* @param string $sNewName the name of the new template
*/
public static function extendsConfig($sToExtends, $sNewName)
{
$sConfigPath = Yii::app()->getConfig('userthemerootdir') . "/" . $sNewName;
// First we get the XML file
if (\PHP_VERSION_ID < 80000) {
libxml_disable_entity_loader(false);
}
$oNewManifest = self::getManifestDOM($sConfigPath);