/
FrontEnd.php
823 lines (741 loc) · 37.9 KB
/
FrontEnd.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
<?php
namespace ls\helpers;
use \Yii;
use \Survey;
use \CHtml;
class FrontEnd
{
public static function makegraph($step, $total)
{
bp();
Yii::app()->getClientScript()->registerCssFile(Yii::app()->getConfig('publicstyleurl') . 'lime-progress.css');
$size = intval(($step) / $total * 100);
$graph = '<script type="text/javascript">
$(document).ready(function() {
$("#progressbar").progressbar({
value: ' . $size . '
});
;});';
if (App()->getLocale()->orientation == 'rtl') {
$graph .= '
$(document).ready(function() {
$("div.ui-progressbar-value").removeClass("ui-corner-left");
$("div.ui-progressbar-value").addClass("ui-corner-right");
});';
}
$graph .= '
</script>
<div id="progress-wrapper">
<span class="hide">' . sprintf(gT('You have completed %s%% of this survey'), $size) . '</span>
<div id="progress-pre">';
if (App()->getLocale()->orientation == 'rtl') {
$graph .= '100%';
} else {
$graph .= '0%';
}
$graph .= '</div>
<div id="progressbar"></div>
<div id="progress-post">';
if (App()->getLocale()->orientation == 'rtl') {
$graph .= '0%';
} else {
$graph .= '100%';
}
$graph .= '</div>
</div>';
if ($size == 0) // Progress bar looks dumb if 0
{
$graph .= '
<script type="text/javascript">
$(document).ready(function() {
$("div.ui-progressbar-value").hide();
});
</script>';
}
eP();
return $graph;
}
/**
* @todo Move this to UploadQuestion.
*/
private static function checkUploadedFileValidity($surveyid, $move, $backok = null)
{
return false;
$session = App()->surveySessionManager->current;
if (!isset($backok) || $backok != "Y") {
$fieldmap = createFieldMap($surveyid, 'full', false, false, $session->language);
if (isset($_POST['fieldnames']) && $_POST['fieldnames'] != "") {
$fields = explode("|", $_POST['fieldnames']);
foreach ($fields as $field) {
if ($fieldmap[$field]['type'] == "|" && !strrpos($fieldmap[$field]['fieldname'], "_filecount")) {
$validation = \QuestionAttribute::model()->getQuestionAttributes($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" || $move == "movenext")
) {
App()->surveySessionManager->current->setStep($thisstep);
}
return $filenotvalidated;
}
}
if (!isset($filenotvalidated)) {
return false;
} else {
return $filenotvalidated;
}
}
/**
* Marks a tokens as completed and sends a confirmation email to the participiant.
* If $quotaexit is set to true then the user exited the survey due to a quota
* restriction and the according token is only marked as 'Q'
*
* @param mixed $quotaexit
*/
public static function submittokens($quotaexit = false)
{
$session = App()->surveySessionManager->current;
$survey = $session->survey;
$token = $session->response->tokenObject;
if ($quotaexit == true) {
$token->completed = 'Q';
$token->usesleft--;
} else {
if ($token->usesleft <= 1) {
// Finish the token
if (!$token->survey->bool_anonymized) {
$token->completed = date('Y-m-d');
} else {
$token->completed = 'Y';
}
if (isset($token->participant_id)) {
$surveyLink = SurveyLink::model()->findByAttributes([
'participant_id' => $token->participant_id,
'survey_id' => $survey->primaryKey,
'token_id' => $token->primaryKey
]);
if (isset($surveyLink)) {
if ($token->survey->bool_anonymized) {
$surveyLink->date_completed = date('Y-m-d');
} else {
// Update the survey_links table if necessary, to protect anonymity, use the date_created field date
$surveyLink->date_completed = $surveyLink->date_created;
}
$surveyLink->save();
}
}
}
$token->usesleft--;
}
$token->save();
if ($quotaexit == false) {
if (trim(strip_tags($survey->localizedConfirmationEmail)) != "" && $survey->bool_sendconfirmation) {
// if($token->completed == "Y" || $token->completed == $today)
// {
$from = "{$survey->admin} <{$survey->adminemail}>";
$subject = $survey->localizedConfirmationEmailSubject;
$aReplacementVars = [];
$aReplacementVars["ADMINNAME"] = $survey->admin;
$aReplacementVars["ADMINEMAIL"] = $survey->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
$aReplacementVars['SURVEYURL'] = App()->createAbsoluteUrl("survey/index", [
'lang' => $session->language,
'token' => $token->token,
'sid' => $survey->primaryKey
]);
$attrfieldnames = $token->customAttributeNames();
foreach ($attrfieldnames as $attr_name) {
$aReplacementVars[strtoupper($attr_name)] = $token->$attr_name;
}
$dateformatdatat = \ls\helpers\SurveyTranslator::getDateFormatData($survey->getLocalizedDateFormat());
$numberformatdatat = \ls\helpers\SurveyTranslator::getRadixPointData($survey->getLocalizedNumberFormat());
$redata = [];
$subject = Replacements::templatereplace($subject, $aReplacementVars, $redata, null);
$subject = html_entity_decode($subject, ENT_QUOTES);
$ishtml = $survey->bool_htmlemail;
$message = html_entity_decode(
Replacements::templatereplace($survey->getLocalizedConfirmationEmail(), $aReplacementVars, $redata, null),
ENT_QUOTES
);
if (!$ishtml) {
$message = strip_tags(breakToNewline($message));
}
//Only send confirmation email if there is a valid email address
$sToAddress = validateEmailAddresses($token->email);
if ($sToAddress) {
$aAttachments = unserialize($survey->getLocalizedAttachments());
$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'];
}
}
}
SendEmailMessage($message, $subject, $sToAddress, $from, SettingGlobal::get('sitename'), $ishtml,
null, $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
*/
public static 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();
if ($thissurvey['allowsave'] == "Y" && isset($_SESSION['survey_' . $surveyid]['scid'])) {
$aReplacementVars['RELOADURL'] = "" . Yii::app()->getController()->createUrl("/survey/index/sid/{$surveyid}/loadall/reload/scid/" . $_SESSION['survey_' . $surveyid]['scid'] . "/loadname/" . urlencode($_SESSION['survey_' . $surveyid]['holdname']) . "/loadpass/" . urlencode($_SESSION['survey_' . $surveyid]['holdpass']) . "/lang/" . urlencode(App()->language));
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(";",
Replacements::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(";",
Replacements::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->language);
$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 = Replacements::templatereplace($thissurvey['email_admin_notification'], $aReplacementVars, $redata, null);
$sSubject = Replacements::templatereplace($thissurvey['email_admin_notification_subj'], $aReplacementVars, $redata, null);
foreach ($aEmailNotificationTo as $sRecipient) {
if (!SendEmailMessage($sMessage, $sSubject, $sRecipient, $sFrom, $sitename, true,
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 = Replacements::templatereplace($thissurvey['email_admin_responses'], $aReplacementVars, $redata, null);
$sSubject = Replacements::templatereplace($thissurvey['email_admin_responses_subj'], $aReplacementVars, $redata, null);
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/>';
}
}
}
}
}
/**
* This function creates the form elements in the survey navigation bar
* Adding a hidden input for default behaviour without javascript
* Use button name="move" for real browser (with or without javascript) and IE6/7/8 with javascript
*/
public static function surveymover(\SurveySession $session)
{
$surveyid = $session->surveyId;
$sMoveNext = "movenext";
$sMovePrev = "";
$iSessionStep = $session->step;
$iSessionMaxStep = $session->maxStep;
$iSessionTotalSteps = $session->stepCount;
$sClass = "submit button";
$sSurveyMover = "";
// Count down
if ($session->survey->navigationdelay > 0 && $iSessionMaxStep == $iSessionStep) {
$sClass .= " disabled";
App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "/navigator-countdown.js");
App()->getClientScript()->registerScript('navigator_countdown',
"navigator_countdown({$session->survey->navigationdelay});\n", CClientScript::POS_BEGIN);
}
// Previous ?
if ($session->format != Survey::FORMAT_ALL_IN_ONE && $session->survey->bool_allowprev) {
$sMovePrev = "moveprev";
}
// Submit ?
if ($iSessionStep == $iSessionTotalSteps
|| $session->format == Survey::FORMAT_ALL_IN_ONE
) {
$sMoveNext = "movesubmit";
}
// Construction of mover
if ($sMovePrev) {
$sLangMoveprev = gT("Previous");
$sSurveyMover .= CHtml::htmlButton($sLangMoveprev, array(
'type' => 'submit',
'id' => "{$sMovePrev}btn",
'value' => $sMovePrev,
'name' => $sMovePrev,
'accesskey' => 'p',
'class' => $sClass
));
}
if ($sMovePrev && $sMoveNext) {
$sSurveyMover .= " ";
}
if ($sMoveNext) {
if ($sMoveNext == "movesubmit") {
$sLangMovenext = gT("Submit");
$sAccessKeyNext = 'l';// Why l ?
} else {
$sLangMovenext = gT("Next");
$sAccessKeyNext = 'n';
}
$sSurveyMover .= CHtml::htmlButton($sLangMovenext, array(
'type' => 'submit',
'id' => "{$sMoveNext}btn",
'value' => $sMoveNext,
'name' => $sMoveNext,
'accesskey' => $sAccessKeyNext,
'class' => $sClass
));
}
return $sSurveyMover;
}
/**
* Caculate assessement scores
*
* @param mixed $surveyid
* @param mixed $returndataonly - only returns an array with data
*/
public static function doAssessment(Survey $survey, $returndataonly = false)
{
$session = App()->surveySessionManager->current;
if (!isset($session) || !$session->survey->bool_assessments) {
return false;
}
$total = 0;
$query = "SELECT * FROM {{assessments}}
WHERE sid={$session->surveyId} and language='{$session->language}'
ORDER BY scope, id";
if ($result = dbExecuteAssoc($query)) //Checked
{
$aResultSet = $result->readAll();
if (count($aResultSet) > 0) {
foreach ($aResultSet as $row) {
if ($row['scope'] == "G") {
$assessment['group'][$row['gid']][] = array(
"name" => $row['name'],
"min" => $row['minimum'],
"max" => $row['maximum'],
"message" => $row['message']
);
} else {
$assessment['total'][] = array(
"name" => $row['name'],
"min" => $row['minimum'],
"max" => $row['maximum'],
"message" => $row['message']
);
}
}
$fieldmap = createFieldMap($surveyid, "full", false, false, $session->language);
$i = 0;
$total = 0;
$groups = array();
foreach ($fieldmap as $field) {
if (in_array($field['type'], array('1', 'F', 'H', 'W', 'Z', 'L', '!', 'M', 'O', 'P'))) {
$fieldmap[$field['fieldname']]['assessment_value'] = 0;
if (isset($_SESSION['survey_' . $surveyid][$field['fieldname']])) {
if (($field['type'] == "M") || ($field['type'] == "P")) //Multiflexi choice - result is the assessment attribute value
{
if ($_SESSION['survey_' . $surveyid][$field['fieldname']] == "Y") {
$aAttributes = \QuestionAttribute::model()->getQuestionAttributes($field['qid'],
$field['type']);
$fieldmap[$field['fieldname']]['assessment_value'] = (int)$aAttributes['assessment_value'];
$total = $total + (int)$aAttributes['assessment_value'];
}
} else // Single choice question
{
$usquery = "SELECT assessment_value FROM {{answers}} where qid=" . $field['qid'] . " and language='$baselang' and code=" . App()->db->quoteValue($_SESSION['survey_' . $surveyid][$field['fieldname']]);
$usresult = dbExecuteAssoc($usquery); //Checked
if ($usresult) {
$usrow = $usresult->read();
$fieldmap[$field['fieldname']]['assessment_value'] = $usrow['assessment_value'];
$total = $total + $usrow['assessment_value'];
}
}
}
$groups[] = $field['gid'];
}
$i++;
}
$groups = array_unique($groups);
foreach ($groups as $group) {
$grouptotal = 0;
foreach ($fieldmap as $field) {
if ($field['gid'] == $group && isset($field['assessment_value'])) {
//$grouptotal=$grouptotal+$field['answer'];
if (isset ($_SESSION['survey_' . $surveyid][$field['fieldname']])) {
$grouptotal = $grouptotal + $field['assessment_value'];
}
}
}
$subtotal[$group] = $grouptotal;
}
}
$assessments = "";
if (isset($subtotal) && is_array($subtotal)) {
foreach ($subtotal as $key => $val) {
if (isset($assessment['group'][$key])) {
foreach ($assessment['group'][$key] as $assessed) {
if ($val >= $assessed['min'] && $val <= $assessed['max'] && $returndataonly === false) {
$assessments .= "\t<!-- GROUP ASSESSMENT: Score: $val Min: " . $assessed['min'] . " Max: " . $assessed['max'] . "-->
<table class='assessments'>
<tr>
<th>" . str_replace(array("{PERC}", "{TOTAL}"), array($val, $total), $assessed['name']) . "
</th>
</tr>
<tr>
<td>" . str_replace(array("{PERC}", "{TOTAL}"), array($val, $total), $assessed['message']) . "
</td>
</tr>
</table><br />\n";
}
}
}
}
}
if (isset($assessment['total'])) {
foreach ($assessment['total'] as $assessed) {
if ($total >= $assessed['min'] && $total <= $assessed['max'] && $returndataonly === false) {
$assessments .= "\t\t\t<!-- TOTAL ASSESSMENT: Score: $total Min: " . $assessed['min'] . " Max: " . $assessed['max'] . "-->
<table class='assessments' align='center'>
<tr>
<th>" . str_replace(array("{PERC}", "{TOTAL}"), array($val, $total),
stripslashes($assessed['name'])) . "
</th>
</tr>
<tr>
<td>" . str_replace(array("{PERC}", "{TOTAL}"), array($val, $total),
stripslashes($assessed['message'])) . "
</td>
</tr>
</table>\n";
}
}
}
if ($returndataonly == true) {
return array('total' => $total);
} else {
return $assessments;
}
}
}
/**
* checkCompletedQuota() returns matched quotas information for the current response
* @param integer $surveyid - Survey identification number
* @param bool $return - set to true to return information, false do the quota
* @return array - nested array, Quotas->Members->Fields, includes quota information matched in session.
*/
public static function checkCompletedQuota($return = false)
{
bP();
static $aMatchedQuotas; // EM call 2 times quotas with 3 lines of php code, then use static.
$session = App()->surveySessionManager->current;
if (!$aMatchedQuotas) {
$aMatchedQuotas = array();
$quota_info = $aQuotasInfo = getQuotaInformation($session->surveyId, $session->language);
// $aQuotasInfo have an 'active' key, we don't use it ?
if (!$aQuotasInfo || empty($aQuotasInfo)) {
return $aMatchedQuotas;
}
// OK, we have some quota, then find if this $_SESSION have some set
$aPostedFields = explode("|",
Yii::app()->request->getPost('fieldnames', '')); // Needed for quota allowing update
foreach ($aQuotasInfo as $aQuotaInfo) {
$iMatchedAnswers = 0;
$bPostedField = false;
// Array of field with quota array value
$aQuotaFields = array();
// Array of fieldnames with relevance value : EM fill $_SESSION with default value even is unrelevant (em_manager_helper line 6548)
$aQuotaRelevantFieldnames = array();
foreach ($aQuotaInfo['members'] as $aQuotaMember) {
$aQuotaFields[$aQuotaMember['fieldname']][] = $aQuotaMember['value'];
$aQuotaRelevantFieldnames[$aQuotaMember['fieldname']] = isset($_SESSION['survey_' . $session->surveyId]['relevanceStatus'][$aQuotaMember['qid']]) && $_SESSION['survey_' . $session->surveyId]['relevanceStatus'][$aQuotaMember['qid']];
}
// For each field : test if actual responses is in quota (and is relevant)
foreach ($aQuotaFields as $sFieldName => $aValues) {
$bInQuota = isset($_SESSION['survey_' . $session->surveyId][$sFieldName]) && in_array($_SESSION['survey_' . $session->surveyId][$sFieldName],
$aValues);
if ($bInQuota && $aQuotaRelevantFieldnames[$sFieldName]) {
$iMatchedAnswers++;
}
if (in_array($sFieldName, $aPostedFields))// Need only one posted value
{
$bPostedField = true;
}
}
// Count only needed quotas
if ($iMatchedAnswers == count($aQuotaFields) && ($aQuotaInfo['action'] != 2 || $bPostedField)) {
if ($aQuotaInfo['qlimit'] == 0) { // Always add the quota if qlimit==0
$aMatchedQuotas[] = $aQuotaInfo;
} else {
$iCompleted = getQuotaCompletedCount($session->surveyId, $aQuotaInfo['id']);
if (!is_null($iCompleted) && ((int)$iCompleted >= (int)$aQuotaInfo['qlimit'])) // This remove invalid quota and not completed
{
$aMatchedQuotas[] = $aQuotaInfo;
}
}
}
}
}
if ($return) {
return $aMatchedQuotas;
}
if (empty($aMatchedQuotas)) {
return;
}
// Now we have all the information we need about the quotas and their status.
// We need to construct the page and do all needed action
$aSurveyInfo = getSurveyInfo($session->surveyId, $session->language);
$sTemplatePath = Template::getTemplatePath($aSurveyInfo['template']);
$sClientToken = isset($_SESSION['survey_' . $session->surveyId]['token']) ? $_SESSION['survey_' . $session->surveyId]['token'] : "";
// $redata for Replacements::templatereplace
$aDataReplacement = array(
'thissurvey' => $aSurveyInfo,
'clienttoken' => $sClientToken,
'token' => $sClientToken,
);
// We take only the first matched quota, no need for each
$aMatchedQuota = $aMatchedQuotas[0];
// If a token is used then mark the token as completed, do it before event : this allow plugin to update token information
$event = new PluginEvent('afterSurveyQuota');
$event->set('surveyId', $session->surveyId);
$event->set('responseId', $_SESSION['survey_' . $session->surveyId]['srid']);// We allways have a responseId
$event->set('aMatchedQuotas', $aMatchedQuotas);// Give all the matched quota : the first is the active
App()->getPluginManager()->dispatchEvent($event);
$blocks = array();
foreach ($event->getAllContent() as $blockData) {
/* @var $blockData PluginEventContent */
$blocks[] = CHtml::tag('div', array('id' => $blockData->getCssId(), 'class' => $blockData->getCssClass()),
$blockData->getContent());
}
// Allow plugin to update message, url, url description and action
$sMessage = $event->get('message', $aMatchedQuota['quotals_message']);
$sUrl = $event->get('url', $aMatchedQuota['quotals_url']);
$sUrlDescription = $event->get('urldescrip', $aMatchedQuota['quotals_urldescrip']);
$sAction = $event->get('action', $aMatchedQuota['action']);
$sAutoloadUrl = $event->get('autoloadurl', $aMatchedQuota['autoload_url']);
// Doing the action and show the page
if ($sAction == "1" && $sClientToken) {
submittokens(true);
}
// Construct the default message
$sMessage = Replacements::templatereplace($sMessage, array(), $aDataReplacement, null);
$sUrl = Replacements::passthruReplace($sUrl, $aSurveyInfo);
$sUrl = Replacements::templatereplace($sUrl, array(), $aDataReplacement, null);
$sUrlDescription = Replacements::templatereplace($sUrlDescription, array(), $aDataReplacement, null);
// Construction of default message inside quotamessage class
$sHtmlQuotaMessage = "<div class='quotamessage limesurveycore'>\n";
$sHtmlQuotaMessage .= "\t" . $sMessage . "\n";
$sHtmlQuotaUrl = ($sUrl) ? "<a href='" . $sUrl . "'>" . $sUrlDescription . "</a>" : "";
// Add the navigator with Previous button if quota allow modification.
if ($sAction == "2") {
$sQuotaStep = App()->surveySessionManager->current->getStep(); // Surely not needed
$sNavigator = CHtml::htmlButton(gT("Previous"), array(
'type' => 'submit',
'id' => "moveprevbtn",
'value' => $sQuotaStep,
'name' => 'move',
'accesskey' => 'p',
'class' => "submit button"
));
//$sNavigator .= " ".CHtml::htmlButton(gT("Submit"),array('type'=>'submit','id'=>"movesubmit",'value'=>"movesubmit",'name'=>"movesubmit",'accesskey'=>'l','class'=>"submit button"));
$sHtmlQuotaMessage .= CHtml::form(array("/survey/index", "sid" => $session->surveyId), 'post',
array('id' => 'limesurvey', 'name' => 'limesurvey'));
$sHtmlQuotaMessage .= renderOldTemplate($sTemplatePath . "/navigator.pstpl",
array('NAVIGATOR' => $sNavigator, 'SAVE' => ''), $aDataReplacement);
$sHtmlQuotaMessage .= CHtml::hiddenField('sid', $session->surveyId);
$sHtmlQuotaMessage .= CHtml::hiddenField('token', $sClientToken);// Did we really need it ?
$sHtmlQuotaMessage .= CHtml::endForm();
}
$sHtmlQuotaMessage .= "</div>\n";
// Add the plugin message before default message
$sHtmlQuotaMessage = implode("\n", $blocks) . "\n" . $sHtmlQuotaMessage;
// Send page to user and end.
sendCacheHeaders();
if ($sAutoloadUrl == 1 && $sUrl != "") {
header("Location: " . $sUrl);
}
doHeader();
renderOldTemplate($sTemplatePath . "/startpage.pstpl", array(), $aDataReplacement);
renderOldTemplate($sTemplatePath . "/completed.pstpl",
array("COMPLETED" => $sHtmlQuotaMessage, "URL" => $sHtmlQuotaUrl), $aDataReplacement);
renderOldTemplate($sTemplatePath . "/endpage.pstpl", array(), $aDataReplacement);
doFooter();
eP();
Yii::app()->end();
}
/**
* Resets all question timers by expiring the related cookie - this needs to be called before any output is done
* @todo Make cookie survey ID aware
*/
public static function resetTimers()
{
$cookie = new CHttpCookie('limesurvey_timers', '');
$cookie->expire = time() - 3600;
Yii::app()->request->cookies['limesurvey_timers'] = $cookie;
}
}