forked from LimeSurvey/LimeSurvey
-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.php
2951 lines (2644 loc) · 115 KB
/
index.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 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: index.php 12361 2012-02-05 19:40:30Z tmswhite $
*/
// Security Checked: POST, GET, SESSION, REQUEST, returnglobal, DB
require_once(dirname(__FILE__).'/classes/core/startup.php');
require_once(dirname(__FILE__).'/config-defaults.php');
require_once(dirname(__FILE__).'/common.php');
require_once(dirname(__FILE__).'/classes/core/language.php');
@ini_set('session.gc_maxlifetime', $sessionlifetime);
$loadname=returnglobal('loadname');
$loadpass=returnglobal('loadpass');
$scid=returnglobal('scid');
$thisstep=returnglobal('thisstep');
$move=sanitize_paranoid_string(returnglobal('move'));
$clienttoken=sanitize_token(returnglobal('token'));
if (!isset($thisstep))
{
$thisstep = "";
}
if (!isset($surveyid))
{
$surveyid=returnglobal('sid');
}
else
{
//This next line ensures that the $surveyid value is never anything but a number.
$surveyid=sanitize_int($surveyid);
}
//LimeExpressionManager::SetSurveyId($surveyid); // must be called early - it clears internal cache if a new survey is being used
//DEFAULT SETTINGS FOR TEMPLATES
if (!$publicdir)
{
$publicdir=".";
}
// Compute the Session name
// Session name is based:
// * on this specific limesurvey installation (Value SessionName in DB)
// * on the surveyid (from Get or Post param). If no surveyid is given we are on the public surveys portal
$usquery = "SELECT stg_value FROM ".db_table_name("settings_global")." where stg_name='SessionName'";
$usresult = db_execute_assoc($usquery,'',true); //Checked
if ($usresult)
{
$usrow = $usresult->FetchRow();
$stg_SessionName=$usrow['stg_value'];
if ($surveyid)
{
@session_name($stg_SessionName.'-runtime-'.$surveyid);
}
else
{
@session_name($stg_SessionName.'-runtime-publicportal');
}
}
else
{
session_name("LimeSurveyRuntime-$surveyid");
}
session_set_cookie_params(0,$relativeurl.'/');
if (!isset($_SESSION) || empty($_SESSION)) // the $_SESSION variable can be empty if register_globals is on
@session_start();
// First check if survey is active
// if not: copy some vars from the admin session
// to a new user session
if ($surveyid)
{
$issurveyactive=false;
$aRow=$connect->GetRow("SELECT * FROM ".db_table_name('surveys')." WHERE sid=$surveyid");
if (isset($aRow['active']))
{
$surveyexists=true;
if($aRow['active']=='Y')
{
$issurveyactive=true;
}
}
else
{
$surveyexists=false;
}
}
if ($clienttoken != '' && isset($_SESSION['token']) &&
$clienttoken != $_SESSION['token'])
{
require_once(dirname(__FILE__).'/classes/core/language.php');
$baselang = GetBaseLanguageFromSurveyID($surveyid);
$clang = new limesurvey_lang($baselang);
// Let's first regenerate a session id
killSession();
// Let's redirect the client to the same URL after having reseted the session
header("Location: $rooturl/index.php?" .$_SERVER['QUERY_STRING']);
sendcacheheaders();
doHeader();
echo templatereplace(file_get_contents("$standardtemplaterootdir/default/startpage.pstpl"));
echo "\t<div id='wrapper'>\n"
."\t<p id='tokenmessage'>\n"
."\t<span class='error'>".$clang->gT("Token mismatch")."</span><br /><br />\n"
."\t".$clang->gT("The token you provided doesn't match the one in your session.")."<br /><br />\n"
."\t".$clang->gT("Please wait to begin with a new session.")."<br /><br />\n"
."\t</p>\n"
."\t</div>\n";
echo templatereplace(file_get_contents("$standardtemplaterootdir/default/endpage.pstpl"));
doFooter();
exit;
}
if (isset($_SESSION['finished']) && $_SESSION['finished'] === true)
{
require_once(dirname(__FILE__).'/classes/core/language.php');
$baselang = GetBaseLanguageFromSurveyID($surveyid);
$clang = new limesurvey_lang($baselang);
// Let's first regenerate a session id
killSession();
// Let's redirect the client to the same URL after having reseted the session
header("Location: $rooturl/index.php?" .$_SERVER['QUERY_STRING']);
sendcacheheaders();
doHeader();
echo templatereplace(file_get_contents("$standardtemplaterootdir/default/startpage.pstpl"));
echo "\t<div id='wrapper'>\n"
."\t<p id='tokenmessage'>\n"
."\t<span class='error'>".$clang->gT("Previous session is set to be finished.")."</span><br /><br />\n"
."\t".$clang->gT("Your browser reports that it was used previously to answer this survey. We are resetting the session so that you can start from the beginning.")."<br /><br />\n"
."\t".$clang->gT("Please wait to begin with a new session.")."<br /><br />\n"
."\t</p>\n"
."\t</div>\n";
echo templatereplace(file_get_contents("$standardtemplaterootdir/default/endpage.pstpl"));
doFooter();
exit;
}
$previewgrp = false;
if (isset($_REQUEST['action']) && ($_REQUEST['action'] == 'previewgroup')){
$rightquery="SELECT uid FROM {$dbprefix}survey_permissions WHERE sid=".db_quote($surveyid)." AND uid = ".db_quote($_SESSION['loginID'].' group by uid');
$rightresult = db_execute_assoc($rightquery);
if ($rightresult->RecordCount() > 0 || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1)
{
$previewgrp = true;
}
}
if (($surveyid &&
$issurveyactive===false && $surveyexists &&
isset ($surveyPreview_require_Auth) &&
$surveyPreview_require_Auth == true) && $previewgrp == false)
{
// admin session and permission have not already been imported
// for this particular survey
if ( !isset($_SESSION['USER_RIGHT_PREVIEW']) ||
$_SESSION['USER_RIGHT_PREVIEW'] != $surveyid)
{
// Store initial session name
$initial_session_name=session_name();
// One way (not implemented here) would be to start the
// user session from a duplicate of the admin session
// - destroy the new session
// - load admin session (with correct session name)
// - close admin session
// - change used session name to default
// - open new session (takes admin session id)
// - regenerate brand new session id for this session
// The solution implemented here is to copy some
// fields from the admin session to the new session
// - first destroy the new (empty) user session
// - then open admin session
// - record interresting values from the admin session
// - duplicate admin session under another name and Id
// - destroy the duplicated admin session
// - start a brand new user session
// - copy interresting values in this user session
@session_destroy(); // make it silent because for
// some strange reasons it fails sometimes
// which is not a problem
// but if it throws an error then future
// session functions won't work because
// headers are already sent.
if (isset($stg_SessionName) && $stg_SessionName)
{
@session_name($stg_SessionName);
}
else
{
session_name("LimeSurveyAdmin");
}
session_start(); // Loads Admin Session
$previewright=false;
$savesessionvars=Array();
if (isset($_SESSION['loginID']))
{
$rightquery="SELECT uid FROM {$dbprefix}survey_permissions WHERE sid=".db_quote($surveyid)." AND uid = ".db_quote($_SESSION['loginID'].' group by uid');
$rightresult = db_execute_assoc($rightquery); //Checked
// Currently it is enough to be listed in the survey
// user operator list to get preview access
if ($rightresult->RecordCount() > 0 || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1)
{
$previewright=true;
$savesessionvars["USER_RIGHT_PREVIEW"]=$surveyid;
$savesessionvars["loginID"]=$_SESSION['loginID'];
$savesessionvars["user"]=$_SESSION['user'];
}
}
// change session name and id
// then delete this new session
// ==> the original admin session remains valid
// ==> it is possible to start a new session
session_name($initial_session_name);
if ($sessionhandler=='db')
{
adodb_session_regenerate_id();
}
elseif (session_regenerate_id() === false)
{
safe_die("Error Regenerating Session Id");
}
@session_destroy();
// start new session
@session_start();
// regenerate id so that the header geenrated by previous
// regenerate_id is overwritten
// needed after clearall
if ($sessionhandler=='db')
{
adodb_session_regenerate_id();
}
elseif (session_regenerate_id() === false)
{
safe_die("Error Regenerating Session Id");
}
if ( $previewright === true)
{
foreach ($savesessionvars as $sesskey => $sessval)
{
$_SESSION[$sesskey]=$sessval;
}
}
}
else
{ // already authorized
$previewright = true;
}
if ($previewright === false)
{
// print an error message
if (isset($_REQUEST['rootdir']))
{
safe_die('You cannot start this script directly');
}
require_once(dirname(__FILE__).'/classes/core/language.php');
$baselang = GetBaseLanguageFromSurveyID($surveyid);
$clang = new limesurvey_lang($baselang);
//A nice exit
sendcacheheaders();
doHeader();
echo templatereplace(file_get_contents("$standardtemplaterootdir/default/startpage.pstpl"));
echo "\t<div id='wrapper'>\n"
."\t<p id='tokenmessage'>\n"
."\t<span class='error'>".$clang->gT("ERROR")."</span><br /><br />\n"
."\t".$clang->gT("We are sorry but you don't have permissions to do this.")."<br /><br />\n"
."\t".sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$siteadminname,encodeEmail($siteadminemail))."<br /><br />\n"
."\t</p>\n"
."\t</div>\n";
echo templatereplace(file_get_contents("$standardtemplaterootdir/default/endpage.pstpl"));
doFooter();
exit;
}
}
if (isset($_SESSION['srid']))
{
$saved_id = $_SESSION['srid'];
}
if (!isset($_SESSION['s_lang']) && (isset($move)) )
// geez ... a session time out! RUN!
{
if (isset($_REQUEST['rootdir']))
{
safe_die('You cannot start this script directly');
}
require_once(dirname(__FILE__).'/classes/core/language.php');
$baselang = GetBaseLanguageFromSurveyID($surveyid);
$clang = new limesurvey_lang($baselang);
//A nice exit
sendcacheheaders();
doHeader();
echo templatereplace(file_get_contents("$standardtemplaterootdir/default/startpage.pstpl"));
echo "\t<div id='wrapper'>\n"
."\t<p id='tokenmessage'>\n"
."\t<span class='error'>".$clang->gT("ERROR")."</span><br /><br />\n"
."\t".$clang->gT("We are sorry but your session has expired.")."<br /><br />\n"
."\t".$clang->gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection.")."<br /><br />\n"
."\t".sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$siteadminname,$siteadminemail)."<br /><br />\n"
."\t</p>\n"
."\t</div>\n";
echo templatereplace(file_get_contents("$standardtemplaterootdir/default/endpage.pstpl"));
doFooter();
exit;
};
if (isset($move) && (preg_match('/^changelang_/',$move)))
{
// Then changing language from the language changer
$_POST['lang'] = substr($_POST['move'],11); // since sanitizing $move removes hyphen in languages like de-informal
}
// Set the language of the survey, either from POST, GET parameter of session var
if (isset($_POST['lang']) && $_POST['lang']!='') // this one comes from the language question
{
$templang = sanitize_languagecode($_POST['lang']);
$clang = SetSurveyLanguage( $surveyid, $templang);
UpdateSessionGroupList($templang); // to refresh the language strings in the group list session variable
UpdateFieldArray(); // to refresh question titles and question text
}
else
if (isset($_GET['lang']) && $surveyid)
{
$templang = sanitize_languagecode($_GET['lang']);
$clang = SetSurveyLanguage( $surveyid, $templang);
UpdateSessionGroupList($templang); // to refresh the language strings in the group list session variable
UpdateFieldArray(); // to refresh question titles and question text
}
else
if (isset($_SESSION['s_lang']))
{
$clang = SetSurveyLanguage( $surveyid, $_SESSION['s_lang']);
}
elseif (isset($surveyid) && $surveyid)
{
$baselang = GetBaseLanguageFromSurveyID($surveyid);
$clang = SetSurveyLanguage( $surveyid, $baselang);
}
if (isset($_REQUEST['embedded_inc']))
{
safe_die('You cannot start this script directly');
}
if ( $embedded && $embedded_inc != '' )
{
require_once( $embedded_inc );
}
//CHECK FOR REQUIRED INFORMATION (sid)
if (!$surveyid)
{
if(isset($_GET['lang']))
{
$baselang = sanitize_languagecode($_GET['lang']);
}
elseif (!isset($baselang))
{
$baselang=$defaultlang;
}
$clang = new limesurvey_lang($baselang);
if(!isset($defaulttemplate))
{
$defaulttemplate="default";
}
$languagechanger = makelanguagechanger();
//Find out if there are any publicly available surveys
$query = "SELECT a.sid, b.surveyls_title, a.publicstatistics
FROM ".db_table_name('surveys')." AS a
INNER JOIN ".db_table_name('surveys_languagesettings')." AS b
ON ( surveyls_survey_id = a.sid AND surveyls_language = a.language )
WHERE surveyls_survey_id=a.sid
AND surveyls_language=a.language
AND a.active='Y'
AND a.listpublic='Y'
AND ((a.expires >= '".date("Y-m-d H:i")."') OR (a.expires is null))
AND ((a.startdate <= '".date("Y-m-d H:i")."') OR (a.startdate is null))
ORDER BY surveyls_title";
$result = db_execute_assoc($query,false,true) or die("Could not connect to database. If you try to install LimeSurvey please refer to the <a href='http://docs.limesurvey.org'>installation docs</a> and/or contact the system administrator of this webpage."); //Checked
$list=array();
if($result->RecordCount() > 0)
{
while($rows = $result->FetchRow())
{
$result2 = db_execute_assoc("Select surveyls_title from ".db_table_name('surveys_languagesettings')." where surveyls_survey_id={$rows['sid']} and surveyls_language='$baselang'");
if ($result2->RecordCount())
{
$languagedetails=$result2->FetchRow();
$rows['surveyls_title']=$languagedetails['surveyls_title'];
}
$link = "<li><a href='$rooturl/index.php?sid=".$rows['sid'];
if (isset($_GET['lang']))
{
$link .= "&lang=".sanitize_languagecode($_GET['lang']);
}
if (isset($_GET['lang']))
{
$link .= "&lang=".sanitize_languagecode($_GET['lang']);
}
$link .= "' class='surveytitle'>".$rows['surveyls_title']."</a>\n";
if ($rows['publicstatistics'] == 'Y') $link .= "<a href='{$relativeurl}/statistics_user.php?sid={$rows['sid']}'>(".$clang->gT('View statistics').")</a>";
$link .= "</li>\n";
$list[]=$link;
}
}
if(count($list) < 1)
{
$list[]="<li class='surveytitle'>".$clang->gT("No available surveys")."</li>";
}
$surveylist=array(
"nosid"=>$clang->gT("You have not provided a survey identification number"),
"contact"=>sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$siteadminname,encodeEmail($siteadminemail)),
"listheading"=>$clang->gT("The following surveys are available:"),
"list"=>implode("\n",$list),
);
$thissurvey['name']=$sitename;
$thissurvey['templatedir']=$defaulttemplate;
//A nice exit
sendcacheheaders();
doHeader();
echo templatereplace(file_get_contents(sGetTemplatePath($defaulttemplate)."/startpage.pstpl"));
echo templatereplace(file_get_contents(sGetTemplatePath($defaulttemplate)."/surveylist.pstpl"));
echo templatereplace(file_get_contents(sGetTemplatePath($defaulttemplate)."/endpage.pstpl"));
doFooter();
exit;
}
// Get token
if (!isset($token))
{
$token=$clienttoken;
}
//GET BASIC INFORMATION ABOUT THIS SURVEY
$totalBoilerplatequestions =0;
$thissurvey=getSurveyInfo($surveyid, $_SESSION['s_lang']);
if (isset($_GET['newtest']) && $_GET['newtest'] == "Y")
{
//Removes any existing timer cookies so timers will start again
setcookie ("limesurvey_timers", "", time() - 3600);
}
//SEE IF SURVEY USES TOKENS AND GROUP TOKENS
$i = 0; //$tokensexist = 0;
if ($surveyexists == 1 && tableExists('tokens_'.$thissurvey['sid']))
{
$tokensexist = 1;
}
else
{
$tokensexist = 0;
unset ($_POST['token']);
unset ($_GET['token']);
unset($token);
unset($clienttoken);
}
//SET THE TEMPLATE DIRECTORY
if (!$thissurvey['templatedir'])
{
$thistpl=sGetTemplatePath($defaulttemplate);
}
else
{
$thistpl=sGetTemplatePath($thissurvey['templatedir']);
}
//MAKE SURE SURVEY HASN'T EXPIRED
if ($thissurvey['expiry']!='' and date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust)>$thissurvey['expiry'] && $thissurvey['active']!='N')
{
sendcacheheaders();
doHeader();
echo templatereplace(file_get_contents("$thistpl/startpage.pstpl"));
echo "\t<div id='wrapper'>\n"
."\t<p id='tokenmessage'>\n"
."\t".$clang->gT("This survey is no longer available.")."<br /><br />\n"
."\t".sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$thissurvey['adminname'],$thissurvey['adminemail']).".<br /><br />\n"
."\t</p>\n"
."\t</div>\n";
echo templatereplace(file_get_contents("$thistpl/endpage.pstpl"));
doFooter();
exit;
}
//MAKE SURE SURVEY IS ALREADY VALID
if ($thissurvey['startdate']!='' and date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust)<$thissurvey['startdate'] && $thissurvey['active']!='N')
{
sendcacheheaders();
doHeader();
echo templatereplace(file_get_contents("$thistpl/startpage.pstpl"));
echo "\t<div id='wrapper'>\n"
."\t<p id='tokenmessage'>\n"
."\t".$clang->gT("This survey is not yet started.")."<br /><br />\n"
."\t".sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$thissurvey['adminname'],$thissurvey['adminemail']).".<br /><br />\n"
."\t</p>\n"
."\t</div>\n";
echo templatereplace(file_get_contents("$thistpl/endpage.pstpl"));
doFooter();
exit;
}
//CHECK FOR PREVIOUSLY COMPLETED COOKIE
//If cookies are being used, and this survey has been completed, a cookie called "PHPSID[sid]STATUS" will exist (ie: SID6STATUS) and will have a value of "COMPLETE"
$cookiename="PHPSID".returnglobal('sid')."STATUS";
if (isset($_COOKIE[$cookiename]) && $_COOKIE[$cookiename] == "COMPLETE" && $thissurvey['usecookie'] == "Y" && $tokensexist != 1 && (!isset($_GET['newtest']) || $_GET['newtest'] != "Y"))
{
sendcacheheaders();
doHeader();
echo templatereplace(file_get_contents("$thistpl/startpage.pstpl"));
echo "\t<div id='wrapper'>\n"
."\t<p id='tokenmessage'>\n"
."\t<span class='error'>".$clang->gT("Error")."</span><br /><br />\n"
."\t".$clang->gT("You have already completed this survey.")."<br /><br />\n"
."\t".sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$thissurvey['adminname'],$thissurvey['adminemail'])."\n"
."\t</p>\n"
."\t</div>\n";
echo templatereplace(file_get_contents("$thistpl/endpage.pstpl"));
doFooter();
exit;
}
//CHECK IF SURVEY ID DETAILS HAVE CHANGED
if (isset($_SESSION['oldsid']))
{
$oldsid=$_SESSION['oldsid'];
}
if (!isset($oldsid))
{
$_SESSION['oldsid'] = $surveyid;
}
if (isset($oldsid) && $oldsid && $oldsid != $surveyid)
{
$savesessionvars=Array();
if (isset($_SESSION['USER_RIGHT_PREVIEW']))
{
$savesessionvars["USER_RIGHT_PREVIEW"]=$surveyid;
$savesessionvars["loginID"]=$_SESSION['loginID'];
$savesessionvars["user"]=$_SESSION['user'];
}
session_unset();
$_SESSION['oldsid']=$surveyid;
foreach ($savesessionvars as $sesskey => $sessval)
{
$_SESSION[$sesskey]=$sessval;
}
}
if (isset($_GET['loadall']) && $_GET['loadall'] == "reload")
{
if (returnglobal('loadname') && returnglobal('loadpass'))
{
$_POST['loadall']="reload";
}
}
//LOAD SAVED SURVEY
if (isset($_POST['loadall']) && $_POST['loadall'] == "reload")
{
$errormsg="";
// if (loadname is not set) or if ((loadname is set) and (loadname is NULL))
if (!isset($loadname) || (isset($loadname) && ($loadname == null)))
{
$errormsg .= $clang->gT("You did not provide a name")."<br />\n";
}
// if (loadpass is not set) or if ((loadpass is set) and (loadpass is NULL))
if (!isset($loadpass) || (isset($loadpass) && ($loadpass == null)))
{
$errormsg .= $clang->gT("You did not provide a password")."<br />\n";
}
// if security question answer is incorrect
// Not called if scid is set in GET params (when using email save/reload reminder URL)
if (function_exists("ImageCreate") && captcha_enabled('saveandloadscreen',$thissurvey['usecaptcha']))
{
if ( (!isset($_POST['loadsecurity']) ||
!isset($_SESSION['secanswer']) ||
$_POST['loadsecurity'] != $_SESSION['secanswer']) &&
!isset($_GET['scid']))
{
$errormsg .= $clang->gT("The answer to the security question is incorrect.")."<br />\n";
}
}
// Load session before loading the values from the saved data
if (isset($_GET['loadall']))
{
$totalquestions = buildsurveysession();
}
$_SESSION['holdname']=$loadname; //Session variable used to load answers every page.
$_SESSION['holdpass']=$loadpass; //Session variable used to load answers every page.
if ($errormsg == "") loadanswers();
$move = "movenext";
$_SESSION['LEMreload']=true;
if ($errormsg)
{
$_POST['loadall'] = $clang->gT("Load Unfinished Survey");
}
}
//Allow loading of saved survey
if (isset($_POST['loadall']) && $_POST['loadall'] == $clang->gT("Load Unfinished Survey"))
{
require_once("load.php");
}
//Check if TOKEN is used for EVERY PAGE
//This function fixes a bug where users able to submit two surveys/votes
//by checking that the token has not been used at each page displayed.
// bypass only this check at first page (Step=0) because
// this check is done in buildsurveysession and error message
// could be more interresting there (takes into accound captcha if used)
if ($tokensexist == 1 && isset($token) && $token &&
isset($_SESSION['step']) && $_SESSION['step']>0 && db_tables_exist($dbprefix.'tokens_'.$surveyid))
{
//check if tokens actually haven't been already used
$areTokensUsed = usedTokens(db_quote(trim(strip_tags(returnglobal('token')))));
// check if token actually does exist
// check also if it is allowed to change survey after completion
if ($thissurvey['alloweditaftercompletion'] == 'Y' ) {
$tkquery = "SELECT * FROM ".db_table_name('tokens_'.$surveyid)." WHERE token='".db_quote($token)."' ";
} else {
$tkquery = "SELECT * FROM ".db_table_name('tokens_'.$surveyid)." WHERE token='".db_quote($token)."' AND (completed = 'N' or completed='')";
}
$tkresult = db_execute_num($tkquery); //Checked
$tokendata = $tkresult->FetchRow();
if ($tkresult->RecordCount()==0 || ($areTokensUsed && $thissurvey['alloweditaftercompletion'] != 'Y'))
{
sendcacheheaders();
doHeader();
//TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
echo templatereplace(file_get_contents("$thistpl/startpage.pstpl"));
echo templatereplace(file_get_contents("$thistpl/survey.pstpl"));
echo "\t<div id='wrapper'>\n"
."\t<p id='tokenmessage'>\n"
."\t".$clang->gT("This is a controlled survey. You need a valid token to participate.")."<br /><br />\n"
."\t".$clang->gT("The token you have provided is either not valid, or has already been used.")."\n"
."\t".sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']
." (<a href='mailto:{$thissurvey['adminemail']}'>"
."{$thissurvey['adminemail']}</a>)")."\n"
."\t</p>\n"
."\t</div>\n";
echo templatereplace(file_get_contents("$thistpl/endpage.pstpl"));
killSession();
doFooter();
exit;
}
}
if ($tokensexist == 1 && isset($token) && $token && db_tables_exist($dbprefix.'tokens_'.$surveyid)) //check if token is in a valid time frame
{
// check also if it is allowed to change survey after completion
if ($thissurvey['alloweditaftercompletion'] == 'Y' ) {
$tkquery = "SELECT * FROM ".db_table_name('tokens_'.$surveyid)." WHERE token='".db_quote($token)."' ";
} else {
$tkquery = "SELECT * FROM ".db_table_name('tokens_'.$surveyid)." WHERE token='".db_quote($token)."' AND (completed = 'N' or completed='')";
}
$tkresult = db_execute_assoc($tkquery); //Checked
$tokendata = $tkresult->FetchRow();
if ((trim($tokendata['validfrom'])!='' && $tokendata['validfrom']>date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust)) ||
(trim($tokendata['validuntil'])!='' && $tokendata['validuntil']<date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust)))
{
sendcacheheaders();
doHeader();
//TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
echo templatereplace(file_get_contents("$thistpl/startpage.pstpl"));
echo templatereplace(file_get_contents("$thistpl/survey.pstpl"));
echo "\t<div id='wrapper'>\n"
."\t<p id='tokenmessage'>\n"
."\t".$clang->gT("We are sorry but you are not allowed to enter this survey.")."<br /><br />\n"
."\t".$clang->gT("Your token seems to be valid but can be used only during a certain time period.")."<br />\n"
."\t".sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']
." (<a href='mailto:{$thissurvey['adminemail']}'>"
."{$thissurvey['adminemail']}</a>)")."\n"
."\t</p>\n"
."\t</div>\n";
echo templatereplace(file_get_contents("$thistpl/endpage.pstpl"));
doFooter();
killSession();
exit;
}
}
//Clear session and remove the incomplete response if requested.
if (isset($_GET['move']) && $_GET['move'] == "clearall")
{
$s_lang = $_SESSION['s_lang'];
if (isset($_SESSION['srid']))
{
// find out if there are any fuqt questions - checked
$fieldmap = createFieldMap($surveyid);
foreach ($fieldmap as $field)
{
if ($field['type'] == "|" && !strpos($field['fieldname'], "_filecount"))
{
if (!isset($qid)) { $qid = array(); }
$qid[] = $field['fieldname'];
}
}
// if yes, extract the response json to those questions
if (isset($qid))
{
$query = "SELECT * FROM ".db_table_name("survey_".$surveyid)." WHERE id=".$_SESSION['srid'];
$result = db_execute_assoc($query);
while ($row = $result->FetchRow())
{
foreach ($qid as $question)
{
$json = $row[$question];
if ($json == "" || $json == NULL)
continue;
// decode them
$phparray = json_decode($json);
foreach ($phparray as $metadata)
{
$target = "{$uploaddir}/surveys/{$surveyid}/files/";
// delete those files
unlink($target.$metadata->filename);
}
}
}
}
// done deleting uploaded files
// delete the response but only if not already completed
$connect->query('DELETE FROM '.db_table_name('survey_'.$surveyid).' WHERE id='.$_SESSION['srid']." AND submitdate IS NULL");
// also delete a record from saved_control when there is one
$connect->query('DELETE FROM '.db_table_name('saved_control'). ' WHERE srid='.$_SESSION['srid'].' AND sid='.$surveyid);
}
session_unset();
session_destroy();
setcookie(session_name(),"EXPIRED",time()-120);
sendcacheheaders();
if (isset($_GET['redirect']))
{
session_write_close();
header("Location: {$_GET['redirect']}");
}
doHeader();
echo templatereplace(file_get_contents("$thistpl/startpage.pstpl"));
echo "\n\n<!-- JAVASCRIPT FOR CONDITIONAL QUESTIONS -->\n"
."\t<script type='text/javascript'>\n"
."\t<!--\n"
."function checkconditions(value, name, type, evt_type)\n"
."\t{\n"
."\t}\n"
."\t//-->\n"
."\t</script>\n\n";
//Present the clear all page using clearall.pstpl template
echo templatereplace(file_get_contents("$thistpl/clearall.pstpl"));
echo templatereplace(file_get_contents("$thistpl/endpage.pstpl"));
doFooter();
exit;
}
if (isset($_GET['newtest']) && $_GET['newtest'] == "Y")
{
$savesessionvars=Array();
if (isset($_SESSION['USER_RIGHT_PREVIEW']))
{
$savesessionvars["USER_RIGHT_PREVIEW"]=$surveyid;
$savesessionvars["loginID"]=$_SESSION['loginID'];
$savesessionvars["user"]=$_SESSION['user'];
}
session_unset();
$_SESSION['oldsid']=$surveyid;
foreach ($savesessionvars as $sesskey => $sessval)
{
$_SESSION[$sesskey]=$sessval;
}
//DELETE COOKIE (allow to use multiple times)
setcookie($cookiename, "INCOMPLETE", time()-120);
//echo "Reset Cookie!";
}
//Check to see if a refering URL has been captured.
GetReferringUrl();
// Let's do this only if
// - a saved answer record hasn't been loaded through the saved feature
// - the survey is not anonymous
// - the survey is active
// - a token information has been provided
// - the survey is setup to allow token-response-persistence
if (!isset($_SESSION['srid']) && $thissurvey['anonymized'] == "N" && $thissurvey['active'] == "Y" && isset($token) && $token !='')
{
// load previous answers if any (dataentry with nosubmit)
$srquery="SELECT id,submitdate FROM {$thissurvey['tablename']}"
. " WHERE {$thissurvey['tablename']}.token='".db_quote($token)."' order by id desc";
$result = db_select_limit_assoc($srquery,1);
if ($result->RecordCount()>0)
{
$row=$result->FetchRow();
if(($row['submitdate']=='' && $thissurvey['tokenanswerspersistence'] == 'Y' )|| ($row['submitdate']!='' && $thissurvey['alloweditaftercompletion'] == 'Y'))
{
$_SESSION['srid'] = $row['id'];
}
buildsurveysession();
loadanswers();
}
}
if (isset($_REQUEST['action']) && ($_REQUEST['action'] == 'previewgroup')){
$thissurvey['format'] = 'G';
buildsurveysession(true);
}
sendcacheheaders();
//CALL APPROPRIATE SCRIPT
require_once("group.php"); // works for all survey styles - rename to navigation_controller.php?
if (isset($_POST['saveall']) || isset($flashmessage))
{
echo "<script language='JavaScript'> $(document).ready( function() {alert('".$clang->gT("Your responses were successfully saved.","js")."');}) </script>";
}
function loadanswers()
{
global $dbprefix,$surveyid,$errormsg;
global $thissurvey, $thisstep, $clang;
global $databasetype, $clienttoken;
$scid=returnglobal('scid');
if (isset($_POST['loadall']) && $_POST['loadall'] == "reload")
{
$query = "SELECT * FROM ".db_table_name('saved_control')." INNER JOIN {$thissurvey['tablename']}
ON ".db_table_name('saved_control').".srid = {$thissurvey['tablename']}.id
WHERE ".db_table_name('saved_control').".sid=$surveyid\n";
if (isset($scid)) //Would only come from email
{
$query .= "AND ".db_table_name('saved_control').".scid={$scid}\n";
}
$query .="AND ".db_table_name('saved_control').".identifier = '".auto_escape($_SESSION['holdname'])."' ";
if ($databasetype=='odbc_mssql' || $databasetype=='odbtp' || $databasetype=='mssql_n' || $databasetype=='mssqlnative')
{
$query .="AND CAST(".db_table_name('saved_control').".access_code as varchar(32))= '".md5(auto_unescape($_SESSION['holdpass']))."'\n";
}
else
{
$query .="AND ".db_table_name('saved_control').".access_code = '".md5(auto_unescape($_SESSION['holdpass']))."'\n";
}
}
elseif (isset($_SESSION['srid']))
{
$query = "SELECT * FROM {$thissurvey['tablename']}
WHERE {$thissurvey['tablename']}.id=".$_SESSION['srid']."\n";
}
else
{
return;
}
$result = db_execute_assoc($query) or safe_die ("Error loading results<br />$query<br />".$connect->ErrorMsg()); //Checked
if ($result->RecordCount() < 1)
{
$errormsg .= $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->FetchRow();
foreach ($row as $column => $value)
{
if ($column == "token")
{
$clienttoken=$value;
$token=$value;
}
elseif ($column == "saved_thisstep" && $thissurvey['alloweditaftercompletion'] != 'Y' )
{
$_SESSION['step']=$value;
$thisstep=$value-1;
}
elseif ($column =='lastpage' && isset($_GET['token']) && $thissurvey['alloweditaftercompletion'] != 'Y' )
{
if ($value<1) $value=1;
$_SESSION['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['scid']=$value;
}
elseif ($column == "srid")
{
$_SESSION['srid']=$value;
}
elseif ($column == "datestamp")
{
$_SESSION['datestamp']=$value;
}
if ($column == "startdate")
{
$_SESSION['startdate']=$value;
}
else
{
//Only make session variables for those in insertarray[]
if (in_array($column, $_SESSION['insertarray']))
{
// if (($_SESSION['fieldmap'][$column]['type'] == 'N' ||
// $_SESSION['fieldmap'][$column]['type'] == 'K' ||
// $_SESSION['fieldmap'][$column]['type'] == 'D') && $value == null)
// { // For type N,K,D NULL in DB is to be considered as NoAnswer in any case.
// // We need to set the _SESSION[field] value to '' in order to evaluate conditions.
// // This is especially important for the deletenonvalue feature,
// // otherwise we would erase any answer with condition such as EQUALS-NO-ANSWER on such
// // question types (NKD)
// $_SESSION[$column]='';