-
Notifications
You must be signed in to change notification settings - Fork 988
/
frontend_helper.php
2422 lines (2189 loc) · 93.5 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.
*/
// TODO: Why needed?
require_once(Yii::app()->basePath . '/libraries/MersenneTwister.php');
function loadanswers()
{
Yii::trace('start', 'survey.loadanswers');
global $surveyid;
global $thissurvey, $thisstep;
global $clienttoken;
$scid=Yii::app()->request->getQuery('scid');
if (Yii::app()->request->getParam('loadall') == "reload")
{
$sLoadName=Yii::app()->request->getParam('loadname');
$sLoadPass=Yii::app()->request->getParam('loadpass');
$oCriteria= new CDbCriteria;
$oCriteria->join="LEFT JOIN {{saved_control}} ON t.id={{saved_control}}.srid";
$oCriteria->condition="{{saved_control}}.sid=:sid";
$aParams=array(':sid'=>$surveyid);
if (isset($scid)) //Would only come from email : we don't need it ....
{
$oCriteria->addCondition("{{saved_control}}.scid=:scid");
$aParams[':scid']=$scid;
}
$oCriteria->addCondition("{{saved_control}}.identifier=:identifier");
$aParams[':identifier']=$sLoadName;
if (in_array(Yii::app()->db->getDriverName(), array('mssql', 'sqlsrv', 'dblib')))
{
// To be validated with mssql, think it's not needed
$oCriteria->addCondition("(CAST({{saved_control}}.access_code as varchar(64))=:md5_code OR CAST({{saved_control}}.access_code as varchar(64))=:sha256_code)");
}
else
{
$oCriteria->addCondition("({{saved_control}}.access_code=:md5_code OR {{saved_control}}.access_code=:sha256_code)");
}
$aParams[':md5_code']=md5($sLoadPass);
$aParams[':sha256_code']=hash('sha256',$sLoadPass);
}
elseif (isset($_SESSION['survey_'.$surveyid]['srid']))
{
$oCriteria= new CDbCriteria;
$oCriteria->condition="id=:id";
$aParams=array(':id'=>$_SESSION['survey_'.$surveyid]['srid']);
}
else
{
return;
}
$oCriteria->params=$aParams;
$oResponses=SurveyDynamic::model($surveyid)->find($oCriteria);
if (!$oResponses)
{
return false;
}
else
{
//A match has been found. Let's load the values!
//If this is from an email, build surveysession first
$_SESSION['survey_'.$surveyid]['LEMtokenResume']=true;
// If survey come from reload (GET or POST); some value need to be found on saved_control, not on survey
if (Yii::app()->request->getParam('loadall') == "reload")
{
$oSavedSurvey=SavedControl::model()->find(
"sid = :sid AND identifier = :identifier AND (access_code = :access_code OR access_code = :sha256_code)",
array(
':sid' => $surveyid,
':identifier' => $sLoadName,
':access_code' => md5($sLoadPass),
':sha256_code' => hash('sha256',$sLoadPass)
)
);
// We don't need to control if we have one, because we do the test before
$_SESSION['survey_'.$surveyid]['scid'] = $oSavedSurvey->scid;
$_SESSION['survey_'.$surveyid]['step'] = ($oSavedSurvey->saved_thisstep>1)?$oSavedSurvey->saved_thisstep:1;
$thisstep=$_SESSION['survey_'.$surveyid]['step']-1;// deprecated ?
$_SESSION['survey_'.$surveyid]['srid'] = $oSavedSurvey->srid;// Seems OK without
$_SESSION['survey_'.$surveyid]['refurl'] = $oSavedSurvey->refurl;
}
// Get if survey is been answered
$submitdate=$oResponses->submitdate;
$aRow=$oResponses->attributes;
foreach ($aRow as $column => $value)
{
if ($column == "token")
{
$clienttoken=$value;
$token=$value;
}
elseif ($column =='lastpage' && !isset($_SESSION['survey_'.$surveyid]['step']))
{
if(is_null($submitdate) || $submitdate=="N")
{
$_SESSION['survey_'.$surveyid]['step']=($value>1? $value:1) ;
$thisstep=$_SESSION['survey_'.$surveyid]['step']-1;
}
else
{
$_SESSION['survey_'.$surveyid]['maxstep']=($value>1? $value:1) ;
}
}
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']) && isset($_SESSION['survey_'.$surveyid]['fieldmap'][$column]))
{
if (($_SESSION['survey_'.$surveyid]['fieldmap'][$column]['type'] == 'N' ||
$_SESSION['survey_'.$surveyid]['fieldmap'][$column]['type'] == 'K' ||
$_SESSION['survey_'.$surveyid]['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['survey_'.$surveyid][$column]='';
}
else
{
$_SESSION['survey_'.$surveyid][$column]=$value;
}
if(isset($token) && !empty($token))
{
$_SESSION['survey_'.$surveyid][$column]=$value;
}
} // if (in_array(
} // else
} // foreach
return true;
}
}
function makegraph($currentstep, $total)
{
global $thissurvey;
Yii::app()->getClientScript()->registerCssFile(Yii::app()->getConfig('publicstyleurl') . 'lime-progress.css');
$size = intval(($currentstep-1)/$total*100);
$graph='
<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="'.$size.'" aria-valuemin="0" aria-valuemax="100" style="min-width: 2em; width: '.$size.'%;">
'.$size.'%
</div>
</div>';
return $graph;
}
/**
* This function creates the language selector for a particular survey
*
* @param string $sSelectedLanguage : lang to be selected (forced)
* @param boolean $withForm : add a form (method="get") around the select
*/
function makeLanguageChangerSurvey($sSelectedLanguage="",$withForm=false, $returnDatas=false)
{
$surveyid = Yii::app()->getConfig('surveyID');
Yii::app()->loadHelper("surveytranslator");
$aSurveyLangs = Survey::model()->findByPk($surveyid)->getAllLanguages();
if (count($aSurveyLangs)>1) // return a dropdow only of there are more than one lanagage
{
$aAllLanguages=getLanguageData(true);
$aSurveyLangs=array_intersect_key($aAllLanguages,array_flip($aSurveyLangs)); // Sort languages by their locale name
$sClass="ls-language-changer-item";
$btnClass='ls-change-lang';
$sAction=Yii::app()->request->getParam('action','');// Different behaviour if preview
$sSelected="";
$routeParams=array(
"sid"=>$surveyid,
);
if(substr($sAction,0,7)=='preview'){
$routeParams["action"]=$sAction;
if (intval(Yii::app()->request->getParam('gid',0)))
{
$routeParams['gid']=intval(Yii::app()->request->getParam('gid',0));
}
if ($sAction=='previewquestion' && intval(Yii::app()->request->getParam('gid',0)) && intval(Yii::app()->request->getParam('qid',0)))
{
$routeParams['qid']=intval(Yii::app()->request->getParam('qid',0));
}
if (!is_null(Yii::app()->request->getParam('token')))
{
$routeParams['token']=Yii::app()->request->getParam('token');
}
// @todo : add other params (for prefilling by URL in preview mode)
$sClass.=" ls-no-js-hidden ls-previewmode-language-dropdown ";
$sTargetURL=Yii::app()->getController()->createUrl("survey/index",$routeParams);
}else{
$sTargetURL=null;
}
$aListLang = array();
foreach ($aSurveyLangs as $sLangCode => $aSurveyLang)
{
$aListLang[$sLangCode]=html_entity_decode($aSurveyLang['nativedescription'], ENT_COMPAT,'UTF-8');
}
$sSelected=($sSelectedLanguage) ? $sSelectedLanguage : App()->language;
$languageChangerDatas = array(
'sSelected' => $sSelected ,
'aListLang' => $aListLang ,
'sClass' => $sClass ,
'targetUrl' => $sTargetURL,
);
if($withForm){
$sHTMLCode = App()->getController()->renderPartial('/survey/system/LanguageChanger/LanguageChangerForm', $languageChangerDatas, true);
}else{
$sHTMLCode = App()->getController()->renderPartial('/survey/system/LanguageChanger/LanguageChanger', $languageChangerDatas, true);
}
if (!$returnDatas){
App()->getClientScript()->registerScript("activateLanguageChanger","activateLanguageChanger();\n",CClientScript::POS_END);
return $sHTMLCode;
}else{
$languageChangerDatas['withForm'] = $withForm;
return $languageChangerDatas;
}
}
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)
{
$aLanguages=getLanguageDataRestricted(true);// Order by native
if(count($aLanguages)>1)
{
$sClass= "ls-language-changer-item";
foreach ($aLanguages as $sLangCode => $aLanguage)
$aListLang[$sLangCode]=html_entity_decode($aLanguage['nativedescription'], ENT_COMPAT,'UTF-8').' - '.$aLanguage['description'];
$sSelected=$sSelectedLanguage;
$languageChangerDatas = array(
'sSelected' => $sSelected ,
'aListLang' => $aListLang ,
'sClass' => $sClass ,
);
$sHTMLCode = Yii::app()->getController()->renderPartial('/surveys/LanguageChangerForm', $languageChangerDatas, true);
return $sHTMLCode;
}
else
{
return false;
}
}
/**
* Construct flash message container
* Used in templatereplace to replace {FLASHMESSAGE} in startpage.tstpl
*
* @return string
*/
function makeFlashMessage() {
global $surveyid;
$html = "";
$language = Yii::app()->getLanguage();
$originalPrefix = Yii::app()->user->getStateKeyPrefix();
// Bug in Yii? Getting the state-key prefix changes the locale, so set the language manually after.
Yii::app()->setLanguage($language);
Yii::app()->user->setStateKeyPrefix('frontend');
$mapYiiToBootstrapClass = array(
'error' => 'danger',
'success' => 'success',
'notice' => 'info'
// no warning in Yii?
);
foreach (Yii::app()->user->getFlashes() as $key => $message) {
$html .= "<div class='alert alert-" . $mapYiiToBootstrapClass[$key] . " alert-dismissible flash-" . $key . "'>" . $message . "</div>\n";
}
Yii::app()->user->setStateKeyPrefix($originalPrefix);
return $html;
}
/**
* checkUploadedFileValidity used in SurveyRuntimeHelper
*/
function checkUploadedFileValidity($surveyid, $move, $backok=null)
{
global $thisstep;
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)
{
if ($fieldmap[$field]['type'] == "|" && !strrpos($fieldmap[$field]['fieldname'], "_filecount"))
{
$validation= getQuestionAttributeValues($fieldmap[$field]['qid']);
$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(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(gT("Sorry, only %s extensions are allowed!"),$validation['allowed_filetypes']);
unset($append);
}
else
{
$filenotvalidated = array();
$filenotvalidated[$field."_file_".$i] .= sprintf(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($fieldmap[$field]['qid']))
{
$filenotvalidated = array();
$filenotvalidated[$field] = 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;
}
/**
* Takes two single element arrays and adds second to end of first if value exists
* Why not use array_merge($array1,array_filter($array2);
*/
function addtoarray_single($array1, $array2)
{
//
if (is_array($array2))
{
foreach ($array2 as $ar)
{
if ($ar && $ar !== null)
{
$array1[]=$ar;
}
}
}
return $array1;
}
/**
* 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 boolean $quotaexit
*/
function submittokens($quotaexit=false)
{
$surveyid=Yii::app()->getConfig('surveyID');
if(isset($_SESSION['survey_'.$surveyid]['s_lang']))
{
$thissurvey=getSurveyInfo($surveyid,$_SESSION['survey_'.$surveyid]['s_lang']);
}
else
{
$thissurvey=getSurveyInfo($surveyid);
}
$clienttoken = $_SESSION['survey_'.$surveyid]['token'];
$sitename = Yii::app()->getConfig("sitename");
$emailcharset = Yii::app()->getConfig("emailcharset");
// Shift the date due to global timeadjust setting
$today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig("timeadjust"));
// check how many uses the token has left
$token = Token::model($surveyid)->findByAttributes(array('token' => $clienttoken));
$token->scenario = 'FinalSubmit'; // Do not XSS filter token data
if ($quotaexit==true)
{
$token->completed = 'Q';
$token->usesleft--;
}
else
{
if ($token->usesleft <= 1)
{
// Finish the token
if (isTokenCompletedDatestamped($thissurvey))
{
$token->completed = $today;
} else {
$token->completed = 'Y';
}
if(isset($token->participant_id))
{
$slquery = SurveyLink::model()->find('participant_id = :pid AND survey_id = :sid AND token_id = :tid', array(':pid'=> $token->participant_id, ':sid'=>$surveyid, ':tid'=>$token->tid));
if ($slquery)
{
if (isTokenCompletedDatestamped($thissurvey))
{
$slquery->date_completed = $today;
} else {
// Update the survey_links table if necessary, to protect anonymity, use the date_created field date
$slquery->date_completed = $slquery->date_created;
}
$slquery->save();
}
}
}
$token->usesleft--;
}
$token->save();
if ($quotaexit==false)
{
if ($token && trim(strip_tags($thissurvey['email_confirm'])) != "" && $thissurvey['sendconfirmation'] == "Y")
{
// if($token->completed == "Y" || $token->completed == $today)
// {
$from = "{$thissurvey['adminname']} <{$thissurvey['adminemail']}>";
$subject=$thissurvey['email_confirm_subj'];
$aReplacementVars=array();
$aReplacementVars["ADMINNAME"]=$thissurvey['admin'];
$aReplacementVars["ADMINEMAIL"]=$thissurvey['adminemail'];
$aReplacementVars['ADMINEMAIL'] = $thissurvey['adminemail'];
//Fill with token info, because user can have his information with anonimity control
$aReplacementVars["FIRSTNAME"]=$token->firstname;
$aReplacementVars["LASTNAME"]=$token->lastname;
$aReplacementVars["TOKEN"]=$token->token;
// added survey url in replacement vars
$surveylink = Yii::app()->createAbsoluteUrl("/survey/index/sid/{$surveyid}",array('lang'=>$_SESSION['survey_'.$surveyid]['s_lang'],'token'=>$token->token));
$aReplacementVars['SURVEYURL'] = $surveylink;
$attrfieldnames=getAttributeFieldNames($surveyid);
foreach ($attrfieldnames as $attr_name)
{
$aReplacementVars[strtoupper($attr_name)] = $token->$attr_name;
}
$dateformatdatat=getDateFormatData($thissurvey['surveyls_dateformat']);
$numberformatdatat = getRadixPointData($thissurvey['surveyls_numberformat']);
$redata=array('thissurvey'=>$thissurvey);
$subject=templatereplace($subject,$aReplacementVars,$redata,'email_confirm_subj', false, NULL, array(), true );
$subject=html_entity_decode($subject,ENT_QUOTES,$emailcharset);
if (getEmailFormat($surveyid) == 'html')
{
$ishtml=true;
}
else
{
$ishtml=false;
}
$message=$thissurvey['email_confirm'];
//$message=ReplaceFields($message, $fieldsarray, true);
$message=templatereplace($message,$aReplacementVars,$redata,'email_confirm', false, NULL, array(), 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
$sToAddress=validateEmailAddresses($token->email);
if ($sToAddress) {
$aAttachments = unserialize($thissurvey['attachments']);
$aRelevantAttachments = array();
/*
* Iterate through attachments and check them for relevance.
*/
if (isset($aAttachments['confirmation']))
{
foreach ($aAttachments['confirmation'] as $aAttachment)
{
$relevance = $aAttachment['relevance'];
// If the attachment is relevant it will be added to the mail.
if (LimeExpressionManager::ProcessRelevance($relevance) && file_exists($aAttachment['url']))
{
$aRelevantAttachments[] = $aAttachment['url'];
}
}
}
$event = new PluginEvent('beforeTokenEmail');
$event->set('survey', $surveyid);
$event->set('type', 'confirm');
$event->set('model', 'confirm');
$event->set('subject', $subject);
$event->set('to', $sToAddress);
$event->set('body', $message);
$event->set('from', $from);
$event->set('bounce', getBounceEmail($surveyid));
$event->set('token', $token->attributes);
App()->getPluginManager()->dispatchEvent($event);
$subject = $event->get('subject');
$message = $event->get('body');
$to = $event->get('to');
$from = $event->get('from');
$bounce = $event->get('bounce');
if ($event->get('send', true) != false)
{
SendEmailMessage($message, $subject, $to, $from, Yii::app()->getConfig("sitename"), $ishtml, $bounce, $aRelevantAttachments);
}
}
// } else {
// Leave it to send optional confirmation at closed token
// }
}
}
}
/**
* Send a submit notification to the email address specified in the notifications tab in the survey settings
*/
function sendSubmitNotifications($surveyid)
{
// @todo: Remove globals
global $thissurvey, $maildebug, $tokensexist;
if (trim($thissurvey['adminemail'])=='')
{
return;
}
$homeurl=Yii::app()->createAbsoluteUrl('/admin');
$sitename = Yii::app()->getConfig("sitename");
$debug=Yii::app()->getConfig('debug');
$bIsHTML = ($thissurvey['htmlemail'] == 'Y');
$aReplacementVars=array();
// TODO: What is holdpass, and is it OK to skip these lines if it is set? Related to 'Resume later' functionality
if ($thissurvey['allowsave'] == "Y" && isset($_SESSION['survey_'.$surveyid]['scid']) && isset($_SESSION['survey_'.$surveyid]['holdpass']))
{
$aReplacementVars['RELOADURL']=Yii::app()->getController()->createUrl("/survey/index/sid/{$surveyid}/loadall/reload/scid/".$_SESSION['survey_'.$surveyid]['scid']."/lang/".urlencode(App()->language),array('loadname'=>$_SESSION['survey_'.$surveyid]['holdname'],'loadpass'=>$_SESSION['survey_'.$surveyid]['holdpass']));
if ($bIsHTML)
{
$aReplacementVars['RELOADURL']="<a href='{$aReplacementVars['RELOADURL']}'>{$aReplacementVars['RELOADURL']}</a>";
}
}
else
{
$aReplacementVars['RELOADURL']='';
}
if (!isset($_SESSION['survey_'.$surveyid]['srid']))
$srid = null;
else
$srid = $_SESSION['survey_'.$surveyid]['srid'];
$aReplacementVars['ADMINNAME'] = $thissurvey['adminname'];
$aReplacementVars['ADMINEMAIL'] = $thissurvey['adminemail'];
$aReplacementVars['VIEWRESPONSEURL']=Yii::app()->createAbsoluteUrl("/admin/responses/sa/view/surveyid/{$surveyid}/id/{$srid}");
$aReplacementVars['EDITRESPONSEURL']=Yii::app()->createAbsoluteUrl("/admin/dataentry/sa/editdata/subaction/edit/surveyid/{$surveyid}/id/{$srid}");
$aReplacementVars['STATISTICSURL']=Yii::app()->createAbsoluteUrl("/admin/statistics/sa/index/surveyid/{$surveyid}");
if ($bIsHTML)
{
$aReplacementVars['VIEWRESPONSEURL']="<a href='{$aReplacementVars['VIEWRESPONSEURL']}'>{$aReplacementVars['VIEWRESPONSEURL']}</a>";
$aReplacementVars['EDITRESPONSEURL']="<a href='{$aReplacementVars['EDITRESPONSEURL']}'>{$aReplacementVars['EDITRESPONSEURL']}</a>";
$aReplacementVars['STATISTICSURL']="<a href='{$aReplacementVars['STATISTICSURL']}'>{$aReplacementVars['STATISTICSURL']}</a>";
}
$aReplacementVars['ANSWERTABLE']='';
$aEmailResponseTo=array();
$aEmailNotificationTo=array();
$sResponseData="";
if (!empty($thissurvey['emailnotificationto']))
{
$aRecipient=explode(";", ReplaceFields($thissurvey['emailnotificationto'],array('ADMINEMAIL' =>$thissurvey['adminemail'] ), true));
foreach($aRecipient as $sRecipient)
{
$sRecipient=trim($sRecipient);
if(validateEmailAddress($sRecipient))
{
$aEmailNotificationTo[]=$sRecipient;
}
}
}
if (!empty($thissurvey['emailresponseto']))
{
// there was no token used so lets remove the token field from insertarray
if (!isset($_SESSION['survey_'.$surveyid]['token']) && $_SESSION['survey_'.$surveyid]['insertarray'][0]=='token')
{
unset($_SESSION['survey_'.$surveyid]['insertarray'][0]);
}
//Make an array of email addresses to send to
$aRecipient=explode(";", ReplaceFields($thissurvey['emailresponseto'],array('ADMINEMAIL' =>$thissurvey['adminemail'] ), true));
foreach($aRecipient as $sRecipient)
{
$sRecipient=trim($sRecipient);
if(validateEmailAddress($sRecipient))
{
$aEmailResponseTo[]=$sRecipient;
}
}
$aFullResponseTable=getFullResponseTable($surveyid,$_SESSION['survey_'.$surveyid]['srid'],$_SESSION['survey_'.$surveyid]['s_lang']);
$ResultTableHTML = "<table class='printouttable' >\n";
$ResultTableText ="\n\n";
$oldgid = 0;
$oldqid = 0;
foreach ($aFullResponseTable as $sFieldname=>$fname)
{
if (substr($sFieldname,0,4)=='gid_')
{
$ResultTableHTML .= "\t<tr class='printanswersgroup'><td colspan='2'>".strip_tags($fname[0])."</td></tr>\n";
$ResultTableText .="\n{$fname[0]}\n\n";
}
elseif (substr($sFieldname,0,4)=='qid_')
{
$ResultTableHTML .= "\t<tr class='printanswersquestionhead'><td colspan='2'>".strip_tags($fname[0])."</td></tr>\n";
$ResultTableText .="\n{$fname[0]}\n";
}
else
{
$ResultTableHTML .= "\t<tr class='printanswersquestion'><td>".strip_tags("{$fname[0]} {$fname[1]}")."</td><td class='printanswersanswertext'>".CHtml::encode($fname[2])."</td></tr>\n";
$ResultTableText .=" {$fname[0]} {$fname[1]}: {$fname[2]}\n";
}
}
$ResultTableHTML .= "</table>\n";
$ResultTableText .= "\n\n";
if ($bIsHTML)
{
$aReplacementVars['ANSWERTABLE']=$ResultTableHTML;
}
else
{
$aReplacementVars['ANSWERTABLE']=$ResultTableText;
}
}
$sFrom = $thissurvey['adminname'].' <'.$thissurvey['adminemail'].'>';
$aAttachments = unserialize($thissurvey['attachments']);
$aRelevantAttachments = array();
/*
* Iterate through attachments and check them for relevance.
*/
if (isset($aAttachments['admin_notification']))
{
foreach ($aAttachments['admin_notification'] as $aAttachment)
{
$relevance = $aAttachment['relevance'];
// If the attachment is relevant it will be added to the mail.
if (LimeExpressionManager::ProcessRelevance($relevance) && file_exists($aAttachment['url']))
{
$aRelevantAttachments[] = $aAttachment['url'];
}
}
}
$redata=compact(array_keys(get_defined_vars()));
if (count($aEmailNotificationTo)>0)
{
$sMessage=templatereplace($thissurvey['email_admin_notification'],$aReplacementVars,$redata,'admin_notification',$thissurvey['anonymized'] == "Y",NULL, array(), true);
$sSubject=templatereplace($thissurvey['email_admin_notification_subj'],$aReplacementVars,$redata,'admin_notification_subj',($thissurvey['anonymized'] == "Y"),NULL, array(), true);
foreach ($aEmailNotificationTo as $sRecipient)
{
if (!SendEmailMessage($sMessage, $sSubject, $sRecipient, $sFrom, $sitename, $bIsHTML, getBounceEmail($surveyid), $aRelevantAttachments))
{
if ($debug>0)
{
echo '<br />Email could not be sent. Reason: '.$maildebug.'<br/>';
}
}
}
}
$aRelevantAttachments = array();
/*
* Iterate through attachments and check them for relevance.
*/
if (isset($aAttachments['detailed_admin_notification']))
{
foreach ($aAttachments['detailed_admin_notification'] as $aAttachment)
{
$relevance = $aAttachment['relevance'];
// If the attachment is relevant it will be added to the mail.
if (LimeExpressionManager::ProcessRelevance($relevance) && file_exists($aAttachment['url']))
{
$aRelevantAttachments[] = $aAttachment['url'];
}
}
}
if (count($aEmailResponseTo)>0)
{
$sMessage=templatereplace($thissurvey['email_admin_responses'],$aReplacementVars,$redata,'detailed_admin_notification',$thissurvey['anonymized'] == "Y",NULL, array(), true);
$sSubject=templatereplace($thissurvey['email_admin_responses_subj'],$aReplacementVars,$redata,'detailed_admin_notification_subj',$thissurvey['anonymized'] == "Y",NULL, array(), true);
foreach ($aEmailResponseTo as $sRecipient)
{
if (!SendEmailMessage($sMessage, $sSubject, $sRecipient, $sFrom, $sitename, $bIsHTML, getBounceEmail($surveyid), $aRelevantAttachments))
{
if ($debug>0)
{
echo '<br />Email could not be sent. Reason: '.$maildebug.'<br/>';
}
}
}
}
}
/**
* submitfailed : used in em_manager_helper.php
*
* "Unexpected error"
*
* Will send e-mail to adminemail if defined.
*
* @param string $errormsg
* @param string $query Will be included in sent email
* @return string Error message
*/
function submitfailed($errormsg = '', $query = null)
{
global $debug;
global $thissurvey;
global $subquery, $surveyid;
$completed = "<p><span class='fa fa-exclamation-triangle'></span> <strong>"
. gT("Did Not Save")."</strong></p>"
. "<p>"
. gT("An unexpected error has occurred and your responses cannot be saved.")
. "</p>";
if ($thissurvey['adminemail'])
{
$completed .= "<p>";
$completed .= gT("Your responses have not been lost and have been emailed to the survey administrator and will be entered into our database at a later point.");
$completed .= "</p>";
if ($debug>0)
{
$completed.='Error message: '.htmlspecialchars($errormsg).'<br />';
}
$email=gT("An error occurred saving a response to survey id","unescaped")." ".$thissurvey['name']." - $surveyid\n\n";
$email .= gT("DATA TO BE ENTERED","unescaped").":\n";
foreach ($_SESSION['survey_'.$surveyid]['insertarray'] as $value)
{
if (isset($_SESSION['survey_' . $surveyid][$value]))
{
$email .= "$value: {$_SESSION['survey_'.$surveyid][$value]}\n";
}
else
{
$email .= "$value: N/A\n";
}
}
$email .= "\n".gT("SQL CODE THAT FAILED","unescaped").":\n"
. "$subquery\n\n"
. ($query ? $query : '') . "\n\n" // In case we have no global subquery, but an argument to the function
. gT("ERROR MESSAGE","unescaped").":\n"
. $errormsg."\n\n";
SendEmailMessage($email, gT("Error saving results","unescaped"), $thissurvey['adminemail'], $thissurvey['adminemail'], "LimeSurvey", false, getBounceEmail($surveyid));
}
else
{
$completed .= "<a href='javascript:location.reload()'>".gT("Try to submit again")."</a><br /><br />\n";
$completed .= $subquery;
}
return $completed;
}
/**
* This function builds all the required session variables when a survey is first started and
* it loads any answer defaults from command line or from the table defaultvalues
* It is called from the related format script (group.php, question.php, survey.php)
* if the survey has just started.
*
* NOTE: THIS FUNCTION IS DOING MUCH MORE THAN BUILD SESSION. IT ALSO RENDER THE TOKEN FORM !!!!
*
*
* @param int $surveyid
* @param boolean $preview Defaults to false
* @return void
*/
function buildsurveysession($surveyid,$preview=false)
{
/// Yii::trace('start', 'survey.buildsurveysession');
global $clienttoken;
global $tokensexist;
global $move, $rooturl;
$preview = ($preview)?$preview:Yii::app()->getConfig('previewmode');
$sLangCode = App()->language;
$thissurvey = getSurveyInfo($surveyid,$sLangCode);
$oTemplate = Template::model()->getInstance('', $surveyid);
App()->getController()->sTemplate = $oTemplate->name; // It's going to be hard to be sure this is used ....
$sTemplatePath = $oTemplate->path;
$sTemplateViewPath = $oTemplate->pstplPath;
// Reset all the session variables and start again
resetAllSessionVariables($surveyid);
// Multi lingual support order : by REQUEST, if not by Token->language else by survey default language
if (returnGlobal('lang',true)){
$language_to_set=returnGlobal('lang',true);
}elseif (isset($oTokenEntry) && $oTokenEntry){
// If survey have token : we have a $oTokenEntry
// Can use $oTokenEntry = Token::model($surveyid)->findByAttributes(array('token'=>$clienttoken)); if we move on another function : this par don't validate the token validity
$language_to_set=$oTokenEntry->language;
}else{
$language_to_set = $thissurvey['language'];
}
// Always SetSurveyLanguage : surveys controller SetSurveyLanguage too, if different : broke survey (#09769)
SetSurveyLanguage ($surveyid, $language_to_set);
UpdateGroupList ($surveyid, $_SESSION['survey_'.$surveyid]['s_lang']);
$totalquestions = Question::model()->getTotalQuestions($surveyid);
$iTotalGroupsWithoutQuestions = QuestionGroup::model()->getTotalGroupsWithoutQuestions($surveyid);
// Fix totalquestions by substracting Test Display questions
$iNumberofQuestions = Question::model()->getNumberOfQuestions($surveyid);
$_SESSION['survey_'.$surveyid]['totalquestions'] = $totalquestions - (int) reset($iNumberofQuestions);
// 2. SESSION VARIABLE: totalsteps
setTotalSteps($surveyid, $thissurvey, $totalquestions);
// Break out and crash if there are no questions!
if ($totalquestions == 0 || $iTotalGroupsWithoutQuestions > 0){
breakOutAndCrash($sTemplateViewPath, $totalquestions, $iTotalGroupsWithoutQuestions, $thissurvey);
}
//Perform a case insensitive natural sort on group name then question title of a multidimensional array
// usort($arows, 'groupOrderThenQuestionOrder');
//3. SESSION VARIABLE - insertarray
//An array containing information about used to insert the data into the db at the submit stage
//4. SESSION VARIABLE - fieldarray
//See rem at end..
if ($tokensexist == 1 && $clienttoken){
$_SESSION['survey_'.$surveyid]['token'] = $clienttoken;
}
if ($thissurvey['anonymized'] == "N"){
$_SESSION['survey_'.$surveyid]['insertarray'][]= "token";
}
$qtypes = getQuestionTypeList('','array');
$fieldmap = createFieldMap($surveyid,'full',true,false,$_SESSION['survey_'.$surveyid]['s_lang']);
$_SESSION['survey_'.$surveyid]['fieldmap'] = $fieldmap;
initFieldArray($surveyid, $fieldmap);
// Prefill questions/answers from command line params
prefillFromCommandLine($surveyid);
if (isset($_SESSION['survey_'.$surveyid]['fieldarray'])) $_SESSION['survey_'.$surveyid]['fieldarray']=array_values($_SESSION['survey_'.$surveyid]['fieldarray']);
//Check if a passthru label and value have been included in the query url
checkPassthruLabel($surveyid, $preview, $fieldmap);
Yii::trace('end', 'survey.buildsurveysession');
}
/**
* Check if a passthru label and value have been included in the query url
* @param int $surveyid
* @param boolean $preview
* @return void
*/
function checkPassthruLabel($surveyid, $preview, $fieldmap)
{
$oResult=SurveyURLParameter::model()->getParametersForSurvey($surveyid);
foreach($oResult->readAll() as $aRow)
{
if(isset($_GET[$aRow['parameter']]) && !$preview)
{
$_SESSION['survey_'.$surveyid]['urlparams'][$aRow['parameter']]=$_GET[$aRow['parameter']];
if ($aRow['targetqid']!='')
{
foreach ($fieldmap as $sFieldname=>$aField)
{
if ($aRow['targetsqid']!='')
{
if ($aField['qid']==$aRow['targetqid'] && $aField['sqid']==$aRow['targetsqid'])
{
$_SESSION['survey_'.$surveyid]['startingValues'][$sFieldname]=$_GET[$aRow['parameter']];
$_SESSION['survey_'.$surveyid]['startingValues'][$aRow['parameter']]=$_GET[$aRow['parameter']];
}
}
else
{
if ($aField['qid']==$aRow['targetqid'])
{
$_SESSION['survey_'.$surveyid]['startingValues'][$sFieldname]=$_GET[$aRow['parameter']];
$_SESSION['survey_'.$surveyid]['startingValues'][$aRow['parameter']]=$_GET[$aRow['parameter']];
}
}
}
}
}