/
Question.php
1017 lines (932 loc) · 41 KB
/
Question.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) 2013 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.
*
*/
/**
* Class Question
*
* @property integer $qid Question ID. NB! Primary key is qid & language columns combined!
* @property integer $parent_qid Questions parent question ID eg for subquestions
* @property integer $sid Survey ID
* @property integer $gid QuestionGroup ID where question is diepolayed
* @property string $type
* @property string $title Question Code
* @property string $question Question dieplay text. The actual question.
* @property string $preg
* @property string $help Question help-text for display
* @property string $other Other option enabled for question (Y/N)
* @property string $mandatory Whther question is mandatory (Y/N)
* @property integer $question_order Question order in greoup
* @property string $language Question language code. NB! Primary key is qid & language columns combined!
* @property integer $scale_qid
* @property integer $same_default Saves if user set to use the same default value across languages in default options dialog
* @property string $relevance Questions relevane equation
* @property string $modulename
*
* @property Survey $survey
* @property QuestionGroup $groups //TODO should be singular
* @property Question $parents //TODO should be singular
* @property Question[] $subquestions
* @property QuestionAttribute[] $questionAttributes NB! returns all QuestionArrtibute Models fot this QID regardless of the specified language
* @property string[] $quotableTypes Question types that can be used for quotas
*/
class Question extends LSActiveRecord
{
/** @var string $group_name Stock the active group_name for questions list filtering */
public $group_name;
public $gid;
/**
* @inheritdoc
* @return Question
*/
public static function model($class = __CLASS__)
{
/** @var self $model */
$model = parent::model($class);
return $model;
}
/** @inheritdoc */
public function tableName()
{
return '{{questions}}';
}
/** @inheritdoc */
public function primaryKey()
{
return array('qid', 'language');
}
/** @inheritdoc */
public function relations()
{
return array(
'survey' => array(self::BELONGS_TO, 'Survey', 'sid'),
'groups' => array(self::BELONGS_TO, 'QuestionGroup', 'gid, language', 'together' => true),
'parents' => array(self::HAS_ONE, 'Question', array("qid" => "parent_qid")),
'questionAttributes' => array(self::HAS_MANY, 'QuestionAttribute', 'qid'),
'subquestions' => array(self::HAS_MANY, 'Question', array('parent_qid'=>'qid', "language" => "language"))
);
}
/**
* @inheritdoc
* TODO: make it easy to read (if possible)
*/
public function rules()
{
$aRules = array(
array('title', 'required', 'on' => 'update, insert', 'message'=>gT('Question code may not be empty.', 'unescaped')),
array('title', 'length', 'min' => 1, 'max'=>20, 'on' => 'update, insert'),
array('qid,sid,gid,parent_qid', 'numerical', 'integerOnly'=>true),
array('qid', 'unique', 'criteria'=>array(
'condition'=>'language=:language',
'params'=>array(':language'=>$this->language)
),
'message'=>'{attribute} "{value}" is already in use.'),
array('language', 'length', 'min' => 2, 'max'=>20), // in array languages ?
array('title,question,help', 'LSYii_Validators'),
array('other', 'in', 'range'=>array('Y', 'N'), 'allowEmpty'=>true),
array('mandatory', 'in', 'range'=>array('Y', 'N'), 'allowEmpty'=>true),
array('question_order', 'numerical', 'integerOnly'=>true, 'allowEmpty'=>true),
array('scale_id', 'numerical', 'integerOnly'=>true, 'allowEmpty'=>true),
array('same_default', 'numerical', 'integerOnly'=>true, 'allowEmpty'=>true),
array('type', 'length', 'min' => 1, 'max'=>1),
array('preg,relevance', 'safe'),
array('modulename', 'length', 'max'=>255),
);
// Always enforce unicity on Sub question code (DB issue).
if ($this->parent_qid) {
$aRules[] = array('title', 'unique', 'caseSensitive'=>false, 'criteria'=>array(
'condition' => 'language=:language AND sid=:sid AND parent_qid=:parent_qid and scale_id=:scale_id',
'params' => array(
':language' => $this->language,
':sid' => $this->sid,
':parent_qid' => $this->parent_qid,
':scale_id' => $this->scale_id
)
),
'message' => gT('Subquestion codes must be unique.'));
// Disallow other title if question allow other
$oParentQuestion = Question::model()->findByPk(array("qid"=>$this->parent_qid, 'language'=>$this->language));
if ($oParentQuestion->other == "Y") {
$aRules[] = array('title', 'LSYii_CompareInsensitiveValidator', 'compareValue'=>'other', 'operator'=>'!=', 'message'=> sprintf(gT("'%s' can not be used if the 'Other' option for this question is activated."), "other"), 'except' => 'archiveimport');
}
} else {
// Disallow other if sub question have 'other' for title
$oSubquestionOther = Question::model()->find("parent_qid=:parent_qid and LOWER(title)='other'", array("parent_qid"=>$this->qid));
if ($oSubquestionOther) {
$aRules[] = array('other', 'compare', 'compareValue'=>'Y', 'operator'=>'!=', 'message'=> sprintf(gT("'%s' can not be used if the 'Other' option for this question is activated."), 'other'), 'except' => 'archiveimport');
}
}
if (!$this->isNewRecord) {
$oActualValue = Question::model()->findByPk(array("qid"=>$this->qid, 'language'=>$this->language));
if ($oActualValue && $oActualValue->title == $this->title) {
return $aRules; // We don't change title, then don't put rules on title
}
}
// 0 or empty
if (!$this->parent_qid) {
$aRules[] = array('title', 'unique', 'caseSensitive'=>true,
'criteria'=>array(
'condition' => 'language=:language AND sid=:sid AND parent_qid=0',
'params' => array(
':language' => $this->language,
':sid' => $this->sid
)
),
'message' => gT('Question codes must be unique.'),
'except' => 'archiveimport'
);
$aRules[] = array('title', 'match', 'pattern' => '/^[a-z,A-Z][[:alnum:]]*$/',
'message' => gT('Question codes must start with a letter and may only contain alphanumeric characters.'),
'except' => 'archiveimport');
} else {
$aRules[] = array('title', 'compare', 'compareValue'=>'time', 'operator'=>'!=',
'message'=> gT("'time' is a reserved word and can not be used for a subquestion."),
'except' => 'archiveimport');
$aRules[] = array('title', 'match', 'pattern' => '/^[[:alnum:]]*$/',
'message' => gT('Subquestion codes may only contain alphanumeric characters.'),
'except' => 'archiveimport');
}
return $aRules;
}
/**
* Rewrites sort order for questions in a group
*
* @static
* @access public
* @param int $gid
* @param int $surveyid
* @return void
*/
public static function updateSortOrder($gid, $surveyid)
{
$questions = self::model()->findAllByAttributes(array('gid' => $gid, 'sid' => $surveyid, 'language' => Survey::model()->findByPk($surveyid)->language), array('order'=>'question_order'));
$p = 0;
foreach ($questions as $question) {
$question->question_order = $p;
$question->save();
$p++;
}
}
/**
* Fix sort order for questions in a group
* @param int $gid
* @param string $language
* @param int $position
*/
public function updateQuestionOrder($gid, $language, $position = 0)
{
$data = Yii::app()->db->createCommand()->select('qid')
->where(array('and', 'gid=:gid', 'language=:language', 'parent_qid=0'))
->order('question_order, title ASC')
->from('{{questions}}')
->bindParam(':gid', $gid, PDO::PARAM_INT)
->bindParam(':language', $language, PDO::PARAM_STR)
->query();
$position = intval($position);
foreach ($data->readAll() as $row) {
Yii::app()->db->createCommand()->update($this->tableName(),
array('question_order' => $position), 'qid='.$row['qid']);
$position++;
}
}
/**
* This function returns an array of the advanced attributes for the particular question
* including their values set in the database
*
* @access public
* @param int $iQuestionID The question ID - if 0 then all settings will use the default value
* @param string $sQuestionType The question type
* @param int $iSurveyID
* @param string $sLanguage If you give a language then only the attributes for that language are returned
* @return array
*/
public function getAdvancedSettingsWithValues($iQuestionID, $sQuestionType, $iSurveyID, $sLanguage = null)
{
if (is_null($sLanguage)) {
$aLanguages = array_merge(array(Survey::model()->findByPk($iSurveyID)->language), Survey::model()->findByPk($iSurveyID)->additionalLanguages);
} else {
$aLanguages = array($sLanguage);
}
$aAttributeValues = QuestionAttribute::model()->getQuestionAttributes($iQuestionID, $sLanguage);
// TODO: move getQuestionAttributesSettings() to QuestionAttribute model to avoid code duplication
$aAttributeNames = \LimeSurvey\Helpers\questionHelper::getQuestionAttributesSettings($sQuestionType);
// If the question has a custom template, we first check if it provides custom attributes
if (!is_null($sLanguage)) {
$oQuestion = Question::model()->findByPk(array('qid'=>$iQuestionID, 'language'=>$sLanguage));
} else {
$oQuestion = Question::model()->find(array('condition'=>'qid=:qid', 'params'=>array(':qid'=>$iQuestionID)));
}
$aAttributeNames = self::getQuestionTemplateAttributes($aAttributeNames, $aAttributeValues, $oQuestion);
uasort($aAttributeNames, 'categorySort');
foreach ($aAttributeNames as $iKey => $aAttribute) {
if ($aAttribute['i18n'] == false) {
if (isset($aAttributeValues[$aAttribute['name']])) {
$aAttributeNames[$iKey]['value'] = $aAttributeValues[$aAttribute['name']];
} else {
$aAttributeNames[$iKey]['value'] = $aAttribute['default'];
}
} else {
foreach ($aLanguages as $sLanguage) {
if (isset($aAttributeValues[$aAttribute['name']][$sLanguage])) {
$aAttributeNames[$iKey][$sLanguage]['value'] = $aAttributeValues[$aAttribute['name']][$sLanguage];
} else {
$aAttributeNames[$iKey][$sLanguage]['value'] = $aAttribute['default'];
}
}
}
}
return $aAttributeNames;
}
/**
* @param array $aAttributeNames
* @param array $aAttributeValues
* @param Question $oQuestion
* @return mixed
*/
public static function getQuestionTemplateAttributes($aAttributeNames, $aAttributeValues, $oQuestion)
{
if (isset($aAttributeValues['question_template'])) {
if ($aAttributeValues['question_template'] != 'core') {
$oQuestionTemplate = QuestionTemplate::getInstance($oQuestion);
if ($oQuestionTemplate->bHasCustomAttributes) {
// Add the custom attributes to the list
foreach ($oQuestionTemplate->oConfig->custom_attributes->attribute as $oCustomAttribute) {
$sAttributeName = (string) $oCustomAttribute->name;
$aCustomAttribute = json_decode(json_encode((array) $oCustomAttribute), 1);
if (!isset($aCustomAttribute['i18n'])) {
$aCustomAttribute['i18n'] = false;
}
if (!isset($aCustomAttribute['readonly'])) {
$aCustomAttribute['readonly'] = false;
}
$aAttributeNames[$sAttributeName] = $aCustomAttribute;
}
}
}
}
return $aAttributeNames;
}
public function getTypeGroup() {
}
/**
* TODO: replace this function call by $oSurvey->questions defining a relation in SurveyModel
* @param integer $sid
* @param integer $gid
* @param string $language
* @return CDbDataReader
*/
public function getQuestions($sid, $gid, $language)
{
return Yii::app()->db->createCommand()
->select()
->from(self::tableName())
->where(array('and', 'sid=:sid', 'gid=:gid', 'language=:language', 'parent_qid=0'))
->order('question_order asc')
->bindParam(":sid", $sid, PDO::PARAM_INT)
->bindParam(":gid", $gid, PDO::PARAM_INT)
->bindParam(":language", $language, PDO::PARAM_STR)
->query();
}
/**
* This function is only called from surveyadmin.php
* @param integer $iSurveyID
* @param string $sLanguage
* @param string|boolean $sCondition
* @return array
*/
public function getQuestionsWithSubQuestions($iSurveyID, $sLanguage, $sCondition = FALSE)
{
$command = Yii::app()->db->createCommand()
->select('{{questions}}.*, q.qid as sqid, q.title as sqtitle, q.question as sqquestion, '.'{{groups}}.*')
->from($this->tableName())
->leftJoin('{{questions}} q', "q.parent_qid = {{questions}}.qid AND q.language = {{questions}}.language")
->join('{{groups}}', "{{groups}}.gid = {{questions}}.gid AND {{questions}}.language = {{groups}}.language");
$command->where("({{questions}}.sid = '$iSurveyID' AND {{questions}}.language = '$sLanguage' AND {{questions}}.parent_qid = 0)");
if ($sCondition != FALSE) {
$command->where("({{questions}}.sid = :iSurveyID AND {{questions}}.language = :sLanguage AND {{questions}}.parent_qid = 0) AND {$sCondition}")
->bindParam(":iSurveyID", $iSurveyID, PDO::PARAM_STR)
->bindParam(":sLanguage", $sLanguage, PDO::PARAM_STR);
}
$command->order("{{groups}}.group_order asc, {{questions}}.question_order asc");
return $command->query()->readAll();
}
/**
* Delete a bunch of questions in one go
*
* @param mixed $questionsIds
* @return void
*/
public static function deleteAllById($questionsIds)
{
if (!is_array($questionsIds)) {
$questionsIds = array($questionsIds);
}
Yii::app()->db->createCommand()->delete(Condition::model()->tableName(), array('in', 'qid', $questionsIds));
Yii::app()->db->createCommand()->delete(QuestionAttribute::model()->tableName(), array('in', 'qid', $questionsIds));
Yii::app()->db->createCommand()->delete(Answer::model()->tableName(), array('in', 'qid', $questionsIds));
Yii::app()->db->createCommand()->delete(Question::model()->tableName(), array('in', 'parent_qid', $questionsIds));
Yii::app()->db->createCommand()->delete(Question::model()->tableName(), array('in', 'qid', $questionsIds));
Yii::app()->db->createCommand()->delete(DefaultValue::model()->tableName(), array('in', 'qid', $questionsIds));
Yii::app()->db->createCommand()->delete(QuotaMember::model()->tableName(), array('in', 'qid', $questionsIds));
}
/**
* This function is called from everywhere, which is quiet weird...
* TODO: replace it everywhere by Answer::model()->findAll([Critieria Object]) (thumbs up)
*/
function getAllRecords($condition, $order = FALSE)
{
$command = Yii::app()->db->createCommand()->select('*')->from($this->tableName())->where($condition);
if ($order != FALSE) {
$command->order($order);
}
return $command->query();
}
/**
* TODO: replace it everywhere by Answer::model()->findAll([Critieria Object])
* @param string $fields
* @param mixed $condition
* @param string $orderby
* @return array
*/
public function getQuestionsForStatistics($fields, $condition, $orderby = FALSE)
{
$command = Yii::app()->db->createCommand()
->select($fields)
->from(self::tableName())
->where($condition);
if ($orderby != FALSE) {
$command->order($orderby);
}
return $command->queryAll();
}
/**
* @param integer $surveyid
* @param string $language
* @return array
*/
public function getQuestionList($surveyid, $language)
{
$query = "SELECT questions.*, groups.group_name, groups.group_order"
." FROM {{questions}} as questions, {{groups}} as groups"
." WHERE groups.gid=questions.gid"
." AND groups.language=:language1"
." AND questions.language=:language2"
." AND questions.parent_qid=0"
." AND questions.sid=:sid";
return Yii::app()->db->createCommand($query)
->bindParam(":language1", $language, PDO::PARAM_STR)
->bindParam(":language2", $language, PDO::PARAM_STR)
->bindParam(":sid", $surveyid, PDO::PARAM_INT)->queryAll();
}
/**
* @return string
*/
public function getTypedesc()
{
$types = self::typeList();
$typeDesc = $types[$this->type]["description"];
if (YII_DEBUG) {
$typeDesc .= ' <em>'.$this->type.'</em>';
}
return $typeDesc;
}
/**
* This function contains the question type definitions.
* @return array The question type definitions
*
* Explanation of questiontype array:
*
* description : Question description
* subquestions : 0= Does not support subquestions x=Number of subquestion scales
* answerscales : 0= Does not need answers x=Number of answer scales (usually 1, but e.g. for dual scale question set to 2)
* assessable : 0=Does not support assessment values when editing answerd 1=Support assessment values
*/
public static function typeList()
{
$questionTypes = array(
"1" => array(
'description' => gT("Array dual scale"),
'group' => gT('Arrays'),
'subquestions' => 1,
'assessable' => 1,
'hasdefaultvalues' => 0,
'answerscales' => 2),
"5" => array(
'description' => gT("5 Point Choice"),
'group' => gT("Single choice questions"),
'subquestions' => 0,
'hasdefaultvalues' => 0,
'assessable' => 0,
'answerscales' => 0),
"A" => array(
'description' => gT("Array (5 Point Choice)"),
'group' => gT('Arrays'),
'subquestions' => 1,
'hasdefaultvalues' => 0,
'assessable' => 1,
'answerscales' => 0),
"B" => array(
'description' => gT("Array (10 Point Choice)"),
'group' => gT('Arrays'),
'subquestions' => 1,
'hasdefaultvalues' => 0,
'assessable' => 1,
'answerscales' => 0),
"C" => array(
'description' => gT("Array (Yes/No/Uncertain)"),
'group' => gT('Arrays'),
'subquestions' => 1,
'hasdefaultvalues' => 0,
'assessable' => 1,
'answerscales' => 0),
"D" => array(
'description' => gT("Date/Time"),
'group' => gT("Mask questions"),
'subquestions' => 0,
'hasdefaultvalues' => 1,
'assessable' => 0,
'answerscales' => 0),
"E" => array(
'description' => gT("Array (Increase/Same/Decrease)"),
'group' => gT('Arrays'),
'subquestions' => 1,
'hasdefaultvalues' => 0,
'assessable' => 1,
'answerscales' => 0),
"F" => array(
'description' => gT("Array"),
'group' => gT('Arrays'),
'subquestions' => 1,
'hasdefaultvalues' => 0,
'assessable' => 1,
'answerscales' => 1),
"G" => array(
'description' => gT("Gender"),
'group' => gT("Mask questions"),
'subquestions' => 0,
'hasdefaultvalues' => 0,
'assessable' => 0,
'answerscales' => 0),
"H" => array(
'description' => gT("Array by column"),
'group' => gT('Arrays'),
'hasdefaultvalues' => 0,
'subquestions' => 1,
'assessable' => 1,
'answerscales' => 1),
"I" => array(
'description' => gT("Language Switch"),
'group' => gT("Mask questions"),
'hasdefaultvalues' => 0,
'subquestions' => 0,
'assessable' => 0,
'answerscales' => 0),
"K" => array(
'description' => gT("Multiple Numerical Input"),
'group' => gT("Mask questions"),
'hasdefaultvalues' => 1,
'subquestions' => 1,
'assessable' => 1,
'answerscales' => 0),
"L" => array(
'description' => gT("List (Radio)"),
'group' => gT("Single choice questions"),
'subquestions' => 0,
'hasdefaultvalues' => 1,
'assessable' => 1,
'answerscales' => 1),
"M" => array(
'description' => gT("Multiple choice"),
'group' => gT("Multiple choice questions"),
'subquestions' => 1,
'hasdefaultvalues' => 1,
'assessable' => 1,
'answerscales' => 0),
"N" => array(
'description' => gT("Numerical Input"),
'group' => gT("Mask questions"),
'subquestions' => 0,
'hasdefaultvalues' => 1,
'assessable' => 0,
'answerscales' => 0),
"O" => array(
'description' => gT("List with comment"),
'group' => gT("Single choice questions"),
'subquestions' => 0,
'hasdefaultvalues' => 1,
'assessable' => 1,
'answerscales' => 1),
"P" => array(
'description' => gT("Multiple choice with comments"),
'group' => gT("Multiple choice questions"),
'subquestions' => 1,
'hasdefaultvalues' => 1,
'assessable' => 1,
'answerscales' => 0),
"Q" => array(
'description' => gT("Multiple Short Text"),
'group' => gT("Text questions"),
'subquestions' => 1,
'hasdefaultvalues' => 1,
'assessable' => 0,
'answerscales' => 0),
"R" => array(
'description' => gT("Ranking"),
'group' => gT("Mask questions"),
'subquestions' => 0,
'hasdefaultvalues' => 0,
'assessable' => 1,
'answerscales' => 1),
"S" => array(
'description' => gT("Short Free Text"),
'group' => gT("Text questions"),
'subquestions' => 0,
'hasdefaultvalues' => 1,
'assessable' => 0,
'answerscales' => 0),
"T" => array(
'description' => gT("Long Free Text"),
'group' => gT("Text questions"),
'subquestions' => 0,
'hasdefaultvalues' => 1,
'assessable' => 0,
'answerscales' => 0),
"U" => array(
'description' => gT("Huge Free Text"),
'group' => gT("Text questions"),
'subquestions' => 0,
'hasdefaultvalues' => 1,
'assessable' => 0,
'answerscales' => 0),
"X" => array(
'description' => gT("Text display"),
'group' => gT("Mask questions"),
'subquestions' => 0,
'hasdefaultvalues' => 0,
'assessable' => 0,
'answerscales' => 0),
"Y" => array(
'description' => gT("Yes/No"),
'group' => gT("Mask questions"),
'subquestions' => 0,
'hasdefaultvalues' => 1,
'assessable' => 0,
'answerscales' => 0),
"!" => array(
'description' => gT("List (Dropdown)"),
'group' => gT("Single choice questions"),
'subquestions' => 0,
'hasdefaultvalues' => 1,
'assessable' => 1,
'answerscales' => 1),
":" => array(
'description' => gT("Array (Numbers)"),
'group' => gT('Arrays'),
'subquestions' => 2,
'hasdefaultvalues' => 0,
'assessable' => 1,
'answerscales' => 0),
";" => array(
'description' => gT("Array (Texts)"),
'group' => gT('Arrays'),
'subquestions' => 2,
'hasdefaultvalues' => 0,
'assessable' => 0,
'answerscales' => 0),
"|" => array(
'description' => gT("File upload"),
'group' => gT("Mask questions"),
'subquestions' => 0,
'hasdefaultvalues' => 0,
'assessable' => 0,
'answerscales' => 0),
"*" => array(
'description' => gT("Equation"),
'group' => gT("Mask questions"),
'subquestions' => 0,
'hasdefaultvalues' => 0,
'assessable' => 0,
'answerscales' => 0),
);
/**
* @todo Check if this actually does anything, since the values are arrays.
*/
asort($questionTypes);
return $questionTypes;
}
/**
* This function return the class by question type
* @param string question type
* @return string Question class to be added to the container
*
* Maybe move class in typeList ?
*/
public static function getQuestionClass($sType)
{
switch ($sType) {
case "1": return 'array-flexible-duel-scale';
case '5': return 'choice-5-pt-radio';
case 'A': return 'array-5-pt';
case 'B': return 'array-10-pt';
case 'C': return 'array-yes-uncertain-no';
case 'D': return 'date';
case 'E': return 'array-increase-same-decrease';
case 'F': return 'array-flexible-row';
case 'G': return 'gender';
case 'H': return 'array-flexible-column';
case 'I': return 'language';
case 'K': return 'numeric-multi';
case 'L': return 'list-radio';
case 'M': return 'multiple-opt';
case 'N': return 'numeric';
case 'O': return 'list-with-comment';
case 'P': return 'multiple-opt-comments';
case 'Q': return 'multiple-short-txt';
case 'R': return 'ranking';
case 'S': return 'text-short';
case 'T': return 'text-long';
case 'U': return 'text-huge';
//case 'W': return 'list-dropdown-flexible'; // LIST drop-down (flexible label)
case 'X': return 'boilerplate';
case 'Y': return 'yes-no';
case 'Z': return 'list-radio-flexible';
case '!': return 'list-dropdown';
//case '^': return 'slider'; // SLIDER CONTROL
case ':': return 'array-multi-flexi';
case ";": return 'array-multi-flexi-text';
case "|": return 'upload-files';
case "*": return 'equation';
default: return 'generic_question'; // fallback
};
}
/**
* Return all group of the active survey
* Used to render group filter in questions list
*/
public function getAllGroups()
{
return QuestionGroup::model()->findAll("sid=:sid and language=:lang",
array(':sid'=>$this->sid,
':lang'=>$this->survey->language));
//return QuestionGroup::model()->getGroups($this->sid);
}
public function getbuttons()
{
$url = Yii::app()->createUrl("/admin/questions/sa/view/surveyid/");
$url .= '/'.$this->sid.'/gid/'.$this->gid.'/qid/'.$this->qid;
$previewUrl = Yii::app()->createUrl("survey/index/action/previewquestion/sid/");
$previewUrl .= '/'.$this->sid.'/gid/'.$this->gid.'/qid/'.$this->qid;
$editurl = Yii::app()->createUrl("admin/questions/sa/editquestion/surveyid/$this->sid/gid/$this->gid/qid/$this->qid");
$button = '<a class="btn btn-default open-preview" data-toggle="tooltip" title="'.gT("Question preview").'" aria-data-url="'.$previewUrl.'" aria-data-sid="'.$this->sid.'" aria-data-gid="'.$this->gid.'" aria-data-qid="'.$this->qid.'" aria-data-language="'.$this->language.'" href="#" role="button" ><span class="fa fa-eye-open" ></span></a> ';
if (Permission::model()->hasSurveyPermission($this->sid, 'surveycontent', 'update'))
{
$button .= '<a class="btn btn-default" data-toggle="tooltip" title="'.gT("Edit question").'" href="'.$editurl.'" role="button"><span class="fa fa-pencil" ></span></a>';
}
if (Permission::model()->hasSurveyPermission($this->sid, 'surveycontent', 'read'))
{
$button .= '<a class="btn btn-default" data-toggle="tooltip" title="'.gT("Question summary").'" href="'.$url.'" role="button"><span class="fa fa-list-alt" ></span></a>';
}
$oSurvey = Survey::model()->findByPk($this->sid);
if ($oSurvey->active != "Y" && Permission::model()->hasSurveyPermission($this->sid, 'surveycontent', 'delete')) {
$button .= '<a class="btn btn-default" data-toggle="tooltip" title="'.gT("Delete").'" href="#" role="button"
onclick="if (confirm(\' '.gT("Deleting will also delete any answer options and subquestions it includes. Are you sure you want to continue?", "js").' \' )){ '.convertGETtoPOST(Yii::app()->createUrl("admin/questions/sa/delete/surveyid/$this->sid/gid/$this->gid/qid/$this->qid")).'} ">
<span class="text-danger fa fa-trash"></span>
</a>';
}
return $button;
}
public function getOrderedAnswers($random = 0, $alpha = 0)
{
//question attribute random order set?
if ($random == 1) {
$ansquery = "SELECT * FROM {{answers}} WHERE qid='$this->qid' AND language='$this->language' and scale_id=0 ORDER BY ".dbRandom();
}
//question attribute alphasort set?
elseif ($alpha == 1) {
$ansquery = "SELECT * FROM {{answers}} WHERE qid='$this->qid' AND language='$this->language' and scale_id=0 ORDER BY answer";
}
//no question attributes -> order by sortorder
else {
$ansquery = "SELECT * FROM {{answers}} WHERE qid='$this->qid' AND language='$this->language' and scale_id=0 ORDER BY sortorder, answer";
}
$ansresult = dbExecuteAssoc($ansquery)->readAll();
return $ansresult;
}
/**
* get subquestions fort the current question object in the right order
* @param int $random
* @param string $exclude_all_others
* @return array
*/
public function getOrderedSubQuestions($random = 0, $exclude_all_others = '')
{
$criteria = (new CDbCriteria());
$criteria->addCondition('t.parent_qid=:qid');
$criteria->addCondition('t.scale_id=0');
$criteria->addCondition('t.language=:language');
$criteria->params = [':qid'=>$this->qid, ':language'=>$this->language];
$criteria->order = ($random == 1 ? (new CDbExpression(dbRandom())) : 'question_order ASC');
$ansresult = Question::model()->findAll($criteria);
//if exclude_all_others is set then the related answer should keep its position at all times
//thats why we have to re-position it if it has been randomized
if (trim($exclude_all_others) != '' && $random == 1) {
$position = 0;
foreach ($ansresult as $answer) {
if (($answer['title'] == trim($exclude_all_others))) {
if ($position == $answer['question_order'] - 1) { //already in the right position
break;
}
$tmp = array_splice($ansresult, $position, 1);
array_splice($ansresult, $answer['question_order'] - 1, 0, $tmp);
break;
}
$position++;
}
}
return $ansresult;
}
public function getMandatoryIcon()
{
if ($this->type != "X" && $this->type != "|") {
$sIcon = ($this->mandatory == "Y") ? '<span class="fa fa-asterisk text-danger"></span>' : '<span></span>';
} else {
$sIcon = '<span class="fa fa-ban text-danger" data-toggle="tooltip" title="'.gT('Not relevant for this question type').'"></span>';
}
return $sIcon;
}
public function getOtherIcon()
{
if (($this->type == "L") || ($this->type == "!") || ($this->type == "P") || ($this->type == "M")) {
$sIcon = ($this->other === "Y") ? '<span class="fa fa-dot-circle-o"></span>' : '<span></span>';
} else {
$sIcon = '<span class="fa fa-ban text-danger" data-toggle="tooltip" title="'.gT('Not relevant for this question type').'"></span>';
}
return $sIcon;
}
/**
* Get an new title/code for a question
* @param integer $index base for question code (exemple : inde of question when survey import)
* @return string|null : new title, null if impossible
*/
public function getNewTitle($index = 0)
{
$sOldTitle = $this->title;
if ($this->validate(array('title'))) {
return $sOldTitle;
}
/* Maybe it's an old invalid title : try to fix it */
$sNewTitle = preg_replace("/[^A-Za-z0-9]/", '', $sOldTitle);
if (is_numeric(substr($sNewTitle, 0, 1))) {
$sNewTitle = 'q'.$sNewTitle;
}
/* Maybe there are another question with same title try to fix it 10 times */
$attempts = 0;
while (!$this->validate(array('title'))) {
$rand = mt_rand(0, 1024);
$sNewTitle = 'q'.$index.'r'.$rand;
$this->title = $sNewTitle;
$attempts++;
if ($attempts > 10) {
$this->addError('title', 'Failed to resolve question code problems after 10 attempts.');
return null;
}
}
return $sNewTitle;
}
public function search()
{
$pageSize = Yii::app()->user->getState('pageSize', Yii::app()->params['defaultPageSize']);
$sort = new CSort();
$sort->attributes = array(
'question_id'=>array(
'asc'=>'t.qid asc',
'desc'=>'t.qid desc',
),
'question_order'=>array(
'asc'=>'t.question_order asc',
'desc'=>'t.question_order desc',
),
'title'=>array(
'asc'=>'t.title asc',
'desc'=>'t.title desc',
),
'question'=>array(
'asc'=>'t.question asc',
'desc'=>'t.question desc',
),
'group'=>array(
'asc'=>'groups.group_name asc',
'desc'=>'groups.group_name desc',
),
'mandatory'=>array(
'asc'=>'t.mandatory asc',
'desc'=>'t.mandatory desc',
),
'other'=>array(
'asc'=>'t.other asc',
'desc'=>'t.other desc',
),
);
$sort->defaultOrder = array('question_order' => CSort::SORT_ASC);
$criteria = new CDbCriteria;
$criteria->with = array('groups');
$criteria->compare("t.sid", $this->sid, false, 'AND');
$criteria->compare("t.language", $this->language, false, 'AND');
$criteria->compare("t.parent_qid", 0, false, 'AND');
$criteria2 = new CDbCriteria;
$criteria2->compare('t.title', $this->title, true, 'OR');
$criteria2->compare('t.question', $this->title, true, 'OR');
$criteria2->compare('t.type', $this->title, true, 'OR');
$qid_reference = (Yii::app()->db->getDriverName() == 'pgsql' ? ' t.qid::varchar' : 't.qid');
$criteria2->compare($qid_reference, $this->title, true, 'OR');
if ($this->gid != '') {
$criteria->compare('groups.gid', $this->gid, true, 'AND');
}
$criteria->mergeWith($criteria2, 'AND');
$dataProvider = new CActiveDataProvider('Question', array(
'criteria'=>$criteria,
'sort'=>$sort,
'pagination'=>array(
'pageSize'=>$pageSize,
),
));
return $dataProvider;
}
/**
* Make sure we don't save a new question group
* while the survey is active.
*
* @return bool
*/
protected function beforeSave()
{
if (parent::beforeSave()) {
$surveyIsActive = Survey::model()->findByPk($this->sid)->active !== 'N';
if ($surveyIsActive && $this->getIsNewRecord()) {
return false;
}
return true;
} else {
return false;
}
}
/**
* Fix sub question of a parent question
* Must be call after base language subquestion is set
* @todo : move other fix here ?
* @return void
*/
public function fixSubQuestions() {
if ($this->parent_qid) {
return;
}
$oSurvey = $this->survey;
/* Delete sub question in all other language */
$criteria = new CDbCriteria;
$criteria->compare('parent_qid', $this->qid);
$criteria->addNotInCondition('language', $oSurvey->getAllLanguages());
Question::model()->deleteAll($criteria); // Must log count of deleted ?
/* Delete invalid subquestions (not in primary language */
$validSubQuestion = Question::model()->findAll(array(
'select'=>'title',
'condition'=>'parent_qid=:parent_qid AND language=:language',
'params'=>array('parent_qid' => $this->qid, 'language' => $oSurvey->language)
));
$criteria = new CDbCriteria;
$criteria->compare('parent_qid', $this->qid);
$criteria->addNotInCondition('title', CHtml::listData($validSubQuestion, 'title', 'title'));
Question::model()->deleteAll($criteria); // Must log count of deleted ?
}
/** @return string[] */
public static function getQuotableTypes() {
return array('G', 'M', 'Y', 'A', 'B', 'I', 'L', 'O', '!', '*');
}
public function getBasicFieldName() {
if ($this->parent_qid != 0) {