/
em_manager_helper.php
1247 lines (1153 loc) · 58.5 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
/**
* 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
*/
include_once('em_core_helper.php');
class LimeExpressionManager {
private static $instance;
private static $em; // Expression Manager
private $groupRelevanceInfo;
private $groupNum;
private $debugLEM = true; // set this to false to turn off debugging
private $knownVars;
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 $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 $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 $pageTailoringLog; // Debug log of tailorings done on this page
private $surveyLogicFile; // Shows current configuration and data from most recent $fieldmap
// A private constructor; prevents direct creation of object
private function __construct()
{
self::$instance =& $this;
$this->em = new ExpressionManager();
}
// The singleton method
public static function &singleton()
{
if (!isset(self::$instance)) {
$c = __CLASS__;
self::$instance = new $c;
}
return self::$instance;
}
// Prevent users to clone the instance
public function __clone()
{
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
/**
* 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)
{
$releqns = self::ConvertConditionsToRelevance($surveyId,$qid);
$num = count($releqns);
if ($num == 0) {
return NULL;
}
$data = array();
foreach ($releqns as $key=>$value) {
$data[] = array(
'qid' => $key,
'attribute' => 'relevance',
'value' => $value,
);
}
$CI =& get_instance();
$CI->db->where('attribute','relevance')->where_in('qid',array_keys($releqns))->delete('question_attributes');
$CI->db->insert_batch('question_attributes',$data);
return $releqns;
}
/**
* This partially reverses UpgradeConditionsToRelevance(). It removes Relevance for questions that have Conditions
* @param <type> $surveyId
* @param <type> $qid
*/
public static function RevertUpgradeConditionsToRelevance($surveyId=NULL, $qid=NULL)
{
$releqns = self::ConvertConditionsToRelevance($surveyId,$qid);
$num = count($releqns);
if ($num == 0) {
return NULL;
}
$CI =& get_instance();
$CI->db->where('attribute','relevance')->where_in('qid',array_keys($releqns))->delete('question_attributes');
return $CI->db->affected_rows();
}
/**
* 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)
{
$CI =& get_instance();
$CI->load->model('conditions_model');
$query = $CI->conditions_model->getAllRecordsForSurvey($surveyId,$qid);
$_qid = -1;
$relevanceEqns = array();
$scenarios = array();
$relAndList = array();
$relOrList = array();
foreach($query->result_array() 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(' and ', $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);
$value = $row['value'];
}
else {
// else create name by concatenating two parts together
$fieldname = $row['cfieldname'] . $row['value'];
$value = 'Y';
}
}
else {
$fieldname = $row['cfieldname'];
$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 {
$value = '"' . $value . '"';
}
// add equation
if ($row['method'] == 'RX')
{
$relOrList[] = "regexMatch(" . $value . "," . $fieldname . ")";
}
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(' and ', $scenarios);
$relevanceEqns[$_qid] = $relevanceEqn;
}
if (is_null($qid)) {
return $relevanceEqns;
}
else {
if (isset($relevanceEqns[$qid]))
{
return $relevanceEqns[$qid];
}
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);
}
/**
* Create the arrays needed by ExpressionManager to process LimeSurvey strings.
* The long part of this function should only be called once per page display (e.g. only if $fieldMap changes)
*
* @param <type> $forceRefresh
* @param <type> $anonymized
* @return boolean - true if $fieldmap had been re-created, so ExpressionManager variables need to be re-set
*/
public function setVariableAndTokenMappingsForExpressionManager($surveyid,$forceRefresh=false,$anonymized=false,$allOnOnePage=false)
{
// TODO - this is called multiple times per page - can it be reduced to once per page?
log_message('debug','Start LEM::setVariableAndTokenMappingsForExpressionManager');
$fieldmap=createFieldMap($surveyid,$style='full',$forceRefresh);
if (!isset($fieldmap)) {
return false; // implies an error occurred
}
$this->knownVars = array(); // mapping of VarName to Value
$this->debugLog = array(); // array of mappings among values to confirm their accuracy
$this->qid2code = array(); // List of codes for each question - needed to know which to NULL if a question is irrelevant
$this->jsVar2qid = array();
$this->alias2varName = array();
$this->varNameAttr = array();
$CI =& get_instance();
$clang = $CI->limesurvey_lang;
$presets = array();
$presets['G'] = array( //GENDER drop-down list
'M' => $clang->gT("Male"),
'F' => $clang->gT("Female"),
);
$presets['Y'] = array( //YES/NO radio-buttons
'Y' => $clang->gT("Yes"),
'N' => $clang->gT("No"),
);
$presets['C'] = array( //ARRAY (YES/UNCERTAIN/NO) radio-buttons
'Y' => $clang->gT("Yes"),
'N' => $clang->gT("No"),
'U' => $clang->gT("Uncertain"),
);
$presets['E'] = array( //ARRAY (Increase/Same/Decrease) radio-buttons
'I' => $clang->gT("Increase"),
'S' => $clang->gT("Same"),
'D' => $clang->gT("Decrease"),
);
$CI->load->model('question_attributes_model');
$qattr = $CI->question_attributes_model->getEMRelatedRecordsForSurvey($surveyid); // what happens if $surveyid is null?
$CI->load->model('answers_model');
$qans = $CI->answers_model->getAllAnswersForEM($surveyid);
foreach($fieldmap as $fielddata)
{
$code = $fielddata['fieldname'];
$type = $fielddata['type'];
if (!preg_match('#^\d+X\d+X\d+#',$code))
{
continue; // not an SGQA value
}
$mandatory = $fielddata['mandatory'];
$fieldNameParts = explode('X',$code);
$groupNum = $fieldNameParts[1];
$isOnCurrentPage = ($allOnOnePage || ($groupNum != NULL && $groupNum == $this->groupNum)) ? 'Y' : 'N';
$questionId = $fieldNameParts[2];
$questionNum = $fielddata['qid'];
$relevance = (isset($qattr[$questionNum]['relevance'])) ? $qattr[$questionNum]['relevance'] : 1;
$hidden = (isset($qattr[$questionNum]['hidden'])) ? $qattr[$questionNum]['hidden'] : 'N';
$scale_id = (isset($fielddata['scale_id'])) ? $fielddata['scale_id'] : '0';
// Create list of codes associated with each question
$codeList = (isset($this->qid2code[$questionNum]) ? $this->qid2code[$questionNum] : '');
if ($codeList == '')
{
$codeList = $code;
}
else
{
$codeList .= '|' . $code;
}
$this->qid2code[$questionNum] = $codeList;
// Check off-page relevance status
if (isset($_SESSION['relevanceStatus'])) {
$relStatus = (isset($_SESSION['relevanceStatus'][$questionId]) ? $_SESSION['relevanceStatus'][$questionId] : 1);
}
else {
$relStatus = 1;
}
$readWrite = 'N';
$codeValue = (isset($_SESSION[$code])) ? $_SESSION[$code] : '';
$displayValue = ''; // default to blank or $clang->gT("No Answer")?
switch($type)
{
case '!': //List - dropdown
case 'L': //LIST drop-down/radio-button list
case 'O': //LIST WITH COMMENT drop-down/radio-button list + textarea
case '1': //Array (Flexible Labels) dual scale // need scale
case 'H': //ARRAY (Flexible) - Column Format
case 'F': //ARRAY (Flexible) - Row Format
case 'R': //RANKING STYLE
$which_ans = $scale_id . '~' . $codeValue;
$displayValue = (isset($qans[$questionNum][$which_ans])) ? $qans[$questionNum][$which_ans] : ''; // what should default be?
$ansArray = $qans[$questionNum];
break;
case 'A': //ARRAY (5 POINT CHOICE) radio-buttons
case 'B': //ARRAY (10 POINT CHOICE) radio-buttons
case ':': //ARRAY (Multi Flexi) 1 to 10
case '5': //5 POINT CHOICE radio-buttons
$displayValue = $codeValue; // what about "no answer"?
break;
case 'N': //NUMERICAL QUESTION TYPE
case 'K': //MULTIPLE NUMERICAL QUESTION
case 'Q': //MULTIPLE SHORT TEXT
case ';': //ARRAY (Multi Flexi) Text
case 'S': //SHORT FREE TEXT
case 'T': //LONG FREE TEXT
case 'U': //HUGE FREE TEXT
case 'M': //Multiple choice checkbox
case 'P': //Multiple choice with comments checkbox + text
case 'D': //DATE
case '*': //Equation
case 'I': //Language Question
case '|': //File Upload
case 'X': //BOILERPLATE QUESTION
$displayValue = $codeValue; // TODO - is this correct?
$ansArray = NULL;
break;
case 'G': //GENDER drop-down list
case 'Y': //YES/NO radio-buttons
case 'C': //ARRAY (YES/UNCERTAIN/NO) radio-buttons
case 'E': //ARRAY (Increase/Same/Decrease) radio-buttons
$displayValue = (isset($presets[$type][$codeValue])) ? $presets[$type][$codeValue] : '';
$ansArray = $presets[$type];
break;
}
switch($type)
{
case '!': //List - dropdown
case '5': //5 POINT CHOICE radio-buttons
case 'D': //DATE
case 'G': //GENDER drop-down list
case 'I': //Language Question
case 'L': //LIST drop-down/radio-button list
case 'N': //NUMERICAL QUESTION TYPE
case 'O': //LIST WITH COMMENT drop-down/radio-button list + textarea
case 'S': //SHORT FREE TEXT
case 'T': //LONG FREE TEXT
case 'U': //HUGE FREE TEXT
case 'X': //BOILERPLATE QUESTION
case 'Y': //YES/NO radio-buttons
case '|': //File Upload
case '*': //Equation
$varName = $fielddata['title'];
$question = $fielddata['question'];
break;
case '1': //Array (Flexible Labels) dual scale
$varName = $fielddata['title'] . '_' . $fielddata['aid'] . '_' . $fielddata['scale_id'];
$question = $fielddata['question'] . ': ' . $fielddata['subquestion'] . '[' . $fielddata['scale'] . ']';
break;
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 'H': //ARRAY (Flexible) - Column Format
case 'K': //MULTIPLE NUMERICAL QUESTION
case 'M': //Multiple choice checkbox
case 'P': //Multiple choice with comments checkbox + text
case 'Q': //MULTIPLE SHORT TEXT
case 'R': //RANKING STYLE
$varName = $fielddata['title'] . '_' . $fielddata['aid'];
$question = $fielddata['question'] . ': ' . $fielddata['subquestion'];
break;
case ':': //ARRAY (Multi Flexi) 1 to 10
case ';': //ARRAY (Multi Flexi) Text
$varName = $fielddata['title'] . '_' . $fielddata['aid'];
$question = $fielddata['question'] . ': ' . $fielddata['subquestion1'] . '[' . $fielddata['subquestion2'] . ']';
break;
}
switch($type)
{
case 'R': //RANKING STYLE
if ($isOnCurrentPage=='Y')
{
$jsVarName = 'fvalue_' . $fieldNameParts[2];
}
else
{
$jsVarName = 'java' . $code;
}
break;
case 'D': //DATE
case 'N': //NUMERICAL QUESTION TYPE
case 'S': //SHORT FREE TEXT
case 'T': //LONG FREE TEXT
case 'U': //HUGE FREE TEXT
case 'Q': //MULTIPLE SHORT TEXT
case 'K': //MULTIPLE NUMERICAL QUESTION
case 'X': //BOILERPLATE QUESTION
if ($isOnCurrentPage=='Y')
{
$jsVarName = 'answer' . $code;
}
else
{
$jsVarName = 'java' . $code;
}
break;
case '!': //List - dropdown
case '5': //5 POINT CHOICE radio-buttons
case 'G': //GENDER drop-down list
case 'I': //Language Question
case 'L': //LIST drop-down/radio-button list
case 'Y': //YES/NO radio-buttons
case '*': //Equation
case '1': //Array (Flexible Labels) dual scale
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 'H': //ARRAY (Flexible) - Column Format
case 'M': //Multiple choice checkbox
case ':': //ARRAY (Multi Flexi) 1 to 10
case ';': //ARRAY (Multi Flexi) Text
$jsVarName = 'java' . $code;
break;
case 'O': //LIST WITH COMMENT drop-down/radio-button list + textarea
if (preg_match("/comment$/", $code)) {
$jsVarName = 'java' . $code;
$varName = $varName . "_comment";
}
else {
$jsVarName = 'java' . $code;
}
break;
case '|': //File Upload
// Only want the use the one that ends in '_filecount'
$goodcode = preg_replace("/^(.*?)(_filecount)?$/","$1",$code);
$jsVarName = $goodcode . '_filecount';
break;
case 'P': //Multiple choice with comments checkbox + text
if (preg_match("/comment$/",$code) && $isOnCurrentPage=='Y')
{
$jsVarName = 'answer' . $code; // is this true for survey.php and not for group.php?
}
else
{
$jsVarName = 'java' . $code;
}
break;
}
// Set mappings of variable names to needed attributes
$varInfo_Code = array(
'codeValue'=>$codeValue,
'jsName'=>$jsVarName,
'readWrite'=>$readWrite,
'isOnCurrentPage'=>$isOnCurrentPage,
'displayValue'=>$displayValue,
'hidden'=>$hidden,
'question'=>$question,
'qid'=>$questionNum,
'relevance'=>$relevance,
'relevanceNum'=>'relevance' . $questionNum,
'relevanceStatus'=>$relStatus,
'qcode'=>$varName,
);
$this->knownVars[$varName] = $varInfo_Code;
$this->knownVars['INSERTANS:' . $code] = $varInfo_Code; // $varInfo_DisplayVal;
$this->knownVars[$code] = $varInfo_Code;
$this->jsVar2qid[$jsVarName] = $questionNum;
// Create JavaScript arrays
$this->alias2varName[$varName] = array('jsName'=>$jsVarName, 'jsPart' => "'" . $varName . "':'" . $jsVarName . "'");
$this->alias2varName[$jsVarName] = array('jsName'=>$jsVarName, 'jsPart' => "'" . $jsVarName . "':'" . $jsVarName . "'");
$this->alias2varName[$code] = array('jsName'=>$jsVarName, 'jsPart' => "'" . $code . "':'" . $jsVarName . "'");
$this->alias2varName['INSERTANS:' . $code] = array('jsName'=>$jsVarName, 'jsPart' => "'INSERTANS:" . $code . "':'" . $jsVarName . "'");
// TODO - should these arrays only be built for questions that require substitution at run-time?
$ansList = '';
if (isset($ansArray) && !is_null($ansArray)) {
$answers = array();
foreach ($ansArray as $key => $value) {
$answers[] = "'" . $key . "':'" . htmlspecialchars(preg_replace('/[[:space:]]/',' ',$value),ENT_QUOTES) . "'";
}
$ansList = ",'answers':{ " . implode(",",$answers) . "}";
}
$this->varNameAttr[$jsVarName] = "'" . $jsVarName . "':{ "
. "'jsName':'" . $jsVarName
// . "','code':'" . htmlspecialchars(preg_replace('/[[:space:]]/',' ',$codeValue),ENT_QUOTES)
. "','qid':" . $questionNum
. ",'mandatory':'" . $mandatory
. "','question':'" . htmlspecialchars(preg_replace('/[[:space:]]/',' ',$question),ENT_QUOTES)
. "','type':'" . $type
. "','relevance':'" . htmlspecialchars(preg_replace('/[[:space:]]/',' ',$relevance),ENT_QUOTES)
. "','shown':'" . htmlspecialchars(preg_replace('/[[:space:]]/',' ',$displayValue),ENT_QUOTES)
. "'".$ansList."}";
if ($this->debugLEM)
{
$this->debugLog[] = array(
'code' => $code,
'type' => $type,
'varname' => $varName,
'jsName' => $jsVarName,
'question' => $question,
'codeValue' => ($codeValue=='') ? ' ' : $codeValue,
'displayValue' => ($displayValue=='') ? ' ' : $displayValue,
'readWrite' => $readWrite,
'isOnCurrentPage' => $isOnCurrentPage,
'relevance' => $relevance,
'hidden' => $hidden,
);
}
}
// Now set tokens
if (isset($_SESSION['token']) && $_SESSION['token'] != '')
{
//Gather survey data for tokenised surveys, for use in presenting questions
$_SESSION['thistoken']=getTokenData($surveyid, $_SESSION['token']);
}
if (isset($_SESSION['thistoken']))
{
foreach (array_keys($_SESSION['thistoken']) as $tokenkey)
{
if ($anonymized)
{
$val = "";
}
else
{
$val = $_SESSION['thistoken'][$tokenkey];
}
$key = "TOKEN:" . strtoupper($tokenkey);
$this->knownVars[$key] = array(
'codeValue'=>$val,
'jsName'=>'',
'readWrite'=>'N',
'isOnCurrentPage'=>'N',
'relevanceNum'=>'',
'relevanceStatus'=>'1',
);
if ($this->debugLEM)
{
$this->debugLog[] = array(
'code' => $key,
'type' => ' ',
'varname' => ' ',
'jsName' => ' ',
'question' => ' ',
'codeValue' => ' ',
'displayValue' => $val,
'readWrite'=>'N',
'isOnCurrentPage'=>'N',
'relevance'=>'',
'hidden'=>'',
);
}
}
}
else
{
// Explicitly set all tokens to blank
$blankVal = array(
'codeValue'=>'',
'jsName'=>'',
'readWrite'=>'N',
'isOnCurrentPage'=>'N',
'relevanceNum'=>'',
'relevanceStatus'=>'1',
);
$this->knownVars['TOKEN:FIRSTNAME'] = $blankVal;
$this->knownVars['TOKEN:LASTNAME'] = $blankVal;
$this->knownVars['TOKEN:EMAIL'] = $blankVal;
$this->knownVars['TOKEN:USESLEFT'] = $blankVal;
for ($i=1;$i<=100;++$i) // TODO - is there a way to know how many attributes are set? Looks like max is 100
{
$this->knownVars['TOKEN:ATTRIBUTE_' . $i] = $blankVal;
}
}
if ($this->debugLEM)
{
$debugLog_html = "<table border='1'>";
$debugLog_html .= "<tr><th>Code</th><th>Type</th><th>VarName</th><th>CodeVal</th><th>DisplayVal</th><th>JSname</th><th>Writable?</th><th>Set On This Page?</th><th>Relevance</th><th>Hidden</th><th>Question</th></tr>";
foreach ($this->debugLog as $t)
{
$debugLog_html .= "<tr><td>" . $t['code']
. "</td><td>" . $t['type']
. "</td><td>" . $t['varname']
. "</td><td>" . $t['codeValue']
. "</td><td>" . $t['displayValue']
. "</td><td>" . $t['jsName']
. "</td><td>" . $t['readWrite']
. "</td><td>" . $t['isOnCurrentPage']
. "</td><td>" . $t['relevance']
. "</td><td>" . $t['hidden']
. "</td><td>" . $t['question']
. "</td></tr>";
}
$debugLog_html .= "</table>";
$this->surveyLogicFile = $debugLog_html;
}
log_message('debug','Finish LEM::setVariableAndTokenMappingsForExpressionManager');
return true;
}
/**
* Translate all Expressions, Macros, registered variables, etc. in $string
* @param <type> $string - the string to be replaced
* @param <type> $replacementFields - optional replacement values
* @param boolean $debug - if true,write translations for this page to html-formatted log file
* @param <type> $numRecursionLevels - the number of times to recursively subtitute values in this string
* @param <type> $whichPrettyPrintIteration - if want to pretty-print the source string, which recursion level should be pretty-printed
* @return <type> - the original $string with all replacements done.
*/
static function ProcessString($string, $questionNum=NULL, $replacementFields=array(), $debug=false, $numRecursionLevels=1, $whichPrettyPrintIteration=1, $noReplacements=false)
{
$LEM =& LimeExpressionManager::singleton();
if ($noReplacements) {
$LEM->em->SetPrettyPrintSource($string);
return $string;
}
if (isset($replacementFields) && is_array($replacementFields) && count($replacementFields) > 0)
{
$replaceArray = array();
foreach ($replacementFields as $key => $value) {
$replaceArray[$key] = array(
'codeValue'=>$value,
'jsName'=>'',
'readWrite'=>'N',
'isOnCurrentPage'=>'N',
);
}
$LEM->em->RegisterVarnamesUsingMerge($replaceArray); // TODO - is it safe to just merge these in each time, or should a refresh be forced?
}
$result = $LEM->em->sProcessStringContainingExpressions(htmlspecialchars_decode($string,ENT_QUOTES),(is_null($questionNum) ? 0 : $questionNum), $numRecursionLevels, $whichPrettyPrintIteration);
if ($LEM->debugLEM)
{
$varsUsed = $LEM->em->GetJSVarsUsed();
if (is_array($varsUsed) and count($varsUsed) > 0) {
$LEM->pageTailoringLog .= '<tr><td>' . $LEM->groupNum . '</td><td>' . $string . '</td><td>' . $LEM->em->GetLastPrettyPrintExpression() . '</td><td>' . $result . "</td></tr>\n";
}
}
return $result;
}
/**
* Compute Relevance, processing $eqn to get a boolean value. If there are syntax errors, currently returns true. My change to returning null so can look for errors?
* @param <type> $eqn
* @return <type>
*/
static function ProcessRelevance($eqn,$questionNum=NULL,$jsResultVar=NULL,$type=NULL,$hidden=0)
{
// These will be called in the order that questions are supposed to be asked
$LEM =& LimeExpressionManager::singleton();
if (!isset($eqn) || trim($eqn=='') || trim($eqn)=='1')
{
$LEM->groupRelevanceInfo[] = array(
'qid' => $questionNum,
'eqn' => $eqn,
'result' => true,
'numJsVars' => 0,
'relevancejs' => '',
'relevanceVars' => '',
'jsResultVar'=> $jsResultVar,
'type'=>$type,
'hidden'=>$hidden,
);
return true;
}
$result = $LEM->em->ProcessBooleanExpression(htmlspecialchars_decode($eqn,ENT_QUOTES));
$jsVars = $LEM->em->GetJSVarsUsed();
$relevanceVars = implode('|',$LEM->em->GetJSVarsUsed());
$relevanceJS = $LEM->em->GetJavaScriptEquivalentOfExpression();
$LEM->groupRelevanceInfo[] = array(
'qid' => $questionNum,
'eqn' => $eqn,
'result' => $result,
'numJsVars' => count($jsVars),
'relevancejs' => $relevanceJS,
'relevanceVars' => $relevanceVars,
'jsResultVar' => $jsResultVar,
'type'=>$type,
'hidden'=>$hidden,
);
return $result;
}
/**
* Used to show potential syntax errors of processing Relevance or Equations.
* @return <type>
*/
static function GetLastPrettyPrintExpression()
{
$LEM =& LimeExpressionManager::singleton();
return $LEM->em->GetLastPrettyPrintExpression();
}
static function StartProcessingPage($debug=true,$allOnOnePage=false)
{
$LEM =& LimeExpressionManager::singleton();
$LEM->pageRelevanceInfo=array();
$LEM->pageTailorInfo=array();
$LEM->alias2varName=array();
$LEM->varNameAttr=array();
$LEM->allOnOnePage=$allOnOnePage;
$LEM->pageTailoringLog='';
$LEM->surveyLogicFile='';
if ($debug && $LEM->debugLEM)
{
$LEM->pageTailoringLog .= '<tr><th>Group</th><th>Source</th><th>Pretty Print</th><th>Result</th></tr>';
}
}
static function StartProcessingGroup($groupNum=NULL,$anonymized=false,$surveyid=NULL)
{
$LEM =& LimeExpressionManager::singleton();
$LEM->em->StartProcessingGroup();
if (!is_null($groupNum))
{
$LEM->groupNum = $groupNum;
$LEM->qid2code = array(); // List of codes for each question - needed to know which to NULL if a question is irrelevant
$LEM->jsVar2qid = array();
if (!is_null($surveyid) && $LEM->setVariableAndTokenMappingsForExpressionManager($surveyid,false,$anonymized,$LEM->allOnOnePage))
{
// means that some values changed, so need to update what was registered to ExpressionManager
$LEM->em->RegisterVarnamesUsingMerge($LEM->knownVars);
}
}
$LEM->groupRelevanceInfo = array();
}
static function FinishProcessingGroup()
{
$LEM =& LimeExpressionManager::singleton();
$LEM->pageTailorInfo[] = $LEM->em->GetCurrentSubstitutionInfo();
$LEM->pageRelevanceInfo[] = $LEM->groupRelevanceInfo;
}
static function FinishProcessingPage()
{
$LEM =& LimeExpressionManager::singleton();
$_SESSION['EM_pageTailoringLog'] = $LEM->pageTailoringLog;
$_SESSION['EM_surveyLogicFile'] = $LEM->surveyLogicFile;
}
static function ShowLogicFile()
{
if (isset($_SESSION['EM_surveyLogicFile'])) {
return $_SESSION['EM_surveyLogicFile'];
}
return '';
}
static function ShowPageTailorings()
{
if (isset($_SESSION['EM_pageTailoringLog'])) {
return $_SESSION['EM_pageTailoringLog'];
}
return '';
}
/*
* Generate JavaScript needed to do dynamic relevance and tailoring
* Also create list of variables that need to be declared
*/
static function GetRelevanceAndTailoringJavaScript()
{
$LEM =& LimeExpressionManager::singleton();
$knownVars = $LEM->knownVars;
$jsParts=array();
$allJsVarsUsed=array();
$jsParts[] = '<script type="text/javascript" src="' . base_url() . '/scripts/admin/expressions/em_javascript.js"></script>';
$jsParts[] = "<script type='text/javascript'>\n<!--\n";
$jsParts[] = "function ExprMgr_process_relevance_and_tailoring(evt_type){\n";
$jsParts[] = "if (typeof LEM_initialized == 'undefined') {\nLEM_initialized=true;\nLEMsetTabIndexes();\nreturn;\n}\n";
$jsParts[] = "if (evt_type == 'onchange' && (typeof last_evt_type != 'undefined' && last_evt_type == 'keydown') && (typeof target_tabIndex != 'undefined' && target_tabIndex == document.activeElement.tabIndex)) {\nreturn;\n}\n";
$jsParts[] = "last_evt_type = evt_type;\n\n";
// flatten relevance array, keeping proper order
$pageRelevanceInfo=array();
$qidList = array(); // list of questions used in relevance and tailoring
if (is_array($LEM->pageRelevanceInfo))
{
foreach($LEM->pageRelevanceInfo as $prel)
{
foreach($prel as $rel)
{
$pageRelevanceInfo[] = $rel;
}
}
}
if (is_array($pageRelevanceInfo))
{
foreach ($pageRelevanceInfo as $arg)
{
// First check if there is any tailoring and construct the tailoring JavaScript if needed
$tailorParts = array();
foreach ($LEM->pageTailorInfo as $tailor)
{
if (is_array($tailor))
{
foreach ($tailor as $sub)
{
if ($sub['questionNum'] == $arg['qid'])
{
$tailorParts[] = $sub['js'];
$vars = explode('|',$sub['vars']);
if (is_array($vars))
{
$allJsVarsUsed = array_merge($allJsVarsUsed,$vars);
}
}
}
}
}
$qidList[$arg['qid']] = $arg['qid'];
$relevance = $arg['relevancejs'];
if (($relevance == '' || $relevance == '1') && count($tailorParts) == 0)
{
// Only show constitutively true relevances if there is tailoring that should be done.
$jsParts[] = "document.getElementById('relevance" . $arg['qid'] . "').value='1'; // always true\n";
continue;
}
$relevance = ($relevance == '') ? '1' : $relevance;
$jsResultVar = $LEM->em->GetJsVarFor($arg['jsResultVar']);
$jsParts[] = "\n// Process Relevance for Question " . $arg['qid'] . "(" . $arg['jsResultVar'] . "=" . $jsResultVar . "): { " . $arg['eqn'] . " }\n";
$jsParts[] = "if (\n";
$jsParts[] = $relevance;
$jsParts[] = "\n)\n{\n";
// Do all tailoring
$jsParts[] = implode("\n",$tailorParts);
if ($arg['hidden'] == 1) {
$jsParts[] = " // This question should always be hidden\n";
$jsParts[] = " $('#question" . $arg['qid'] . "').hide();\n";
$jsParts[] = " document.getElementById('display" . $arg['qid'] . "').value='';\n";
}
else {
$jsParts[] = " $('#question" . $arg['qid'] . "').show();\n";
$jsParts[] = " document.getElementById('display" . $arg['qid'] . "').value='on';\n";
}
// If it is an equation, and relevance is true, then write the value from the question to the answer field storing the result
if ($arg['type'] == '*')
{
$jsParts[] = " // Write value from the question into the answer field\n";
$jsParts[] = " document.getElementById('" . $jsResultVar . "').value=escape(jQuery.trim(LEMstrip_tags($('#question" . $arg['qid'] . " .questiontext').find('span').next().next().html()))).replace(/%20/g,' ');\n";
}
$jsParts[] = " document.getElementById('relevance" . $arg['qid'] . "').value='1';\n";
$jsParts[] = "}\nelse {\n";
$jsParts[] = " $('#question" . $arg['qid'] . "').hide();\n";
$jsParts[] = " document.getElementById('display" . $arg['qid'] . "').value='';\n";
$jsParts[] = " document.getElementById('relevance" . $arg['qid'] . "').value='0';\n";
$jsParts[] = "}\n";
$vars = explode('|',$arg['relevanceVars']);
if (is_array($vars))
{
$allJsVarsUsed = array_merge($allJsVarsUsed,$vars);
}
}
}
$jsParts[] = "}\n";
$allJsVarsUsed = array_unique($allJsVarsUsed);
// Add JavaScript Mapping Arrays
if (isset($LEM->alias2varName) && count($LEM->alias2varName) > 0)
{
$neededAliases=array();
$neededCanonical=array();
$neededCanonicalAttr=array();
foreach ($allJsVarsUsed as $jsVar)
{
if ($jsVar == '') {
continue;
}
if (preg_match("/^.*\.NAOK$/", $jsVar)) {
$jsVar = preg_replace("/\.NAOK$/","",$jsVar);
}
$neededCanonical[] = $jsVar;
foreach ($LEM->alias2varName as $key=>$value)
{
if ($jsVar == $value['jsName'])
{
$neededAliases[] = $value['jsPart'];
}
}
}
$neededCanonical = array_unique($neededCanonical);
foreach ($neededCanonical as $nc)
{
$neededCanonicalAttr[] = $LEM->varNameAttr[$nc];
}
$neededAliases = array_unique($neededAliases);
if (count($neededAliases) > 0)
{
$jsParts[] = "var LEMalias2varName = {\n";
$jsParts[] = implode(",\n",$neededAliases);
$jsParts[] = "};\n";
}
if (count($neededCanonicalAttr) > 0)
{
$jsParts[] = "var LEMvarNameAttr = {\n";
$jsParts[] = implode(",\n",$neededCanonicalAttr);
$jsParts[] = "};\n";
}
}
$jsParts[] = "//-->\n</script>\n";
// Now figure out which variables have not been declared (those not on the current page)
$undeclaredJsVars = array();
$undeclaredVal = array();
if (isset($knownVars) && is_array($knownVars))
{
foreach ($knownVars as $knownVar)
{
foreach ($allJsVarsUsed as $jsVar)