/
frontend_helper.php
2641 lines (2390 loc) · 109 KB
/
frontend_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 if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
* LimeSurvey
* Copyright (C) 2007-2012 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$
*/
function loadanswers()
{
global $surveyid;
global $thissurvey, $thisstep;
global $clienttoken;
$clang = Yii::app()->lang;
$scid=returnGlobal('scid');
if (isset($_POST['loadall']) && $_POST['loadall'] == "reload")
{
$query = "SELECT * FROM {{saved_control}} INNER JOIN {$thissurvey['tablename']}
ON {{saved_control}}.srid = {$thissurvey['tablename']}.id
WHERE {{saved_control}}.sid=$surveyid\n";
if (isset($scid)) //Would only come from email
{
$query .= "AND {{saved_control}}.scid={$scid}\n";
}
$query .="AND {{saved_control}}.identifier = '".autoEscape($_SESSION['survey_'.$surveyid]['holdname'])."' ";
if (in_array(Yii::app()->db->getDriverName(), array('mssql', 'sqlsrv')))
{
$query .="AND CAST({{saved_control}}.access_code as varchar(32))= '".md5(autoUnescape($_SESSION['survey_'.$surveyid]['holdpass']))."'\n";
}
else
{
$query .="AND {{saved_control}}.access_code = '".md5(autoUnescape($_SESSION['survey_'.$surveyid]['holdpass']))."'\n";
}
}
elseif (isset($_SESSION['survey_'.$surveyid]['srid']))
{
$query = "SELECT * FROM {$thissurvey['tablename']}
WHERE {$thissurvey['tablename']}.id=".$_SESSION['survey_'.$surveyid]['srid']."\n";
}
else
{
return;
}
$result = dbExecuteAssoc($query) or safeDie ("Error loading results<br />$query<br />"); //Checked
if ($result->count() < 1)
{
safeDie($clang->gT("There is no matching saved survey")."<br />\n");
}
else
{
//A match has been found. Let's load the values!
//If this is from an email, build surveysession first
$_SESSION['LEMtokenResume']=true;
$row=$result->read();
foreach ($row as $column => $value)
{
if ($column == "token")
{
$clienttoken=$value;
$token=$value;
}
elseif ($column == "saved_thisstep" && $thissurvey['alloweditaftercompletion'] != 'Y' )
{
$_SESSION['survey_'.$surveyid]['step']=$value;
$thisstep=$value-1;
}
elseif ($column =='lastpage' && isset($_GET['token']) && $thissurvey['alloweditaftercompletion'] != 'Y' )
{
if ($value<1) $value=1;
$_SESSION['survey_'.$surveyid]['step']=$value;
$thisstep=$value-1;
}
/*
Commented this part out because otherwise startlanguage would overwrite any other language during a running survey.
We will need a new field named 'endlanguage' to save the current language (for example for returning participants)
/the language the survey was completed in.
elseif ($column =='startlanguage')
{
$clang = SetSurveyLanguage( $surveyid, $value);
UpdateSessionGroupList($value); // to refresh the language strings in the group list session variable
UpdateFieldArray(); // to refresh question titles and question text
}*/
elseif ($column == "scid")
{
$_SESSION['survey_'.$surveyid]['scid']=$value;
}
elseif ($column == "srid")
{
$_SESSION['survey_'.$surveyid]['srid']=$value;
}
elseif ($column == "datestamp")
{
$_SESSION['survey_'.$surveyid]['datestamp']=$value;
}
if ($column == "startdate")
{
$_SESSION['survey_'.$surveyid]['startdate']=$value;
}
else
{
//Only make session variables for those in insertarray[]
if (in_array($column, $_SESSION['survey_'.$surveyid]['insertarray']))
{
$q = $_SESSION['survey_'.$surveyid]['fieldmap'][$column]['q'];
$_SESSION['survey_'.$surveyid][$column] = $q->loadAnswer($value);
} // if (in_array(
} // else
} // foreach
}
return true;
}
function makegraph($currentstep, $total)
{
global $thissurvey;
$clang = Yii::app()->lang;
header_includes('lime-progress.css','css');
$size = intval(($currentstep-1)/$total*100);
$graph = '<script type="text/javascript">
$(document).ready(function() {
$("#progressbar").progressbar({
value: '.$size.'
});
;});';
if (getLanguageRTL($clang->langcode))
{
$graph.='
$(document).ready(function() {
$("div.ui-progressbar-value").removeClass("ui-corner-left");
$("div.ui-progressbar-value").addClass("ui-corner-right");
});';
}
$graph.='
</script>
<div id="progress-wrapper">
<span class="hide">'.sprintf($clang->gT('You have completed %s%% of this survey'),$size).'</span>
<div id="progress-pre">';
if (getLanguageRTL($clang->langcode))
{
$graph.='100%';
}
else
{
$graph.='0%';
}
$graph.='</div>
<div id="progressbar"></div>
<div id="progress-post">';
if (getLanguageRTL($clang->langcode))
{
$graph.='0%';
}
else
{
$graph.='100%';
}
$graph.='</div>
</div>';
if ($size == 0) // Progress bar looks dumb if 0
{
$graph.='
<script type="text/javascript">
$(document).ready(function() {
$("div.ui-progressbar-value").hide();
});
</script>';
}
return $graph;
}
/**
* This function creates the language selector for a particular survey
*
* @param mixed $sSelectedLanguage The language in which all information is shown
*/
function makeLanguageChangerSurvey($sSelectedLanguage)
{
$surveyid = Yii::app()->getConfig('surveyID');
Yii::app()->loadHelper("surveytranslator");
$slangs = Survey::model()->findByPk($surveyid)->getAdditionalLanguages();
$slangs[]= GetBaseLanguageFromSurveyID($surveyid);
if (count($slangs)>1) // return a dropdow only of there are more than one lanagage
{
$previewgrp = false;
if (isset($_REQUEST['action'])&& $_REQUEST['action']=='previewgroup')
{
$previewgrp = true;
}
$sHTMLCode = "<select id='languagechanger' name='languagechanger' class='languagechanger' onchange='javascript:window.location=this.value'>\n";
$sAddToURL = "";
$sTargetURL = Yii::app()->getController()->createUrl("/survey/index");
if ($previewgrp){
$sAddToURL = "&action=previewgroup&gid={$_REQUEST['gid']}";
}
foreach ($slangs as $sLanguage)
{
$sHTMLCode .= "<option value=\"{$sTargetURL}?sid=". $surveyid ."&lang=". $sLanguage ."{$sAddToURL}\" ";
if ($sLanguage==$sSelectedLanguage)
{
$sHTMLCode .=" selected='selected'";
}
$sHTMLCode .=">".getLanguageNameFromCode($sLanguage,false,$sLanguage)." - ".getLanguageNameFromCode($sLanguage,false,$sSelectedLanguage)."</option>\n";
}
$sHTMLCode .= "</select>\n";
return $sHTMLCode;
}
else
{
return false;
}
}
/**
* This function creates the language selector for the public survey index page
*
* @param mixed $sSelectedLanguage The language in which all information is shown
*/
function makeLanguageChanger($sSelectedLanguage)
{
if(count(getLanguageDataRestricted())>1)
{
$sHTMLCode = "<select id='languagechanger' name='languagechanger' class='languagechanger' onchange='javascript:window.location=this.value'>\n";
foreach(getLanguageDataRestricted(true, $sSelectedLanguage) as $sLanguageID=>$aLanguageProperties)
{
$sHTMLCode .= "<option value='".Yii::app()->getController()->createUrl("/survey/index")."?lang=".$sLanguageID."' ";
if($sLanguageID == $sSelectedLanguage)
{
$sHTMLCode .= " selected='selected' ";
$sHTMLCode .= ">{$aLanguageProperties['nativedescription']}</option>\n";
}
else
{
$sHTMLCode .= ">".$aLanguageProperties['nativedescription'].' - '.$aLanguageProperties['description']."</option>\n";
}
}
$sHTMLCode .= "</select>\n";
return $sHTMLCode;
}
else
{
return false;
}
}
// TMSW Conditions->Relevance: this function is not needed. Use EM to NULL fields that are irrelevant
function checkconfield($value)
{
global $surveyid,$thissurvey,$qattributes;
$fieldisdisplayed=true;
if (!is_array($thissurvey))
{
$local_thissurvey=getSurveyInfo($surveyid);
}
else
{
$local_thissurvey=$thissurvey;
}
// we know the true fieldname $value (for instance SGQA for each checkboxes)
// and we want to compare it to the values stored in $_SESSION['fieldarray'] which are simple fieldnames
// ==> We first translate $value to the simple fieldname (let's call it the masterFieldName) from
// the $_SESSION['survey_X']['fieldnamesInfo'] translation table
if (isset($_SESSION['survey_'.$surveyid]['fieldnamesInfo'][$value]))
{
$masterFieldName = $_SESSION['survey_'.$surveyid]['fieldnamesInfo'][$value];
}
else
{ // for token refurl, ipaddr...
$masterFieldName = 'token';
}
$value_question = false;
//$value is the fieldname for the field we are checking for conditions
foreach ($_SESSION['survey_'.$surveyid]['questions'] as $q) //Go through each field
{
// record the qid and question type for future use
if ($q->fieldname == $masterFieldName)
{
$value_question = $q;
break;
}
}
// check if this question is conditionnal ($sfa[7]): if yes eval conditions
if ($value_question->conditionsexist == "Y" && isset($_SESSION['survey_'.$surveyid][$value]) ) //Do this if there is a condition based on this answer
{
$scenarioquery = "SELECT DISTINCT scenario FROM {{conditions}}"
." WHERE {{conditions}}.qid=$sfa[0] ORDER BY scenario";
$scenarioresult=dbExecuteAssoc($scenarioquery);
$matchfound=0;
//$scenario=1;
//while ($scenario > 0)
$evalNextScenario = true;
foreach($scenarioresult->readAll() as $scenariorow)
{
if($evalNextScenario !== true)
break;
$aAllCondrows=Array();
$cqval=Array();
$container=Array();
$scenario = $scenariorow['scenario'];
$currentcfield="";
$query = "SELECT {{conditions}}.*, {{question_types}}.clas "
. "FROM {{conditions}}, {{questions}} "
. "WHERE {{conditions}}.cqid={{questions}}.qid "
. "AND {{questions}}.tid={{question_types}}.tid "
. "AND {{conditions}}.qid=$value_question->id "
. "AND {{conditions}}.scenario=$scenario "
. "AND {{conditions}}.cfieldname NOT LIKE '{%' "
. "ORDER BY {{conditions}}.qid,{{conditions}}.cfieldname";
$result=dbExecuteAssoc($query) or safeDie($query."<br />"); //Checked
$conditionsfound = $result->count();
$querytoken = "SELECT {{conditions}}.*, 'Display' as class "
. "FROM {{conditions}} "
. "WHERE "
. " {{conditions}}.qid=$value_question->id "
. "AND {{conditions}}.scenario=$scenario "
. "AND {{conditions}}.cfieldname LIKE '{%' "
. "ORDER BY {{conditions}}.qid,{{conditions}}.cfieldname";
$resulttoken=dbExecuteAssoc($querytoken) or safeDie($querytoken."<br />"); //Checked
$conditionsfoundtoken = $resulttoken->count();
$conditionsfound = $conditionsfound + $conditionsfoundtoken;
foreach($resulttoken->readAll() as $Condrow)
{
$aAllCondrows[] = $Condrow;
}
foreach($result->readAll() as $Condrow)
{
$aAllCondrows[] = $Condrow;
}
foreach ($aAllCondrows as $rows)
{
$q = createQuestion($rows['class']);
$val = $q->prepareConditions();
$cqval[]=$val;
if ($val['cfieldname'] != $currentcfield)
{
$container[]=$val['cfieldname'];
}
$currentcfield=$val['cfieldname'];
}
if ($conditionsfound > 0)
{
//At least one match must be found for each "$container"
$total=0;
foreach($container as $con)
{
$conditionCanBeEvaluated=true;
$addon=0;
foreach($cqval as $cqv)
{//Go through each condition
// Replace @SGQA@ condition values
// By corresponding value
if (preg_match('/^@([0-9]+X[0-9]+X[^@]+)@/',$cqv["matchvalue"], $targetconditionfieldname))
{
if (isset($_SESSION['survey_'.$surveyid][$targetconditionfieldname[1]]))
{
$cqv["matchvalue"] = $_SESSION['survey_'.$surveyid][$targetconditionfieldname[1]];
}
else
{
$conditionCanBeEvaluated=false;
}
}
// Replace {TOKEN:XXX} condition values
// By corresponding value
if ($local_thissurvey['anonymized'] == 'N' &&
preg_match('/^{TOKEN:([^}]*)}$/',$cqv["matchvalue"], $targetconditiontokenattr))
{
if (isset($_SESSION['survey_'.$surveyid]['token']) && in_array(strtolower($targetconditiontokenattr[1]),getTokenConditionsFieldNames($surveyid)))
{
$cqv["matchvalue"] = getAttributeValue($surveyid,strtolower($targetconditiontokenattr[1]),$_SESSION['survey_'.$surveyid]['token']);
}
else
{
$conditionCanBeEvaluated=false;
}
}
// Use == as default operator
if (trim($cqv['matchmethod'])=='')
{
$cqv['matchmethod']='==';
}
if($cqv['cfieldname'] == $con && $conditionCanBeEvaluated === true)
{
if (!preg_match("/^{/",$cqv['cfieldname']))
{
if (isset($_SESSION['survey_'.$surveyid][$cqv['matchfield']]))
{
$comparisonLeftOperand = $_SESSION['survey_'.$surveyid][$cqv['matchfield']];
}
else
{
$comparisonLeftOperand = null;
}
}
elseif ($local_thissurvey['anonymized'] == "N" && preg_match('/^{TOKEN:([^}]*)}$/',$cqv['cfieldname'],$sourceconditiontokenattr))
{
if ( isset($_SESSION['survey_'.$surveyid]['token']) &&
in_array(strtolower($sourceconditiontokenattr[1]),getTokenConditionsFieldNames($surveyid)))
{
$comparisonLeftOperand = getAttributeValue($surveyid,strtolower($sourceconditiontokenattr[1]),$_SESSION['survey_'.$surveyid]['token']);
}
else
{
$comparisonLeftOperand = null;
}
}
else
{
$comparisonLeftOperand = null;
}
if ($cqv['matchmethod'] != "RX")
{
if (preg_match("/^a(.*)b$/",$cqv['matchmethod'],$matchmethods))
{
// strings comparizon operator in PHP are the same as numerical operators
$matchOperator = $matchmethods[1];
}
else
{
$matchOperator = $cqv['matchmethod'];
}
if (isset($comparisonLeftOperand) && !is_null($comparisonLeftOperand) && eval('if (trim($comparisonLeftOperand) '.$matchOperator.' trim($cqv["matchvalue"]) ) {return true;} else {return false;}'))
{//plug successful matches into appropriate container
$addon=1;
}
}
elseif ( isset($comparisonLeftOperand) && !is_null($comparisonLeftOperand) && preg_match('/'.$cqv["matchvalue"].'/',$comparisonLeftOperand))
{
$addon=1;
}
}
}
if($addon==1)
{
$total++;
}
}
if($total==count($container))
{
$matchfound=1;
$evalNextScenario=false; // Don't look for other scenario's.
}
unset($cqval);
unset($container);
} else
{
//Curious there is no condition for this question in this scenario
// this is not a normal behaviour, but I propose to defaults to a
// condition-matched state in this case
$matchfound=1;
$evalNextScenario=false;
}
} // while ($scenario)
if($matchfound==0)
{
//If this is not a "moveprev" then
// Reset the value in SESSION
//if(isset($move) && $move != "moveprev")
//{
$_SESSION['survey_'.$surveyid][$value]="";
$fieldisdisplayed=false;
//}
}
}
if ($value_question->id != 0)
{ // not token masterFieldname
$value_qa=$value_question->getAttributeValues();
}
if ($fieldisdisplayed === true && isset($value_qa) && (
(isset($value_qa['array_filter']) && trim($value_qa['array_filter']) != '') ||
(isset($value_qa['array_filter_exclude']) && trim($value_qa['array_filter_exclude']) != '') ))
{ // check if array_filter//array_filter_exclude have hidden the field
$value_code = preg_replace("/$masterFieldName(.*)/","$1",$value);
//If this question is a multi-flexible, the value_code will be both the array_filter value
// (at the beginning) and then a labelset value after an underscore
// ie: 2_1 for answer code=2 and labelset code=1 then 2_2 for answer_code=2 and
// labelset code=2. So for these question types we need to split it again at the underscore!
// 1. Find out if this is question type ":" or ";"
$properties = $value_question->questionProperties();
if($properties['subquestions'] == 2)
{
list($value_code, $value_label)=explode("_", $value_code);
}
if (isset($value_qa['array_filter_exclude']))
{
$arrayfilterXcludes_selected_codes = getArrayFilterExcludesForQuestion($value_question->id);
if ( $arrayfilterXcludes_selected_codes !== false &&
in_array($value_code,$arrayfilterXcludes_selected_codes))
{
$fieldisdisplayed=false;
}
}
elseif (isset($value_qa['array_filter']))
{
$arrayfilter_selected_codes = getArrayFiltersForQuestion($value_question->id);
if ( $arrayfilter_selected_codes !== false &&
!in_array($value_code,$arrayfilter_selected_codes))
{
$fieldisdisplayed=false;
}
}
}
return $fieldisdisplayed;
}
// TMSW Conditions->Relevance: Not needed - use EM to check mandatories
function checkmandatorys($move, $backok=null)
{
global $thisstep;
if ((isset($_POST['mandatory']) && $_POST['mandatory']) && (!isset($backok) || $backok != "Y"))
{
$chkmands=explode("|", $_POST['mandatory']); //These are the mandatory questions to check
$mfns=explode("|", $_POST['mandatoryfn']); //These are the fieldnames of the mandatory questions
$mi=0;
foreach ($chkmands as $cm)
{
if (!isset($multiname) || (isset($multiname) && $multiname != "MULTI$mfns[$mi]")) //no multiple type mandatory set, or does not match this question (set later on for first time)
{
if ((isset($multiname) && $multiname) && (isset($_POST[$multiname]) && $_POST[$multiname])) //This isn't the first time (multiname exists, and is a posted variable)
{
if ($$multiname == $$multiname2 && isset($visibleanswers) && $visibleanswers > 0) //The number of questions not answered is equal to the number of questions
{
//The number of questions not answered is equal to the number of questions
//This section gets used if it is a multiple choice type question
$_SESSION['survey_'.$surveyid]['step'] = $thisstep;
$notanswered[]=substr($multiname, 5, strlen($multiname));
$$multiname=0;
$$multiname2=0;
}
}
$multiname="MULTI$mfns[$mi]";
$multiname2=$multiname."2"; //Make a copy, to store a second version
$$multiname=0;
$$multiname2=0;
}
else
{
$multiname="MULTI$mfns[$mi]";
}
$dtcm = "tbdisp$cm";
if (isset($_SESSION['survey_'.$surveyid][$cm]) && ($_SESSION['survey_'.$surveyid][$cm] == "0" || $_SESSION['survey_'.$surveyid][$cm]))
{
}
elseif ((!isset($_POST[$multiname]) || !$_POST[$multiname]) && (!isset($_POST[$dtcm]) || $_POST[$dtcm] == "on"))
{
//One of the mandatory questions hasn't been asnwered
$_SESSION['survey_'.$surveyid]['step'] = $thisstep;
$notanswered[]=$mfns[$mi];
}
else
{
//One of the mandatory questions hasn't been answered
$$multiname++;
}
/* We need to have some variable to use later that indicates whether any of the
multiple option answers were actually displayed (since it's impossible to
answer them if they aren't). The $visibleanswers field is created here to
record how many of the answers were actually available to be answered */
if(!isset($visibleanswers) && (isset($_POST[$dtcm]) && $_POST[$dtcm] == "off" || isset($_POST[$dtcm])))
{
$visibleanswers=0;
}
if(isset($_POST[$dtcm]) && $_POST[$dtcm] == "on")
{
$visibleanswers++;
}
$$multiname2++;
$mi++;
}
if ($multiname && isset($_POST[$multiname]) && $_POST[$multiname]) // Catch the last Multiple choice question in the lot
{
if ($$multiname == $$multiname2 && isset($visibleanswers) && $visibleanswers > 0) //so far all multiple choice options are unanswered
{
//The number of questions not answered is equal to the number of questions
if (isset($move) && $move == "moveprev")
{
$_SESSION['survey_'.$surveyid]['step'] = $thisstep;
}
if (isset($move) && $move == "movenext")
{
$_SESSION['survey_'.$surveyid]['step'] = $thisstep;
}
$notanswered[]=substr($multiname, 5, strlen($multiname));
$$multiname="";
$$multiname2="";
}
}
}
if (!isset($notanswered))
{
return false;
}//$notanswered=null;}
return $notanswered;
}
// TMSW Conditions->Relevance: Not needed - use EM to check mandatories
function checkconditionalmandatorys($move, $backok=null)
{
global $thisstep;
// TODO - also check whether relevance set?
if ((isset($_POST['conmandatory']) && $_POST['conmandatory']) && (!isset($backok) || $backok != "Y")) //Mandatory conditional questions that should only be checked if the conditions for displaying that question are met
{
$chkcmands=explode("|", $_POST['conmandatory']);
$cmfns=explode("|", $_POST['conmandatoryfn']);
$mi=0;
foreach ($chkcmands as $ccm)
{
if (!isset($multiname) || $multiname != "MULTI$cmfns[$mi]") //the last multipleanswerchecked is different to this one
{
if (isset($multiname) && $multiname && isset($_POST[$multiname]) && $_POST[$multiname])
{
if ($$multiname == $$multiname2) //For this lot all multiple choice options are unanswered
{
//The number of questions not answered is equal to the number of questions
$_SESSION['survey_'.$surveyid]['step'] = $thisstep;
$notanswered[]=substr($multiname, 5, strlen($multiname));
$$multiname=0;
$$multiname2=0;
}
}
$multiname="MULTI$cmfns[$mi]";
$multiname2=$multiname."2"; //POSSIBLE CORRUPTION OF PROCESS - CHECK LATER
$$multiname=0;
$$multiname2=0;
}
else
{
$multiname="MULTI$cmfns[$mi]";
}
$dccm="display$cmfns[$mi]";
$dtccm = "tbdisp$ccm";
if (isset($_SESSION['survey_'.$surveyid][$ccm]) && ($_SESSION['survey_'.$surveyid][$ccm] == "0" || $_SESSION['survey_'.$surveyid][$ccm]) && isset($_POST[$dccm]) && $_POST[$dccm] == "on") //There is an answer
{
//The question has an answer, and the answer was displaying
}
elseif ((isset($_POST[$dccm]) && $_POST[$dccm] == "on") && (!isset($_POST[$multiname]) || !$_POST[$multiname]) && (!isset($_POST[$dtccm]) || $_POST[$dtccm] == "on")) // Question and Answers is on, there is no answer, but it's a multiple
{
if (isset($move) && $move == "moveprev")
{
$_SESSION['survey_'.$surveyid]['step'] = $thisstep;
}
if (isset($move) && $move == "movenext")
{
$_SESSION['survey_'.$surveyid]['step'] = $thisstep;
}
$notanswered[]=$cmfns[$mi];
}
elseif (isset($_POST[$dccm]) && $_POST[$dccm] == "on")
{
//One of the conditional mandatory questions was on, but hasn't been answered
$$multiname++;
}
$$multiname2++;
$mi++;
}
if (isset($multiname) && $multiname && isset($_POST[$multiname]) && $_POST[$multiname])
{
if ($$multiname == $$multiname2) //so far all multiple choice options are unanswered
{
//The number of questions not answered is equal to the number of questions
if (isset($move) && $move == "moveprev")
{
$_SESSION['survey_'.$surveyid]['step'] = $thisstep;
}
if (isset($move) && $move == "movenext")
{
$_SESSION['survey_'.$surveyid]['step'] = $thisstep;
}
$notanswered[]=substr($multiname, 5, strlen($multiname));
}
}
}
if (!isset($notanswered))
{
return false;
}//$notanswered=null;}
return $notanswered;
}
function checkUploadedFileValidity($surveyid, $move, $backok=null)
{
global $thisstep;
$clang = Yii::app()->lang;
if (!isset($backok) || $backok != "Y")
{
$fieldmap = createFieldMap($surveyid,'full',false,false,$_SESSION['survey_'.$surveyid]['s_lang']);
if (isset($_POST['fieldnames']) && $_POST['fieldnames']!="")
{
$fields = explode("|", $_POST['fieldnames']);
foreach ($fields as $field)
{
$q = $fieldmap[$field]['q'];
if ($q->fileUpload() && !strrpos($q->fieldname, "_filecount"))
{
$validation= getQuestionAttributeValues($q);
$filecount = 0;
$json = $_POST[$field];
// if name is blank, its basic, hence check
// else, its ajax, don't check, bypass it.
if ($json != "" && $json != "[]")
{
$phparray = json_decode(stripslashes($json));
if ($phparray[0]->size != "")
{ // ajax
$filecount = count($phparray);
}
else
{ // basic
for ($i = 1; $i <= $validation['max_num_of_files']; $i++)
{
if (!isset($_FILES[$field."_file_".$i]) || $_FILES[$field."_file_".$i]['name'] == '')
continue;
$filecount++;
$file = $_FILES[$field."_file_".$i];
// File size validation
if ($file['size'] > $validation['max_filesize'] * 1000)
{
$filenotvalidated = array();
$filenotvalidated[$field."_file_".$i] = sprintf($clang->gT("Sorry, the uploaded file (%s) is larger than the allowed filesize of %s KB."), $file['size'], $validation['max_filesize']);
$append = true;
}
// File extension validation
$pathinfo = pathinfo(basename($file['name']));
$ext = $pathinfo['extension'];
$validExtensions = explode(",", $validation['allowed_filetypes']);
if (!(in_array($ext, $validExtensions)))
{
if (isset($append) && $append)
{
$filenotvalidated[$field."_file_".$i] .= sprintf($clang->gT("Sorry, only %s extensions are allowed!"),$validation['allowed_filetypes']);
unset($append);
}
else
{
$filenotvalidated = array();
$filenotvalidated[$field."_file_".$i] .= sprintf($clang->gT("Sorry, only %s extensions are allowed!"),$validation['allowed_filetypes']);
}
}
}
}
}
else
$filecount = 0;
if (isset($validation['min_num_of_files']) && $filecount < $validation['min_num_of_files'] && LimeExpressionManager::QuestionIsRelevant($q->id))
{
$filenotvalidated = array();
$filenotvalidated[$field] = $clang->gT("The minimum number of files has not been uploaded.");
}
}
}
}
if (isset($filenotvalidated))
{
if (isset($move) && $move == "moveprev")
$_SESSION['survey_'.$surveyid]['step'] = $thisstep;
if (isset($move) && $move == "movenext")
$_SESSION['survey_'.$surveyid]['step'] = $thisstep;
return $filenotvalidated;
}
}
if (!isset($filenotvalidated))
return false;
else
return $filenotvalidated;
}
function addtoarray_single($array1, $array2)
{
//Takes two single element arrays and adds second to end of first if value exists
if (is_array($array2))
{
foreach ($array2 as $ar)
{
if ($ar && $ar !== null)
{
$array1[]=$ar;
}
}
}
return $array1;
}
function remove_nulls_from_array($array)
{
foreach ($array as $ar)
{
if ($ar !== null)
{
$return[]=$ar;
}
}
if (isset($return))
{
return $return;
}
else
{
return false;
}
}
/**
* Marks a tokens as completed and sends a confirmation email to the participiant.
* If $quotaexit is set to true then the user exited the survey due to a quota
* restriction and the according token is only marked as 'Q'
*
* @param mixed $quotaexit
*/
function submittokens($quotaexit=false)
{
global $thissurvey, $timeadjust, $emailcharset ;
global $surveyid;
global $thistpl, $clienttoken;
$clang = Yii::app()->lang;
$sitename = Yii::app()->getConfig("sitename");
// Shift the date due to global timeadjust setting
$today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", $timeadjust);
// check how many uses the token has left
$usesquery = "SELECT usesleft FROM {{tokens_$surveyid}} WHERE token='".$clienttoken."'";
$usesresult = dbExecuteAssoc($usesquery);
$usesrow = $usesresult->read();
if (isset($usesrow)) { $usesleft = $usesrow['usesleft']; }
$utquery = "UPDATE {{tokens_$surveyid}}\n";
if ($quotaexit==true)
{
$utquery .= "SET completed='Q', usesleft=usesleft-1\n";
}
elseif (isTokenCompletedDatestamped($thissurvey))
{
if (isset($usesleft) && $usesleft<=1)
{
$utquery .= "SET usesleft=usesleft-1, completed='$today'\n";
}
else
{
$utquery .= "SET usesleft=usesleft-1\n";
}
}
else
{
if (isset($usesleft) && $usesleft<=1)
{
$utquery .= "SET usesleft=usesleft-1, completed='Y'\n";
}
else
{
$utquery .= "SET usesleft=usesleft-1\n";
}
}
$utquery .= "WHERE token='".$clienttoken."'";
$utresult = dbExecuteAssoc($utquery) or safeDie ("Couldn't update tokens table!<br />\n$utquery<br />\n"); //Checked
if ($quotaexit==false)
{
// TLR change to put date into sent and completed
$cnfquery = "SELECT * FROM {{tokens_$surveyid}} WHERE token='".$clienttoken."' AND completed!='N' AND completed!=''";
$cnfresult = dbExecuteAssoc($cnfquery); //Checked
$cnfrow = $cnfresult->read();
if (isset($cnfrow))
{
$from = "{$thissurvey['adminname']} <{$thissurvey['adminemail']}>";
$to = $cnfrow['email'];
$subject=$thissurvey['email_confirm_subj'];
$fieldsarray["{ADMINNAME}"]=$thissurvey['adminname'];
$fieldsarray["{ADMINEMAIL}"]=$thissurvey['adminemail'];
$fieldsarray["{SURVEYNAME}"]=$thissurvey['name'];
$fieldsarray["{SURVEYDESCRIPTION}"]=$thissurvey['description'];
$fieldsarray["{FIRSTNAME}"]=$cnfrow['firstname'];
$fieldsarray["{LASTNAME}"]=$cnfrow['lastname'];
$fieldsarray["{TOKEN}"]=$clienttoken;
$attrfieldnames=getAttributeFieldNames($surveyid);
foreach ($attrfieldnames as $attr_name)
{
$fieldsarray["{".strtoupper($attr_name)."}"]=$cnfrow[$attr_name];
}
$dateformatdatat=getDateFormatData($thissurvey['surveyls_dateformat']);
$numberformatdatat = getRadixPointData($thissurvey['surveyls_numberformat']);
$fieldsarray["{EXPIRY}"]=convertDateTimeFormat($thissurvey["expiry"],'Y-m-d H:i:s',$dateformatdatat['phpdate']);
$subject=ReplaceFields($subject, $fieldsarray, true);
$subject=html_entity_decode($subject,ENT_QUOTES,$emailcharset);
if (getEmailFormat($surveyid) == 'html')
{
$ishtml=true;
}
else
{
$ishtml=false;
}
if (trim(strip_tags($thissurvey['email_confirm'])) != "" && $thissurvey['sendconfirmation'] == "Y")
{
$message=$thissurvey['email_confirm'];
$message=ReplaceFields($message, $fieldsarray, true);
if (!$ishtml)
{
$message=strip_tags(breakToNewline(html_entity_decode($message,ENT_QUOTES,$emailcharset)));
}
else
{
$message=html_entity_decode($message,ENT_QUOTES, $emailcharset );
}
//Only send confirmation email if there is a valid email address
if (validateEmailAddress($cnfrow['email']))
{
SendEmailMessage($message, $subject, $to, $from, $sitename,$ishtml);
}
}
else
{
//There is nothing in the message or "Send confirmation emails" is set to "No" , so don't send a confirmation email
//This section only here as placeholder to indicate new feature :-)
}
}
}
}
/**
* Send a submit notification to the email address specified in the notifications tab in the survey settings
*/
function sendSubmitNotifications($surveyid)
{
global $thissurvey, $debug;
global $emailcharset;
global $homeurl, $maildebug, $tokensexist;
$clang = Yii::app()->lang;
$sitename = Yii::app()->getConfig("sitename");