/
Question.php
1803 lines (1671 loc) · 69.2 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
/*
* LimeSurvey
* Copyright (C) 2013-2022 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\Helpers\questionHelper;
/**
* Class Question
*
* @property integer $qid Question ID.
* @property integer $sid Survey ID
* @property integer $gid QuestionGroup ID where question is displayed
* @property string $type
* @property string $title Question Code
* @property string $preg
* @property string $other Other option enabled for question (Y/N)
* @property string $mandatory Whether question is mandatory (Y/S/N)
* @property string $encrypted Whether question is encrypted (Y/N)
* @property string $question_theme_name
* @property integer $question_order Question order in greoup
* @property integer $parent_qid Questions parent question ID eg for subquestions
* @property integer $scale_id The scale ID
* @property integer $same_default Saves if user set to use the same default value across languages in default options dialog ('Edit default answers')
* @property string $relevance Questions relevane equation
* @property string $modulename
* @property integer $same_script Whether the same script should be used for all languages
*
* @property Survey $survey
* @property QuestionGroup $group
* @property Question $parent
* @property Question[] $subquestions
* @property QuestionAttribute[] $questionAttributes NB! returns all QuestionArrtibute Models fot this QID regardless of the specified language
* @property QuestionL10n[] $questionl10ns Question Languagesettings indexd by language code
* @property string[] $quotableTypes Question types that can be used for quotas
* @property Answer[] $answers
* @property QuestionType $questionType
* @property array $allSubQuestionIds QID-s of all question subquestions, empty array returned if no subquestions
* @inheritdoc
*/
class Question extends LSActiveRecord
{
const QT_1_ARRAY_DUAL = '1'; // Array Dual scale
const QT_5_POINT_CHOICE = '5';
const QT_A_ARRAY_5_POINT = 'A'; // Array of 5 point choice questions
const QT_B_ARRAY_10_CHOICE_QUESTIONS = 'B'; // Array of 10 point choice questions
const QT_C_ARRAY_YES_UNCERTAIN_NO = 'C'; // ARRAY OF YES\No\gT("Uncertain") QUESTIONS
const QT_D_DATE = 'D';
const QT_E_ARRAY_INC_SAME_DEC = 'E';
const QT_F_ARRAY = 'F';
const QT_G_GENDER = 'G';
const QT_H_ARRAY_COLUMN = 'H';
const QT_I_LANGUAGE = 'I';
const QT_K_MULTIPLE_NUMERICAL = 'K';
const QT_L_LIST = 'L';
const QT_M_MULTIPLE_CHOICE = 'M';
const QT_N_NUMERICAL = 'N';
const QT_O_LIST_WITH_COMMENT = 'O';
const QT_P_MULTIPLE_CHOICE_WITH_COMMENTS = 'P';
const QT_Q_MULTIPLE_SHORT_TEXT = 'Q';
const QT_R_RANKING = 'R';
const QT_S_SHORT_FREE_TEXT = 'S';
const QT_T_LONG_FREE_TEXT = 'T';
const QT_U_HUGE_FREE_TEXT = 'U';
const QT_X_TEXT_DISPLAY = 'X';
const QT_Y_YES_NO_RADIO = 'Y';
const QT_EXCLAMATION_LIST_DROPDOWN = '!';
const QT_VERTICAL_FILE_UPLOAD = '|';
const QT_ASTERISK_EQUATION = '*';
const QT_COLON_ARRAY_NUMBERS = ':';
const QT_SEMICOLON_ARRAY_TEXT = ';';
const START_SORTING_VALUE = 1; //this is the start value for question_order
const DEFAULT_QUESTION_THEME = 'core'; // The question theme name to use when no theme is specified
/** @var string $group_name Stock the active group_name for questions list filtering */
public $group_name;
public $gid;
/** Defaut relevance **/
public $relevance = '';
/** defaut same_script , avoid public break during update **/
public $same_script = 0;
/** @var QuestionTheme cached question theme*/
private $relatedQuestionTheme;
/**
* @inheritdoc
* @return Question
*/
public static function model($className = __CLASS__)
{
/** @var self $model */
$model = parent::model($className);
return $model;
}
/** @inheritdoc */
public function tableName()
{
return '{{questions}}';
}
/** @inheritdoc */
public function primaryKey()
{
return 'qid';
}
/** @inheritdoc */
public function relations()
{
return array(
'survey' => array(self::BELONGS_TO, 'Survey', 'sid'),
'group' => array(self::BELONGS_TO, 'QuestionGroup', 'gid', 'together' => true),
'parent' => array(self::HAS_ONE, 'Question', array("qid" => "parent_qid")),
'questionattributes' => array(self::HAS_MANY, 'QuestionAttribute', 'qid'),
'questionl10ns' => array(self::HAS_MANY, 'QuestionL10n', 'qid', 'together' => true),
'subquestions' => array(
self::HAS_MANY,
'Question',
array('parent_qid' => 'qid'),
'order' => 'subquestions.question_order ASC',
'together' => false
),
'conditions' => array(self::HAS_MANY, 'Condition', 'qid'),
'answers' => array(self::HAS_MANY, 'Answer', 'qid'),
// This relation will fail for non saved questions, which is often the case
// when using question editor on create mode. Better use getQuestionTheme()
'question_theme' => [self::HAS_ONE, 'QuestionTheme', ['question_type' => 'type', 'name' => 'question_theme_name']],
);
}
/**
* @inheritdoc
* TODO: make it easy to read (if possible)
*/
public function rules()
{
/* Basic rules */
$aRules = array(
array('title', 'required', 'on' => 'update, insert, saveall', 'message' => gT('The question code is mandatory.', 'unescaped')),
array('title', 'length', 'min' => 1, 'max' => 20, 'on' => 'update, insert, saveall'),
array('qid,sid,gid,parent_qid', 'numerical', 'integerOnly' => true),
array('qid', 'unique','message' => sprintf(gT("Question id (qid) : '%s' is already in use."), $this->qid)),// Still needed ?
array('other', 'in', 'range' => array('Y', 'N'), 'allowEmpty' => true),
array('mandatory', 'in', 'range' => array('Y', 'S', 'N'), 'allowEmpty' => true),
array('encrypted', '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('relevance', 'LSYii_FilterValidator', 'filter' => 'trim', 'skipOnEmpty' => true),
array('preg', 'safe'),
array('modulename', 'length', 'max' => 255),
array('same_script', 'numerical', 'integerOnly' => true, 'allowEmpty' => true),
);
/* Filtering */
/* other must be no when other is not allowed */
$aRules[] = array('other', 'filter', 'filter' => function ($value) {
if ($this->getAllowOther()) {
return $value;
}
return 'N';
});
/* Don't save empty or 'core' question theme name */
$aRules[] = ['question_theme_name', 'filter', 'filter' => [$this, 'questionThemeNameValidator'] ];
/* Specific rules to avoid collapse with column name in database */
if ($this->parent_qid) {
/* Subquestion specific rules */
/* unicity of title by scale */
$aRules[] = array('title', 'unique', 'caseSensitive' => false,
'criteria' => array(
'condition' => 'sid=:sid AND parent_qid=:parent_qid and scale_id=:scale_id',
'params' => array(
':sid' => $this->sid,
':parent_qid' => $this->parent_qid,
':scale_id' => $this->scale_id
)
),
'message' => gT('Subquestion codes must be unique.'),
'except' => 'saveall'
);
/* Disallow other title if question allow other */
$oParentQuestion = Question::model()->findByPk(array("qid" => $this->parent_qid));
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'
);
}
/* #14495: comment suffix can't be used with P Question */
if ($oParentQuestion->type == "P") {
$aRules[] = array('title', 'match', 'pattern' => '/comment$/', 'not' => true, 'message' => gT("'comment' suffix can not be used with multiple choice with comments."));
}
} else {
/* Question specific rules*/
if ($this->getHasOtherSubquestions()) {
// Disallow other if sub question have 'other' for title
$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'));
}
}
if ($this->survey->isActive) {
$aRules = array_merge($aRules, $this->rulesForActiveSurvey());
}
/* When question exist and are already set with title, allow keep bad title */
if (!$this->isNewRecord) {
$oActualValue = Question::model()->findByPk(array("qid" => $this->qid));
if ($oActualValue && $oActualValue->title == $this->title) {
/* We don't change title, then don't put rules on title */
/* We don't want to broke existing survey, We only disallow to set it or update it according to this value */
return $aRules;
}
}
/**
* Question was new or title was updated : we add minor rules.
* This rules don't broke DB, only potential “ExpressionScript Engine” issue.
* usage of 'archiveimport' scenaruio for import LSA (survey archive) file
**/
if (empty($this->parent_qid)) {
/* Unicity for ExpressionManager */
$aRules[] = array('title', 'unique', 'caseSensitive' => true,
'criteria' => array(
'condition' => 'sid=:sid AND parent_qid=0',
'params' => array(
':sid' => $this->sid
)
),
'message' => gT('Question codes must be unique.'),
'except' => 'archiveimport'
);
/* ExpressionManager basic rule */
$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'
);
/* ExpressionManager reserved word (partial) */
$aRules[] = array('title', 'in', 'not' => true,
'range' => array(
'LANG','SID', // Global var
'SAVEDID','TOKEN', // current survey related var
'QID','GID','SGQ', // current question related var
'self','that','this', // EM reserved variables
),
'message' => sprintf(gT("Code: '%s' is a reserved word."), $this->title), // Usage of {attribute} need attributeLabels, {value} never exist in message
'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' => '/^[a-zA-z0-9]*$/',
'message' => gT('Subquestion codes may only contain alphanumeric characters.'),
'except' => 'archiveimport'
);
}
return $aRules;
}
/**
* return rules specific for activated survey
* @return array
*/
private function rulesForActiveSurvey()
{
$aRules = array();
/* can not update group */
$aRules[] = array('gid', 'LSYii_DisableUpdateValidator');
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, 'parent_qid' => 0),
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
* All questions in the group will be assigned a sequential question order,
* starting in the specified value
* @param int $gid
* @param int $startingOrder the starting question order.
*/
public function updateQuestionOrder($gid, $startingOrder = 1)
{
$data = Yii::app()->db->createCommand()->select('qid')
->where(array('and', 'gid=:gid', 'parent_qid=0'))
->order('question_order, title ASC')
->from('{{questions}}')
->bindParam(':gid', $gid, PDO::PARAM_INT)
->query();
$position = intval($startingOrder);
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
*
* @param string|null $sLanguage If you give a language then only the attributes for that language are returned
* @param string|null $sQuestionThemeOverride Name of the question theme to use instead of the question's current theme
* @return array
*/
public function getAdvancedSettingsWithValues($sLanguage = null, $sQuestionThemeOverride = null)
{
$questionAttributeHelper = new LimeSurvey\Models\Services\QuestionAttributeHelper();
$aAttributes = $questionAttributeHelper->getQuestionAttributesWithValues($this, $sLanguage, $sQuestionThemeOverride, true);
return $aAttributes;
}
/**
* Add custom attributes (if there are any custom attributes). It also removes all attributeNames where inputType is
* empty. Otherwise (not adding and removing anything)it returns the incoming parameter $aAttributeNames.
*
* @param array $aAttributeNames the values from getQuestionAttributesSettings($sType)
* @param array $aAttributeValues $attributeValues['question_template'] != 'core', only if this is true the function changes something
* @param Question $oQuestion this is needed to check if a questionTemplate has custom attributes
* @return mixed returns the incoming parameter $aAttributeNames or
*
* @deprecated use QuestionTheme::getAdditionalAttrFromExtendedTheme() to retrieve question theme attributes and
* QuestionAttributeHelper->mergeQuestionAttributes() to merge with base attributes.
*/
public static function getQuestionTemplateAttributes($aAttributeNames, $aAttributeValues, $oQuestion)
{
if (isset($aAttributeValues['question_template']) && ($aAttributeValues['question_template'] != 'core')) {
if (empty($oQuestion)) {
throw new Exception('oQuestion cannot be empty');
}
$oQuestionTemplate = QuestionTemplate::getInstance($oQuestion);
if ($oQuestionTemplate->bHasCustomAttributes) {
// Add the custom attributes to the list
foreach ($oQuestionTemplate->oConfig->attributes->attribute as $attribute) {
$sAttributeName = (string)$attribute->name;
$sInputType = (string)$attribute->inputtype;
// remove attribute if inputtype is empty
if (empty($sInputType)) {
unset($aAttributeNames[$sAttributeName]);
} else {
$aCustomAttribute = json_decode(json_encode((array)$attribute), 1);
$aCustomAttribute = array_merge(
QuestionAttribute::getDefaultSettings(),
array("category" => gT("Template")),
$aCustomAttribute
);
$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
* @return CDbDataReader
*/
public function getQuestions($sid, $gid)
{
return Yii::app()->db->createCommand()
->select()
->from(self::tableName())
->where(array('and', 'sid=:sid', 'gid=:gid', '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();
}
/**
* 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));
}
/**
* Deletes a question and ALL its relations (subquestions, answers, etc, etc)
* @return bool
* @throws CDbException
*/
public function delete()
{
$ids = array_merge([$this->qid], $this->allSubQuestionIds);
$qidsCriteria = (new CDbCriteria())->addInCondition('qid', $ids);
self::model()->deleteAll((new CDbCriteria())->addInCondition('parent_qid', $ids));
QuestionAttribute::model()->deleteAll($qidsCriteria);
QuestionL10n::model()->deleteAll($qidsCriteria);
QuotaMember::model()->deleteAll($qidsCriteria);
Condition::model()->deleteAll($qidsCriteria);
// delete defaultvalues and defaultvalueL10ns
$oDefaultValues = DefaultValue::model()->findAll((new CDbCriteria())->addInCondition('qid', $ids));
foreach ($oDefaultValues as $defaultvalue) {
DefaultValue::model()->deleteAll('dvid = :dvid', array(':dvid' => $defaultvalue->dvid));
DefaultValueL10n::model()->deleteAll('dvid = :dvid', array(':dvid' => $defaultvalue->dvid));
}
$this->deleteAllAnswers();
$this->removeFromLastVisited();
if (parent::delete()) {
Question::model()->updateQuestionOrder($this->gid);
return true;
}
return false;
}
/**
* remove question from lastVisited
*/
public function removeFromLastVisited()
{
$oCriteria = new CDbCriteria();
$oCriteria->compare('stg_name', 'last_question_%', true, 'AND', false);
$oCriteria->compare('stg_value', $this->qid, false, 'AND');
SettingGlobal::model()->deleteAll($oCriteria);
}
/**
* Delete all subquestions that belong to this question.
*
* @param ?array $exceptIds Don't delete subquestions with these ids.
* @return void
* @todo Duplication from delete()
*/
public function deleteAllSubquestions($exceptIds = [])
{
$ids = !empty($exceptIds)
? array_diff($this->allSubQuestionIds, $exceptIds)
: $this->allSubQuestionIds;
$qidsCriteria = (new CDbCriteria())->addInCondition('qid', $ids);
$res = Question::model()->deleteAll((new CDbCriteria())->addInCondition('qid', $ids));
QuestionAttribute::model()->deleteAll($qidsCriteria);
QuestionL10n::model()->deleteAll($qidsCriteria);
QuotaMember::model()->deleteAll($qidsCriteria);
$defaultValues = DefaultValue::model()->findAll((new CDbCriteria())->addInCondition('qid', $ids));
foreach ($defaultValues as $defaultValue) {
DefaultValue::model()->deleteAll('dvid = :dvid', array(':dvid' => $defaultValue->dvid));
DefaultValueL10n::model()->deleteAll('dvid = :dvid', array(':dvid' => $defaultValue->dvid));
}
}
/**
* Delete all question and its subQuestion Answers
* @param array $exceptIds Don't delete answers with these ids.
* @return void
*/
public function deleteAllAnswers(array $exceptIds = [])
{
$ids = array_merge([$this->qid], $this->allSubQuestionIds);
$qidsCriteria = (new CDbCriteria())->addInCondition('qid', $ids);
$qidsCriteria->addNotInCondition('aid', $exceptIds);
$answerIds = [];
$answers = Answer::model()->findAll($qidsCriteria);
if (!empty($answers)) {
foreach ($answers as $answer) {
$answerIds[] = $answer->aid;
}
}
$aidsCriteria = (new CDbCriteria())->addInCondition('aid', $answerIds);
AnswerL10n::model()->deleteAll($aidsCriteria);
Answer::model()->deleteAll($qidsCriteria);
}
/**
* TODO: replace it everywhere by Answer::model()->findAll([Critieria Object])
* @param string $fields
* @param mixed $condition
* @param string|false $orderby
* @return array
*/
public function getQuestionsForStatistics($fields, $condition, $orderby = false)
{
if ($orderby === false) {
$oQuestions = Question::model()->with('questionl10ns')->findAll(array('condition' => $condition));
} else {
$oQuestions = Question::model()->with('questionl10ns')->findAll(array('condition' => $condition, 'order' => $orderby));
}
$arr = array();
foreach ($oQuestions as $key => $question) {
$arr[$key] = array_merge($question->attributes, current($question->questionl10ns)->attributes);
}
return $arr;
}
/**
* @param integer $surveyid
* @param string $language
* @return Question[]
*/
public function getQuestionList($surveyid)
{
return Question::model()
->with('group')
->findAll(
array(
'condition' => 't.sid=:sid',
/* table name not needed , see #17777 */
'order' => 'group_order,question_order',
'params' => array(':sid' => $surveyid)
)
);
}
/**
* @return string
* NOTE: Not used anymore. Based on a deprecated method. Should be deprecated.
*/
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.
* @param string $language Language for translation
* @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
* @deprecated use QuestionTheme::findQuestionMetaDataForAllTypes() instead
*/
public static function typeList($language = null)
{
$QuestionTypes = QuestionType::modelsAttributes($language);
/**
* @todo Check if this actually does anything, since the values are arrays.
*/
asort($QuestionTypes);
return $QuestionTypes;
}
/**
* This function return the name by question type
* @param string question type
* @return string Question type name
*
* Maybe move class in typeList ?
* @deprecated use $this->>questionType->description instead
*/
public static function getQuestionTypeName($sType)
{
$typeList = self::typeList();
return $typeList[$sType]['description'];
}
/**
* 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 ?
* //TODO move to QuestionType
*/
public static function getQuestionClass($sType)
{
switch ($sType) {
case Question::QT_1_ARRAY_DUAL:
return 'array-flexible-dual-scale';
case Question::QT_5_POINT_CHOICE:
return 'choice-5-pt-radio';
case Question::QT_A_ARRAY_5_POINT:
return 'array-5-pt';
case Question::QT_B_ARRAY_10_CHOICE_QUESTIONS:
return 'array-10-pt';
case Question::QT_C_ARRAY_YES_UNCERTAIN_NO:
return 'array-yes-uncertain-no';
case Question::QT_D_DATE:
return 'date';
case Question::QT_E_ARRAY_INC_SAME_DEC:
return 'array-increase-same-decrease';
case Question::QT_F_ARRAY:
return 'array-flexible-row';
case Question::QT_G_GENDER:
return 'gender';
case Question::QT_H_ARRAY_COLUMN:
return 'array-flexible-column';
case Question::QT_I_LANGUAGE:
return 'language';
case Question::QT_K_MULTIPLE_NUMERICAL:
return 'numeric-multi';
case Question::QT_L_LIST:
return 'list-radio';
case Question::QT_M_MULTIPLE_CHOICE:
return 'multiple-opt';
case Question::QT_N_NUMERICAL:
return 'numeric';
case Question::QT_O_LIST_WITH_COMMENT:
return 'list-with-comment';
case Question::QT_P_MULTIPLE_CHOICE_WITH_COMMENTS:
return 'multiple-opt-comments';
case Question::QT_Q_MULTIPLE_SHORT_TEXT:
return 'multiple-short-txt';
case Question::QT_R_RANKING:
return 'ranking';
case Question::QT_S_SHORT_FREE_TEXT:
return 'text-short';
case Question::QT_T_LONG_FREE_TEXT:
return 'text-long';
case Question::QT_U_HUGE_FREE_TEXT:
return 'text-huge';
case Question::QT_X_TEXT_DISPLAY:
return 'boilerplate';
case Question::QT_Y_YES_NO_RADIO:
return 'yes-no';
case Question::QT_EXCLAMATION_LIST_DROPDOWN:
return 'list-dropdown';
case Question::QT_COLON_ARRAY_NUMBERS:
return 'array-multi-flexi';
case Question::QT_SEMICOLON_ARRAY_TEXT:
return 'array-multi-flexi-text';
case Question::QT_VERTICAL_FILE_UPLOAD:
return 'upload-files';
case Question::QT_ASTERISK_EQUATION:
return 'equation';
default:
return 'generic_question'; // fallback
};
}
public function getbuttons()
{
$url = App()->createUrl("questionAdministration/view/surveyid/$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("questionAdministration/edit/questionId/$this->qid/tabOverviewEditor/editor");
$permission_edit_question = Permission::model()->hasSurveyPermission($this->sid, 'surveycontent', 'update');
$permission_summary_question = Permission::model()->hasSurveyPermission($this->sid, 'surveycontent', 'read');
$permission_delete_question = Permission::model()->hasSurveyPermission($this->sid, 'surveycontent', 'delete');
$dropdownItems = [];
$dropdownItems[] = [
'title' => gT('Edit question'),
'iconClass' => 'ri-pencil-fill',
'url' => $editurl,
'enabledCondition' => $permission_edit_question
];
$dropdownItems[] = [
'title' => gT('Question preview'),
'iconClass' => 'ri-eye-fill',
'linkClass' => 'open-preview',
'linkAttributes' => [
'data-bs-toggle' => 'tooltip',
'aria-data-url' => $previewUrl,
'aria-data-sid' => $this->sid,
'aria-data-gid' => $this->gid,
'aria-data-qid' => $this->qid,
'aria-data-language' => $this->survey->language
]
];
$dropdownItems[] = [
'title' => gT('Question summary'),
'iconClass' => 'ri-list-unordered',
'url' => $url,
'enabledCondition' => $permission_summary_question,
'linkAttributes' => [
'data-bs-toggle' => 'tooltip',
]
];
$oSurvey = Survey::model()->findByPk($this->sid);
$surveyIsNotActive = $oSurvey->active !== 'Y';
$dropdownItems[] = [
'title' => gT('Delete question'),
'iconClass' => 'ri-delete-bin-fill text-danger',
'enabledCondition' => $surveyIsNotActive && $permission_delete_question,
'linkAttributes' => [
'data-bs-toggle' => 'tooltip',
'onclick' => '$.fn.bsconfirm("'
. CHtml::encode(gT("Deleting will also delete any answer options and subquestions it includes. Are you sure you want to continue?"))
. '", {"confirm_ok": "'
. gT("Delete")
. '", "confirm_cancel": "'
. gT("Cancel")
. '"}, function() {'
. convertGETtoPOST(Yii::app()->createUrl("questionAdministration/delete/", ["qid" => $this->qid]))
. "});"
]
];
return App()->getController()->widget(
'ext.admin.grid.GridActionsWidget.GridActionsWidget',
['dropdownItems' => $dropdownItems],
true
);
}
/**
* get the ordered answers
* @param null|integer scale
* @param null|string $language
* @return array
*/
public function getOrderedAnswers($scale_id = null, $language = null)
{
//reset answers set prior to this call
$aAnswerOptions = [
0 => []
];
foreach ($this->answers as $oAnswer) {
if ($scale_id !== null && $oAnswer->scale_id != $scale_id) {
continue;
}
$aAnswerOptions[$oAnswer->scale_id][] = $oAnswer;
}
if ($scale_id !== null) {
return $aAnswerOptions[$scale_id];
}
$aAnswerOptions = $this->sortAnswerOptions($aAnswerOptions, $language);
return $aAnswerOptions;
}
/**
* Returns the specified answer options sorted according to the question attributes.
* Refactored from getOrderedAnswers();
* @param array<int,Answer[]> The answer options to sort
* @param null|string $language
* @return array<int,Answer[]>
*/
private function sortAnswerOptions($answerOptions, $language = null)
{
// Sort randomly if applicable
if ($this->shouldOrderAnswersRandomly()) {
foreach ($answerOptions as $scaleId => $scaleArray) {
$keys = array_keys($scaleArray);
shuffle($keys); // See: https://forum.yiiframework.com/t/order-by-rand-and-total-posts/68099
$sortedScaleAnswers = array();
foreach ($keys as $key) {
$sortedScaleAnswers[$key] = $scaleArray[$key];
}
$answerOptions[$scaleId] = $sortedScaleAnswers;
}
return $answerOptions;
}
// Sort alphabetically if applicable
if ($this->shouldOrderAnswersAlphabetically()) {
if (empty($language) || !in_array($language, $this->survey->allLanguages)) {
$language = $this->survey->language;
}
foreach ($answerOptions as $scaleId => $scaleArray) {
$sorted = array();
// We create an array sorted that will use the answer in the current language as value, and keep key
foreach ($scaleArray as $key => $answer) {
$sorted[$key] = $answer->answerl10ns[$language]->answer;
}
LimeSurvey\Helpers\SortHelper::getInstance($language)->asort($sorted, LimeSurvey\Helpers\SortHelper::SORT_STRING);
// Now, we create a new array that store the old values of $answerOptions in the order of $sorted
$sortedScaleAnswers = array();
foreach ($sorted as $key => $answer) {
$sortedScaleAnswers[] = $scaleArray[$key];
}
$answerOptions[$scaleId] = $sortedScaleAnswers;
}
return $answerOptions;
}
// Sort by Answer's own sort order
foreach ($answerOptions as $scaleId => $scaleArray) {
usort($scaleArray, function ($a, $b) {
return $a->sortorder > $b->sortorder
? 1
: ($a->sortorder < $b->sortorder ? -1 : 0);
});
$answerOptions[$scaleId] = $scaleArray;
}
return $answerOptions;
}
/**
* Returns true if the answer options should be ordered randomly.
* @return bool
*/
private function shouldOrderAnswersRandomly()
{
// Question types supporting both Random Order and Alphabetical Order should
// implement the 'answer_order' attribute instead of using separate attributes.
$answerOrder = $this->getQuestionAttribute('answer_order');
if (!is_null($answerOrder)) {
return $answerOrder == 'random';
}
return $this->getQuestionAttribute('random_order') == 1 && $this->getQuestionType()->subquestions == 0;
}
/**
* Returns true if the answer options should be ordered alphabetically.
* @return bool
*/
private function shouldOrderAnswersAlphabetically()
{
// Question types supporting both Random Order and Alphabetical Order should
// implement the 'answer_order' attribute instead of using separate attributes.
$answerOrder = $this->getQuestionAttribute('answer_order');
if (!is_null($answerOrder)) {
return $answerOrder == 'alphabetical';
}
return $this->getQuestionAttribute('alphasort') == 1;
}
/**
* get subquestions fort the current question object in the right order
* @param int $random
* @param string $exclude_all_others
* @return array
*/
public function getOrderedSubQuestions($scale_id = null)
{
//reset subquestions set prior to this call
$aSubQuestions = [
0 => []
];
$aOrderedSubquestions = $this->subquestions;
if ($this->getQuestionAttribute('random_order') == 1) {
require_once(Yii::app()->basePath . '/libraries/MersenneTwister.php');
ls\mersenne\setSeed($this->sid);
$aOrderedSubquestions = ls\mersenne\shuffle($aOrderedSubquestions);
} else {
usort($aOrderedSubquestions, function ($oQuestionA, $oQuestionB) {
if ($oQuestionA->question_order == $oQuestionB->question_order) {
return 0;
}
return $oQuestionA->question_order < $oQuestionB->question_order ? -1 : 1;
});
}
$excludedSubquestion = null;
foreach ($aOrderedSubquestions as $i => $oSubquestion) {
if ($scale_id !== null && $oSubquestion->scale_id != $scale_id) {
continue;
}
//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 (
($this->getQuestionAttribute('exclude_all_others') != '' && $this->getQuestionAttribute('random_order') == 1)
&& ($oSubquestion->title == $this->getQuestionAttribute('exclude_all_others'))
) {
$excludedSubquestionPosition = (safecount($aSubQuestions[$oSubquestion->scale_id]) - 1);
$excludedSubquestion = $oSubquestion;
continue;
}
$aSubQuestions[$oSubquestion->scale_id][] = $oSubquestion;
}
if ($excludedSubquestion != null) {
array_splice($aSubQuestions[$excludedSubquestion->scale_id], ($excludedSubquestion->question_order - 1), 0, [$excludedSubquestion]);
}
if ($scale_id !== null) {
return $aSubQuestions[$scale_id];
}
return $aSubQuestions;
}
public function getMandatoryIcon()
{
if ($this->type != Question::QT_X_TEXT_DISPLAY && $this->type != Question::QT_VERTICAL_FILE_UPLOAD) {
if ($this->mandatory == "Y") {
$sIcon = '<span class="ri-star-fill text-danger"></span>';
} elseif ($this->mandatory == "S") {
$sIcon = '<span class="ri-star-fill text-danger"> ' . gT('Soft') . '</span>';
} else {
$sIcon = '<span></span>';
}
} else {
$sIcon = '<span class="ri-forbid-2-line text-danger" data-bs-toggle="tooltip" title="' . gT('Not relevant for this question type') . '"></span>';
}
return $sIcon;
}
/**
* Return other icon according to state
* @return boolean
*/
public function getOtherIcon()
{
if ($this->getAllowOther()) {
$sIcon = ($this->other === "Y") ? '<span class="ri-record-circle-line"></span>' : '<span></span>';
} else {
$sIcon = '<span class="ri-forbid-2-line text-danger" data-bs-toggle="tooltip" title="' . gT('Not relevant for this question type') . '"></span>';
}
return $sIcon;
}
/**
* Return if question allow other
* @return boolean
*/
public function getAllowOther()
{
return (
!$this->parent_qid
&& $this->getQuestionType()->other
);
}
/**
* Return if question has managed subquestions
* usage in rules : allow set other even if existing subquestions 'other' exist (but deleted after)
* @return boolean
*/
public function getAllowSubquestions()
{
return (
!$this->parent_qid
&& $this->getQuestionType()->subquestions