/
index.php
832 lines (730 loc) · 36.7 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
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
* LimeSurvey
* Copyright (C) 2007-2011 The LimeSurvey Project Team / Carsten Schmitz
* All rights reserved.
* License: GNU/GPL License v2 or later, see LICENSE.php
* LimeSurvey is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*/
class index extends CAction {
public function run()
{
/*
* Instead of manually rendering scripts after this function returns we
* use the callback. This ensures that scripts are always rendered, even
* if we call exit at some point in the code. (Which we shouldn't, but
* it happens.)
*/
ob_start(function($buffer, $phase) {
App()->getClientScript()->render($buffer);
App()->getClientScript()->reset();
return $buffer;
});
ob_implicit_flush(false);
$this->action();
ob_flush();
}
function action()
{
global $surveyid;
global $thissurvey, $thisstep;
global $clienttoken, $tokensexist, $token;
global $clang;
$clang = Yii::app()->lang;
// only attempt to change session lifetime if using a DB backend
// with file based sessions, it's up to the admin to configure maxlifetime
if(isset(Yii::app()->session->connectionID)) {
@ini_set('session.gc_maxlifetime', Yii::app()->getConfig('iSessionExpirationTime'));
}
$this->_loadRequiredHelpersAndLibraries();
$param = $this->_getParameters(func_get_args(), $_POST);
$surveyid = $param['sid'];
Yii::app()->setConfig('surveyID',$surveyid);
$thisstep = $param['thisstep'];
$move=getMove();
Yii::app()->setConfig('move',$move);
$clienttoken = $param['token'];
$standardtemplaterootdir = Yii::app()->getConfig('standardtemplaterootdir');
if (is_null($thissurvey) && !is_null($surveyid)) $thissurvey = getSurveyInfo($surveyid);
// unused vars in this method (used in methods using compacted method vars)
@$loadname = $param['loadname'];
@$loadpass = $param['loadpass'];
$sitename = Yii::app()->getConfig('sitename');
if (isset($param['newtest']) && $param['newtest'] == "Y")
{
killSurveySession($surveyid);
}
$surveyExists=($surveyid && Survey::model()->findByPk($surveyid));
$isSurveyActive=($surveyExists && Survey::model()->findByPk($surveyid)->active=="Y");
// collect all data in this method to pass on later
$redata = compact(array_keys(get_defined_vars()));
$clang = $this->_loadLimesurveyLang($surveyid);
if ( $this->_isClientTokenDifferentFromSessionToken($clienttoken,$surveyid) )
{
$sReloadUrl=$this->getController()->createUrl("/survey/index/sid/{$surveyid}",array('token'=>$clienttoken,'lang'=>$clang->langcode,'newtest'=>'Y'));
$asMessage = array(
$clang->gT('Token mismatch'),
$clang->gT('The token you provided doesn\'t match the one in your session.'),
"<a class='reloadlink newsurvey' href={$sReloadUrl}>".$clang->gT("Click here to start the survey.")."</a>"
);
$this->_createNewUserSessionAndRedirect($surveyid, $redata, __LINE__, $asMessage);
}
if ( $this->_isSurveyFinished($surveyid) && ($thissurvey['alloweditaftercompletion'] != 'Y' || $thissurvey['tokenanswerspersistence'] != 'Y')) // No test for response update
{
$aReloadUrlParam=array('lang'=>$clang->langcode,'newtest'=>'Y');
if($clienttoken){$aReloadUrlParam['token']=$clienttoken;}
$sReloadUrl=$this->getController()->createUrl("/survey/index/sid/{$surveyid}",$aReloadUrlParam);
$asMessage = array(
$clang->gT('Previous session is set to be finished.'),
$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.'),
"<a class='reloadlink newsurvey' href={$sReloadUrl}>".$clang->gT("Click here to start the survey.")."</a>"
);
$this->_createNewUserSessionAndRedirect($surveyid, $redata, __LINE__, $asMessage);
}
$previewmode=false;
if (isset($param['action']) && (in_array($param['action'],array('previewgroup','previewquestion'))))
{
if(!$this->_canUserPreviewSurvey($surveyid))
{
$asMessage = array(
$clang->gT('Error'),
$clang->gT("We are sorry but you don't have permissions to do this.")
);
$this->_niceExit($redata, __LINE__, null, $asMessage);
}
else
{
if((intval($param['qid']) && $param['action']=='previewquestion')) $previewmode='question';
if((intval($param['gid']) && $param['action']=='previewgroup')) $previewmode='group';
}
}
Yii::app()->setConfig('previewmode',$previewmode);
if ( $this->_surveyCantBeViewedWithCurrentPreviewAccess($surveyid, $isSurveyActive, $surveyExists) )
{
$bPreviewRight = $this->_userHasPreviewAccessSession($surveyid);
if ($bPreviewRight === false)
{
$asMessage = array(
$clang->gT("Error"),
$clang->gT("We are sorry but you don't have permissions to do this."),
sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$thissurvey['adminname'],$thissurvey['adminemail'])
);
$this->_niceExit($redata, __LINE__, null, $asMessage);
}
}
// TODO can this be moved to the top?
// (Used to be global, used in ExpressionManager, merged into amVars. If not filled in === '')
// can this be added in the first computation of $redata?
if (isset($_SESSION['survey_'.$surveyid]['srid']))
{
$saved_id = $_SESSION['survey_'.$surveyid]['srid'];
}
// recompute $redata since $saved_id used to be a global
$redata = compact(array_keys(get_defined_vars()));
/*if ( $this->_didSessionTimeOut() )
{
// @TODO is this still required ?
$asMessage = array(
$clang->gT("Error"),
$clang->gT("We are sorry but your session has expired."),
$clang->gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection."),
sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$thissurvey['adminname'],$thissurvey['adminemail'])
);
$this->_niceExit($redata, __LINE__, null, $asMessage);
};*/
// Set the language of the survey, either from POST, GET parameter of session var
// Keep the old value, because SetSurveyLanguage update $_SESSION
$sOldLang=isset($_SESSION['survey_'.$surveyid]['s_lang'])?$_SESSION['survey_'.$surveyid]['s_lang']:"";// Keep the old value, because SetSurveyLanguage update $_SESSION
if (!is_null($param['lang']) )
{
$sDisplayLanguage = $param['lang'];// $param take lang from returnGlobal and returnGlobal sanitize langagecode
}
elseif (isset($_SESSION['survey_'.$surveyid]['s_lang']))
{
$sDisplayLanguage = $_SESSION['survey_'.$surveyid]['s_lang'];
}
else
{
$sDisplayLanguage=Yii::app()->getConfig('defaultlang');
}
//CHECK FOR REQUIRED INFORMATION (sid)
if ($surveyid && $surveyExists)
{
LimeExpressionManager::SetSurveyId($surveyid); // must be called early - it clears internal cache if a new survey is being used
$clang = SetSurveyLanguage( $surveyid, $sDisplayLanguage);
if($previewmode) LimeExpressionManager::SetPreviewMode($previewmode);
if ($clang->langcode != $sOldLang) // Update the Session var only if needed
{
UpdateGroupList($surveyid, $clang->langcode); // to refresh the language strings in the group list session variable
UpdateFieldArray(); // to refresh question titles and question text
}
}
else
{
$clang = $this->_loadLimesurveyLang($sDisplayLanguage);
Yii::app()->session['s_lang']=$clang->langcode;
$languagechanger = makeLanguageChanger($clang->langcode);
//Find out if there are any publicly available surveys
$query = "SELECT sid, surveyls_title, publicstatistics, language
FROM {{surveys}}
INNER JOIN {{surveys_languagesettings}}
ON ( surveyls_survey_id = sid )
AND (surveyls_language=language)
WHERE
active='Y'
AND listpublic='Y'
AND ((expires >= '".date("Y-m-d H:i")."') OR (expires is null))
AND ((startdate <= '".date("Y-m-d H:i")."') OR (startdate is null))
ORDER BY surveyls_title";
$result = dbExecuteAssoc($query,false,true) or safeDie("Could not connect to database. If you try to install LimeSurvey please refer to the <a href='http://manual.limesurvey.org'>installation docs</a> and/or contact the system administrator of this webpage."); //Checked
$list=array();
foreach($result->readAll() as $rows)
{
# $querylang="SELECT surveyls_title
# FROM {{surveys_languagesettings}}
# WHERE surveyls_survey_id={$rows['sid']}
# AND surveyls_language='{$sDisplayLanguage}'";
# $resultlang=Yii::app()->db->createCommand($querylang)->queryRow();
$resultlang=SurveyLanguageSetting::model()->find(
"surveyls_survey_id=:surveyls_survey_id AND surveyls_language=:surveyls_language",
array(':surveyls_survey_id'=>intval($rows['sid']),':surveyls_language'=>$sDisplayLanguage)
);
$langparam=array();
$langtag = "";
if ($resultlang )
{
$rows['surveyls_title']=$resultlang->surveyls_title;
$langparam=array('lang'=>$sDisplayLanguage);
}
else
{
$langtag = "lang=\"{$rows['language']}\"";
}
$link = "<li><a href='".$this->getController()->createUrl('/survey/index/sid/'.$rows['sid'],$langparam);
$link .= "' $langtag class='surveytitle'>".$rows['surveyls_title']."</a>\n";
if ($rows['publicstatistics'] == 'Y') $link .= "<a href='".$this->getController()->createUrl("/statistics_user/action/surveyid/".$rows['sid'])."/language/".$sDisplayLanguage."'>(".$clang->gT('View statistics').")</a>";
$link .= "</li>\n";
$list[]=$link;
}
//Check for inactive surveys which allow public registration.
// TODO add a new template replace {SURVEYREGISTERLIST} ?
$squery = "SELECT sid, surveyls_title, publicstatistics, language
FROM {{surveys}}
INNER JOIN {{surveys_languagesettings}}
ON (surveyls_survey_id = sid)
AND (surveyls_language=language)
WHERE allowregister='Y'
AND active='Y'
AND listpublic='Y'
AND ((expires >= '".date("Y-m-d H:i")."') OR (expires is null))
AND (startdate >= '".date("Y-m-d H:i")."')
ORDER BY surveyls_title";
$sresult = dbExecuteAssoc($squery) or safeDie("Couldn't execute $squery");
$aRows=$sresult->readAll();
if(count($aRows) > 0)
{
$list[] = "</ul>"
." <div class=\"survey-list-heading\">".$clang->gT("Following survey(s) are not yet active but you can register for them.")."</div>"
." <ul>"; // TODO give it to template
foreach($aRows as $rows)
{
$querylang="SELECT surveyls_title
FROM {{surveys_languagesettings}}
WHERE surveyls_survey_id={$rows['sid']}
AND surveyls_language='{$sDisplayLanguage}'";
$resultlang=Yii::app()->db->createCommand($querylang)->queryRow();
if ($resultlang['surveyls_title'] )
{
$rows['surveyls_title']=$resultlang['surveyls_title'];
$langtag = "";
}
else
{
$langtag = "lang=\"{$rows['language']}\"";
}
$link = "<li><a href=\"#\" id='inactivesurvey' onclick = 'sendreq(".$rows['sid'].");' ";
//$link = "<li><a href=\"#\" id='inactivesurvey' onclick = 'convertGETtoPOST(".$this->getController()->createUrl('survey/send/')."?sid={$rows['sid']}&)sendreq(".$rows['sid'].",".$rows['startdate'].",".$rows['expires'].");' ";
$link .= " $langtag class='surveytitle'>".$rows['surveyls_title']."</a>\n";
$link .= "</li><div id='regform'></div>\n";
$list[]=$link;
}
}
if(count($list) < 1)
{
$list[]="<li class='surveytitle'>".$clang->gT("No available surveys")."</li>";
}
if(!$surveyid)
{
$thissurvey['name']=Yii::app()->getConfig("sitename");
$nosid=$clang->gT("You have not provided a survey identification number");
}
else
{
$thissurvey['name']=$clang->gT("The survey identification number is invalid");
$nosid=$clang->gT("The survey identification number is invalid");
}
$surveylist=array(
"nosid"=>$nosid,
"contact"=>sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),Yii::app()->getConfig("siteadminname"),encodeEmail(Yii::app()->getConfig("siteadminemail"))),
"listheading"=>$clang->gT("The following surveys are available:"),
"list"=>implode("\n",$list),
);
$data['thissurvey'] = $thissurvey;
//$data['privacy'] = $privacy;
$data['surveylist'] = $surveylist;
$data['surveyid'] = $surveyid;
$data['templatedir'] = getTemplatePath(Yii::app()->getConfig("defaulttemplate"));
$data['templateurl'] = getTemplateURL(Yii::app()->getConfig("defaulttemplate"))."/";
$data['templatename'] = Yii::app()->getConfig("defaulttemplate");
$data['sitename'] = Yii::app()->getConfig("sitename");
$data['languagechanger'] = $languagechanger;
//A nice exit
sendCacheHeaders();
doHeader();
$this->_printTemplateContent(getTemplatePath(Yii::app()->getConfig("defaulttemplate"))."/startpage.pstpl", $data, __LINE__);
$this->_printTemplateContent(getTemplatePath(Yii::app()->getConfig("defaulttemplate"))."/surveylist.pstpl", $data, __LINE__);
echo '<script type="text/javascript" >
function sendreq(surveyid)
{
$.ajax({
type: "GET",
url: "'.$this->getController()->createUrl("/register/ajaxregisterform/surveyid").'/" + surveyid,
}).done(function(msg) {
document.getElementById("regform").innerHTML = msg;
});
}
</script>';
$this->_printTemplateContent(getTemplatePath(Yii::app()->getConfig("defaulttemplate"))."/endpage.pstpl", $data, __LINE__);
doFooter();
return;
}
// Get token
if (!isset($token))
{
$token=$clienttoken;
}
//GET BASIC INFORMATION ABOUT THIS SURVEY
$thissurvey=getSurveyInfo($surveyid, $_SESSION['survey_'.$surveyid]['s_lang']);
//SEE IF SURVEY USES TOKENS
if ($surveyExists == 1 && tableExists('{{tokens_'.$thissurvey['sid'].'}}'))
{
$tokensexist = 1;
}
else
{
$tokensexist = 0;
unset($_POST['token']);
unset($param['token']);
unset($token);
unset($clienttoken);
}
//SET THE TEMPLATE DIRECTORY
$thistpl = getTemplatePath($thissurvey['templatedir']);
$timeadjust = Yii::app()->getConfig("timeadjust");
//MAKE SURE SURVEY HASN'T EXPIRED
if ($thissurvey['expiry']!='' and dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust)>$thissurvey['expiry'] && $thissurvey['active']!='N' && !$previewmode)
{
$redata = compact(array_keys(get_defined_vars()));
$asMessage = array(
$clang->gT("Error"),
$clang->gT("This survey is no longer available."),
sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$thissurvey['adminname'],$thissurvey['adminemail'])
);
$this->_niceExit($redata, __LINE__, $thissurvey['templatedir'], $asMessage);
}
//MAKE SURE SURVEY IS ALREADY VALID
if ($thissurvey['startdate']!='' and dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust)<$thissurvey['startdate'] && $thissurvey['active']!='N' && !$previewmode)
{
$redata = compact(array_keys(get_defined_vars()));
$asMessage = array(
$clang->gT("Error"),
$clang->gT("This survey is not yet started."),
sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$thissurvey['adminname'],$thissurvey['adminemail'])
);
$this->_niceExit($redata, __LINE__, $thissurvey['templatedir'], $asMessage);
}
//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"
$sCookieName="LS_".$surveyid."_STATUS";
if (isset($_COOKIE[$sCookieName]) && $_COOKIE[$sCookieName] == "COMPLETE" && $thissurvey['usecookie'] == "Y" && $tokensexist != 1 && (!isset($param['newtest']) || $param['newtest'] != "Y"))
{
$redata = compact(array_keys(get_defined_vars()));
$asMessage = array(
$clang->gT("Error"),
$clang->gT("You have already completed this survey."),
sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$thissurvey['adminname'],$thissurvey['adminemail'])
);
$this->_niceExit($redata, __LINE__, $thissurvey['templatedir'], $asMessage);
}
if (returnGlobal('loadall',true)=="reload") // Used if reload is done by URL (GET)
{
$_POST['loadall']="reload";
}
//LOAD SAVED SURVEY
if (isset($_POST['loadall']) && $_POST['loadall'] == "reload")
{
$errormsg="";
if ( !isset($param['loadname']) || $param['loadname'] == null )
{
$errormsg .= $clang->gT("You did not provide a name")."<br />\n";
}
if (!isset($param['loadpass']) || $param['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") && isCaptchaEnabled('saveandloadscreen',$thissurvey['usecaptcha']))
{
if ( (!isset($_POST['loadsecurity']) ||
!isset($_SESSION['survey_'.$surveyid]['secanswer']) ||
$_POST['loadsecurity'] != $_SESSION['survey_'.$surveyid]['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($_POST['loadall']))
{
LimeExpressionManager::SetDirtyFlag();
buildsurveysession($surveyid);
}
$_SESSION['survey_'.$surveyid]['holdname'] = $param['loadname']; //Session variable used to load answers every page.
$_SESSION['survey_'.$surveyid]['holdpass'] = $param['loadpass']; //Session variable used to load answers every page.
if ($errormsg == "") {
if (loadanswers()){
$move = "movenext";
} else {
$errormsg .= $clang->gT("There is no matching saved survey");
}
}
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"))
{
$redata = compact(array_keys(get_defined_vars()));
Yii::import("application.libraries.Load_answers");
$tmp = new Load_answers();
$tmp->run($redata);
}
//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['survey_'.$surveyid]['step']) && $_SESSION['survey_'.$surveyid]['step']>0 && tableExists("tokens_{$surveyid}}}"))
{
// check also if it is allowed to change survey after completion
if ($thissurvey['alloweditaftercompletion'] == 'Y' ) {
$tokenInstance = Token::model($surveyid)->findByAttributes(array('token' => $token));
} else {
$tokenInstance = Token::model($surveyid)->usable()->incomplete()->findByAttributes(array('token' => $token));
}
if (!isset($tokenInstance) && !$previewmode)
{
sendCacheHeaders();
doHeader();
//TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
$redata = compact(array_keys(get_defined_vars()));
$this->_printTemplateContent($thistpl.'/startpage.pstpl', $redata, __LINE__);
$this->_printTemplateContent($thistpl.'/survey.pstpl', $redata, __LINE__);
$asMessage = array(
null,
$clang->gT("This is a controlled survey. You need a valid token to participate."),
sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']." (<a href='mailto:{$thissurvey['adminemail']}'>"."{$thissurvey['adminemail']}</a>)")
);
$this->_niceExit($redata, __LINE__, $thistpl, $asMessage, true);
}
}
if ($tokensexist == 1 && isset($token) && tableExists("{{tokens_".$surveyid."}}") && !$previewmode) //check if token is in a valid time frame
{
// check also if it is allowed to change survey after completion
if ($thissurvey['alloweditaftercompletion'] == 'Y' ) {
$tokenInstance = Token::model($surveyid)->editable()->findByAttributes(array('token' => $token));
} else {
$tokenInstance = Token::model($surveyid)->usable()->incomplete()->findByAttributes(array('token' => $token));
}
if (!isset($tokenInstance))
{
sendCacheHeaders();
doHeader();
//TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
$redata = compact(array_keys(get_defined_vars()));
$this->_printTemplateContent($thistpl.'/startpage.pstpl', $redata, __LINE__);
$this->_printTemplateContent($thistpl.'/survey.pstpl', $redata, __LINE__);
$asMessage = array(
null,
$clang->gT("We are sorry but you are not allowed to enter this survey."),
$clang->gT("Your token seems to be valid but can be used only during a certain time period."),
sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']." (<a href='mailto:{$thissurvey['adminemail']}'>"."{$thissurvey['adminemail']}</a>)")
);
$this->_niceExit($redata, __LINE__, $thistpl, $asMessage, true);
}
}
//Clear session and remove the incomplete response if requested.
if (isset($move) && $move == "clearall")
{
// delete the response but only if not already completed
$s_lang = $_SESSION['survey_'.$surveyid]['s_lang'];
if (isset($_SESSION['survey_'.$surveyid]['srid']) && !SurveyDynamic::model($surveyid)->isCompleted($_SESSION['survey_'.$surveyid]['srid']))
{
// delete the response but only if not already completed
$result= dbExecuteAssoc('DELETE FROM {{survey_'.$surveyid.'}} WHERE id='.$_SESSION['survey_'.$surveyid]['srid']." AND submitdate IS NULL");
if($result->count()>0){ // Using count() here *should* be okay for MSSQL because it is a delete statement
// find out if there are any fuqt questions - checked
$fieldmap = createFieldMap($surveyid,'short',false,false,$s_lang);
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 {{survey_".$surveyid."}} WHERE id=".$_SESSION['survey_'.$surveyid]['srid'];
$result = dbExecuteAssoc($query);
foreach($result->readAll() as $row)
{
foreach ($qid as $question)
{
$json = $row[$question];
if ($json == "" || $json == NULL)
continue;
// decode them
$phparray = json_decode($json);
foreach ($phparray as $metadata)
{
$target = Yii::app()->getConfig("uploaddir")."/surveys/".$surveyid."/files/";
// delete those files
unlink($target.$metadata->filename);
}
}
}
}
// done deleting uploaded files
}
// also delete a record from saved_control when there is one
dbExecuteAssoc('DELETE FROM {{saved_control}} WHERE srid='.$_SESSION['survey_'.$surveyid]['srid'].' AND sid='.$surveyid);
}
killSurveySession($surveyid);
sendCacheHeaders();
doHeader();
$redata = compact(array_keys(get_defined_vars()));
$this->_printTemplateContent($thistpl.'/startpage.pstpl', $redata, __LINE__);
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
$this->_printTemplateContent($thistpl.'/clearall.pstpl', $redata, __LINE__);
$this->_printTemplateContent($thistpl.'/endpage.pstpl', $redata, __LINE__);
doFooter();
exit;
}
//Check to see if a refering URL has been captured.
if (!isset($_SESSION['survey_'.$surveyid]['refurl']))
{
$_SESSION['survey_'.$surveyid]['refurl']=GetReferringUrl(); // do not overwrite refurl
}
// 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['survey_'.$surveyid]['srid']) && $thissurvey['anonymized'] == "N" && $thissurvey['active'] == "Y" && isset($token) && $token !='')
{
// load previous answers if any (dataentry with nosubmit)
//$oSurveyTokenInstance=SurveyDynamic::model($surveyid)->find(array('select'=>'id,submitdate,lastpage', 'condition'=>'token=:token', 'order'=>'id DESC','params'=>array('token' => $token)));
$oSurveyTokenInstance=SurveyDynamic::model($surveyid)->find(array('condition'=>'token=:token', 'order'=>'id DESC','params'=>array('token' => $token)));
if ( $oSurveyTokenInstance )
{
if((empty($oSurveyTokenInstance->submitdate) || $thissurvey['alloweditaftercompletion'] == 'Y' ) && $thissurvey['tokenanswerspersistence'] == 'Y')
{
$_SESSION['survey_'.$surveyid]['srid'] = $oSurveyTokenInstance->id;
if (!empty($oSurveyTokenInstance->lastpage))
{
$_SESSION['survey_'.$surveyid]['LEMtokenResume'] = true;
$_SESSION['survey_'.$surveyid]['step'] = $oSurveyTokenInstance->lastpage;
}
}
buildsurveysession($surveyid);
if(!empty($oSurveyTokenInstance->submitdate)) // alloweditaftercompletion
{
$_SESSION['survey_'.$surveyid]['maxstep'] = $_SESSION['survey_'.$surveyid]['totalsteps'];
}
loadanswers();
}
}
// Preview action : Preview right already tested before
if ($previewmode)
{
// Unset all SESSION: be sure to have the last version
unset($_SESSION['fieldmap-' . $surveyid . $clang->langcode]);// Needed by createFieldMap: else fieldmap can be outdated
unset($_SESSION['survey_'.$surveyid]);
if ($param['action'] == 'previewgroup')
{
$thissurvey['format'] = 'G';
}
elseif ($param['action'] == 'previewquestion')
{
$thissurvey['format'] = 'S';
}
buildsurveysession($surveyid,true);
}
sendCacheHeaders();
//Send local variables to the appropriate survey type
unset($redata);
$redata = compact(array_keys(get_defined_vars()));
Yii::import('application.helpers.SurveyRuntimeHelper');
$tmp = new SurveyRuntimeHelper();
$tmp->run($surveyid,$redata);
if (isset($_POST['saveall']) || isset($flashmessage))
{
echo "<script type='text/javascript'> $(document).ready( function() { alert('".$clang->gT("Your responses were successfully saved.","js")."');}) </script>";
}
}
function _getParameters($args = array(), $post = array())
{
$param = array();
if(@$args[0]==__CLASS__) array_shift($args);
if(count($args)%2 == 0) {
for ($i = 0; $i < count($args); $i+=2) {
//Sanitize input from URL with returnGlobal
$param[$args[$i]] = returnGlobal($args[$i], true);
}
}
// Need some $param (else PHP notice)
foreach(array('lang','action','newtest','qid','gid','sid','loadname','loadpass','scid','thisstep','move','token') as $sNeededParam)
{
$param[$sNeededParam]=returnGlobal($sNeededParam,true);
}
return $param;
}
function _loadRequiredHelpersAndLibraries()
{
//Load helpers, libraries and config vars
Yii::app()->loadHelper("database");
Yii::app()->loadHelper("frontend");
Yii::app()->loadHelper("surveytranslator");
}
function _loadLimesurveyLang($mvSurveyIdOrBaseLang)
{
if ( is_numeric($mvSurveyIdOrBaseLang) && Survey::model()->findByPk($mvSurveyIdOrBaseLang))
{
$baselang = Survey::model()->findByPk($mvSurveyIdOrBaseLang)->language;
}
elseif (!empty($mvSurveyIdOrBaseLang))
{
$baselang = $mvSurveyIdOrBaseLang;
}
else
{
$baselang = Yii::app()->getConfig('defaultlang');
}
Yii::import("application.libraries.Limesurvey_lang");
return new Limesurvey_lang($baselang);
}
function _isClientTokenDifferentFromSessionToken($clientToken, $surveyid)
{
return $clientToken != '' && isset($_SESSION['survey_'.$surveyid]['token']) && $clientToken != $_SESSION['survey_'.$surveyid]['token'];
}
function _isSurveyFinished($surveyid)
{
return isset($_SESSION['survey_'.$surveyid]['finished']) && $_SESSION['survey_'.$surveyid]['finished'] === true;
}
function _surveyCantBeViewedWithCurrentPreviewAccess($surveyid, $bIsSurveyActive, $bSurveyExists)
{
$bSurveyPreviewRequireAuth = Yii::app()->getConfig('surveyPreview_require_Auth');
return $surveyid && $bIsSurveyActive === false && $bSurveyExists && isset($bSurveyPreviewRequireAuth) && $bSurveyPreviewRequireAuth == true && !$this->_canUserPreviewSurvey($surveyid);
}
function _didSessionTimeout()
{
return !isset($_SESSION['survey_'.$surveyid]['s_lang']);
}
function _canUserPreviewSurvey($iSurveyID)
{
if ( !isset($_SESSION['loginID']) ) // This is not needed because Permission::model()->hasSurveyPermission control connexion
return false;
return Permission::model()->hasSurveyPermission($iSurveyID,'surveycontent','read');
}
function _userHasPreviewAccessSession($iSurveyID){
return (isset($_SESSION['USER_RIGHT_PREVIEW']) && ($_SESSION['USER_RIGHT_PREVIEW'] == $iSurveyID));
}
function _niceExit(&$redata, $iDebugLine, $sTemplateDir = null, $asMessage = array())
{
if(isset($redata['surveyid']) && $redata['surveyid'] && !isset($thisurvey))
{
$thissurvey=getSurveyInfo($redata['surveyid']);
$sTemplateDir= getTemplatePath($thissurvey['template']);
}
else
{
$sTemplateDir= getTemplatePath($sTemplateDir);
}
sendCacheHeaders();
doHeader();
$this->_printTemplateContent($sTemplateDir.'/startpage.pstpl', $redata, $iDebugLine);
$this->_printMessage($asMessage);
$this->_printTemplateContent($sTemplateDir.'/endpage.pstpl', $redata, $iDebugLine);
doFooter();
exit;
}
function _createNewUserSessionAndRedirect($surveyid, &$redata, $iDebugLine, $asMessage = array())
{
$clang = Yii::app()->lang;
killSurveySession($surveyid);
$thissurvey=getSurveyInfo($surveyid);
if($thissurvey)
{
$templatename=$thissurvey['template'];
}
else
{
$templatename=Yii::app()->getConfig('defaulttemplate');;
}
// Let's redirect the client to the same URL after having reset the session
$this->_niceExit($redata, $iDebugLine, $templatename, $asMessage);
}
function _printMessage($asLines)
{
if ( func_num_args() > 1 )
$asLines = func_get_args();
if ( count($asLines) == 0 )
return;
$sError = array_shift($asLines);
echo "\t<div id='wrapper'>\n";
echo "\t<p id='tokenmessage'>\n";
if ( $sError != null )
{
echo "\t<span class='error'>".$sError."</span><br /><br />\n";
}
echo "\t".implode ("<br /><br />\n\t", $asLines)."<br /><br />\n";
echo "\t</p>\n";
echo "\t</div>\n";
}
function _printTemplateContent($sTemplateFile, &$redata, $iDebugLine = -1)
{
echo templatereplace(file_get_contents($sTemplateFile),array(),$redata,'survey['.$iDebugLine.']');
}
}
/* End of file survey.php */
/* Location: ./application/controllers/survey.php */