forked from PoetOS/moodle-mod_questionnaire
-
Notifications
You must be signed in to change notification settings - Fork 0
/
questionnaire.class.php
3342 lines (2997 loc) · 137 KB
/
questionnaire.class.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
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package mod_questionnaire
* @copyright 2016 Mike Churchward ([email protected])
* @author Mike Churchward
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once($CFG->dirroot.'/mod/questionnaire/locallib.php');
class questionnaire {
// Class Properties.
/**
* @var \mod_questionnaire\question\base[] $quesitons
*/
public $questions = [];
/**
* The survey record.
* @var object $survey
*/
// Todo var $survey; TODO.
/**
* @var $renderer Contains the page renderer when loaded, or false if not.
*/
public $renderer = false;
/**
* @var $page Contains the renderable, templatable page when loaded, or false if not.
*/
public $page = false;
// Class Methods.
/*
* The class constructor
*
*/
public function __construct($id = 0, $questionnaire = null, &$course, &$cm, $addquestions = true) {
global $DB;
if ($id) {
$questionnaire = $DB->get_record('questionnaire', array('id' => $id));
}
if (is_object($questionnaire)) {
$properties = get_object_vars($questionnaire);
foreach ($properties as $property => $value) {
$this->$property = $value;
}
}
if (!empty($this->sid)) {
$this->add_survey($this->sid);
}
$this->course = $course;
$this->cm = $cm;
// When we are creating a brand new questionnaire, we will not yet have a context.
if (!empty($cm) && !empty($this->id)) {
$this->context = context_module::instance($cm->id);
} else {
$this->context = null;
}
if ($addquestions && !empty($this->sid)) {
$this->add_questions($this->sid);
}
// Load the capabilities for this user and questionnaire, if not creating a new one.
if (!empty($this->cm->id)) {
$this->capabilities = questionnaire_load_capabilities($this->cm->id);
}
}
/**
* Adding a survey record to the object.
*
*/
public function add_survey($sid = 0, $survey = null) {
global $DB;
if ($sid) {
$this->survey = $DB->get_record('questionnaire_survey', array('id' => $sid));
} else if (is_object($survey)) {
$this->survey = clone($survey);
}
}
/**
* Adding questions to the object.
*/
public function add_questions($sid = false) {
global $DB;
if ($sid === false) {
$sid = $this->sid;
}
if (!isset($this->questions)) {
$this->questions = [];
$this->questionsbysec = [];
}
$select = 'survey_id = ? AND deleted = ?';
$params = [$sid, 'n'];
if ($records = $DB->get_records_select('questionnaire_question', $select, $params, 'position')) {
$sec = 1;
$isbreak = false;
foreach ($records as $record) {
$this->questions[$record->id] = \mod_questionnaire\question\base::question_builder($record->type_id,
$record, $this->context);
if ($record->type_id != QUESPAGEBREAK) {
$this->questionsbysec[$sec][$record->id] = &$this->questions[$record->id];
$isbreak = false;
} else {
// Sanity check: no section break allowed as first position, no 2 consecutive section breaks.
if ($record->position != 1 && $isbreak == false) {
$sec++;
$isbreak = true;
}
}
}
}
}
/**
* Add the renderer to the questionnaire object.
* @param \plugin_renderer_base $renderer The module renderer, extended from core renderer.
*/
public function add_renderer($renderer) {
$this->renderer = $renderer;
}
/**
* Add the templatable page to the questionnaire object.
* @param \renderable, \templatable $page The page to rendere, implementing core classes.
*/
public function add_page($page) {
$this->page = $page;
}
public function view() {
global $CFG, $USER, $PAGE;
$PAGE->set_title(format_string($this->name));
$PAGE->set_heading(format_string($this->course->fullname));
// Initialise the JavaScript.
$PAGE->requires->js_init_call('M.mod_questionnaire.init_attempt_form', null, false, questionnaire_get_js_module());
$questionnaire = $this;
if (!$this->capabilities->view) {
$this->page->add_to_page('notifications',
$this->renderer->notification(get_string('noteligible', 'questionnaire', $this->name),
\core\output\notification::NOTIFY_ERROR));
} else if (!$this->is_active()) {
$this->page->add_to_page('notifications',
$this->renderer->notification(get_string('notavail', 'questionnaire'), \core\output\notification::NOTIFY_ERROR));
} else if (!$this->is_open()) {
$this->page->add_to_page('notifications',
$this->renderer->notification(get_string('notopen', 'questionnaire', userdate($this->opendate)),
\core\output\notification::NOTIFY_ERROR));
} else if ($this->is_closed()) {
$this->page->add_to_page('notifications',
$this->renderer->notification(get_string('closed', 'questionnaire', userdate($this->closedate)),
\core\output\notification::NOTIFY_ERROR));
} else if (!$this->user_is_eligible($USER->id)) {
$this->page->add_to_page('notifications',
$this->renderer->notification(get_string('noteligible', 'questionnaire'), \core\output\notification::NOTIFY_ERROR));
} else if ($this->survey->realm == 'template') {
$this->page->add_to_page('notifications',
$this->renderer->notification(get_string('templatenotviewable', 'questionnaire'),
\core\output\notification::NOTIFY_ERROR));
} else if (!$this->user_can_take($USER->id)) {
switch ($this->qtype) {
case QUESTIONNAIREDAILY:
$msgstring = ' '.get_string('today', 'questionnaire');
break;
case QUESTIONNAIREWEEKLY:
$msgstring = ' '.get_string('thisweek', 'questionnaire');
break;
case QUESTIONNAIREMONTHLY:
$msgstring = ' '.get_string('thismonth', 'questionnaire');
break;
default:
$msgstring = '';
break;
}
$this->page->add_to_page('notifications',
$this->renderer->notification(get_string('alreadyfilled', 'questionnaire', $msgstring),
\core\output\notification::NOTIFY_ERROR));
} else {
// Handle the main questionnaire completion page.
$quser = $USER->id;
$msg = $this->print_survey($USER->id, $quser);
// If Questionnaire was submitted with all required fields completed ($msg is empty),
// then record the submittal.
$viewform = data_submitted($CFG->wwwroot."/mod/questionnaire/complete.php");
if (!empty($viewform->rid)) {
$viewform->rid = (int)$viewform->rid;
}
if (!empty($viewform->sec)) {
$viewform->sec = (int)$viewform->sec;
}
if (data_submitted() && confirm_sesskey() && isset($viewform->submit) && isset($viewform->submittype) &&
($viewform->submittype == "Submit Survey") && empty($msg)) {
$this->response_delete($viewform->rid, $viewform->sec);
$this->rid = $this->response_insert($this->survey->id, $viewform->sec, $viewform->rid, $quser);
$this->response_commit($this->rid);
// If it was a previous save, rid is in the form...
if (!empty($viewform->rid) && is_numeric($viewform->rid)) {
$rid = $viewform->rid;
// Otherwise its in this object.
} else {
$rid = $this->rid;
}
questionnaire_record_submission($this, $USER->id, $rid);
if ($this->grade != 0) {
$questionnaire = new stdClass();
$questionnaire->id = $this->id;
$questionnaire->name = $this->name;
$questionnaire->grade = $this->grade;
$questionnaire->cmidnumber = $this->cm->idnumber;
$questionnaire->courseid = $this->course->id;
questionnaire_update_grades($questionnaire, $quser);
}
// Update completion state.
$completion = new completion_info($this->course);
if ($completion->is_enabled($this->cm) && $this->completionsubmit) {
$completion->update_state($this->cm, COMPLETION_COMPLETE);
}
// Log this submitted response.
$context = context_module::instance($this->cm->id);
$anonymous = $this->respondenttype == 'anonymous';
$params = array(
'context' => $context,
'courseid' => $this->course->id,
'relateduserid' => $USER->id,
'anonymous' => $anonymous,
'other' => array('questionnaireid' => $questionnaire->id)
);
$event = \mod_questionnaire\event\attempt_submitted::create($params);
$event->trigger();
$this->submission_notify($this->rid);
$this->response_goto_thankyou();
}
}
}
/*
* Function to view an entire responses data.
*
*/
public function view_response($rid, $referer= '', $blankquestionnaire = false, $resps = '', $compare = false,
$isgroupmember = false, $allresponses = false, $currentgroupid = 0) {
$this->print_survey_start('', 1, 1, 0, $rid, false);
$data = new stdClass();
$i = 0;
$this->response_import_all($rid, $data);
if ($referer != 'print') {
$feedbackmessages = $this->response_analysis($rid, $resps, $compare, $isgroupmember, $allresponses, $currentgroupid);
if ($feedbackmessages) {
$msgout = '';
foreach ($feedbackmessages as $msg) {
$msgout .= $msg;
}
$this->page->add_to_page('feedbackmessages', $msgout);
}
if ($this->survey->feedbacknotes) {
$text = file_rewrite_pluginfile_urls($this->survey->feedbacknotes, 'pluginfile.php',
$this->context->id, 'mod_questionnaire', 'feedbacknotes', $this->survey->id);
$this->page->add_to_page('feedbacknotes', $this->renderer->box(format_text($text, FORMAT_HTML)));
}
}
foreach ($this->questions as $question) {
if ($question->type_id < QUESPAGEBREAK) {
$i++;
}
if ($question->type_id != QUESPAGEBREAK) {
$this->page->add_to_page('responses', $this->renderer->response_output($question, $data, $i));
}
}
}
/*
* Function to view an entire responses data.
*
* $value is unused, but is needed in order to get the $key elements of the array. Suppress PHPMD warning.
*
* @SuppressWarnings(PHPMD.UnusedLocalVariable)
*/
public function view_all_responses($resps) {
$this->print_survey_start('', 1, 1, 0);
// If a student's responses have been deleted by teacher while student was viewing the report,
// then responses may have become empty, hence this test is necessary.
if ($resps) {
foreach ($resps as $resp) {
$data[$resp->id] = new stdClass();
$this->response_import_all($resp->id, $data[$resp->id]);
}
$i = 0;
$allrespdata = [];
foreach ($this->questions as $question) {
if ($question->type_id < QUESPAGEBREAK) {
$i++;
}
$qid = preg_quote('q'.$question->id, '/');
if ($question->type_id != QUESPAGEBREAK) {
$allrespdata[$i] = [];
$allrespdata[$i]['question'] = $question;
foreach ($data as $respid => $respdata) {
$hasresp = false;
foreach ($respdata as $key => $value) {
if ($hasresp = preg_match("/$qid(_|$)/", $key)) {
break;
}
}
// Do not display empty responses.
if ($hasresp) {
$allrespdata[$i][] = [
'respdate' => userdate($resps[$respid]->submitted),
'respdata' => $respdata
];
}
}
}
}
$this->page->add_to_page('responses', $this->renderer->all_response_output($allrespdata));
} else {
$this->page->add_to_page('responses', $this->renderer->all_response_output(get_string('noresponses', 'questionnaire')));
}
$this->print_survey_end(1, 1);
}
// Access Methods.
public function is_active() {
return (!empty($this->survey));
}
public function is_open() {
return ($this->opendate > 0) ? ($this->opendate < time()) : true;
}
public function is_closed() {
return ($this->closedate > 0) ? ($this->closedate < time()) : false;
}
public function user_can_take($userid) {
if (!$this->is_active() || !$this->user_is_eligible($userid)) {
return false;
} else if ($this->qtype == QUESTIONNAIREUNLIMITED) {
return true;
} else if ($userid > 0) {
return $this->user_time_for_new_attempt($userid);
} else {
return false;
}
}
public function user_is_eligible($userid) {
return ($this->capabilities->view && $this->capabilities->submit);
}
public function user_has_saved_response($userid) {
global $DB;
return $DB->record_exists('questionnaire_response',
['survey_id' => $this->survey->id, 'userid' => $userid, 'complete' => 'n']);
}
public function user_time_for_new_attempt($userid) {
global $DB;
$params = array('qid' => $this->id, 'userid' => $userid);
if (!($attempts = $DB->get_records('questionnaire_attempts', $params, 'timemodified DESC'))) {
return true;
}
$attempt = reset($attempts);
$timenow = time();
switch ($this->qtype) {
case QUESTIONNAIREUNLIMITED:
$cantake = true;
break;
case QUESTIONNAIREONCE:
$cantake = false;
break;
case QUESTIONNAIREDAILY:
$attemptyear = date('Y', $attempt->timemodified);
$currentyear = date('Y', $timenow);
$attemptdayofyear = date('z', $attempt->timemodified);
$currentdayofyear = date('z', $timenow);
$cantake = (($attemptyear < $currentyear) ||
(($attemptyear == $currentyear) && ($attemptdayofyear < $currentdayofyear)));
break;
case QUESTIONNAIREWEEKLY:
$attemptyear = date('Y', $attempt->timemodified);
$currentyear = date('Y', $timenow);
$attemptweekofyear = date('W', $attempt->timemodified);
$currentweekofyear = date('W', $timenow);
$cantake = (($attemptyear < $currentyear) ||
(($attemptyear == $currentyear) && ($attemptweekofyear < $currentweekofyear)));
break;
case QUESTIONNAIREMONTHLY:
$attemptyear = date('Y', $attempt->timemodified);
$currentyear = date('Y', $timenow);
$attemptmonthofyear = date('n', $attempt->timemodified);
$currentmonthofyear = date('n', $timenow);
$cantake = (($attemptyear < $currentyear) ||
(($attemptyear == $currentyear) && ($attemptmonthofyear < $currentmonthofyear)));
break;
default:
$cantake = false;
break;
}
return $cantake;
}
public function is_survey_owner() {
return (!empty($this->survey->courseid) && ($this->course->id == $this->survey->courseid));
}
public function can_view_response($rid) {
global $USER, $DB;
if (!empty($rid)) {
$response = $DB->get_record('questionnaire_response', array('id' => $rid));
// If the response was not found, can't view it.
if (empty($response)) {
return false;
}
// If the response belongs to a different survey than this one, can't view it.
if ($response->survey_id != $this->survey->id) {
return false;
}
// If you can view all responses always, then you can view it.
if ($this->capabilities->readallresponseanytime) {
return true;
}
// If you are allowed to view this response for another user.
// If resp_view is set to QUESTIONNAIRE_STUDENTVIEWRESPONSES_NEVER, then this will always be false.
if ($this->capabilities->readallresponses &&
($this->resp_view == QUESTIONNAIRE_STUDENTVIEWRESPONSES_ALWAYS ||
($this->resp_view == QUESTIONNAIRE_STUDENTVIEWRESPONSES_WHENCLOSED && $this->is_closed()) ||
($this->resp_view == QUESTIONNAIRE_STUDENTVIEWRESPONSES_WHENANSWERED && !$this->user_can_take($USER->id)))) {
return true;
}
// If you can read your own response.
if (($response->userid == $USER->id) && $this->capabilities->readownresponses &&
($this->count_submissions($USER->id) > 0)) {
return true;
}
} else {
// If you can view all responses always, then you can view it.
if ($this->capabilities->readallresponseanytime) {
return true;
}
// If you are allowed to view this response for another user.
// If resp_view is set to QUESTIONNAIRE_STUDENTVIEWRESPONSES_NEVER, then this will always be false.
if ($this->capabilities->readallresponses &&
($this->resp_view == QUESTIONNAIRE_STUDENTVIEWRESPONSES_ALWAYS ||
($this->resp_view == QUESTIONNAIRE_STUDENTVIEWRESPONSES_WHENCLOSED && $this->is_closed()) ||
($this->resp_view == QUESTIONNAIRE_STUDENTVIEWRESPONSES_WHENANSWERED && !$this->user_can_take($USER->id)))) {
return true;
}
// If you can read your own response.
if ($this->capabilities->readownresponses && ($this->count_submissions($USER->id) > 0)) {
return true;
}
}
}
public function can_view_all_responses($usernumresp = null) {
global $USER, $DB, $SESSION;
if ($owner = $DB->get_field('questionnaire_survey', 'courseid', ['id' => $this->sid])) {
$owner = ($owner == $this->course->id);
} else {
$owner = true;
}
$numresp = $this->count_submissions();
if ($usernumresp === null) {
$usernumresp = $this->count_submissions($USER->id);
}
// Number of Responses in currently selected group (or all participants etc.).
if (isset($SESSION->questionnaire->numselectedresps)) {
$numselectedresps = $SESSION->questionnaire->numselectedresps;
} else {
$numselectedresps = $numresp;
}
// If questionnaire is set to separate groups, prevent user who is not member of any group
// to view All responses.
$canviewgroups = true;
$groupmode = groups_get_activity_groupmode($this->cm, $this->course);
if ($groupmode == 1) {
$canviewgroups = groups_has_membership($this->cm, $USER->id);
}
$canviewallgroups = has_capability('moodle/site:accessallgroups', $this->context);
return (( // Teacher or non-editing teacher (if can view all groups).
($canviewallgroups ||
// Non-editing teacher (with canviewallgroups capability removed), if member of a group.
($canviewgroups && $this->capabilities->readallresponseanytime)) &&
($numresp > 0) && $owner && ($numselectedresps > 0)) ||
($this->capabilities->readallresponses && ($numresp > 0) && $canviewgroups &&
// If resp_view is set to QUESTIONNAIRE_STUDENTVIEWRESPONSES_NEVER, then this will always be false.
($this->resp_view == QUESTIONNAIRE_STUDENTVIEWRESPONSES_ALWAYS ||
($this->resp_view == QUESTIONNAIRE_STUDENTVIEWRESPONSES_WHENCLOSED && $this->is_closed()) ||
($this->resp_view == QUESTIONNAIRE_STUDENTVIEWRESPONSES_WHENANSWERED && ($usernumresp > 0))) &&
$this->is_survey_owner()));
}
public function count_submissions($userid=false) {
global $DB;
if (!$userid) {
// Provide for groups setting.
return $DB->count_records('questionnaire_response', array('survey_id' => $this->sid, 'complete' => 'y'));
} else {
return $DB->count_records('questionnaire_response', array('survey_id' => $this->sid, 'userid' => $userid,
'complete' => 'y'));
}
}
private function has_required($section = 0) {
if (empty($this->questions)) {
return false;
} else if ($section <= 0) {
foreach ($this->questions as $question) {
if ($question->required()) {
return true;
}
}
} else {
foreach ($this->questionsbysec[$section] as $question) {
if ($question->required()) {
return true;
}
}
}
return false;
}
/**
* Check if current questionnaire has dependencies set and any question has dependencies.
*
* @return boolean Whether dependencies are set or not.
*/
public function has_dependencies() {
$hasdependencies = false;
if (($this->navigate > 0) && isset($this->questions) && !empty($this->questions)) {
foreach ($this->questions as $question) {
if ($question->has_dependencies()) {
$hasdependencies = true;
break;
}
}
}
return $hasdependencies;
}
/**
* @param $questionid
* @return array
*/
public function get_all_dependants($questionid) {
$directids = $this->get_dependants($questionid);
$directs = [];
$indirects = [];
foreach ($directids as $directid) {
$this->load_parents($this->questions[$directid]);
$indirectids = $this->get_dependants($directid);
foreach ($this->questions[$directid]->dependencies as $dep) {
if ($dep->dependquestionid == $questionid) {
$directs[$directid][] = $dep;
}
}
foreach ($indirectids as $indirectid) {
$this->load_parents($this->questions[$indirectid]);
foreach ($this->questions[$indirectid]->dependencies as $dep) {
if ($dep->dependquestionid != $questionid) {
$indirects[$indirectid][] = $dep;
}
}
}
}
$alldependants = new stdClass();
$alldependants->directs = $directs;
$alldependants->indirects = $indirects;
return($alldependants);
}
/**
* @param $questionid
* @return array
*/
public function get_dependants($questionid) {
$qu = [];
// Create an array which shows for every question the child-IDs.
foreach ($this->questions as $question) {
if ($question->has_dependencies()) {
foreach ($question->dependencies as $dependency) {
if (($dependency->dependquestionid == $questionid) && !in_array($question->id, $qu)) {
$qu[] = $question->id;
}
}
}
}
return($qu);
}
/**
* Function to sort descendants array in get_dependants function.
* @param $a
* @param $b
* @return int
*/
private static function cmp($a, $b) {
if ($a == $b) {
return 0;
} else if ($a < $b) {
return -1;
} else {
return 1;
}
}
/**
* Get all descendants and choices for questions with descendants.
* @return array
*/
public function get_dependants_and_choices() {
$questions = array_reverse($this->questions, true);
$parents = [];
foreach ($questions as $question) {
foreach ($question->dependencies as $dependency) {
$child = new stdClass();
$child->choiceid = $dependency->dependchoiceid;
$child->logic = $dependency->dependlogic;
$child->andor = $dependency->dependandor;
$parents[$dependency->dependquestionid][$question->id][] = $child;
}
}
return($parents);
}
/**
* Load needed parent question information into the dependencies structure for the requested question.
* @param $question
* @return bool
*/
public function load_parents($question) {
foreach ($question->dependencies as $did => $dependency) {
$dependquestion = $this->questions[$dependency->dependquestionid];
$qdependchoice = '';
switch ($dependquestion->type_id) {
case QUESRADIO:
case QUESDROP:
case QUESCHECK:
$qdependchoice = $dependency->dependchoiceid;
$dependchoice = $dependquestion->choices[$dependency->dependchoiceid]->content;
$contents = questionnaire_choice_values($dependchoice);
if ($contents->modname) {
$dependchoice = $contents->modname;
}
break;
case QUESYESNO:
switch ($dependency->dependchoiceid) {
case 0:
$dependchoice = get_string('yes');
$qdependchoice = 'y';
break;
case 1:
$dependchoice = get_string('no');
$qdependchoice = 'n';
break;
}
break;
}
// Qdependquestion, parenttype and qdependchoice fields to be used in preview mode.
$question->dependencies[$did]->qdependquestion = 'q'.$dependquestion->id;
$question->dependencies[$did]->qdependchoice = $qdependchoice;
$question->dependencies[$did]->parenttype = $dependquestion->type_id;
// Other fields to be used in Questions edit mode.
$question->dependencies[$did]->position = $question->position;
$question->dependencies[$did]->name = $question->name;
$question->dependencies[$did]->content = $question->content;
$question->dependencies[$did]->parentposition = $dependquestion->position;
$question->dependencies[$did]->parent = $dependquestion->name.'->'.$dependchoice;
}
return true;
}
/**
* Are there any eligible questions to be displayed on the specified page/section.
* @param $secnum The section number to check.
* @param $rid The current response id.
* @return boolean
*/
public function eligible_questions_on_page($secnum, $rid) {
$questionstodisplay = false;
foreach ($this->questionsbysec[$secnum] as $question) {
if ($question->dependency_fulfilled($rid, $this->questions)) {
$questionstodisplay = true;
break;
}
}
return $questionstodisplay;
}
// Display Methods.
public function print_survey($userid=false, $quser) {
global $SESSION, $CFG;
$formdata = new stdClass();
if (data_submitted() && confirm_sesskey()) {
$formdata = data_submitted();
}
$formdata->rid = $this->get_response($quser);
// If student saved a "resume" questionnaire OR left a questionnaire unfinished
// and there are more pages than one find the page of the last answered question.
if (!empty($formdata->rid) && (empty($formdata->sec) || intval($formdata->sec) < 1)) {
$formdata->sec = $this->response_select_max_sec($formdata->rid);
}
if (empty($formdata->sec)) {
$formdata->sec = 1;
} else {
$formdata->sec = (intval($formdata->sec) > 0) ? intval($formdata->sec) : 1;
}
$numsections = isset($this->questionsbysec) ? count($this->questionsbysec) : 0; // Indexed by section.
$msg = '';
$action = $CFG->wwwroot.'/mod/questionnaire/complete.php?id='.$this->cm->id;
// TODO - Need to rework this. Too much crossover with ->view method.
// Skip logic :: if this is page 1, it cannot be the end page with no questions on it!
if ($formdata->sec == 1) {
$SESSION->questionnaire->end = false;
}
if (!empty($formdata->submit)) {
// Skip logic: we have reached the last page without any questions on it.
if (isset($SESSION->questionnaire->end) && $SESSION->questionnaire->end == true) {
return;
}
$msg = $this->response_check_format($formdata->sec, $formdata);
if (empty($msg)) {
return;
}
}
if (!empty($formdata->resume) && ($this->resume)) {
$this->response_delete($formdata->rid, $formdata->sec);
$formdata->rid = $this->response_insert($this->survey->id, $formdata->sec, $formdata->rid, $quser, $resume = true);
$this->response_goto_saved($action);
return;
}
// Save each section 's $formdata somewhere in case user returns to that page when navigating the questionnaire.
if (!empty($formdata->next)) {
$this->response_delete($formdata->rid, $formdata->sec);
$formdata->rid = $this->response_insert($this->survey->id, $formdata->sec, $formdata->rid, $quser);
$msg = $this->response_check_format($formdata->sec, $formdata);
if ( $msg ) {
$formdata->next = '';
} else {
// Skip logic.
$formdata->sec++;
if ($this->has_dependencies()) {
while (!$this->eligible_questions_on_page($formdata->sec, $formdata->rid)) {
$this->response_delete($formdata->rid, $formdata->sec);
$formdata->sec++;
// We have reached the end of questionnaire on a page without any question left.
if ($formdata->sec > $numsections) {
$SESSION->questionnaire->end = true; // End of questionnaire reached on a no questions page.
break;
}
}
}
}
}
if (!empty($formdata->prev)) {
$this->response_delete($formdata->rid, $formdata->sec);
// If skip logic and this is last page reached with no questions,
// unlock questionnaire->end to allow navigate back to previous page.
if (isset($SESSION->questionnaire->end) && ($SESSION->questionnaire->end == true)) {
$SESSION->questionnaire->end = false;
$formdata->sec--;
}
$formdata->rid = $this->response_insert($this->survey->id, $formdata->sec, $formdata->rid, $quser);
// Prevent navigation to previous page if wrong format in answered questions).
$msg = $this->response_check_format($formdata->sec, $formdata, $checkmissing = false, $checkwrongformat = true);
if ( $msg ) {
$formdata->prev = '';
} else {
$formdata->sec--;
// Skip logic.
if ($this->has_dependencies()) {
while (($formdata->sec > 0) && !$this->eligible_questions_on_page($formdata->sec, $formdata->rid)) {
$formdata->sec--;
}
}
}
}
if (!empty($formdata->rid)) {
$this->response_import_sec($formdata->rid, $formdata->sec, $formdata);
}
$formdatareferer = !empty($formdata->referer) ? htmlspecialchars($formdata->referer) : '';
$formdatarid = isset($formdata->rid) ? $formdata->rid : '0';
$this->page->add_to_page('formstart', $this->renderer->complete_formstart($action, ['referer' => $formdatareferer,
'a' => $this->id, 'sid' => $this->survey->id, 'rid' => $formdatarid, 'sec' => $formdata->sec, 'sesskey' => sesskey()]));
if (isset($this->questions) && $numsections) { // Sanity check.
$this->survey_render($formdata->sec, $msg, $formdata);
$controlbuttons = [];
if ($formdata->sec > 1) {
$controlbuttons['prev'] = ['type' => 'submit', 'value' => '<< '.get_string('previouspage', 'questionnaire')];
}
if ($this->resume) {
$controlbuttons['resume'] = ['type' => 'submit', 'value' => get_string('save', 'questionnaire')];
}
// Add a 'hidden' variable for the mod's 'view.php', and use a language variable for the submit button.
if ($formdata->sec == $numsections) {
$controlbuttons['submittype'] = ['type' => 'hidden', 'value' => 'Submit Survey'];
$controlbuttons['submit'] = ['type' => 'submit', 'value' => get_string('submitsurvey', 'questionnaire')];
} else {
$controlbuttons['next'] = ['type' => 'submit', 'value' => get_string('nextpage', 'questionnaire').' >>'];
}
$this->page->add_to_page('controlbuttons', $this->renderer->complete_controlbuttons($controlbuttons));
} else {
$this->page->add_to_page('controlbuttons',
$this->renderer->complete_controlbuttons(get_string('noneinuse', 'questionnaire')));
}
$this->page->add_to_page('formend', $this->renderer->complete_formend());
return $msg;
}
private function survey_render($section = 1, $message = '', &$formdata) {
$this->usehtmleditor = null;
if (empty($section)) {
$section = 1;
}
$numsections = isset($this->questionsbysec) ? count($this->questionsbysec) : 0;
if ($section > $numsections) {
$formdata->sec = $numsections;
$this->page->add_to_page('notifications',
$this->renderer->notification(get_string('finished', 'questionnaire'), \core\output\notification::NOTIFY_WARNING));
return(false); // Invalid section.
}
// Check to see if there are required questions.
$hasrequired = $this->has_required($section);
// Find out what question number we are on $i New fix for question numbering.
$i = 0;
if ($section > 1) {
for ($j = 2; $j <= $section; $j++) {
foreach ($this->questionsbysec[$j - 1] as $question) {
if ($question->type_id < QUESPAGEBREAK) {
$i++;
}
}
}
}
$this->print_survey_start($message, $section, $numsections, $hasrequired, '', 1);
foreach ($this->questionsbysec[$section] as $question) {
if ($question->type_id != QUESSECTIONTEXT) {
$i++;
}
// Need questionnaire id to get the questionnaire object in sectiontext (Label) question class.
$formdata->questionnaire_id = $this->id;
$this->page->add_to_page('questions',
$this->renderer->question_output($question, $formdata, [], $i, $this->usehtmleditor));
}
$this->print_survey_end($section, $numsections);
return;
}
private function print_survey_start($message, $section, $numsections, $hasrequired, $rid='', $blankquestionnaire=false) {
global $CFG, $DB;
require_once($CFG->libdir.'/filelib.php');
$userid = '';
$resp = '';
$groupname = '';
$currentgroupid = 0;
$timesubmitted = '';
// Available group modes (0 = no groups; 1 = separate groups; 2 = visible groups).
if ($rid) {
$courseid = $this->course->id;
if ($resp = $DB->get_record('questionnaire_response', array('id' => $rid)) ) {
if ($this->respondenttype == 'fullname') {
$userid = $resp->userid;
// Display name of group(s) that student belongs to... if questionnaire is set to Groups separate or visible.
if (groups_get_activity_groupmode($this->cm, $this->course)) {
if ($groups = groups_get_all_groups($courseid, $resp->userid)) {
if (count($groups) == 1) {
$group = current($groups);
$currentgroupid = $group->id;
$groupname = ' ('.get_string('group').': '.$group->name.')';
} else {
$groupname = ' ('.get_string('groups').': ';
foreach ($groups as $group) {
$groupname .= $group->name.', ';
}
$groupname = substr($groupname, 0, strlen($groupname) - 2).')';
}
} else {
$groupname = ' ('.get_string('groupnonmembers').')';
}
}
$params = array(
'objectid' => $this->survey->id,
'context' => $this->context,
'courseid' => $this->course->id,
'relateduserid' => $userid,
'other' => array('action' => 'vresp', 'currentgroupid' => $currentgroupid, 'rid' => $rid)
);
$event = \mod_questionnaire\event\response_viewed::create($params);
$event->trigger();
}
}
}