/
Survey.php
executable file
·1973 lines (1787 loc) · 74.5 KB
/
Survey.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')) {
die('No direct script access allowed');
}
/*
* LimeSurvey
* Copyright (C) 2007-2011 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.
*
*/
use \LimeSurvey\PluginManager\PluginEvent;
/**
* Class Survey
*
* @property integer $sid Survey ID
* @property integer $owner_id
* @property integer $gsid Survey ID
* @property string $admin Survey Admin's full name
* @property string $active Whether survey is acive or not (Y/N)
* @property string $expires Expiry date (YYYY-MM-DD hh:mm:ss)
* @property string $startdate Survey Start date (YYYY-MM-DD hh:mm:ss)
* @property string $adminemail Survey administrator email address
* @property string $anonymized Whether survey is anonymized or not (Y/N)
* @property string $faxto
* @property string $format A : All in one, G : Group by group, Q : question by question
* @property string $savetimings Whether survey timings are saved (Y/N)
* @property string $template Template name
* @property string $language Survey base language
* @property string $additional_languages Survey additional languages delimited by space ' '
* @property string $datestamp Whether respondents' datestamps will be saved (Y/N)
* @property string $usecookie Are cookies used to prevent repeated participation (Y/N)
* @property string $allowregister Allow public registration (Y/N)
* @property string $allowsave Is participant allowed save and resume later (Y/N)
* @property integer $autonumber_start
* @property integer $tokenlength Token length: MIN:5 MAX:36
* @property string $autoredirect Automatically load URL when survey complete: (Y/N)
* @property string $allowprev Allow backwards navigation (Y/N)
* @property string $printanswers Participants may print answers: (Y/N)
* @property string $ipaddr Whether Participants IP address will be saved: (Y/N)
* @property string $refurl Save referrer URL: (Y/N)
* @property string $datecreated Date survey was created (YYYY-MM-DD hh:mm:ss)
* @property string $publicstatistics Public statistics: (Y/N)
* @property string $publicgraphs Show graphs in public statistics: (Y/N)
* @property string $listpublic List survey publicly: (Y/N)
* @property string $htmlemail Use HTML format for token emails: (Y/N)
* @property string $sendconfirmation Send confirmation emails:(Y/N)
* @property string $tokenanswerspersistence Enable token-based response persistence: (Y/N)
* @property string $assessments Enable assessment mode: (Y/N)
* @property string $usecaptcha
* @property string $usetokens
* @property string $bounce_email Bounce email address
* @property string $attributedescriptions
* @property string $emailresponseto e-mail address to send detailed admin notification email to
* @property string $emailnotificationto Email address to send basic admin notification email to
* @property string $showxquestions Show "There are X questions in this survey": (Y/N)
* @property string $showgroupinfo Show group name and/or group description: (Y/N)
* @property string $shownoanswer Show "No answer": (Y/N)
* @property string $showqnumcode Show question number and/or code: (Y/N)
* @property integer $bouncetime
* @property string $bounceprocessing
* @property string $bounceaccounttype
* @property string $bounceaccounthost
* @property string $bounceaccountpass
* @property string $bounceaccountencryption
* @property string $bounceaccountuser
* @property string $showwelcome Show welcome screen: (Y/N)
* @property string $showprogress how progress bar: (Y/N)
* @property integer $questionindex Show question index / allow jumping (0: diabled; 1: Incremental; 2: Full)
* @property integer $navigationdelay Navigation delay (seconds)
* @property string $nokeyboard Show on-screen keyboard: (Y/N)
* @property string $alloweditaftercompletion Allow multiple responses or update responses with one token: (Y/N)
* @property string $googleanalyticsstyle Google Analytics style: (0: off; 1:Default; 2:Survey-SID/Group)
* @property string $googleanalyticsapikey Google Analytics Tracking ID
*
* @property Permission[] $permissions
* @property SurveyLanguageSetting[] $languagesettings
* @property User $owner
* @property QuestionGroup[] $groups
* @property Quota[] $quotas
* @property Question[] $quotableQuestions
*
* @property array $fullAnswers
* @property array $partialAnswers
* @property integer $countFullAnswers Full-answers count
* @property integer $countPartialAnswers Full-answers count
* @property integer $countTotalAnswers Total-answers count
* @property integer $groupsCount Number of groups in a survey (in base language)
* @property array $surveyinfo
* @property SurveyLanguageSetting $currentLanguageSettings Survey languagesettings in currently active language
* @property string[] $allLanguages
* @property string[] $additionalLanguages Additional survey languages
* @property array $tokenAttributes Additional token attribute names
* @property string $creationDate Creation date formatted according to user format
* @property string $startDateFormatted Start date formatted according to user format
* @property string $expiryDateFormatted Expiry date formatted according to user format
* @property string $tokensTableName Name of survey tokens table
* @property string $responsesTableName Name of survey resonses table
* @property string $timingsTableName Name of survey timings table
* @property boolean $hasTokensTable Whether survey has a tokens table or not
* @property boolean $hasResponsesTable Wheteher the survey reponses (data) table exists in DB
* @property boolean $hasTimingsTable Wheteher the survey timings table exists in DB
* @property string $googleanalyticsapikeysetting Returns the value for the SurveyEdit GoogleAnalytics API-Key UseGlobal Setting
* @property integer $countTotalQuestions Count of questions (in that language, without subquestions)
* @property integer $countInputQuestions Count of questions that need input (skipping text-display etc.)
* @property integer $countNoInputQuestions Count of questions that DO NOT need input (skipping text-display etc.)
*
* All Y/N columns in the model can be accessed as boolean values:
* @property bool $isActive Whether Survey is active
* @property bool $isAnonymized Whether survey is anonymized or not
* @property bool $isSaveTimings Whether survey timings are saved
* @property bool $isDateStamp Whether respondents' datestamps will be saved
* @property bool $isUseCookie Are cookies used to prevent repeated participation
* @property bool $isAllowRegister Allow public registration
* @property bool $isAllowSave Is participant allowed save and resume later
* @property bool $isAutoRedirect Automatically load URL when survey complete
* @property bool $isAllowPrev Allow backwards navigation
* @property bool $isPrintAnswers Participants may print answers
* @property bool $isIpAddr Whether Participants IP address will be saved
* @property bool $isRefUrl Save referrer URL
* @property bool $isPublicStatistics Public statistics
* @property bool $isPublicGraphs Show graphs in public statistics
* @property bool $isListPublic List survey publicly
* @property bool $isHtmlEmail Use HTML format for token emails
* @property bool $isSendConfirmation Send confirmation emails
* @property bool $isTokenAnswersPersistence Enable token-based response persistence
* @property bool $isAssessments Enable assessment mode
* @property bool $isShowXQuestions Show "There are X questions in this survey"
* @property bool $isShowGroupInfo Show group name and/or group description
* @property bool $isShowNoAnswer Show "No answer"
* @property bool $isShowQnumCode Show question number and/or code
* @property bool $isShowWelcome Show welcome screen
* @property bool $isShowProgress how progress bar
* @property bool $showsurveypolicynotice Show the security notice
* @property bool $isNoKeyboard Show on-screen keyboard
* @property bool $isAllowEditAfterCompletion Allow multiple responses or update responses with one token
* @property SurveyLanguageSetting $defaultlanguage
* @method mixed active()
*/
class Survey extends LSActiveRecord
{
/**
* This is a static cache, it lasts only during the active request. If you ever need
* to clear it, like on activation of a survey when in the same request a row is read,
* saved and read again you can use resetCache() method.
*
* @var array $findByPkCache
*/
protected $findByPkCache = array();
public $searched_value;
public $showsurveypolicynotice = 0;
private $sSurveyUrl;
/**
* Set defaults
* @inheritdoc
*/
public function init()
{
/** @inheritdoc */
// Set the default values
$this->htmlemail = 'Y';
$this->format = 'G';
// Default setting is to use the global Google Analytics key If one exists
$globalKey = App()->getConfig('googleanalyticsapikey');
if ($globalKey != "") {
$this->googleanalyticsapikey = "9999useGlobal9999";
$this->googleanalyticsapikeysetting = "G";
}
/* default template */
$this->template = Template::templateNameFilter(App()->getConfig('defaulttheme'));
/* default language */
$validator = new LSYii_Validators;
$this->language = $validator->languageFilter(App()->getConfig('defaultlang'));
/* default user */
$this->owner_id = 1;
$this->admin = App()->getConfig('siteadminname');
$this->adminemail = App()->getConfig('siteadminemail');
if(!(Yii::app() instanceof CConsoleApplication)) {
$iUserid = Permission::getUserId();
if($iUserid) {
$this->owner_id = $iUserid;
$oUser = User::model()->findByPk($iUserid);
if($oUser) {
$this->admin = $oUser->full_name;
$this->adminemail = $oUser->email;
}
}
}
$this->attachEventHandler("onAfterFind", array($this, 'afterFindSurvey'));
}
/** @inheritdoc */
public function attributeLabels()
{
return array(
'running' => gT('running')
);
}
/**
* @inheritdoc With allow to delete all related models and data and test Permission.
* @param bool $recursive
**/
public function delete($recursive=true)
{
if (!Permission::model()->hasSurveyPermission($this->sid, 'survey', 'delete')) {
return false;
}
if(!parent::delete()) {
return false;
}
if ($recursive) {
//delete the survey_$iSurveyID table
if (tableExists("{{survey_".$this->sid."}}")) {
Yii::app()->db->createCommand()->dropTable("{{survey_".$this->sid."}}");
}
//delete the survey_$iSurveyID_timings table
if (tableExists("{{survey_".$this->sid."_timings}}")) {
Yii::app()->db->createCommand()->dropTable("{{survey_".$this->sid."_timings}}");
}
//delete the tokens_$iSurveyID table
if (tableExists("{{tokens_".$this->sid."}}")) {
Yii::app()->db->createCommand()->dropTable("{{tokens_".$this->sid."}}");
}
/* Remove User/global settings part : need Question and QuestionGroup*/
// Settings specific for this survey
$oCriteria = new CDbCriteria();
$oCriteria->compare('stg_name', 'last_%', true, 'AND', false);
$oCriteria->compare('stg_value', $this->sid, false, 'AND');
SettingGlobal::model()->deleteAll($oCriteria);
// Settings specific for this survey, 2nd part
$oCriteria = new CDbCriteria();
$oCriteria->compare('stg_name', 'last_%'.$this->sid.'%', true, 'AND', false);
SettingGlobal::model()->deleteAll($oCriteria);
// All Group id from this survey for ALL users
$aGroupId = CHtml::listData(QuestionGroup::model()->findAll(array('select'=>'gid', 'condition'=>'sid=:sid', 'params'=>array(':sid'=>$this->sid))), 'gid', 'gid');
$oCriteria = new CDbCriteria();
$oCriteria->compare('stg_name', 'last_question_gid_%', true, 'AND', false);
// pgsql need casting, unsure for mssql
if (Yii::app()->db->getDriverName() == 'pgsql') {
$oCriteria->addInCondition('CAST(stg_value as '.App()->db->schema->getColumnType("integer").')', $aGroupId);
}
//mysql App()->db->schema->getColumnType("integer") give int(11), mssql seems to have issue if cast alpha to numeric
else {
$oCriteria->addInCondition('stg_value', $aGroupId);
}
SettingGlobal::model()->deleteAll($oCriteria);
// All Question id from this survey for ALL users
$aQuestionId = CHtml::listData(Question::model()->findAll(array('select'=>'qid', 'condition'=>'sid=:sid', 'params'=>array(':sid'=>$this->sid))), 'qid', 'qid');
$oCriteria = new CDbCriteria();
$oCriteria->compare('stg_name', 'last_question_%', true, 'OR', false);
if (Yii::app()->db->getDriverName() == 'pgsql') {
$oCriteria->addInCondition('CAST(stg_value as '.App()->db->schema->getColumnType("integer").')', $aQuestionId);
} else {
$oCriteria->addInCondition('stg_value', $aQuestionId);
}
SettingGlobal::model()->deleteAll($oCriteria);
$oResult = Question::model()->findAllByAttributes(array('sid' => $this->sid));
foreach ($oResult as $aRow) {
Answer::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
Condition::model()->deleteAllByAttributes(array('qid' =>$aRow['qid']));
QuestionAttribute::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
DefaultValue::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
}
Question::model()->deleteAllByAttributes(array('sid' => $this->sid));
Assessment::model()->deleteAllByAttributes(array('sid' => $this->sid));
QuestionGroup::model()->deleteAllByAttributes(array('sid' => $this->sid));
SurveyLanguageSetting::model()->deleteAllByAttributes(array('surveyls_survey_id' => $this->sid));
Permission::model()->deleteAllByAttributes(array('entity_id' => $this->sid, 'entity'=>'survey'));
SavedControl::model()->deleteAllByAttributes(array('sid' => $this->sid));
SurveyURLParameter::model()->deleteAllByAttributes(array('sid' => $this->sid));
//Remove any survey_links to the CPDB
SurveyLink::model()->deleteLinksBySurvey($this->sid);
Quota::model()->deleteQuota(array('sid' => $this->sid), true);
// Remove all related plugin settings
PluginSetting::model()->deleteAllByAttributes(array("model" =>'Survey', "model_id" => $this->sid));
// Delete all uploaded files.
rmdirr(Yii::app()->getConfig('uploaddir').'/surveys/'.$this->sid);
}
return true;
}
/**
* The Survey languagesettings in currently active language. Falls back to the surveys' default language if the current language is not available.
* @return SurveyLanguageSetting
*/
public function getCurrentLanguageSettings()
{
if (isset($this->languagesettings[App()->language])) {
return $this->languagesettings[App()->language];
} else if(isset($this->languagesettings[$this->language])){
return $this->languagesettings[$this->language];
} else {
throw new Exception('Selected Surveys language not found');
}
}
/**
* Return the language of the current survey
* It can be:
* - the selected language by user via the language selector (POST then Session)
* - the selected language via URL (GET then Session)
* - the survey default language
*
* @return string the correct language
*/
public function getLanguageForSurveyTaking()
{
// Default: the survey language
$sLang = $this->language;
if (Yii::app()->request->getParam('lang', null) !== null) {
// POST or GET
$sLang = Yii::app()->request->getParam('lang');
} else {
// SESSION
if (isset(Yii::app()->session['survey_'.$this->sid]['s_lang'])) {
$sLang = Yii::app()->session['survey_'.$this->sid]['s_lang'];
}
}
return $sLang;
}
/**
* Expires a survey. If the object was invoked using find or new surveyId can be ommited.
* @param int $surveyId
* @return boolean|null
*/
public function expire($surveyId = null)
{
$dateTime = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig('timeadjust'));
$dateTime = dateShift($dateTime, "Y-m-d H:i:s", '-1 minute');
if (!isset($surveyId)) {
$this->expires = $dateTime;
if ($this->scenario == 'update') {
return $this->save();
}
} else {
self::model()->updateByPk($surveyId, array('expires' => $dateTime));
}
}
/** @inheritdoc */
public function tableName()
{
return '{{surveys}}';
}
/** @inheritdoc */
public function primaryKey()
{
return 'sid';
}
/**
* @inheritdoc
* @return Survey
*/
public static function model($class = __CLASS__)
{
return parent::model($class);
}
/** @inheritdoc */
public function relations()
{
return array(
'permissions' => array(self::HAS_MANY, 'Permission', array('entity_id'=> 'sid')), //
'languagesettings' => array(self::HAS_MANY, 'SurveyLanguageSetting', 'surveyls_survey_id', 'index' => 'surveyls_language'),
'defaultlanguage' => array(self::BELONGS_TO, 'SurveyLanguageSetting', array('language' => 'surveyls_language', 'sid' => 'surveyls_survey_id')),
'correct_relation_defaultlanguage' => array(self::HAS_ONE, 'SurveyLanguageSetting', array('surveyls_language' => 'language', 'surveyls_survey_id' => 'sid')),
'owner' => array(self::BELONGS_TO, 'User', 'owner_id',),
'groups' => array(self::HAS_MANY, 'QuestionGroup', 'sid', 'order'=>'groups.group_order ASC'),
'quotas' => array(self::HAS_MANY, 'Quota', 'sid', 'order'=>'name ASC'),
'surveymenus' => array(self::HAS_MANY, 'Surveymenu', array('survey_id' => 'sid')),
'surveygroup' => array(self::BELONGS_TO, 'SurveysGroups', array('gsid' => 'gsid')),
'templateModel' => array(self::HAS_ONE, 'Template', array('name' => 'template')),
'templateConfiguration' => array(self::HAS_ONE, 'TemplateConfiguration', array('sid' => 'sid'))
);
}
/* public function defaultScope()
{
return array('order'=> $this->getTableAlias().'.sid');
} */
/** @inheritdoc */
public function scopes()
{
return array(
'active' => array('condition' => "active = 'Y'"),
'open' => array('condition' => '(startdate <= :now1 OR startdate IS NULL) AND (expires >= :now2 OR expires IS NULL)', 'params' => array(
':now1' => dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig("timeadjust")),
':now2' => dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig("timeadjust"))
)
),
'public' => array('condition' => "listpublic = 'Y'"),
'registration' => array('condition' => "allowregister = 'Y' AND startdate > :now3 AND (expires < :now4 OR expires IS NULL)", 'params' => array(
':now3' => dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig("timeadjust")),
':now4' => dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig("timeadjust"))
))
);
}
/** @inheritdoc */
public function rules()
{
return array(
array('sid', 'unique'),// Not in pk
array('sid', 'numerical', 'integerOnly'=>true,'min'=>1), // max ?
array('gsid', 'numerical', 'integerOnly'=>true),
array('datecreated', 'default', 'value'=>date("Y-m-d")),
array('startdate', 'default', 'value'=>null),
array('expires', 'default', 'value'=>null),
array('admin,faxto', 'LSYii_Validators'),
array('adminemail', 'filter', 'filter'=>'trim'),
array('bounce_email', 'filter', 'filter'=>'trim'),
array('bounce_email', 'LSYii_EmailIDNAValidator', 'allowEmpty'=>true),
array('active', 'in', 'range'=>array('Y', 'N'), 'allowEmpty'=>true),
array('gsid', 'numerical', 'min'=>'0', 'allowEmpty'=>true),
array('anonymized', 'in', 'range'=>array('Y', 'N'), 'allowEmpty'=>true),
array('savetimings', 'in', 'range'=>array('Y', 'N'), 'allowEmpty'=>true),
array('datestamp', 'in', 'range'=>array('Y', 'N'), 'allowEmpty'=>true),
array('usecookie', 'in', 'range'=>array('Y', 'N'), 'allowEmpty'=>true),
array('allowregister', 'in', 'range'=>array('Y', 'N'), 'allowEmpty'=>true),
array('allowsave', 'in', 'range'=>array('Y', 'N'), 'allowEmpty'=>true),
array('autoredirect', 'in', 'range'=>array('Y', 'N'), 'allowEmpty'=>true),
array('allowprev', 'in', 'range'=>array('Y', 'N'), 'allowEmpty'=>true),
array('printanswers', 'in', 'range'=>array('Y', 'N'), 'allowEmpty'=>true),
array('ipaddr', 'in', 'range'=>array('Y', 'N'), 'allowEmpty'=>true),
array('refurl', 'in', 'range'=>array('Y', 'N'), 'allowEmpty'=>true),
array('publicstatistics', 'in', 'range'=>array('Y', 'N'), 'allowEmpty'=>true),
array('publicgraphs', 'in', 'range'=>array('Y', 'N'), 'allowEmpty'=>true),
array('listpublic', 'in', 'range'=>array('Y', 'N'), 'allowEmpty'=>true),
array('htmlemail', 'in', 'range'=>array('Y', 'N'), 'allowEmpty'=>true),
array('sendconfirmation', 'in', 'range'=>array('Y', 'N'), 'allowEmpty'=>true),
array('tokenanswerspersistence', 'in', 'range'=>array('Y', 'N'), 'allowEmpty'=>true),
array('assessments', 'in', 'range'=>array('Y', 'N'), 'allowEmpty'=>true),
array('usetokens', 'in', 'range'=>array('Y', 'N'), 'allowEmpty'=>true),
array('showxquestions', 'in', 'range'=>array('Y', 'N'), 'allowEmpty'=>true),
array('shownoanswer', 'in', 'range'=>array('Y', 'N'), 'allowEmpty'=>true),
array('showwelcome', 'in', 'range'=>array('Y', 'N'), 'allowEmpty'=>true),
array('showsurveypolicynotice', 'in', 'range'=>array('0', '1', '2'), 'allowEmpty'=>true),
array('showprogress', 'in', 'range'=>array('Y', 'N'), 'allowEmpty'=>true),
array('questionindex', 'numerical', 'min' => 0, 'max' => 2, 'allowEmpty'=>false),
array('nokeyboard', 'in', 'range'=>array('Y', 'N'), 'allowEmpty'=>true),
array('alloweditaftercompletion', 'in', 'range'=>array('Y', 'N'), 'allowEmpty'=>true),
array('bounceprocessing', 'in', 'range'=>array('L', 'N', 'G'), 'allowEmpty'=>true),
array('usecaptcha', 'in', 'range'=>array('A', 'B', 'C', 'D', 'X', 'R', 'S', 'N'), 'allowEmpty'=>true),
array('showgroupinfo', 'in', 'range'=>array('B', 'N', 'D', 'X'), 'allowEmpty'=>true),
array('showqnumcode', 'in', 'range'=>array('B', 'N', 'C', 'X'), 'allowEmpty'=>true),
array('format', 'in', 'range'=>array('G', 'S', 'A'), 'allowEmpty'=>true),
array('googleanalyticsstyle', 'numerical', 'integerOnly'=>true, 'min'=>'0', 'max'=>'2', 'allowEmpty'=>true),
array('autonumber_start', 'numerical', 'integerOnly'=>true, 'allowEmpty'=>true),
array('tokenlength', 'default', 'value'=>15),
array('tokenlength', 'numerical', 'integerOnly'=>true, 'allowEmpty'=>false, 'min'=>'5', 'max'=>'36'),
array('bouncetime', 'numerical', 'integerOnly'=>true, 'allowEmpty'=>true),
array('navigationdelay', 'numerical', 'integerOnly'=>true, 'allowEmpty'=>true),
array('template', 'filter', 'filter'=>array($this, 'filterTemplateSave')),
array('language', 'LSYii_Validators', 'isLanguage'=>true),
array('language', 'required', 'on' => 'insert'),
array('language', 'filter', 'filter'=>'trim'),
array('additional_languages', 'filter', 'filter'=>'trim'),
array('additional_languages', 'LSYii_Validators', 'isLanguageMulti'=>true),
array('running', 'safe', 'on'=>'search'),
// Date rules currently don't work properly with MSSQL, deactivating for now
// array('expires','date', 'format'=>array('yyyy-MM-dd', 'yyyy-MM-dd HH:mm', 'yyyy-MM-dd HH:mm:ss',), 'allowEmpty'=>true),
// array('startdate','date', 'format'=>array('yyyy-MM-dd', 'yyyy-MM-dd HH:mm', 'yyyy-MM-dd HH:mm:ss',), 'allowEmpty'=>true),
// array('datecreated','date', 'format'=>array('yyyy-MM-dd', 'yyyy-MM-dd HH:mm', 'yyyy-MM-dd HH:mm:ss',), 'allowEmpty'=>true),
);
}
/**
* afterFindSurvey to fix and/or add some survey attribute
* - Fix template name to be sure template exist
*/
public function afterFindSurvey()
{
$event = new PluginEvent('afterFindSurvey');
$event->set('surveyid', $this->sid);
App()->getPluginManager()->dispatchEvent($event);
// set the attributes we allow to be fixed
$allowedAttributes = array('template', 'usecookie', 'allowprev',
'showxquestions', 'shownoanswer', 'showprogress', 'questionindex',
'usecaptcha', 'showgroupinfo', 'showqnumcode', 'navigationdelay',
'expires','stardate','admin','adminemail','emailnotificationto','emailresponseto');
foreach ($allowedAttributes as $attribute) {
if (!is_null($event->get($attribute))) {
$this->{$attribute} = $event->get($attribute);
}
}
$this->template = Template::templateNameFilter($this->template);
}
/**
* filterTemplateSave to fix some template name
* @param string $sTemplateName
* @return string
*/
public function filterTemplateSave($sTemplateName)
{
if (!Permission::model()->hasTemplatePermission($sTemplateName)) {
// Reset to default only if different from actual value
if (!$this->isNewRecord) {
$oSurvey = self::model()->findByPk($this->sid);
if ($oSurvey->template != $sTemplateName) {
// No need to test !is_null($oSurvey)
$sTemplateName = getGlobalSetting('defaulttheme');
}
} else {
$sTemplateName = getGlobalSetting('defaulttheme');
}
}
return Template::templateNameFilter($sTemplateName);
}
/**
* permission scope for this model
* Actually only test if user have minimal access to survey (read)
* @access public
* @param int $loginID
* @return CActiveRecord
*
*/
public function permission($loginID)
{
$loginID = (int) $loginID;
if (Permission::model()->hasGlobalPermission('surveys', 'read', $loginID)) {
// Test global before adding criteria
return $this;
}
$criteria = $this->getDBCriteria();
$criteria->mergeWith(array(
'condition' => 'sid IN (SELECT entity_id FROM {{permissions}} WHERE entity = :entity AND uid = :uid AND permission = :permission AND read_p = 1)
OR owner_id = :owner_id',
));
$criteria->params[':uid'] = $loginID;
$criteria->params[':permission'] = 'survey';
$criteria->params[':owner_id'] = $loginID;
$criteria->params[':entity'] = 'survey';
return $this;
}
/**
* Returns additional languages formatted into a string
*
* @access public
* @return array
*/
public function getAdditionalLanguages()
{
$sLanguages = trim($this->additional_languages);
if ($sLanguages != '') {
return explode(' ', $sLanguages);
} else {
return array();
}
}
/**
* Returns all languages array
*
* @access public
* @return array
*/
public function getAllLanguages()
{
$sLanguages = self::getAdditionalLanguages();
array_unshift($sLanguages, $this->language);
return $sLanguages;
}
/**
* Returns the additional token attributes
*
* @access public
* @return array
*/
public function getTokenAttributes()
{
$attdescriptiondata = decodeTokenAttributes($this->attributedescriptions);
// checked for invalid data
if ($attdescriptiondata == null) {
return array();
}
// Catches malformed data
if ($attdescriptiondata && strpos(key(reset($attdescriptiondata)), 'attribute_') === false) {
// don't know why yet but this breaks normal tokenAttributes functionning
//$attdescriptiondata=array_flip(GetAttributeFieldNames($this->sid));
} elseif (is_null($attdescriptiondata)) {
$attdescriptiondata = array();
}
// Legacy records support
if ($attdescriptiondata === false) {
$attdescriptiondata = explode("\n", $this->attributedescriptions);
$fields = array();
$languagesettings = array();
foreach ($attdescriptiondata as $attdescription) {
if (trim($attdescription) != '') {
$fieldname = substr($attdescription, 0, strpos($attdescription, '='));
$desc = substr($attdescription, strpos($attdescription, '=') + 1);
$fields[$fieldname] = array(
'description' => $desc,
'mandatory' => 'N',
'show_register' => 'N',
'cpdbmap' =>''
);
$languagesettings[$fieldname] = $desc;
}
}
$ls = SurveyLanguageSetting::model()->findByAttributes(array('surveyls_survey_id' => $this->sid, 'surveyls_language' => $this->language));
self::model()->updateByPk($this->sid, array('attributedescriptions' => json_encode($fields)));
$ls->surveyls_attributecaptions = json_encode($languagesettings);
$ls->save();
$attdescriptiondata = $fields;
}
// Without token table : all extra attribute are only saved on $this->attributedescriptions
$allKnowAttributes = $attdescriptiondata;
// Without token table : all attribute $this->attributedescriptions AND real attribute. @see issue #13924
if($this->getHasTokensTable()){
$allKnowAttributes = array_intersect_key(
( $attdescriptiondata + Token::model($this->sid)->getAttributes()),
Token::model($this->sid)->getAttributes()
);
// We remove deleted attribute even if deleted manually in DB
}
$aCompleteData = array();
foreach ($allKnowAttributes as $sKey=>$aValues) {
if (preg_match("/^attribute_[0-9]{1,}$/", $sKey)) { // Select only extra attributes here
if (!is_array($aValues)) {
$aValues = array();
}
// merge default with attributedescriptions
$aCompleteData[$sKey] = array_merge(array(
'description' => $sKey,
'mandatory' => 'N',
'show_register' => 'N',
'cpdbmap' =>''
), $aValues);
}
}
return $aCompleteData;
}
/**
* Return the name of survey tokens table
* @return string
*/
public function getTokensTableName()
{
return "{{tokens_".$this->primaryKey."}}";
}
/**
* Return the name of survey timigs table
* @return string
*/
public function getTimingsTableName()
{
return "{{survey_".$this->primaryKey."_timings}}";
}
/**
* Return the name of survey responses (the data) table name
* @return string
*/
public function getResponsesTableName()
{
return '{{survey_'.$this->primaryKey.'}}';
}
/**
* Returns true in a survey participants table exists for survey
* @return boolean
*/
public function getHasTokensTable()
{
// Make sure common_helper is loaded
Yii::import('application.helpers.common_helper', true);
return tableExists($this->tokensTableName);
}
/**
* Wheteher the survey reponses (data) table exists in DB
* @return boolean
*/
public function getHasResponsesTable()
{
// Make sure common_helper is loaded
Yii::import('application.helpers.common_helper', true);
return tableExists($this->responsesTableName);
}
/**
* Wheteher the survey reponses timings exists in DB
* @return boolean
*/
public function getHasTimingsTable()
{
// Make sure common_helper is loaded
Yii::import('application.helpers.common_helper', true);
return tableExists($this->timingsTableName);
}
/**
* Returns the value for the SurveyEdit GoogleAnalytics API-Key UseGlobal Setting
* @return string
*/
public function getGoogleanalyticsapikeysetting()
{
if ($this->googleanalyticsapikey === "9999useGlobal9999") {
return "G";
} else if ($this->googleanalyticsapikey == "") {
return "N";
} else {
return "Y";
}
}
/**
* @param string $value
*/
public function setGoogleanalyticsapikeysetting($value)
{
if ($value == "G") {
$this->googleanalyticsapikey = "9999useGlobal9999";
} else if ($value == "N") {
$this->googleanalyticsapikey = "";
}
}
/**
* Returns the value for the SurveyEdit GoogleAnalytics API-Key UseGlobal Setting
* @return string
*/
public function getGoogleanalyticsapikey()
{
if ($this->googleanalyticsapikey === "9999useGlobal9999") {
return getGlobalSetting('googleanalyticsapikey');
} else {
return $this->googleanalyticsapikey;
}
}
public function getSurveyTemplateConfiguration()
{
return TemplateConfiguration::getInstance(null, null, $this->sid);
}
private function __useTranslationForSurveymenu(&$entryData) {
$entryData['title'] = gT($entryData['title']);
$entryData['menu_title'] = gT($entryData['menu_title']);
$entryData['menu_description'] = gT($entryData['menu_description']);
}
private function _createSurveymenuArray($oSurveyMenuObjects, $collapsed=false)
{
//Posibility to add more languages to the database is given, so it is possible to add a call by language
//Also for peripheral menues we may add submenus someday.
$aResultCollected = [];
foreach ($oSurveyMenuObjects as $oSurveyMenuObject) {
$entries = [];
$aMenuEntries = $oSurveyMenuObject->surveymenuEntries;
$submenus = $this->_getSurveymenuSubmenus($oSurveyMenuObject, $collapsed);
foreach ($aMenuEntries as $menuEntry) {
$aEntry = $menuEntry->attributes;
//Skip menu if not activated in collapsed mode
if ($collapsed && $aEntry['showincollapse'] == 0 ) {
continue;
}
//Skip menu if no permission
if (!empty($aEntry['permission']) && !empty($aEntry['permission_grade'])){
$inArray = array_search($aEntry['permission'],array_keys(Permission::getGlobalBasePermissions()));
if($inArray) {
$hasPermission = Permission::model()->hasGlobalPermission($aEntry['permission'], $aEntry['permission_grade']);
} else {
$hasPermission = Permission::model()->hasSurveyPermission($this->sid, $aEntry['permission'], $aEntry['permission_grade']);
}
if(!$hasPermission) {
continue;
}
}
// Check if a specific user owns this menu.
if (!empty($aEntry['user_id'])) {
$userId = Yii::app()->session['loginID'];
if ($userId != $aEntry['user_id']) {
continue;
}
}
//parse the render part of the data attribute
$oDataAttribute = new SurveymenuEntryData();
$oDataAttribute->apply($menuEntry, $this->sid);
if ($oDataAttribute->isActive !== null) {
if (($oDataAttribute->isActive == true && $this->active == 'N') || ($oDataAttribute->isActive == false && $this->active == 'Y')) {
continue;
}
}
$aEntry['link'] = $oDataAttribute->linkCreator();
$aEntry['link_external'] = $oDataAttribute->linkExternal;
$aEntry['debugData'] = $oDataAttribute->attributes;
$aEntry['pjax'] = $oDataAttribute->pjaxed;
$this->__useTranslationForSurveymenu($aEntry);
$entries[$aEntry['id']] = $aEntry;
}
$aResultCollected[$oSurveyMenuObject->id] = [
"id" => $oSurveyMenuObject->id,
"title" => gt($oSurveyMenuObject->title),
"name" => $oSurveyMenuObject->name,
"ordering" => $oSurveyMenuObject->ordering,
"level" => $oSurveyMenuObject->level,
"description" => gT($oSurveyMenuObject->description),
"entries" => $entries,
"submenus" => $submenus
];
}
return $aResultCollected;
}
private function _getSurveymenuSubmenus($oParentSurveymenu, $collapsed=false)
{
$criteria = new CDbCriteria;
$criteria->addCondition('survey_id=:surveyid OR survey_id IS NULL');
$criteria->addCondition('parent_id=:parentid');
$criteria->addCondition('level=:level');
if ($collapsed === true) {
$criteria->addCondition('showincollapse=1');
}
$criteria->params = [
':surveyid' => $oParentSurveymenu->survey_id,
':parentid' => $oParentSurveymenu->id,
':level'=> ($oParentSurveymenu->level + 1)
];
$oMenus = Surveymenu::model()->findAll($criteria);
$aResultCollected = $this->_createSurveymenuArray($oMenus, $collapsed);
return $aResultCollected;
}
private function _getDefaultSurveyMenus($position = '')
{
$criteria = new CDbCriteria;
$criteria->condition = 'survey_id IS NULL AND parent_id IS NULL';
$collapsed = $position==='collapsed';
if ($position != '' && !$collapsed) {
$criteria->condition .= ' AND position=:position';
$criteria->params = array(':position'=>$position);
}
if ($collapsed) {
$criteria->condition .= ' AND (position=:position OR showincollapse=1 )';
$criteria->params = array(':position'=>$position);
$collapsed = true;
}
$oDefaultMenus = Surveymenu::model()->findAll($criteria);
$aResultCollected = $this->_createSurveymenuArray($oDefaultMenus, $collapsed);
return $aResultCollected;
}
/**
* Get surveymenu configuration
* This will be made bigger in future releases, but right now it only collects the default menu-entries
*/
public function getSurveyMenus($position = '')
{
$collapsed = $position==='collapsed';
//Get the default menus
$aDefaultSurveyMenus = $this->_getDefaultSurveyMenus($position);
//get all survey specific menus
$aThisSurveyMenues = $this->_createSurveymenuArray($this->surveymenus, $collapsed);
//merge them
$aSurveyMenus = $aDefaultSurveyMenus + $aThisSurveyMenues;
// var_dump($aDefaultSurveyMenus);
// var_dump($aThisSurveyMenues);
//soon to come => Event to add menus for plugins
return $aSurveyMenus;
}
/**
* Creates a new survey - with a random sid
*
* @param array $aData Array with fieldname=>fieldcontents data
* @return \Survey
*/
public function insertNewSurvey($aData)
{
if (!isset($aData['datecreated'])) {
$aData['datecreated'] = date('Y-m-d H:i:s');
}
if(isset($aData['wishSID'])) {
$aData['sid'] = $aData['wishSID'];
unset($aData['wishSID']);
}
if(empty($aData['sid'])) {
$aData['sid'] = intval(randomChars(6, '123456789'));
}
$survey = new self;
foreach ($aData as $k => $v) {
$survey->$k = $v;
}
$attempts = 0;
/* Validate sid : > 1 and unique */
while(!$survey->validate(array('sid'))) {
$attempts++;
$survey->sid = intval(randomChars(6, '123456789'));
/* If it's happen : there are an issue in server … (or in randomChars function …) */
if($attempts > 50) {
throw new Exception("Unable to get a valid survey id after 50 attempts");
}
}
if (!$survey->save()) {
$survey->sid = null;
}
return $survey;
}
/**
* Deletes a survey and all its data
*
* @access public
* @param int $iSurveyID
* @param bool $recursive
* @return boolean
*/
public function deleteSurvey($iSurveyID, $recursive = true)
{
$oSurvey = Survey::Model()->findByPk($iSurveyID);
if (!$oSurvey) {
return false;
}
return $oSurvey->delete($recursive);
}
/**
* @inheritdoc . But use a static var because can be used a lot of time.
*/
public function findByPk($pk, $condition = '', $params = array())
{
if (empty($condition) && empty($params)) {
if (array_key_exists($pk, $this->findByPkCache)) {
return $this->findByPkCache[$pk];
} else {
$result = parent::findByPk($pk, $condition, $params);
if (!is_null($result)) {
$this->findByPkCache[$pk] = $result;
}
return $result;
}
}
return parent::findByPk($pk, $condition, $params);
}
/**
* findByPk uses a cache to store a result. Use this method to force clearing that cache.