/
TemplateConfiguration.php
executable file
·1352 lines (1161 loc) · 53 KB
/
TemplateConfiguration.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
if (!defined('BASEPATH')) {
exit('No direct script access allowed');
}
/*
* 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.
*/
/*
* This is the model class for table "{{template_configuration}}".
*
* NOTE: if you only need to access to the table, you don't need to call prepareTemplateRendering
*
* The followings are the available columns in table '{{template_configuration}}':
* @property integer $id Primary key
* @property string $template_name
* @property integer $sid Survey ID
* @property integer $gsid
* @property integer $uid user ID
* @property string $files_css
* @property string $files_js
* @property string $files_print_css
* @property string $options
* @property string $cssframework_name
* @property string $cssframework_css
* @property string $cssframework_js
* @property string $packages_to_load
* @property string $packages_ltr
* @property string $packages_rtl
* @property string $packages_rtl
*
* @package LimeSurvey
* @subpackage Backend
*/
class TemplateConfiguration extends TemplateConfig
{
/**
* @var TemplateConfiguration $oParentTemplate The parent template name
* A template configuration, in the database, can inherit from another one.
* This used to manage the different configuration levels for a very same template: global, survey group, survey
* This is not related to motherTemplate (inheritance between two different templates)
*/
public $oParentTemplate;
/**@var boolean Should the magic getters automatically retreives the parent value when field is set to inherit. Only turn to on for template rendering. There is no option inheritance on Manifest mode: values from XML are always used. */
public $bUseMagicInherit = false;
/**@var boolean Indicate if this entry in DB get created on the fly. If yes, because of Cache, it can need a page redirect */
public $bJustCreated = false;
// Caches
/** @var string $sPreviewImgTag the template preview image tag for the template list*/
public $sPreviewImgTag;
/** @var array $aInstancesFromTemplateName cache for method getInstanceFromTemplateName*/
public static $aInstancesFromTemplateName;
/** @var array $aInstancesFromTemplateName cache for method prepareTemplateRendering*/
public static $aPreparedToRender;
/** @var boolean $bTemplateCheckResult is the template valid?*/
private $bTemplateCheckResult;
/** @var string $sTypeIcon the type of template for icon (core vs user)*/
private $sTypeIcon;
/** @var array $aFilesTo cache for the method getFilesTo*/
private $aFilesTo;
/** @var array $aFrameworkAssetsToReplace cache for the method getFrameworkAssetsToReplace()*/
private $aFrameworkAssetsToReplace;
/** @var array $aReplacements cache for the method getFrameworkAssetsReplacement */
private $aReplacements;
/** @var array $Ofiles cache for the method getOfiles */
private $Ofiles;
public $generalFilesPath; //Yii::app()->getConfig("userthemerootdir").DIRECTORY_SEPARATOR.'generalfiles'.DIRECTORY_SEPARATOR;
/** @var int $showpopups show warnings when running survey */
public $showpopups; //
// for survey theme gridview columns
public $template_type;
public $template_extends;
public $template_description;
/**
* @return string the associated database table name
*/
public function tableName()
{
return '{{template_configuration}}';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('template_name', 'required'),
array('id, sid, gsid', 'numerical', 'integerOnly'=>true),
array('template_name', 'length', 'max'=>150),
array('cssframework_name', 'length', 'max'=>45),
array('files_css, files_js, files_print_css, options, cssframework_css, cssframework_js, packages_to_load', 'safe'),
// The following rule is used by search().
array('id, template_name, sid, gsid, files_css, files_js, files_print_css, options, cssframework_name, cssframework_css, cssframework_js, packages_to_load', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
return array(
'template' => array(self::HAS_ONE, 'Template', array('name' => 'template_name'), 'together' => true),
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'template_name' => 'Templates Name',
'sid' => 'Sid',
'gsid' => 'Gsid',
'files_css' => 'Files Css',
'files_js' => 'Files Js',
'files_print_css' => 'Files Print Css',
'options' => 'Options',
'cssframework_name' => 'Cssframework Name',
'cssframework_css' => 'Cssframework Css',
'cssframework_js' => 'Cssframework Js',
'packages_to_load' => 'Packages To Load',
);
}
/**
* Gets an instance of a templateconfiguration by name
*
* @param string $sTemplateName
* @return TemplateConfiguration
*/
public static function getInstanceFromTemplateName($sTemplateName, $abstractInstance = false)
{
if (!empty(self::$aInstancesFromTemplateName[$sTemplateName]) && !$abstractInstance) {
return self::$aInstancesFromTemplateName[$sTemplateName];
}
$oInstance = self::model()->find(
'template_name=:template_name AND sid IS NULL AND gsid IS NULL',
array(':template_name'=>$sTemplateName)
);
// If the survey configuration table of the wanted template doesn't exist (eg: manually deleted), then we provide the default one.
if (!is_a($oInstance, 'TemplateConfiguration')) {
$oInstance = self::getInstanceFromTemplateName(getGlobalSetting('defaulttheme'));
}
if($abstractInstance === true) {
return $oInstance;
}
self::$aInstancesFromTemplateName[$sTemplateName] = $oInstance;
return $oInstance;
}
/**
* Returns a TemplateConfiguration Object based on a surveygroup ID
* If no instance is existing, it will create one.
*
* @param integer $iSurveyGroupId
* @param string $sTemplateName
* @return TemplateConfiguration
*/
public static function getInstanceFromSurveyGroup($iSurveyGroupId, $sTemplateName = null, $abstractInstance = false)
{
//if a template name is given also check against that
$sTemplateName = $sTemplateName != null ? $sTemplateName : SurveysGroups::model()->findByPk($iSurveyGroupId)->template;
$criteria = new CDbCriteria();
$criteria->addCondition('gsid=:gsid');
$criteria->addCondition('template_name=:template_name');
$criteria->params = array('gsid' => $iSurveyGroupId, 'template_name' => $sTemplateName);
$oTemplateConfigurationModel = TemplateConfiguration::model()->find($criteria);
// No specific template configuration for this surveygroup => create one
// TODO: Move to SurveyGroup creation, right now the 'lazy loading' approach is ok.
if (!is_a($oTemplateConfigurationModel, 'TemplateConfiguration') && $sTemplateName != null) {
$oTemplateConfigurationModel = TemplateConfiguration::getInstanceFromTemplateName($sTemplateName, $abstractInstance);
$oTemplateConfigurationModel->bUseMagicInherit = false;
$oTemplateConfigurationModel->id = null;
$oTemplateConfigurationModel->isNewRecord = true;
$oTemplateConfigurationModel->sid = null;
$oTemplateConfigurationModel->gsid = $iSurveyGroupId;
$oTemplateConfigurationModel->setToInherit();
$oTemplateConfigurationModel->save();
$oTemplateConfigurationModel->bJustCreated = true;
}
return $oTemplateConfigurationModel;
}
/**
* Returns a TemplateConfiguration Object based on a surveyID
* If no instance is existing, it will create one.
*
* @param integer $iSurveyId
* @param string $sTemplateName
* @return TemplateConfiguration
*/
public static function getInstanceFromSurveyId($iSurveyId, $sTemplateName = null, $abstractInstance = false)
{
// set template name if it does not exists or if it is inherit
if ($sTemplateName === null || $sTemplateName == 'inherit'){
$oSurvey = Survey::model()->findByPk($iSurveyId);
// set real value from inheritance
if (!empty($oSurvey->oOptions->template)){
$sTemplateName = $oSurvey->oOptions->template;
}
}
$criteria = new CDbCriteria();
$criteria->addCondition('sid=:sid');
$criteria->addCondition('template_name=:template_name');
$criteria->params = array('sid' => $iSurveyId, 'template_name' => $sTemplateName);
$oTemplateConfigurationModel = TemplateConfiguration::model()->find($criteria);
// No specific template configuration for this surveygroup => create one
// TODO: Move to SurveyGroup creation, right now the 'lazy loading' approach is ok.
if (!is_a($oTemplateConfigurationModel, 'TemplateConfiguration') && $sTemplateName != null) {
$oTemplateConfigurationModel = TemplateConfiguration::getInstanceFromTemplateName($sTemplateName, $abstractInstance);
$oTemplateConfigurationModel->bUseMagicInherit = false;
$oTemplateConfigurationModel->id = null;
$oTemplateConfigurationModel->isNewRecord = true;
$oTemplateConfigurationModel->gsid = null;
$oTemplateConfigurationModel->sid = $iSurveyId;
$oTemplateConfigurationModel->setToInherit();
$oTemplateConfigurationModel->save();
}
return $oTemplateConfigurationModel;
}
/**
* Returns a Theme options array based on a surveyID
*
* @param integer $iSurveyId
* @param bool $bInherited should inherited theme option values be used?
* @return array
*/
public static function getThemeOptionsFromSurveyId($iSurveyId = 0, $bInherited = false)
{
$aTemplateConfigurations = array();
// fetch all themes belonging to $iSurveyId
$criteria = new CDbCriteria();
$criteria->addCondition('sid=:sid');
$criteria->params = array('sid' => $iSurveyId);
$oTemplateConfigurations = self::model()->findAll($criteria);
if ($bInherited){ // inherited values
foreach ($oTemplateConfigurations as $key => $oTemplateConfiguration) {
$oTemplateConfiguration->bUseMagicInherit = true;
$oTemplateConfiguration->setOptions();
// set array with values
$aTemplateConfigurations[$key]['id'] = null;
$aTemplateConfigurations[$key]['sid'] = $iSurveyId;
$aTemplateConfigurations[$key]['template_name'] = $oTemplateConfiguration->template_name;
$aTemplateConfigurations[$key]['config']['options'] = (array)$oTemplateConfiguration->oOptions;
}
} else { // db values
foreach ($oTemplateConfigurations as $key => $oTemplateConfiguration) {
$oTemplateConfiguration->bUseMagicInherit = false;
$oAttributes = $oTemplateConfiguration->attributes;
// set array with values
$aTemplateConfigurations[$key]['id'] = null;
$aTemplateConfigurations[$key]['sid'] = $iSurveyId;
$aTemplateConfigurations[$key]['template_name'] = $oAttributes['template_name'];
$aTemplateConfigurations[$key]['config']['options'] = isJson($oAttributes['options'])?(array)json_decode($oAttributes['options']):$oAttributes['options'];
}
}
return $aTemplateConfigurations;
}
/**
* For a given survey, it checks if its theme have a all the needed configuration entries (survey + survey group). Else, it will create it.
* @TODO: recursivity for survey group
* @param int $iSurveyId
* @return TemplateConfiguration the template configuration for the survey group
*/
public static function checkAndcreateSurveyConfig($iSurveyId)
{
//if a template name is given also check against that
$oSurvey = Survey::model()->findByPk($iSurveyId);
$sTemplateName = $oSurvey->template;
$iSurveyGroupId = $oSurvey->gsid;
$criteria = new CDbCriteria();
$criteria->addCondition('sid=:sid');
$criteria->addCondition('template_name=:template_name');
$criteria->params = array('sid' => $iSurveyId, 'template_name' => $sTemplateName);
$oTemplateConfigurationModel = TemplateConfiguration::model()->find($criteria);
// TODO: Move to SurveyGroup creation, right now the 'lazy loading' approach is ok.
if (!is_a($oTemplateConfigurationModel, 'TemplateConfiguration') && $sTemplateName != null) {
$oTemplateConfigurationModel = TemplateConfiguration::getInstanceFromTemplateName($sTemplateName);
$oTemplateConfigurationModel->bUseMagicInherit = false;
$oTemplateConfigurationModel->id = null;
$oTemplateConfigurationModel->isNewRecord = true;
$oTemplateConfigurationModel->gsid = null;
$oTemplateConfigurationModel->sid = $iSurveyId;
$oTemplateConfigurationModel->setToInherit();
$oTemplateConfigurationModel->save();
}
$criteria = new CDbCriteria();
$criteria->addCondition('gsid=:gsid');
$criteria->addCondition('template_name=:template_name');
$criteria->params = array('gsid' => $iSurveyGroupId, 'template_name' => $sTemplateName);
$oTemplateConfigurationModel = TemplateConfiguration::model()->find($criteria);
if (!is_a($oTemplateConfigurationModel, 'TemplateConfiguration') && $sTemplateName != null) {
$oTemplateConfigurationModel = TemplateConfiguration::getInstanceFromTemplateName($sTemplateName);
$oTemplateConfigurationModel->bUseMagicInherit = false;
$oTemplateConfigurationModel->id = null;
$oTemplateConfigurationModel->isNewRecord = true;
$oTemplateConfigurationModel->sid = null;
$oTemplateConfigurationModel->gsid = $iSurveyGroupId;
$oTemplateConfigurationModel->setToInherit();
$oTemplateConfigurationModel->save();
}
return $oTemplateConfigurationModel;
}
/**
* Get an instance of a fitting TemplateConfiguration
*
* @param string $sTemplateName
* @param integer $iSurveyGroupId
* @param integer $iSurveyId
* @return TemplateConfiguration
*/
public static function getInstance($sTemplateName = null, $iSurveyGroupId = null, $iSurveyId = null, $abstractInstance = false)
{
$oTemplateConfigurationModel = new TemplateConfiguration();
if ($sTemplateName != null && $iSurveyGroupId == null && $iSurveyId == null) {
$oTemplateConfigurationModel = TemplateConfiguration::getInstanceFromTemplateName($sTemplateName, $abstractInstance);
}
if ($iSurveyGroupId != null && $iSurveyId == null) {
$oTemplateConfigurationModel = TemplateConfiguration::getInstanceFromSurveyGroup($iSurveyGroupId, $sTemplateName, $abstractInstance);
}
if ($iSurveyId != null) {
$oTemplateConfigurationModel = TemplateConfiguration::getInstanceFromSurveyId($iSurveyId, $sTemplateName, $abstractInstance);
}
return $oTemplateConfigurationModel;
}
/**
* Retrieves a list of models based on the current search/filter conditions.
*
* Typical usecase:
* - Initialize the model fields with values from filter form.
* - Execute this method to get CActiveDataProvider instance which will filter
* models according to data in model fields.
* - Pass data provider to CGridView, CListView or any similar widget.
*
* @return CActiveDataProvider the data provider that can return the models
* based on the search/filter conditions.
*/
public function search()
{
// @todo Please modify the following code to remove attributes that should not be searched.
$criteria = new CDbCriteria;
$criteria->join = 'INNER JOIN {{templates}} AS template ON t.template_name = template.name';
//Don't show surveyspecifi settings on the overview
$criteria->addCondition('t.sid IS NULL');
$criteria->addCondition('t.gsid IS NULL');
$criteria->addCondition('template.name IS NOT NULL');
$criteria->compare('id', $this->id);
$criteria->compare('template_name', $this->template_name, true);
$criteria->compare('files_css', $this->files_css, true);
$criteria->compare('files_js', $this->files_js, true);
$criteria->compare('files_print_css', $this->files_print_css, true);
$criteria->compare('options', $this->options, true);
$criteria->compare('cssframework_name', $this->cssframework_name, true);
$criteria->compare('cssframework_css', $this->cssframework_css, true);
$criteria->compare('cssframework_js', $this->cssframework_js, true);
$criteria->compare('packages_to_load', $this->packages_to_load, true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
public function searchGrid()
{
// @todo Please modify the following code to remove attributes that should not be searched.
$pageSizeTemplateView = Yii::app()->user->getState('pageSizeTemplateView', Yii::app()->params['defaultPageSize']);
$criteria = new CDbCriteria;
$criteria->join = 'INNER JOIN {{templates}} AS template ON t.template_name = template.name';
$criteria->together = true;
//Don't show surveyspecifi settings on the overview
$criteria->addCondition('t.sid IS NULL');
$criteria->addCondition('template.name IS NOT NULL');
// check if survey group id is present
$gsid = Yii::app()->request->getQuery('id', null);
if ($gsid !== null){
$criteria->addCondition('t.gsid = ' . $gsid);
} else {
$criteria->addCondition('t.gsid IS NULL');
}
$criteria->compare('id', $this->id);
$criteria->compare('template_name', $this->template_name, true);
$criteria->compare('files_css', $this->files_css, true);
$criteria->compare('files_js', $this->files_js, true);
$criteria->compare('files_print_css', $this->files_print_css, true);
$criteria->compare('options', $this->options, true);
$criteria->compare('cssframework_name', $this->cssframework_name, true);
$criteria->compare('cssframework_css', $this->cssframework_css, true);
$criteria->compare('cssframework_js', $this->cssframework_js, true);
$criteria->compare('packages_to_load', $this->packages_to_load, true);
$criteria->compare('template.description', $this->template_description, true);
$criteria->compare('template.extends', $this->template_extends, true);
$coreTemplates = Template::getStandardTemplateList();
if ($this->template_type == 'core'){
$criteria->addInCondition('template_name', $coreTemplates);
} elseif ($this->template_type == 'user'){
$criteria->addNotInCondition('template_name', $coreTemplates);
}
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'pagination'=>array(
'pageSize'=>$pageSizeTemplateView,
),
));
}
/**
* Returns the static model of the specified AR class.
* Please note that you should have this exact method in all your CActiveRecord descendants!
* @param string $className active record class name.
* @return TemplateConfiguration the static model class
*/
public static function model($className = __CLASS__)
{
/** @var self $model */
$model = parent::model($className);
return $model;
}
/**
* 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())
{
if (!empty($aDatas['extends'])) {
$oMotherTemplate = self::getInstanceFromTemplateName($aDatas['extends']);
if (is_a($oMotherTemplate, 'TemplateConfiguration')) {
$aDatas['api_version'] = $oMotherTemplate->template->api_version;
$aDatas['view_folder'] = $oMotherTemplate->template->view_folder;
$aDatas['author_email'] = $oMotherTemplate->template->author_email;
$aDatas['author_url'] = $oMotherTemplate->template->author_url;
$aDatas['copyright'] = $oMotherTemplate->template->copyright;
$aDatas['version'] = $oMotherTemplate->template->version;
$aDatas['license'] = $oMotherTemplate->template->license;
$aDatas['files_folder'] = $oMotherTemplate->template->files_folder;
$aDatas['aOptions'] = (empty($aDatas['aOptions'])) ? json_decode($oMotherTemplate->options) : $aDatas['aOptions'];
}
}
return parent::importManifest($sTemplateName, $aDatas);
}
public function setToInherit()
{
$this->files_css = 'inherit';
$this->files_js = 'inherit';
$this->files_print_css = 'inherit';
$this->options = 'inherit';
$this->cssframework_name = 'inherit';
$this->cssframework_css = 'inherit';
$this->cssframework_js = 'inherit';
$this->packages_to_load = 'inherit';
}
public function checkTemplate()
{
if (empty($this->bTemplateCheckResult)) {
$this->bTemplateCheckResult = true;
if (!is_object($this->template) || (is_object($this->template) && !Template::checkTemplateXML($this->template->folder))) {
$this->bTemplateCheckResult = false;
}
}
return $this->bTemplateCheckResult;
}
public function setBasics($sTemplateName = '', $iSurveyId = '', $bUseMagicInherit = false)
{
$this->bUseMagicInherit = $bUseMagicInherit;
$this->sTemplateName = $this->template->name;
$this->setIsStandard(); // Check if it is a CORE template
$this->path = ($this->isStandard)
? Yii::app()->getConfig("standardthemerootdir").DIRECTORY_SEPARATOR.$this->template->folder.DIRECTORY_SEPARATOR
: Yii::app()->getConfig("userthemerootdir").DIRECTORY_SEPARATOR.$this->template->folder.DIRECTORY_SEPARATOR;
}
/**
* Add a file replacement in the field `file_{css|js|print_css}` in table {{template_configuration}},
* eg: {"replace": [ {original files to replace here...}, "css/template.css",]}
* In general, should be called from TemplateManifest, after adding a file replacement inside the manifest.
*
* @param string $sFile the file to replace
* @param string $sType css|js
* @return bool|void
* @throws Exception
*/
public function addFileReplacement($sFile, $sType)
{
$sField = 'files_'.$sType;
$oFiles = (array) json_decode($this->$sField);
$oFiles['replace'][] = $sFile;
$this->$sField = json_encode($oFiles);
if ($this->save()) {
return true;
} else {
throw new Exception("could not add $sFile to $sField replacements! ".$this->getErrors());
}
}
public function getTypeIcon()
{
if (empty($this->sTypeIcon)) {
$this->sTypeIcon = (Template::isStandardTemplate($this->template->name)) ?gT("Core theme") : gT("User theme");
}
return $this->sTypeIcon;
}
public function getButtons()
{
$sEditorUrl = Yii::app()->getController()->createUrl('admin/themes/sa/view', array("templatename"=>$this->template_name));
$sUninstallUrl = Yii::app()->getController()->createUrl('admin/themeoptions/sa/uninstall/');
$sExtendUrl = Yii::app()->getController()->createUrl('admin/themes/sa/templatecopy');
$sResetUrl = Yii::app()->getController()->createUrl('admin/themeoptions/sa/reset/');
$gisd = Yii::app()->request->getQuery('id', null);
$sOptionUrl = (App()->getController()->action->id == "surveysgroups")?Yii::app()->getController()->createUrl('admin/themeoptions/sa/updatesurveygroup', array("id"=>$this->id, "gsid"=>$gisd)):Yii::app()->getController()->createUrl('admin/themeoptions/sa/update', array("id"=>$this->id));
$sEditorLink = "<a
id='template_editor_link_".$this->template_name."'
href='".$sEditorUrl."'
class='btn btn-default btn-block'>
<span class='icon-templates'></span>
".gT('Theme editor')."
</a>";
$OptionLink = '';
if ($this->hasOptionPage) {
$OptionLink .= "<a
id='template_options_link_".$this->template_name."'
href='".$sOptionUrl."'
class='btn btn-default btn-block'>
<span class='fa fa-tachometer'></span>
".gT('Theme options')."
</a>";
}
$sUninstallLink = '<a
id="remove_fromdb_link_'.$this->template_name.'"
href="'.$sUninstallUrl.'"
data-post=\'{ "templatename": "'.$this->template_name.'" }\'
data-text="'.gT('This will reset all the specific configurations of this theme.').'<br>'.gT('Do you want to continue?').'"
title="'.gT('Uninstall this theme').'"
class="btn btn-danger btn-block selector--ConfirmModal">
<span class="icon-trash"></span>
'.gT('Uninstall').'
</a>';
$sExtendLink = '<a
id="extendthis_'.$this->template_name.'"
href="'.$sExtendUrl.'"
data-post=\''
.json_encode([
"copydir" => $this->template_name,
"action" => "templatecopy",
"newname" => ["value"=> "extends_".$this->template_name, "type" => "text", "class" => "form-control col-sm-12"]
])
.'\'
data-text="'.gT('Please type in the new theme name above.').'"
title="'.sprintf(gT('Type in the new name to extend %s'), $this->template_name).'"
class="btn btn-primary btn-block selector--ConfirmModal">
<i class="fa fa-copy"></i>
'.gT('Extend').'
</a>';
$sResetLink = '<a
id="remove_fromdb_link_'.$this->template_name.'"
href="'.$sResetUrl.'"
data-post=\'{ "templatename": "'.$this->template_name.'" }\'
data-text="'.gT('This will reload the configuration file of this theme.').'<br>'.gT('Do you want to continue?').'"
title="'.gT('Reset this theme').'"
class="btn btn-warning btn-block selector--ConfirmModal">
<span class="icon-trash"></span>
'.gT('Reset').'
</a>';
if (App()->getController()->action->id == "surveysgroups") {
$sButtons = $OptionLink;
} else {
$sButtons = $sEditorLink.$OptionLink.$sExtendLink;
if ($this->template_name != getGlobalSetting('defaulttheme')) {
$sButtons .= $sUninstallLink;
} else {
$sButtons .= '
<a
class="btn btn-danger btn-block"
disabled
data-toggle="tooltip"
title="' . gT('You cannot uninstall the default template.').'"
>
<span class="icon-trash"></span>
'.gT('Uninstall').'
</a>
';
}
}
$sButtons .= $sResetLink;
return $sButtons;
}
public function getHasOptionPage()
{
$filteredName = Template::templateNameFilter($this->template->name);
$oRTemplate = $this->prepareTemplateRendering($filteredName);
$sOptionFile = 'options'.DIRECTORY_SEPARATOR.'options.twig';
while (!file_exists($oRTemplate->path.$sOptionFile)) {
$oMotherTemplate = $oRTemplate->oMotherTemplate;
if (!($oMotherTemplate instanceof TemplateConfiguration)) {
return false;
break;
}
$oRTemplate = $oMotherTemplate->prepareTemplateRendering($this->template->name);
}
return true;
}
/**
* Set a value on a given option at global setting level (survey level not affected).
* Will be used to turn ON ajax mode on update.
*
* @param string $name
* @param mixed $value
* @return void
*/
public function setGlobalOption($name, $value)
{
if ($this->options != 'inherit') {
$oOptions = json_decode($this->options);
if (empty($this->sid)) {
$oOptions->$name = $value;
$sOptions = json_encode($oOptions);
$this->options = $sOptions;
$this->save();
}
}
}
/**
* Apply options from XML configuration for all missing template options
*
* @return void
*/
public function addOptionFromXMLToLiveTheme()
{
if ($this->options != 'inherit') {
$oOptions = get_object_vars(json_decode($this->options));
$oTemplateConfigurationModel = new TemplateManifest;
$oTemplateConfigurationModel->setBasics();
$oXmlOptions = get_object_vars($oTemplateConfigurationModel->config->options);
// compare template options to options from the XML and add if missing
foreach ($oXmlOptions as $key=>$value){
if (!array_key_exists($key, $oOptions)){
$this->addOptionToLiveTheme($key, $value);
}
}
}
}
/**
* Add an option definition to the current theme.
* Will be used to turn ON ajax mode on update.
*
* @param string $name
* @param mixed $value
* @return void
*/
public function addOptionToLiveTheme($name, $value)
{
if ($this->options != 'inherit') {
$oOptions = json_decode($this->options);
$oOptions->$name = $value;
$sOptions = json_encode($oOptions);
$this->options = $sOptions;
$this->save();
}
}
/**
* Set option (unless if options is set to "inherit").
* @param string $name
* @param mixed $value
* @return void
*/
public function setOption($name, $value)
{
if ($this->options != 'inherit') {
$oOptions = json_decode($this->options);
$oOptions->$name = $value;
$sOptions = json_encode($oOptions);
$this->options = $sOptions;
$this->save();
}
}
private function _getRelativePath($from, $to) {
$dir = explode(DIRECTORY_SEPARATOR, is_file($from) ? dirname($from) : rtrim($from, DIRECTORY_SEPARATOR));
$file = explode(DIRECTORY_SEPARATOR, $to);
while ($dir && $file && ($dir[0] == $file[0])) {
array_shift($dir);
array_shift($file);
}
return str_repeat('..'.DIRECTORY_SEPARATOR, count($dir)) . implode(DIRECTORY_SEPARATOR, $file);
}
/**
* Return image information
* @param string $file with Path
* @return array|null
*/
private function _getImageInfo($file)
{
if(!file_exists($file)) {
return;
}
// Currently it's private and only used one time, before put this function in twig : must validate directory is inside rootdir
$checkImage = LSYii_ImageValidator::validateImage($file);
if (!$checkImage['check']) {
return;
}
$filePath = $this->_getRelativePath(Yii::app()->getConfig('rootdir'), $file);
$previewFilePath = App()->getAssetManager()->publish($file);
return ['preview' => $previewFilePath, 'filepath' => $filePath, 'filepathOptions' => $filePath ,'filename'=>basename($file)];
}
protected function getOptionPageAttributes()
{
$aData = $this->attributes;
$fileList = array_merge(Template::getOtherFiles($this->filesPath), Template::getOtherFiles($this->generalFilesPath));
$aData['maxFileSize'] = getMaximumFileUploadSize();
$aData['imageFileList'] = [];
$categoryList = []; // Array with optgroup label and path
$categoryList[] = ['group' => gT("Global"),'path' => $this->generalFilesPath];
$categoryList[] = ['group' => gT("Theme"),'path' => $this->filesPath];
if($this->sid) {
$categoryList[] = ['group' => gT("Survey"),'path' => Yii::app()->getConfig('uploaddir').'/surveys/'.$this->sid.'/images/'];
}
foreach($categoryList as $category) {
$fileList = Template::getOtherFiles($category['path']);
foreach ($fileList as $file) {
$imageInfo = $this->_getImageInfo($category['path'].$file['name']);
if ($imageInfo) {
$aData['imageFileList'][] = array_merge($category,$imageInfo);
}
};
}
return $aData;
}
public function getOptionPage()
{
$oSimpleInheritance = Template::getInstance($this->template->name, $this->sid, $this->gsid, null, true);
$oSimpleInheritance->options = 'inherit';
$oSimpleInheritanceTemplate = $oSimpleInheritance->prepareTemplateRendering($this->template->name);
$oTemplate = $this->prepareTemplateRendering($this->template->name);
$renderArray = array('templateConfiguration' => $oTemplate->getOptionPageAttributes());
$oTemplate->setToInherit();
$oTemplate->setOptions();
$oTemplate->setOptionInheritance();
$oOptions = (array) $oSimpleInheritanceTemplate->oOptions;
// translation of database values, to match labels on the page
foreach ($oOptions as $key=>$value){
if ($key == 'showpopups'){
$oOptions[$key] = str_replace(array('1', '0', '-1'), array(gT("Popup"), gT("On page"), gT("No")), $value);
} elseif ($key == 'notables'){
$oOptions[$key] = str_replace(array('2', '1', '0'), array(gT("Always on"), gT("Small screens"), gT("Off")), $value);
} else {
$oOptions[$key] = str_replace(array('on', 'off', 'top', 'bottom'), array(gT("Yes"), gT("No"), gT("Top"), gT("Bottom")), $value);
}
}
//We add some extra values to the option page
//This is just a dirty hack, and somewhere in the future we will correct it
$renderArray['oParentOptions'] = array_merge(
($oOptions),
array(
'packages_to_load' => $oTemplate->packages_to_load,
'files_css' => $oTemplate->files_css
)
);
return Yii::app()->twigRenderer->renderOptionPage($oTemplate, $renderArray);
}
/**
* From a list of json files in db it will generate a PHP array ready to use by removeFileFromPackage()
*
* @param TemplateConfiguration $oTemplate
* @param string $sType
* @return array
* @internal param string $jFiles json
*/
protected function getFilesTo($oTemplate, $sType, $sAction)
{
// Todo: make it in a recursive way
if ( !empty($this->aFilesTo[$oTemplate->template->name]) ) {
if ( !empty($this->aFilesTo[$oTemplate->template->name][$sType]) ) {
if ( !empty($this->aFilesTo[$oTemplate->template->name][$sType][$sAction] ) ){
return $this->aFilesTo[$oTemplate->template->name][$sType][$sAction];
}else{
$this->aFilesTo[$oTemplate->template->name][$sType][$sAction] = array();
}
}else{
$this->aFilesTo[$oTemplate->template->name][$sType] = array();
$this->aFilesTo[$oTemplate->template->name][$sType][$sAction] = array();
}
}else{
$this->aFilesTo[$oTemplate->template->name] = array();
$this->aFilesTo[$oTemplate->template->name][$sType] = array();
$this->aFilesTo[$oTemplate->template->name][$sType][$sAction] = array();
}
$sField = 'files_'.$sType;
$oFiles = $this->getOfiles($oTemplate, $sField);
$aFiles = array();
if ($oFiles) {
foreach ($oFiles as $action => $aFileList) {
if (is_array($aFileList)) {
if ($action == $sAction) {
// Specific inheritance of one of the value of the json array
if ($aFileList[0] == 'inherit') {
$aParentjFiles = (array) json_decode($oTemplate->getParentConfiguration->$sField);
$aFileList = $aParentjFiles[$action];
}
$aFiles = array_merge($aFiles, $aFileList);
}
}
}
}
$this->aFilesTo[$oTemplate->template->name][$sType][$sAction] = $aFiles;
return $aFiles;
}
/**
* Get the json files (to load/replace/remove) from a theme, and checks if its correctly formated
*
* @param $oTemplate the theme to check
* @param $sField name of the DB field to get (file_css, file_js, file_print_css)
*/
protected function getOfiles($oTemplate, $sField)
{
if ( !empty($this->Ofiles[$oTemplate->template->name])){
if (!empty($this->Ofiles[$oTemplate->template->name][$sField] )) {
return $this->Ofiles[$oTemplate->template->name][$sField];
}else{
$this->Ofiles[$oTemplate->template->name][$sField] = array();
}
}else{
$this->Ofiles[$oTemplate->template->name] = array();
$this->Ofiles[$oTemplate->template->name][$sField] = array();
}
$files = $oTemplate->$sField;
if (!empty($files)) {
$oFiles = json_decode($files, true);
if ($oFiles === null) {
Yii::app()->setFlashMessage(
sprintf(
gT('Error: Malformed JSON: Field %s must be either a JSON array or the string "inherit". Found "%s".'),
$sField,
$oFiles
),
'error'
);
return false;
}
}
$this->Ofiles[$oTemplate->template->name][$sField] = $oFiles;
return $oFiles;
}
/**
* Proxy for Yii::app()->clientScript->removeFileFromPackage()
*
* @param string $sPackageName string name of the package to edit
* @param string $sType string the type of settings to change (css or js)
* @param $aSettings array array of local setting
* @return array
*/
protected function removeFileFromPackage($sPackageName, $sType, $aSettings)
{
foreach ($aSettings as $sFile) {
Yii::app()->clientScript->removeFileFromPackage($sPackageName, $sType, $sFile);
}
}