forked from PoetOS/moodle-mod_questionnaire
-
Notifications
You must be signed in to change notification settings - Fork 0
/
questionnaire.class.php
4081 lines (3687 loc) · 161 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/>.
defined('MOODLE_INTERNAL') || die();
require_once($CFG->dirroot.'/mod/questionnaire/locallib.php');
/**
* Provided the main API functions for questionnaire.
*
* @package mod_questionnaire
* @copyright 2016 Mike Churchward (mike.churchward@poetgroup.org)
* @author Mike Churchward
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class questionnaire {
// Class Properties.
/**
* @var \mod_questionnaire\question\question[] $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 constructor.
* @param stdClass $course
* @param stdClass $cm
* @param int $id
* @param null|stdClass $questionnaire
* @param bool $addquestions
* @throws dml_exception
*/
public function __construct(&$course, &$cm, $id = 0, $questionnaire = null, $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);
}
// Don't automatically add responses.
$this->responses = [];
}
/**
* Adding a survey record to the object.
* @param int $sid
* @param null $survey
*/
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.
* @param bool $sid
*/
public function add_questions($sid = false) {
global $DB;
if ($sid === false) {
$sid = $this->sid;
}
if (!isset($this->questions)) {
$this->questions = [];
$this->questionsbysec = [];
}
$select = 'surveyid = ? 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\question::question_builder($record->type_id,
$record, $this->context);
if ($record->type_id != QUESPAGEBREAK) {
$this->questionsbysec[$sec][] = $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;
}
}
}
}
}
/**
* Load all response information for this user.
*
* @param int $userid
*/
public function add_user_responses($userid = null) {
global $USER, $DB;
// Empty questionnaires cannot have responses.
if (empty($this->id)) {
return;
}
if ($userid === null) {
$userid = $USER->id;
}
$responses = $this->get_responses($userid);
foreach ($responses as $response) {
$this->responses[$response->id] = mod_questionnaire\responsetype\response\response::create_from_data($response);
}
}
/**
* Load the specified response information.
*
* @param int $responseid
*/
public function add_response(int $responseid) {
global $DB;
// Empty questionnaires cannot have responses.
if (empty($this->id)) {
return;
}
$response = $DB->get_record('questionnaire_response', ['id' => $responseid]);
$this->responses[$response->id] = mod_questionnaire\responsetype\response\response::create_from_data($response);
}
/**
* Load the response information from a submitted web form.
*
* @param stdClass $formdata
*/
public function add_response_from_formdata(stdClass $formdata) {
$this->responses[0] = mod_questionnaire\responsetype\response\response::response_from_webform($formdata, $this->questions);
}
/**
* Return a response object from a submitted mobile app form.
*
* @param stdClass $appdata
* @param int $sec
* @return bool|\mod_questionnaire\responsetype\response\response
*/
public function build_response_from_appdata(stdClass $appdata, $sec=0) {
$questions = [];
if ($sec == 0) {
$questions = $this->questions;
} else {
foreach ($this->questionsbysec[$sec] as $questionid) {
$questions[$questionid] = $this->questions[$questionid];
}
}
return mod_questionnaire\responsetype\response\response::response_from_appdata($this->id, 0, $appdata, $questions);
}
/**
* Add the renderer to the questionnaire object.
* @param plugin_renderer_base $renderer The module renderer, extended from core renderer.
*/
public function add_renderer(plugin_renderer_base $renderer) {
$this->renderer = $renderer;
}
/**
* Add the templatable page to the questionnaire object.
* @param templatable $page The page to render, implementing core classes.
*/
public function add_page($page) {
$this->page = $page;
}
/**
* Return true if questions should be automatically numbered.
* @return bool
*/
public function questions_autonumbered() {
// Value of 1 if questions should be numbered. Value of 3 if both questions and pages should be numbered.
return (!empty($this->autonum) && (($this->autonum == 1) || ($this->autonum == 3)));
}
/**
* Return true if pages should be automatically numbered.
* @return bool
*/
public function pages_autonumbered() {
// Value of 2 if pages should be numbered. Value of 3 if both questions and pages should be numbered.
return (!empty($this->autonum) && (($this->autonum == 2) || ($this->autonum == 3)));
}
/**
* The main module view function.
*/
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());
$message = $this->user_access_messages($USER->id, true);
if ($message !== false) {
$this->page->add_to_page('notifications', $message);
} else {
// Handle the main questionnaire completion page.
$quser = $USER->id;
$msg = $this->print_survey($quser, $USER->id);
// 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 ($viewform && confirm_sesskey() && isset($viewform->submit) && isset($viewform->submittype) &&
($viewform->submittype == "Submit Survey") && empty($msg)) {
if (!empty($viewform->rid)) {
$viewform->rid = (int)$viewform->rid;
}
if (!empty($viewform->sec)) {
$viewform->sec = (int)$viewform->sec;
}
$this->response_delete($viewform->rid, $viewform->sec);
$this->rid = $this->response_insert($viewform, $quser);
$this->response_commit($this->rid);
$this->update_grades($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. Note this removes the anonymity in the logged event.
$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' => $this->id)
);
$event = \mod_questionnaire\event\attempt_submitted::create($params);
$event->trigger();
$this->submission_notify($this->rid);
$this->response_goto_thankyou();
}
}
}
/**
* Delete the specified response, and insert a new one.
* @param int $rid
* @param int $sec
* @param int $quser
* @return bool|int
*/
public function delete_insert_response($rid, $sec, $quser) {
$this->response_delete($rid, $sec);
$this->rid = $this->response_insert((object)['sec' => $sec, 'rid' => $rid], $quser);
return $this->rid;
}
/**
* Commit the response.
* @param int $rid
* @param int $quser
*/
public function commit_submission_response($rid, $quser) {
$this->response_commit($rid);
// If it was a previous save, rid is in the form...
if (!empty($rid) && is_numeric($rid)) {
$rid = $rid;
// Otherwise its in this object.
} else {
$rid = $this->rid;
}
$this->update_grades($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 = [
'context' => $context,
'courseid' => $this->course->id,
'relateduserid' => $quser,
'anonymous' => $anonymous,
'other' => array('questionnaireid' => $this->id)
];
$event = \mod_questionnaire\event\attempt_submitted::create($params);
$event->trigger();
}
/**
* Update the grade for this questionnaire and user.
*
* @param int $userid
*/
private function update_grades($userid) {
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, $userid);
}
}
/**
* Function to view an entire responses data.
* @param int $rid
* @param string $referer
* @param string $resps
* @param bool $compare
* @param bool $isgroupmember
* @param bool $allresponses
* @param int $currentgroupid
* @param string $outputtarget
*/
public function view_response($rid, $referer= '', $resps = '', $compare = false, $isgroupmember = false, $allresponses = false,
$currentgroupid = 0, $outputtarget = 'html') {
$this->print_survey_start('', 1, 1, 0, $rid, false, $outputtarget);
$i = 0;
$this->add_response($rid);
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)));
}
}
$pdf = ($outputtarget == 'pdf') ? true : false;
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, $this->responses[$rid], $i, $pdf));
}
}
}
/**
* Function to view all loaded responses.
*/
public function view_all_responses() {
$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 (!empty($this->responses)) {
$this->page->add_to_page('responses', $this->renderer->all_response_output($this->responses, $this->questions));
} else {
$this->page->add_to_page('responses', $this->renderer->all_response_output(get_string('noresponses', 'questionnaire')));
}
$this->print_survey_end(1, 1);
}
// Access Methods.
/**
* True if the questionnaire is active.
* @return bool
*/
public function is_active() {
return (!empty($this->survey));
}
/**
* True if the questionnaire is open.
* @return bool
*/
public function is_open() {
return ($this->opendate > 0) ? ($this->opendate < time()) : true;
}
/**
* True if the questionnaire is closed.
* @return bool
*/
public function is_closed() {
return ($this->closedate > 0) ? ($this->closedate < time()) : false;
}
/**
* True if the specified user can complete this questionnaire.
* @param int $userid
* @return bool
*/
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;
}
}
/**
* True if the specified user is eligible to complete this questionnaire.
* @param int $userid
* @return bool
*/
public function user_is_eligible($userid) {
return ($this->capabilities->view && $this->capabilities->submit);
}
/**
* Return any message if the user cannot complete this questionnaire, explaining why.
* @param int $userid
* @param bool $asnotification Return as a rendered notification.
* @return bool|string
*/
public function user_access_messages($userid = 0, $asnotification = false) {
global $USER;
if ($userid == 0) {
$userid = $USER->id;
}
$message = false;
if (!$this->is_active()) {
if ($this->capabilities->manage) {
$msg = 'removenotinuse';
} else {
$msg = 'notavail';
}
$message = get_string($msg, 'questionnaire');
} else if ($this->survey->realm == 'template') {
$message = get_string('templatenotviewable', 'questionnaire');
} else if (!$this->is_open()) {
$message = get_string('notopen', 'questionnaire', userdate($this->opendate));
} else if ($this->is_closed()) {
$message = get_string('closed', 'questionnaire', userdate($this->closedate));
} else if (!$this->user_is_eligible($userid)) {
$message = get_string('noteligible', 'questionnaire');
} else if (!$this->user_can_take($userid)) {
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;
}
$message = get_string("alreadyfilled", "questionnaire", $msgstring);
}
if (($message !== false) && $asnotification) {
$message = $this->renderer->notification($message, \core\output\notification::NOTIFY_ERROR);
}
return $message;
}
/**
* True if the specified user has a saved response for this questionnaire.
* @param int $userid
* @return bool
*/
public function user_has_saved_response($userid) {
global $DB;
return $DB->record_exists('questionnaire_response',
['questionnaireid' => $this->id, 'userid' => $userid, 'complete' => 'n']);
}
/**
* True if the specified user can complete this questionnaire at this time.
* @param int $userid
* @return bool
*/
public function user_time_for_new_attempt($userid) {
global $DB;
$params = ['questionnaireid' => $this->id, 'userid' => $userid, 'complete' => 'y'];
if (!($attempts = $DB->get_records('questionnaire_response', $params, 'submitted 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->submitted);
$currentyear = date('Y', $timenow);
$attemptdayofyear = date('z', $attempt->submitted);
$currentdayofyear = date('z', $timenow);
$cantake = (($attemptyear < $currentyear) ||
(($attemptyear == $currentyear) && ($attemptdayofyear < $currentdayofyear)));
break;
case QUESTIONNAIREWEEKLY:
$attemptyear = date('Y', $attempt->submitted);
$currentyear = date('Y', $timenow);
$attemptweekofyear = date('W', $attempt->submitted);
$currentweekofyear = date('W', $timenow);
$cantake = (($attemptyear < $currentyear) ||
(($attemptyear == $currentyear) && ($attemptweekofyear < $currentweekofyear)));
break;
case QUESTIONNAIREMONTHLY:
$attemptyear = date('Y', $attempt->submitted);
$currentyear = date('Y', $timenow);
$attemptmonthofyear = date('n', $attempt->submitted);
$currentmonthofyear = date('n', $timenow);
$cantake = (($attemptyear < $currentyear) ||
(($attemptyear == $currentyear) && ($attemptmonthofyear < $currentmonthofyear)));
break;
default:
$cantake = false;
break;
}
return $cantake;
}
/**
* True if the accessing course contains the actual questionnaire, as opposed to an instance of a public questionnaire.
* @return bool
*/
public function is_survey_owner() {
return (!empty($this->survey->courseid) && ($this->course->id == $this->survey->courseid));
}
/**
* True if the user can view the specified response.
* @param int $rid
* @return bool|void
*/
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->questionnaireid != $this->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;
}
}
}
/**
* True if the user can view the responses to this questionnaire, and there are valid responses.
* @param null|int $usernumresp
* @return bool
*/
public function can_view_all_responses($usernumresp = null) {
global $USER, $SESSION;
$owner = $this->is_survey_owner();
$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;
$canviewallgroups = has_capability('moodle/site:accessallgroups', $this->context);
$groupmode = groups_get_activity_groupmode($this->cm, $this->course);
if ($groupmode == 1) {
$canviewgroups = groups_has_membership($this->cm, $USER->id);
}
$grouplogic = $canviewgroups || $canviewallgroups;
$respslogic = ($numresp > 0) && ($numselectedresps > 0);
return $this->can_view_all_responses_anytime($grouplogic, $respslogic) ||
$this->can_view_all_responses_with_restrictions($usernumresp, $grouplogic, $respslogic);
}
/**
* True if the user can view all of the responses to this questionnaire any time, and there are valid responses.
* @param bool $grouplogic
* @param bool $respslogic
* @return bool
*/
public function can_view_all_responses_anytime($grouplogic = true, $respslogic = true) {
// Can view if you are a valid group user, this is the owning course, and there are responses, and you have no
// response view restrictions.
return $grouplogic && $respslogic && $this->is_survey_owner() && $this->capabilities->readallresponseanytime;
}
/**
* True if the user can view all of the responses to this questionnaire any time, and there are valid responses.
* @param null|int $usernumresp
* @param bool $grouplogic
* @param bool $respslogic
* @return bool
*/
public function can_view_all_responses_with_restrictions($usernumresp, $grouplogic = true, $respslogic = true) {
// Can view if you are a valid group user, this is the owning course, and there are responses, and you can view
// subject to viewing settings..
return $grouplogic && $respslogic && $this->is_survey_owner() &&
($this->capabilities->readallresponses &&
($this->resp_view == QUESTIONNAIRE_STUDENTVIEWRESPONSES_ALWAYS ||
($this->resp_view == QUESTIONNAIRE_STUDENTVIEWRESPONSES_WHENCLOSED && $this->is_closed()) ||
($this->resp_view == QUESTIONNAIRE_STUDENTVIEWRESPONSES_WHENANSWERED && $usernumresp)));
}
/**
* Return the number of submissions for this questionnaire.
* @param bool $userid
* @param int $groupid
* @return int
*/
public function count_submissions($userid=false, $groupid=0) {
global $DB;
$params = [];
$groupsql = '';
$groupcnd = '';
if ($groupid != 0) {
$groupsql = 'INNER JOIN {groups_members} gm ON r.userid = gm.userid ';
$groupcnd = ' AND gm.groupid = :groupid ';
$params['groupid'] = $groupid;
}
// Since submission can be across questionnaires in the case of public questionnaires, need to check the realm.
// Public questionnaires can have responses to multiple questionnaire instances.
if ($this->survey_is_public_master()) {
$sql = 'SELECT COUNT(r.id) ' .
'FROM {questionnaire_response} r ' .
'INNER JOIN {questionnaire} q ON r.questionnaireid = q.id ' .
'INNER JOIN {questionnaire_survey} s ON q.sid = s.id ' .
$groupsql .
'WHERE s.id = :surveyid AND r.complete = :status' . $groupcnd;
$params['surveyid'] = $this->sid;
$params['status'] = 'y';
} else {
$sql = 'SELECT COUNT(r.id) ' .
'FROM {questionnaire_response} r ' .
$groupsql .
'WHERE r.questionnaireid = :questionnaireid AND r.complete = :status' . $groupcnd;
$params['questionnaireid'] = $this->id;
$params['status'] = 'y';
}
if ($userid) {
$sql .= ' AND r.userid = :userid';
$params['userid'] = $userid;
}
return $DB->count_records_sql($sql, $params);
}
/**
* Get the requested responses for this questionnaire.
*
* @param int|bool $userid
* @param int $groupid
* @return array
*/
public function get_responses($userid=false, $groupid=0) {
global $DB;
$params = [];
$groupsql = '';
$groupcnd = '';
if ($groupid != 0) {
$groupsql = 'INNER JOIN {groups_members} gm ON r.userid = gm.userid ';
$groupcnd = ' AND gm.groupid = :groupid ';
$params['groupid'] = $groupid;
}
// Since submission can be across questionnaires in the case of public questionnaires, need to check the realm.
// Public questionnaires can have responses to multiple questionnaire instances.
if ($this->survey_is_public_master()) {
$sql = 'SELECT r.* ' .
'FROM {questionnaire_response} r ' .
'INNER JOIN {questionnaire} q ON r.questionnaireid = q.id ' .
'INNER JOIN {questionnaire_survey} s ON q.sid = s.id ' .
$groupsql .
'WHERE s.id = :surveyid AND r.complete = :status' . $groupcnd;
$params['surveyid'] = $this->sid;
$params['status'] = 'y';
} else {
$sql = 'SELECT r.* ' .
'FROM {questionnaire_response} r ' .
$groupsql .
'WHERE r.questionnaireid = :questionnaireid AND r.complete = :status' . $groupcnd;
$params['questionnaireid'] = $this->id;
$params['status'] = 'y';
}
if ($userid) {
$sql .= ' AND r.userid = :userid';
$params['userid'] = $userid;
}
$sql .= ' ORDER BY r.id';
return $DB->get_records_sql($sql, $params);
}
/**
* True if any of the questions are required.
* @param int $section
* @return bool
*/
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 $questionid) {
if ($this->questions[$questionid]->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;
}
/**
* Get a list of all dependent questions.
* @param int $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);
}
/**
* Get a list of all dependent questions.
* @param int $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 mixed $a
* @param mixed $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 \mod_questionnaire\question\question $question
* @return bool