/
em_manager_helper.php
7424 lines (6960 loc) · 359 KB
/
em_manager_helper.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* LimeSurvey
* Copyright (C) 2007-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.
*
* $Id$
*/
/**
* Description of LimeExpressionManager
* This is a wrapper class around ExpressionManager that implements a Singleton and eases
* passing of LimeSurvey variable values into ExpressionManager
*
* @author Thomas M. White (TMSWhite)
*/
include_once('em_core_helper.php');
Yii::app()->loadHelper('database');
Yii::app()->loadHelper('frontend');
Yii::import("application.libraries.Date_Time_Converter");
define('LEM_DEBUG_TIMING',1);
define('LEM_DEBUG_VALIDATION_SUMMARY',2); // also includes SQL error messages
define('LEM_DEBUG_VALIDATION_DETAIL',4);
define('LEM_PRETTY_PRINT_ALL_SYNTAX',32);
define('LEM_DEFAULT_PRECISION',12);
class LimeExpressionManager {
private static $instance;
private $em; // Expression Manager
private $groupRelevanceInfo;
private $sid;
private $sessid; // session name
private $debugLevel=0; // sum of LEM_DEBUG constants - use bitwise AND comparisons to identify which parts to use
private $knownVars; // collection of variable attributes, indexed by SGQA code
private $qcode2sgqa; // maps qcode varname to SGQA code
private $tempVars; // variables temporarily set for substitution purposes
private $pageRelevanceInfo;
private $pageTailorInfo;
private $allOnOnePage=false; // internally set to true for survey.php so get group-specific logging but keep javascript variable namings consistent on the page.
private $surveyMode='group'; // survey mode
private $surveyOptions=array(); // a set of global survey options passed from LimeSurvey
private $qid2code; // array of mappings of Question # to list of SGQA codes used within it
private $jsVar2qid; // reverse mapping of JavaScript Variable name to Question
private $qcode2sgq; // maps name of the variable to the SGQ name
private $alias2varName; // JavaScript array of mappings of aliases to the JavaScript variable names
private $varNameAttr; // JavaScript array of mappings of canonical JavaScript variable name to key attributes.
private $qans; // array of answer lists indexed by qid
private $groupId2groupSeq; // map of gid to 0-based sequence number of groups
private $questionId2questionSeq; // map question # to an incremental count of question order across the whole survey
private $questionId2groupSeq; // map question # to the group it is within, using an incremental count of group order
private $groupSeqInfo; // array of info about each Group, indexed by GroupSeq
private $gseq2relevanceStatus; // tracks which groups have at least one relevant, non-hidden question
private $qid2validationEqn; // maps question # to the validation equation for that question.
private $questionSeq2relevance; // keeps relevance in proper sequence so can minimize relevance processing to see what should be see on page and in indexes
private $currentGroupSeq; // current Group sequence (0-based index)
private $currentQuestionSeq; // for Question-by-Question mode, the 0-based index
private $currentQID; // used in Question-by-Question mode
private $currentQset=NULL; // set of the current set of questions to be displayed, indexed by QID - at least one must be relevant
private $lastMoveResult=NULL; // last result of NavigateForwards, NavigateBackwards, or JumpTo
private $indexQseq; // array of information needed to generate navigation index in question-by-question mode
private $indexGseq; // array of information needed to generate navigation index in group-by-group mode
private $gseq2info; // array of group sequence number to static info
private $maxGroupSeq; // the maximum groupSeq reached - this is needed for Index
private $q2subqInfo; // mapping of questions to information about their subquestions.
private $qattr; // array of attributes for each question
private $subQrelInfo=array(); // list of needed sub-question relevance (e.g. array_filter)
private $gRelInfo=array(); // array of Group-level relevance status
private $runtimeTimings=array();
private $initialized=false;
private $processedRelevance=false;
private $debugTimingMsg='';
private $ParseResultCache; // temporary variable to reduce need to parse same equation multiple times. Used for relevance and validation
private $multiflexiAnswers; // array of 2nd scale answer lists for types ':' and ';' -- needed for convenient print of logic file
private $sgqaNaming = true; // used to specify whether to generate equations using SGQA codes or qcodes
private $numGroups=0;
private $numQuestions=0;
// A private constructor; prevents direct creation of object
private function __construct()
{
self::$instance =& $this;
$this->em = new ExpressionManager();
if (!isset($_SESSION['LEMlang'])) {
$_SESSION['LEMlang'] = 'en'; // so that there is a default
}
}
/**
* Ensures there is only one instances of LEM. Note, if switch between surveys, have to clear this cache
* @return <type>
*/
public static function &singleton()
{
$now = microtime(true);
if (isset($_SESSION['LEMdirtyFlag'])) {
$c = __CLASS__;
self::$instance = new $c;
unset($_SESSION['LEMdirtyFlag']);
}
else if (!isset(self::$instance)) {
if (isset($_SESSION['LEMsingleton'])) {
self::$instance = unserialize($_SESSION['LEMsingleton']);
}
else {
$c = __CLASS__;
self::$instance = new $c;
}
}
else {
// does exist, and OK to cache
return self::$instance;
}
// only record duration if have to create new (or unserialize) an instance
self::$instance->runtimeTimings[] = array(__METHOD__,(microtime(true) - $now));
return self::$instance;
}
// Prevent users to clone the instance
public function __clone()
{
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
/**
* Tells Expression Manager that something has changed enough that needs to eliminate caching
*/
public static function SetDirtyFlag()
{
$_SESSION['LEMdirtyFlag'] = true;
$_SESSION['LEMforceRefresh'] = true;
}
/**
* Set the SurveyId - really checks whether the survey you're about to work with is new, and if so, clears the LEM cache
* @param <type> $sid
*/
public static function SetSurveyId($sid=NULL)
{
if (!is_null($sid)) {
if (isset($_SESSION['LEMsid']) && $sid != $_SESSION['LEMsid']) {
// then trying to use a new survey - so clear the LEM cache
$_SESSION['LEMdirtyFlag'] = true;
}
$_SESSION['LEMsid'] = $sid;
}
}
/**
* Sets the language for Expression Manager. If the language has changed, then EM cache must be invalidated and refreshed
* @param string $lang
*/
public static function SetEMLanguage($lang=NULL)
{
if (is_null($lang)) {
return; // should never happen
}
if (!isset($_SESSION['LEMlang'])) {
$_SESSION['LEMlang'] = $lang;
}
if ($_SESSION['LEMlang'] != $lang) {
// then changing languages, so clear cache
// $_SESSION['LEMdirtyFlag'] = true;
$_SESSION['LEMforceRefresh'] = true;
}
$_SESSION['LEMlang'] = $lang;
}
/**
* Do bulk-update/save of Conditions to Relevance
* @param <type> $surveyId - if NULL, processes the entire database, otherwise just the specified survey
* @param <type> $qid - if specified, just updates that one question
* @return <type>
*/
public static function UpgradeConditionsToRelevance($surveyId=NULL, $qid=NULL)
{
LimeExpressionManager::SetDirtyFlag(); // set dirty flag even if not conditions, since must have had a DB change
// Cheat and upgrade question attributes here too.
self::UpgradeQuestionAttributes(true,$surveyId,$qid);
$releqns = self::ConvertConditionsToRelevance($surveyId,$qid);
$num = count($releqns);
if ($num == 0) {
return NULL;
}
$queries = array();
foreach ($releqns as $key=>$value) {
$query = "UPDATE {{questions}} SET relevance=".Yii::app()->db->quoteValue($value)." WHERE qid=".$key;
dbExecuteAssoc($query);
$queries[] = $query;
}
LimeExpressionManager::SetDirtyFlag();
return $queries;
}
/**
* This reverses UpgradeConditionsToRelevance(). It removes Relevance for questions that have Conditions
* @param <type> $surveyId
* @param <type> $qid
*/
public static function RevertUpgradeConditionsToRelevance($surveyId=NULL, $qid=NULL)
{
LimeExpressionManager::SetDirtyFlag(); // set dirty flag even if not conditions, since must have had a DB change
$releqns = self::ConvertConditionsToRelevance($surveyId,$qid);
$num = count($releqns);
if ($num == 0) {
return NULL;
}
foreach ($releqns as $key=>$value) {
$query = "UPDATE {{questions}} SET relevance=1 WHERE qid=".$key;
dbExecuteAssoc($query);
}
return count($releqns);
}
/**
* If $qid is set, returns the relevance equation generated from conditions (or NULL if there are no conditions for that $qid)
* If $qid is NULL, returns an array of relevance equations generated from Conditions, keyed on the question ID
* @param <type> $surveyId
* @param <type> $qid - if passed, only generates relevance equation for that question - otherwise genereates for all questions with conditions
* @return <type>
*/
public static function ConvertConditionsToRelevance($surveyId=NULL, $qid=NULL)
{
$query = LimeExpressionManager::getConditionsForEM($surveyId,$qid);
$_qid = -1;
$relevanceEqns = array();
$scenarios = array();
$relAndList = array();
$relOrList = array();
foreach($query->readAll() as $row)
{
if ($row['qid'] != $_qid)
{
// output the values for prior question is there was one
if ($_qid != -1)
{
if (count($relOrList) > 0)
{
$relAndList[] = '(' . implode(' or ', $relOrList) . ')';
}
if (count($relAndList) > 0)
{
$scenarios[] = '(' . implode(' and ', $relAndList) . ')';
}
$relevanceEqn = implode(' or ', $scenarios);
$relevanceEqns[$_qid] = $relevanceEqn;
}
// clear for next question
$_qid = $row['qid'];
$_scenario = $row['scenario'];
$_cqid = $row['cqid'];
$relAndList = array();
$relOrList = array();
$scenarios = array();
$releqn = '';
}
if ($row['scenario'] != $_scenario)
{
if (count($relOrList) > 0)
{
$relAndList[] = '(' . implode(' or ', $relOrList) . ')';
}
$scenarios[] = '(' . implode(' and ', $relAndList) . ')';
$relAndList = array();
$relOrList = array();
$_scenario = $row['scenario'];
$_cqid = $row['cqid'];
}
if ($row['cqid'] != $_cqid)
{
$relAndList[] = '(' . implode(' or ', $relOrList) . ')';
$relOrList = array();
$_cqid = $row['cqid'];
}
// fix fieldnames
if ($row['type'] == '' && preg_match('/^{.+}$/',$row['cfieldname'])) {
$fieldname = substr($row['cfieldname'],1,-1); // {TOKEN:xxxx}
$value = $row['value'];
}
else if ($row['type'] == 'M' || $row['type'] == 'P') {
if (substr($row['cfieldname'],0,1) == '+') {
// if prefixed with +, then a fully resolved name
$fieldname = substr($row['cfieldname'],1) . '.NAOK';
$value = $row['value'];
}
else {
// else create name by concatenating two parts together
$fieldname = $row['cfieldname'] . $row['value'] . '.NAOK';
$value = 'Y';
}
}
else {
$fieldname = $row['cfieldname'] . '.NAOK';
$value = $row['value'];
}
// fix values
if (preg_match('/^@\d+X\d+X\d+.*@$/',$value)) {
$value = substr($value,1,-1);
}
else if (preg_match('/^{.+}$/',$value)) {
$value = substr($value,1,-1);
}
else if ($row['method'] == 'RX') {
if (!preg_match('#^/.*/$#',$value))
{
$value = '"/' . $value . '/"'; // if not surrounded by slashes, add them.
}
}
else {
$value = '"' . $value . '"';
}
// add equation
if ($row['method'] == 'RX')
{
$relOrList[] = "regexMatch(" . $value . "," . $fieldname . ")";
}
else
{
// Conditions uses ' ' to mean not answered, but internally it is really stored as ''. Fix this
if ($value === '" "') {
if ($row['method'] == '==') {
$relOrList[] = "is_empty(" . $fieldname . ")";
}
else if ($row['method'] == '!=') {
$relOrList[] = "!is_empty(" . $fieldname . ")";
}
else {
$relOrList[] = $fieldname . " " . $row['method'] . " " . $value;
}
}
else {
$relOrList[] = $fieldname . " " . $row['method'] . " " . $value;
}
}
if ($row['cqid'] == 0 || substr($row['cfieldname'],0,1) == '+') {
$_cqid = -1; // forces this statement to be ANDed instead of being part of a cqid OR group
}
}
// output last one
if ($_qid != -1)
{
if (count($relOrList) > 0)
{
$relAndList[] = '(' . implode(' or ', $relOrList) . ')';
}
if (count($relAndList) > 0)
{
$scenarios[] = '(' . implode(' and ', $relAndList) . ')';
}
$relevanceEqn = implode(' or ', $scenarios);
$relevanceEqns[$_qid] = $relevanceEqn;
}
if (is_null($qid)) {
return $relevanceEqns;
}
else {
if (isset($relevanceEqns[$qid]))
{
$result = array();
$result[$qid] = $relevanceEqns[$qid];
return $result;
}
else
{
return NULL;
}
}
}
/**
* Return list of relevance equations generated from conditions
* @param <type> $surveyId
* @param <type> $qid
* @return <type>
*/
public static function UnitTestConvertConditionsToRelevance($surveyId=NULL, $qid=NULL)
{
$LEM =& LimeExpressionManager::singleton();
return $LEM->ConvertConditionsToRelevance($surveyId, $qid);
}
/**
* Process all question attributes that apply to EM
* (1) Sub-question-level relevance: e.g. array_filter, array_filter_exclude
* (2) Validations: e.g. min/max number of answers; min/max/eq sum of answers
*/
public function _CreateSubQLevelRelevanceAndValidationEqns($onlyThisQseq=NULL)
{
// $now = microtime(true);
$this->subQrelInfo=array(); // reset it each time this is called
$subQrels = array(); // array of sub-question-level relevance equations
$validationEqn = array();
$validationTips = array(); // array of visible tips for validation criteria, indexed by $qid
// Associate these with $qid so that can be nested under appropriate question-level relevance
foreach ($this->q2subqInfo as $qinfo)
{
if (!is_null($onlyThisQseq) && $onlyThisQseq != $qinfo['qseq']) {
continue;
}
else if (!$this->allOnOnePage && $this->currentGroupSeq != $qinfo['gseq']) {
continue; // only need subq relevance for current page.
}
$questionNum = $qinfo['qid'];
$type = $qinfo['type'];
$hasSubqs = (isset($qinfo['subqs']) && count($qinfo['subqs'] > 0));
$qattr = isset($this->qattr[$questionNum]) ? $this->qattr[$questionNum] : array();
if (isset($qattr['input_boxes']) && $qattr['input_boxes'] == '1')
{
$input_boxes='1';
}
else
{
$input_boxes='';
}
// array_filter
// If want to filter question Q2 on Q1, where each have subquestions SQ1-SQ3, this is equivalent to relevance equations of:
// relevance for Q2_SQ1 is Q1_SQ1!=''
if (isset($qattr['array_filter']) && trim($qattr['array_filter']) != '')
{
$array_filter = $qattr['array_filter'];
$sgq = ((isset($this->qcode2sgq[$array_filter])) ? $this->qcode2sgq[$array_filter] : $array_filter);
if ($hasSubqs) {
$subqs = $qinfo['subqs'];
foreach ($subqs as $sq) {
$sq_name = NULL;
switch ($type)
{
case '1': //Array (Flexible Labels) dual scale
case ':': //ARRAY (Multi Flexi) 1 to 10
case ';': //ARRAY (Multi Flexi) Text
case 'A': //ARRAY (5 POINT CHOICE) radio-buttons
case 'B': //ARRAY (10 POINT CHOICE) radio-buttons
case 'C': //ARRAY (YES/UNCERTAIN/NO) radio-buttons
case 'E': //ARRAY (Increase/Same/Decrease) radio-buttons
case 'F': //ARRAY (Flexible) - Row Format
case 'L': //LIST drop-down/radio-button list
case 'M': //Multiple choice checkbox
case 'P': //Multiple choice with comments checkbox + text
case 'K': //MULTIPLE NUMERICAL QUESTION
case 'Q': //MULTIPLE SHORT TEXT
if ($this->sgqaNaming)
{
$sq_name = $sgq . substr($sq['sqsuffix'],1);
}
else
{
$sq_name = $array_filter . $sq['sqsuffix'];
}
break;
default:
break;
}
if (!is_null($sq_name)) {
$subQrels[] = array(
'qtype' => $type,
'type' => 'array_filter',
'rowdivid' => $sq['rowdivid'],
'eqn' => '(' . $sq_name . ' != "")',
'qid' => $questionNum,
'sgqa' => $qinfo['sgqa'],
);
}
}
}
}
// array_filter_exclude
// If want to filter question Q2 on Q1, where each have subquestions SQ1-SQ3, this is equivalent to relevance equations of:
// relevance for Q2_SQ1 is Q1_SQ1==''
if (isset($qattr['array_filter_exclude']) && trim($qattr['array_filter_exclude']) != '')
{
$array_filter_exclude = $qattr['array_filter_exclude'];
$sgq = ((isset($this->qcode2sgq[$array_filter_exclude])) ? $this->qcode2sgq[$array_filter_exclude] : $array_filter_exclude);
if ($hasSubqs) {
$subqs = $qinfo['subqs'];
$sq_names = array();
foreach ($subqs as $sq) {
$sq_name = NULL;
switch ($type)
{
case '1': //Array (Flexible Labels) dual scale
case ':': //ARRAY (Multi Flexi) 1 to 10
case ';': //ARRAY (Multi Flexi) Text
case 'A': //ARRAY (5 POINT CHOICE) radio-buttons
case 'B': //ARRAY (10 POINT CHOICE) radio-buttons
case 'C': //ARRAY (YES/UNCERTAIN/NO) radio-buttons
case 'E': //ARRAY (Increase/Same/Decrease) radio-buttons
case 'F': //ARRAY (Flexible) - Row Format
case 'L': //LIST drop-down/radio-button list
case 'M': //Multiple choice checkbox
case 'P': //Multiple choice with comments checkbox + text
case 'K': //MULTIPLE NUMERICAL QUESTION
case 'Q': //MULTIPLE SHORT TEXT
if ($this->sgqaNaming)
{
$sq_name = $sgq . substr($sq['sqsuffix'],1);
}
else
{
$sq_name = $array_filter_exclude . $sq['sqsuffix'];
}
break;
default:
break;
}
if (!is_null($sq_name)) {
$subQrels[] = array(
'qtype' => $type,
'type' => 'array_filter_exclude',
'rowdivid' => $sq['rowdivid'],
'eqn' => '(' . $sq_name . ' == "")',
'qid' => $questionNum,
'sgqa' => $qinfo['sgqa'],
);
}
}
}
}
// code_filter: WZ
// This can be skipped, since question types 'W' (list-dropdown-flexible) and 'Z'(list-radio-flexible) are no longer supported
// equals_num_value
// Validation:= sum(sq1,...,sqN) == value (which could be an expression).
if (isset($qattr['equals_num_value']) && trim($qattr['equals_num_value']) != '')
{
$equals_num_value = $qattr['equals_num_value'];
if ($hasSubqs) {
$subqs = $qinfo['subqs'];
$sq_names = array();
foreach ($subqs as $sq) {
$sq_name = NULL;
switch ($type)
{
case 'K': //MULTIPLE NUMERICAL QUESTION
if ($this->sgqaNaming)
{
$sq_name = $sq['rowdivid'] . '.NAOK';
}
else
{
$sq_name = $sq['varName'] . '.NAOK';
}
break;
default:
break;
}
if (!is_null($sq_name)) {
$sq_names[] = $sq_name;
}
}
if (count($sq_names) > 0) {
if (!isset($validationEqn[$questionNum]))
{
$validationEqn[$questionNum] = array();
}
// sumEqn and sumRemainingEqn may need to be rounded if using sliders
$precision=LEM_DEFAULT_PRECISION; // default is not to round
if (isset($qattr['slider_layout']) && $qattr['slider_layout']=='1')
{
$precision=0; // default is to round to whole numbers
if (isset($qattr['slider_accuracy']) && trim($qattr['slider_accuracy'])!='')
{
$slider_accuracy = $qattr['slider_accuracy'];
$_parts = explode('.',$slider_accuracy);
if (isset($_parts[1]))
{
$precision = strlen($_parts[1]); // number of digits after mantissa
}
}
}
$sumEqn = 'sum(' . implode(', ', $sq_names) . ')';
$sumRemainingEqn = '(' . $equals_num_value . ' - sum(' . implode(', ', $sq_names) . '))';
$mainEqn = 'sum(' . implode(', ', $sq_names) . ')';
if (!is_null($precision))
{
$sumEqn = 'round(' . $sumEqn . ', ' . $precision . ')';
$sumRemainingEqn = 'round(' . $sumRemainingEqn . ', ' . $precision . ')';
$mainEqn = 'round(' . $mainEqn . ', ' . $precision . ')';
}
$validationEqn[$questionNum][] = array(
'qtype' => $type,
'type' => 'equals_num_value',
'class' => 'sum_range',
'eqn' => '(' . $mainEqn . ' == (' . $equals_num_value . ') || count(' . implode(', ', $sq_names) . ') == 0)',
'qid' => $questionNum,
'sumEqn' => $sumEqn,
'sumRemainingEqn' => $sumRemainingEqn,
);
}
}
}
else
{
$equals_num_value='';
}
// exclude_all_others
if (isset($qattr['exclude_all_others']) && trim($qattr['exclude_all_others']) != '')
{
$exclusive_options = explode(';',$qattr['exclude_all_others']);
if ($hasSubqs) {
foreach ($exclusive_options as $exclusive_option)
{
$exclusive_option = trim($exclusive_option);
if ($exclusive_option == '') {
continue;
}
$subqs = $qinfo['subqs'];
$sq_names = array();
foreach ($subqs as $sq) {
$sq_name = NULL;
if ($sq['csuffix'] == $exclusive_option)
{
continue; // so don't make the excluded option irrelevant
}
switch ($type)
{
case 'M': //Multiple choice checkbox
case 'P': //Multiple choice with comments checkbox + text
if ($this->sgqaNaming)
{
$sq_name = $qinfo['sgqa'] . trim($exclusive_option) . '.NAOK';
}
else
{
$sq_name = $qinfo['sgqa'] . trim($exclusive_option) . '.NAOK';
}
break;
default:
break;
}
if (!is_null($sq_name)) {
$subQrels[] = array(
'qtype' => $type,
'type' => 'exclude_all_others',
'rowdivid' => $sq['rowdivid'],
'eqn' => '(' . $sq_name . ' == "")',
'qid' => $questionNum,
'sgqa' => $qinfo['sgqa'],
);
}
}
}
}
}
else
{
$exclusive_option = '';
}
// exclude_all_others_auto
// TODO
// min_answers
// Validation:= count(sq1,...,sqN) >= value (which could be an expression).
if (isset($qattr['min_answers']) && trim($qattr['min_answers']) != '')
{
$min_answers = $qattr['min_answers'];
if ($hasSubqs) {
$subqs = $qinfo['subqs'];
$sq_names = array();
foreach ($subqs as $sq) {
$sq_name = NULL;
switch ($type)
{
case '1': //Array (Flexible Labels) dual scale
if (substr($sq['varName'],-1,1) == '0')
{
if ($this->sgqaNaming)
{
$base = substr(substr($sq['jsVarName'],4),0,-1);
$sq_name = "if(count(" . $base . "0.NAOK," . $base . "1.NAOK)==2,1,'')";
}
else
{
$base = substr($sq['varName'],0,-1);
$sq_name = "if(count(" . $base . "0.NAOK," . $base . "1.NAOK)==2,1,'')";
}
}
break;
case ':': //ARRAY (Multi Flexi) 1 to 10
case ';': //ARRAY (Multi Flexi) Text
case 'A': //ARRAY (5 POINT CHOICE) radio-buttons
case 'B': //ARRAY (10 POINT CHOICE) radio-buttons
case 'C': //ARRAY (YES/UNCERTAIN/NO) radio-buttons
case 'E': //ARRAY (Increase/Same/Decrease) radio-buttons
case 'F': //ARRAY (Flexible) - Row Format
case 'K': //MULTIPLE NUMERICAL QUESTION
case 'Q': //MULTIPLE SHORT TEXT
case 'M': //Multiple choice checkbox
if ($this->sgqaNaming)
{
$sq_name = substr($sq['jsVarName'],4) . '.NAOK';
}
else
{
$sq_name = $sq['varName'] . '.NAOK';
}
break;
case 'P': //Multiple choice with comments checkbox + text
if (!preg_match('/comment$/',$sq['varName'])) {
if ($this->sgqaNaming)
{
$sq_name = $sq['rowdivid'] . '.NAOK';
}
else
{
$sq_name = $sq['rowdivid'] . '.NAOK';
}
}
break;
case 'R': //RANKING STYLE
// TODO - does not have sub-questions, so how should this be done?
// Current JavaScript works fine, but can't use expression value
break;
default:
break;
}
if (!is_null($sq_name)) {
$sq_names[] = $sq_name;
}
}
if (count($sq_names) > 0) {
if (!isset($validationEqn[$questionNum]))
{
$validationEqn[$questionNum] = array();
}
$validationEqn[$questionNum][] = array(
'qtype' => $type,
'type' => 'min_answers',
'class' => 'num_answers',
'eqn' => '(count(' . implode(', ', $sq_names) . ') >= (' . $min_answers . '))',
'qid' => $questionNum,
);
}
}
}
else
{
$min_answers='';
}
// max_answers
// Validation:= count(sq1,...,sqN) <= value (which could be an expression).
if (isset($qattr['max_answers']) && trim($qattr['max_answers']) != '')
{
$max_answers = $qattr['max_answers'];
if ($hasSubqs) {
$subqs = $qinfo['subqs'];
$sq_names = array();
foreach ($subqs as $sq) {
$sq_name = NULL;
switch ($type)
{
case '1': //Array (Flexible Labels) dual scale
if (substr($sq['varName'],-1,1) == '0')
{
if ($this->sgqaNaming)
{
$base = substr(substr($sq['jsVarName'],4),0,-1);
$sq_name = "if(count(" . $base . "0.NAOK," . $base . "1.NAOK)==2,1,'')";
}
else
{
$base = substr($sq['varName'],0,-1);
$sq_name = "if(count(" . $base . "0.NAOK," . $base . "1.NAOK)==2,1,'')";
}
}
break;
case ':': //ARRAY (Multi Flexi) 1 to 10
case ';': //ARRAY (Multi Flexi) Text
case 'A': //ARRAY (5 POINT CHOICE) radio-buttons
case 'B': //ARRAY (10 POINT CHOICE) radio-buttons
case 'C': //ARRAY (YES/UNCERTAIN/NO) radio-buttons
case 'E': //ARRAY (Increase/Same/Decrease) radio-buttons
case 'F': //ARRAY (Flexible) - Row Format
case 'K': //MULTIPLE NUMERICAL QUESTION
case 'Q': //MULTIPLE SHORT TEXT
case 'M': //Multiple choice checkbox
if ($this->sgqaNaming)
{
$sq_name = substr($sq['jsVarName'],4) . '.NAOK';
}
else
{
$sq_name = $sq['varName'] . '.NAOK';
}
break;
case 'P': //Multiple choice with comments checkbox + text
if (!preg_match('/comment$/',$sq['varName'])) {
if ($this->sgqaNaming)
{
$sq_name = $sq['rowdivid'] . '.NAOK';
}
else
{
$sq_name = $sq['varName'] . '.NAOK';
}
}
break;
case 'R': //RANKING STYLE
// TODO - does not have sub-questions, so how should this be done?
// Current JavaScript works fine, but can't use expression value
break;
default:
break;
}
if (!is_null($sq_name)) {
$sq_names[] = $sq_name;
}
}
if (count($sq_names) > 0) {
if (!isset($validationEqn[$questionNum]))
{
$validationEqn[$questionNum] = array();
}
$validationEqn[$questionNum][] = array(
'qtype' => $type,
'type' => 'max_answers',
'class' => 'num_answers',
'eqn' => '(count(' . implode(', ', $sq_names) . ') <= (' . $max_answers . '))',
'qid' => $questionNum,
);
}
}
}
else
{
$max_answers='';
}
// min_num_value_n
// Validation:= N >= value (which could be an expression).
if (isset($qattr['min_num_value_n']) && trim($qattr['min_num_value_n']) != '')
{
$min_num_value_n = $qattr['min_num_value_n'];
if ($hasSubqs) {
$subqs = $qinfo['subqs'];
$sq_names = array();
$subqValidEqns = array();
foreach ($subqs as $sq) {
$sq_name = NULL;
switch ($type)
{
case 'K': //MULTIPLE NUMERICAL QUESTION
if ($this->sgqaNaming)
{
$sq_name = '(is_empty(' . $sq['rowdivid'] . '.NAOK) || '. $sq['rowdivid'] . '.NAOK >= (' . $min_num_value_n . '))';
}
else
{
$sq_name = '(is_empty(' . $sq['varName'] . '.NAOK) || '. $sq['varName'] . '.NAOK >= (' . $min_num_value_n . '))';
}
$subqValidSelector = $sq['jsVarName_on'];
break;
case 'N': //NUMERICAL QUESTION TYPE
if ($this->sgqaNaming)
{
$sq_name = '(is_empty(' . $sq['rowdivid'] . '.NAOK) || '. $sq['rowdivid'] . '.NAOK >= (' . $min_num_value_n . '))';
}
else
{
$sq_name = '(is_empty(' . $sq['varName'] . '.NAOK) || '. $sq['varName'] . '.NAOK >= (' . $min_num_value_n . '))';
}
$subqValidSelector = '';
break;
default:
break;
}
if (!is_null($sq_name)) {
$sq_names[] = $sq_name;
$subqValidEqns[$subqValidSelector] = array(
'subqValidEqn' => $sq_name,
'subqValidSelector' => $subqValidSelector,
);
}
}
if (count($sq_names) > 0) {
if (!isset($validationEqn[$questionNum]))
{
$validationEqn[$questionNum] = array();
}
$validationEqn[$questionNum][] = array(
'qtype' => $type,
'type' => 'min_num_value_n',
'class' => 'value_range',
'eqn' => implode(' && ', $sq_names),
'qid' => $questionNum,
'subqValidEqns' => $subqValidEqns,
);
}
}
}
else
{
$min_num_value_n='';
}
// max_num_value_n
// Validation:= N <= value (which could be an expression).
if (isset($qattr['max_num_value_n']) && trim($qattr['max_num_value_n']) != '')
{
$max_num_value_n = $qattr['max_num_value_n'];
if ($hasSubqs) {
$subqs = $qinfo['subqs'];
$sq_names = array();
$subqValidEqns = array();
foreach ($subqs as $sq) {
$sq_name = NULL;
switch ($type)
{
case 'K': //MULTIPLE NUMERICAL QUESTION
if ($this->sgqaNaming)
{
$sq_name = '(is_empty(' . $sq['rowdivid'] . '.NAOK) || '. $sq['rowdivid'] . '.NAOK <= (' . $max_num_value_n . '))';
}
else
{
$sq_name = '(is_empty(' . $sq['varName'] . '.NAOK) || '. $sq['varName'] . '.NAOK <= (' . $max_num_value_n . '))';
}
$subqValidSelector = $sq['jsVarName_on'];
break;
case 'N': //NUMERICAL QUESTION TYPE
if ($this->sgqaNaming)
{
$sq_name = '(is_empty(' . $sq['rowdivid'] . '.NAOK) || '. $sq['rowdivid'] . '.NAOK <= (' . $max_num_value_n . '))';
}
else
{
$sq_name = '(is_empty(' . $sq['varName'] . '.NAOK) || '. $sq['varName'] . '.NAOK <= (' . $max_num_value_n . '))';
}
$subqValidSelector = '';
break;
default:
break;
}
if (!is_null($sq_name)) {
$sq_names[] = $sq_name;
$subqValidEqns[$subqValidSelector] = array(
'subqValidEqn' => $sq_name,
'subqValidSelector' => $subqValidSelector,
);
}
}
if (count($sq_names) > 0) {
if (!isset($validationEqn[$questionNum]))
{
$validationEqn[$questionNum] = array();
}
$validationEqn[$questionNum][] = array(
'qtype' => $type,
'type' => 'max_num_value_n',
'class' => 'value_range',
'eqn' => implode(' && ', $sq_names),
'qid' => $questionNum,
'subqValidEqns' => $subqValidEqns,
);
}
}
}
else
{
$max_num_value_n='';
}
// min_num_value
// Validation:= sum(sq1,...,sqN) >= value (which could be an expression).
if (isset($qattr['min_num_value']) && trim($qattr['min_num_value']) != '')
{
$min_num_value = $qattr['min_num_value'];
if ($hasSubqs) {
$subqs = $qinfo['subqs'];
$sq_names = array();
foreach ($subqs as $sq) {
$sq_name = NULL;