Merge branch 'MDL-72646-font-mimetype-311' of https://github.com/doctorlard/moodle...
[moodle.git] / mod / survey / lib.php
blob49319b5daa588225eafffe166614811f40f2e530
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * @package mod_survey
20 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
21 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 /**
25 * Graph size
26 * @global int $SURVEY_GHEIGHT
28 global $SURVEY_GHEIGHT;
29 $SURVEY_GHEIGHT = 500;
30 /**
31 * Graph size
32 * @global int $SURVEY_GWIDTH
34 global $SURVEY_GWIDTH;
35 $SURVEY_GWIDTH = 900;
36 /**
37 * Question Type
38 * @global array $SURVEY_QTYPE
40 global $SURVEY_QTYPE;
41 $SURVEY_QTYPE = array (
42 "-3" => "Virtual Actual and Preferred",
43 "-2" => "Virtual Preferred",
44 "-1" => "Virtual Actual",
45 "0" => "Text",
46 "1" => "Actual",
47 "2" => "Preferred",
48 "3" => "Actual and Preferred",
52 define("SURVEY_COLLES_ACTUAL", "1");
53 define("SURVEY_COLLES_PREFERRED", "2");
54 define("SURVEY_COLLES_PREFERRED_ACTUAL", "3");
55 define("SURVEY_ATTLS", "4");
56 define("SURVEY_CIQ", "5");
58 require_once(__DIR__ . '/deprecatedlib.php');
60 // STANDARD FUNCTIONS ////////////////////////////////////////////////////////
61 /**
62 * Given an object containing all the necessary data,
63 * (defined by the form in mod_form.php) this function
64 * will create a new instance and return the id number
65 * of the new instance.
67 * @global object
68 * @param object $survey
69 * @return int|bool
71 function survey_add_instance($survey) {
72 global $DB;
74 if (!$template = $DB->get_record("survey", array("id"=>$survey->template))) {
75 return 0;
78 $survey->questions = $template->questions;
79 $survey->timecreated = time();
80 $survey->timemodified = $survey->timecreated;
82 $id = $DB->insert_record("survey", $survey);
84 $completiontimeexpected = !empty($survey->completionexpected) ? $survey->completionexpected : null;
85 \core_completion\api::update_completion_date_event($survey->coursemodule, 'survey', $id, $completiontimeexpected);
87 return $id;
91 /**
92 * Given an object containing all the necessary data,
93 * (defined by the form in mod_form.php) this function
94 * will update an existing instance with new data.
96 * @global object
97 * @param object $survey
98 * @return bool
100 function survey_update_instance($survey) {
101 global $DB;
103 if (!$template = $DB->get_record("survey", array("id"=>$survey->template))) {
104 return 0;
107 $survey->id = $survey->instance;
108 $survey->questions = $template->questions;
109 $survey->timemodified = time();
111 $completiontimeexpected = !empty($survey->completionexpected) ? $survey->completionexpected : null;
112 \core_completion\api::update_completion_date_event($survey->coursemodule, 'survey', $survey->id, $completiontimeexpected);
114 return $DB->update_record("survey", $survey);
118 * Given an ID of an instance of this module,
119 * this function will permanently delete the instance
120 * and any data that depends on it.
122 * @global object
123 * @param int $id
124 * @return bool
126 function survey_delete_instance($id) {
127 global $DB;
129 if (! $survey = $DB->get_record("survey", array("id"=>$id))) {
130 return false;
133 $cm = get_coursemodule_from_instance('survey', $id);
134 \core_completion\api::update_completion_date_event($cm->id, 'survey', $id, null);
136 $result = true;
138 if (! $DB->delete_records("survey_analysis", array("survey"=>$survey->id))) {
139 $result = false;
142 if (! $DB->delete_records("survey_answers", array("survey"=>$survey->id))) {
143 $result = false;
146 if (! $DB->delete_records("survey", array("id"=>$survey->id))) {
147 $result = false;
150 return $result;
154 * @global object
155 * @param object $course
156 * @param object $user
157 * @param object $mod
158 * @param object $survey
159 * @return $result
161 function survey_user_outline($course, $user, $mod, $survey) {
162 global $DB;
164 if ($answers = $DB->get_records("survey_answers", array('survey'=>$survey->id, 'userid'=>$user->id))) {
165 $lastanswer = array_pop($answers);
167 $result = new stdClass();
168 $result->info = get_string("done", "survey");
169 $result->time = $lastanswer->time;
170 return $result;
172 return NULL;
176 * @global stdObject
177 * @global object
178 * @uses SURVEY_CIQ
179 * @param object $course
180 * @param object $user
181 * @param object $mod
182 * @param object $survey
184 function survey_user_complete($course, $user, $mod, $survey) {
185 global $CFG, $DB, $OUTPUT;
187 if (survey_already_done($survey->id, $user->id)) {
188 if ($survey->template == SURVEY_CIQ) { // print out answers for critical incidents
189 $table = new html_table();
190 $table->align = array("left", "left");
192 $questions = $DB->get_records_list("survey_questions", "id", explode(',', $survey->questions));
193 $questionorder = explode(",", $survey->questions);
195 foreach ($questionorder as $key=>$val) {
196 $question = $questions[$val];
197 $questiontext = get_string($question->shorttext, "survey");
199 if ($answer = survey_get_user_answer($survey->id, $question->id, $user->id)) {
200 $answertext = "$answer->answer1";
201 } else {
202 $answertext = "No answer";
204 $table->data[] = array("<b>$questiontext</b>", s($answertext));
206 echo html_writer::table($table);
208 } else {
210 survey_print_graph("id=$mod->id&amp;sid=$user->id&amp;type=student.png");
213 } else {
214 print_string("notdone", "survey");
219 * @global stdClass
220 * @global object
221 * @param object $course
222 * @param mixed $viewfullnames
223 * @param int $timestamp
224 * @return bool
226 function survey_print_recent_activity($course, $viewfullnames, $timestart) {
227 global $CFG, $DB, $OUTPUT;
229 $modinfo = get_fast_modinfo($course);
230 $ids = array();
231 foreach ($modinfo->cms as $cm) {
232 if ($cm->modname != 'survey') {
233 continue;
235 if (!$cm->uservisible) {
236 continue;
238 $ids[$cm->instance] = $cm->instance;
241 if (!$ids) {
242 return false;
245 $slist = implode(',', $ids); // there should not be hundreds of glossaries in one course, right?
247 $userfieldsapi = \core_user\fields::for_userpic();
248 $allusernames = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
249 $rs = $DB->get_recordset_sql("SELECT sa.userid, sa.survey, MAX(sa.time) AS time,
250 $allusernames
251 FROM {survey_answers} sa
252 JOIN {user} u ON u.id = sa.userid
253 WHERE sa.survey IN ($slist) AND sa.time > ?
254 GROUP BY sa.userid, sa.survey, $allusernames
255 ORDER BY time ASC", array($timestart));
256 if (!$rs->valid()) {
257 $rs->close(); // Not going to iterate (but exit), close rs
258 return false;
261 $surveys = array();
263 foreach ($rs as $survey) {
264 $cm = $modinfo->instances['survey'][$survey->survey];
265 $survey->name = $cm->name;
266 $survey->cmid = $cm->id;
267 $surveys[] = $survey;
269 $rs->close();
271 if (!$surveys) {
272 return false;
275 echo $OUTPUT->heading(get_string('newsurveyresponses', 'survey') . ':', 6);
276 foreach ($surveys as $survey) {
277 $url = $CFG->wwwroot.'/mod/survey/view.php?id='.$survey->cmid;
278 print_recent_activity_note($survey->time, $survey, $survey->name, $url, false, $viewfullnames);
281 return true;
284 // SQL FUNCTIONS ////////////////////////////////////////////////////////
287 * @global object
288 * @param sting $log
289 * @return array
291 function survey_log_info($log) {
292 global $DB;
293 return $DB->get_record_sql("SELECT s.name, u.firstname, u.lastname, u.picture
294 FROM {survey} s, {user} u
295 WHERE s.id = ? AND u.id = ?", array($log->info, $log->userid));
299 * @global object
300 * @param int $surveyid
301 * @param int $groupid
302 * @param int $groupingid
303 * @return array
305 function survey_get_responses($surveyid, $groupid, $groupingid) {
306 global $DB;
308 $params = array('surveyid'=>$surveyid, 'groupid'=>$groupid, 'groupingid'=>$groupingid);
310 if ($groupid) {
311 $groupsjoin = "JOIN {groups_members} gm ON u.id = gm.userid AND gm.groupid = :groupid ";
313 } else if ($groupingid) {
314 $groupsjoin = "JOIN {groups_members} gm ON u.id = gm.userid
315 JOIN {groupings_groups} gg ON gm.groupid = gg.groupid AND gg.groupingid = :groupingid ";
316 } else {
317 $groupsjoin = "";
320 $userfieldsapi = \core_user\fields::for_userpic();
321 $userfields = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
322 return $DB->get_records_sql("SELECT $userfields, MAX(a.time) as time
323 FROM {survey_answers} a
324 JOIN {user} u ON a.userid = u.id
325 $groupsjoin
326 WHERE a.survey = :surveyid
327 GROUP BY $userfields
328 ORDER BY time ASC", $params);
332 * @global object
333 * @param int $survey
334 * @param int $user
335 * @return array
337 function survey_get_analysis($survey, $user) {
338 global $DB;
340 return $DB->get_record_sql("SELECT notes
341 FROM {survey_analysis}
342 WHERE survey=? AND userid=?", array($survey, $user));
346 * @global object
347 * @param int $survey
348 * @param int $user
349 * @param string $notes
351 function survey_update_analysis($survey, $user, $notes) {
352 global $DB;
354 return $DB->execute("UPDATE {survey_analysis}
355 SET notes=?
356 WHERE survey=?
357 AND userid=?", array($notes, $survey, $user));
361 * @global object
362 * @param int $surveyid
363 * @param int $groupid
364 * @param string $sort
365 * @return array
367 function survey_get_user_answers($surveyid, $questionid, $groupid, $sort="sa.answer1,sa.answer2 ASC") {
368 global $DB;
370 $params = array('surveyid'=>$surveyid, 'questionid'=>$questionid);
372 if ($groupid) {
373 $groupfrom = ', {groups_members} gm';
374 $groupsql = 'AND gm.groupid = :groupid AND u.id = gm.userid';
375 $params['groupid'] = $groupid;
376 } else {
377 $groupfrom = '';
378 $groupsql = '';
381 $userfieldsapi = \core_user\fields::for_userpic();
382 $userfields = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
383 return $DB->get_records_sql("SELECT sa.*, $userfields
384 FROM {survey_answers} sa, {user} u $groupfrom
385 WHERE sa.survey = :surveyid
386 AND sa.question = :questionid
387 AND u.id = sa.userid $groupsql
388 ORDER BY $sort", $params);
392 * @global object
393 * @param int $surveyid
394 * @param int $questionid
395 * @param int $userid
396 * @return array
398 function survey_get_user_answer($surveyid, $questionid, $userid) {
399 global $DB;
401 return $DB->get_record_sql("SELECT sa.*
402 FROM {survey_answers} sa
403 WHERE sa.survey = ?
404 AND sa.question = ?
405 AND sa.userid = ?", array($surveyid, $questionid, $userid));
408 // MODULE FUNCTIONS ////////////////////////////////////////////////////////
410 * @global object
411 * @param int $survey
412 * @param int $user
413 * @param string $notes
414 * @return bool|int
416 function survey_add_analysis($survey, $user, $notes) {
417 global $DB;
419 $record = new stdClass();
420 $record->survey = $survey;
421 $record->userid = $user;
422 $record->notes = $notes;
424 return $DB->insert_record("survey_analysis", $record, false);
427 * @global object
428 * @param int $survey
429 * @param int $user
430 * @return bool
432 function survey_already_done($survey, $user) {
433 global $DB;
435 return $DB->record_exists("survey_answers", array("survey"=>$survey, "userid"=>$user));
438 * @param int $surveyid
439 * @param int $groupid
440 * @param int $groupingid
441 * @return int
443 function survey_count_responses($surveyid, $groupid, $groupingid) {
444 if ($responses = survey_get_responses($surveyid, $groupid, $groupingid)) {
445 return count($responses);
446 } else {
447 return 0;
452 * @param int $cmid
453 * @param array $results
454 * @param int $courseid
456 function survey_print_all_responses($cmid, $results, $courseid) {
457 global $OUTPUT;
458 $table = new html_table();
459 $table->head = array ("", get_string("name"), get_string("time"));
460 $table->align = array ("", "left", "left");
461 $table->size = array (35, "", "" );
463 foreach ($results as $a) {
464 $table->data[] = array($OUTPUT->user_picture($a, array('courseid'=>$courseid)),
465 html_writer::link("report.php?action=student&student=$a->id&id=$cmid", fullname($a)),
466 userdate($a->time));
469 echo html_writer::table($table);
473 * @global object
474 * @param int $templateid
475 * @return string
477 function survey_get_template_name($templateid) {
478 global $DB;
480 if ($templateid) {
481 if ($ss = $DB->get_record("surveys", array("id"=>$templateid))) {
482 return $ss->name;
484 } else {
485 return "";
491 * @param string $name
492 * @param array $numwords
493 * @return string
495 function survey_shorten_name ($name, $numwords) {
496 $words = explode(" ", $name);
497 $output = '';
498 for ($i=0; $i < $numwords; $i++) {
499 $output .= $words[$i]." ";
501 return $output;
505 * @todo Check this function
507 * @global object
508 * @global object
509 * @global int
510 * @global void This is never defined
511 * @global object This is defined twice?
512 * @param object $question
514 function survey_print_multi($question) {
515 global $USER, $DB, $qnum, $DB, $OUTPUT; //TODO: this is sloppy globals abuse
517 $stripreferthat = get_string("ipreferthat", "survey");
518 $strifoundthat = get_string("ifoundthat", "survey");
519 $strdefault = get_string('notyetanswered', 'survey');
520 $strresponses = get_string('responses', 'survey');
522 echo $OUTPUT->heading($question->text, 3);
523 echo "\n<table width=\"90%\" cellpadding=\"4\" cellspacing=\"1\" border=\"0\" class=\"surveytable\">";
525 $options = explode( ",", $question->options);
526 $numoptions = count($options);
528 // COLLES Actual (which is having questions of type 1) and COLLES Preferred (type 2)
529 // expect just one answer per question. COLLES Actual and Preferred (type 3) expects
530 // two answers per question. ATTLS (having a single question of type 1) expects one
531 // answer per question. CIQ is not using multiquestions (i.e. a question with subquestions).
532 // Note that the type of subquestions does not really matter, it's the type of the
533 // question itself that determines everything.
534 $oneanswer = ($question->type == 1 || $question->type == 2) ? true : false;
536 // COLLES Preferred (having questions of type 2) will use the radio elements with the name
537 // like qP1, qP2 etc. COLLES Actual and ATTLS have radios like q1, q2 etc.
538 if ($question->type == 2) {
539 $P = "P";
540 } else {
541 $P = "";
544 echo "<colgroup colspan=\"7\"></colgroup>";
545 echo "<tr class=\"smalltext\"><th scope=\"row\">$strresponses</th>";
546 echo "<th scope=\"col\" class=\"hresponse\">". get_string('notyetanswered', 'survey'). "</th>";
547 foreach ($options as $key => $val) {
548 echo "<th scope=\"col\" class=\"hresponse\">$val</th>\n";
550 echo "</tr>\n";
552 echo "<tr><th scope=\"colgroup\" colspan=\"7\">$question->intro</th></tr>\n";
554 $subquestions = survey_get_subquestions($question);
556 foreach ($subquestions as $q) {
557 $qnum++;
558 if ($oneanswer) {
559 $rowclass = survey_question_rowclass($qnum);
560 } else {
561 $rowclass = survey_question_rowclass(round($qnum / 2));
563 if ($q->text) {
564 $q->text = get_string($q->text, "survey");
567 echo "<tr class=\"$rowclass rblock\">";
568 if ($oneanswer) {
569 echo "<th scope=\"row\" class=\"optioncell\">";
570 echo "<b class=\"qnumtopcell\">$qnum</b> &nbsp; ";
571 echo $q->text ."</th>\n";
573 $default = get_accesshide($strdefault);
574 echo "<td class=\"whitecell\"><label for=\"q$P$q->id\"><input type=\"radio\" name=\"q$P$q->id\" id=\"q$P" . $q->id . "_D\" value=\"0\" checked=\"checked\" data-survey-default=\"true\" />$default</label></td>";
576 for ($i=1;$i<=$numoptions;$i++) {
577 $hiddentext = get_accesshide($options[$i-1]);
578 $id = "q$P" . $q->id . "_$i";
579 echo "<td><label for=\"$id\"><input type=\"radio\" name=\"q$P$q->id\" id=\"$id\" value=\"$i\" />$hiddentext</label></td>";
581 } else {
582 echo "<th scope=\"row\" class=\"optioncell\">";
583 echo "<b class=\"qnumtopcell\">$qnum</b> &nbsp; ";
584 $qnum++;
585 echo "<span class=\"preferthat\">$stripreferthat</span> &nbsp; ";
586 echo "<span class=\"option\">$q->text</span></th>\n";
588 $default = get_accesshide($strdefault);
589 echo '<td class="whitecell"><label for="qP'.$q->id.'"><input type="radio" name="qP'.$q->id.'" id="qP'.$q->id.'" value="0" checked="checked" data-survey-default="true" />'.$default.'</label></td>';
592 for ($i=1;$i<=$numoptions;$i++) {
593 $hiddentext = get_accesshide($options[$i-1]);
594 $id = "qP" . $q->id . "_$i";
595 echo "<td><label for=\"$id\"><input type=\"radio\" name=\"qP$q->id\" id=\"$id\" value=\"$i\" />$hiddentext</label></td>";
597 echo "</tr>";
599 echo "<tr class=\"$rowclass rblock\">";
600 echo "<th scope=\"row\" class=\"optioncell\">";
601 echo "<b class=\"qnumtopcell\">$qnum</b> &nbsp; ";
602 echo "<span class=\"foundthat\">$strifoundthat</span> &nbsp; ";
603 echo "<span class=\"option\">$q->text</span></th>\n";
605 $default = get_accesshide($strdefault);
606 echo '<td class="whitecell"><label for="q'. $q->id .'"><input type="radio" name="q'.$q->id. '" id="q'. $q->id .'" value="0" checked="checked" data-survey-default="true" />'.$default.'</label></td>';
608 for ($i=1;$i<=$numoptions;$i++) {
609 $hiddentext = get_accesshide($options[$i-1]);
610 $id = "q" . $q->id . "_$i";
611 echo "<td><label for=\"$id\"><input type=\"radio\" name=\"q$q->id\" id=\"$id\" value=\"$i\" />$hiddentext</label></td>";
614 echo "</tr>\n";
616 echo "</table>";
621 * @global object
622 * @global int
623 * @param object $question
625 function survey_print_single($question) {
626 global $DB, $qnum, $OUTPUT;
628 $rowclass = survey_question_rowclass(0);
630 $qnum++;
632 echo "<br />\n";
633 echo "<table width=\"90%\" cellpadding=\"4\" cellspacing=\"0\">\n";
634 echo "<tr class=\"$rowclass\">";
635 echo "<th scope=\"row\" class=\"optioncell\"><label for=\"q$question->id\"><b class=\"qnumtopcell\">$qnum</b> &nbsp; ";
636 echo "<span class=\"questioncell\">$question->text</span></label></th>\n";
637 echo "<td class=\"questioncell smalltext\">\n";
640 if ($question->type == 0) { // Plain text field
641 echo "<textarea rows=\"3\" cols=\"30\" class=\"form-control\" name=\"q$question->id\" id=\"q$question->id\">$question->options</textarea>";
643 } else if ($question->type > 0) { // Choose one of a number
644 $strchoose = get_string("choose");
645 echo "<select name=\"q$question->id\" id=\"q$question->id\" class=\"custom-select\">";
646 echo "<option value=\"0\" selected=\"selected\">$strchoose...</option>";
647 $options = explode( ",", $question->options);
648 foreach ($options as $key => $val) {
649 $key++;
650 echo "<option value=\"$key\">$val</option>";
652 echo "</select>";
654 } else if ($question->type < 0) { // Choose several of a number
655 $options = explode( ",", $question->options);
656 echo $OUTPUT->notification("This question type not supported yet");
659 echo "</td></tr></table>";
665 * @param int $qnum
666 * @return string
668 function survey_question_rowclass($qnum) {
670 if ($qnum) {
671 return $qnum % 2 ? 'r0' : 'r1';
672 } else {
673 return 'r0';
678 * @global object
679 * @global int
680 * @global int
681 * @param string $url
683 function survey_print_graph($url) {
684 global $CFG, $SURVEY_GHEIGHT, $SURVEY_GWIDTH;
686 echo "<img class='resultgraph' height=\"$SURVEY_GHEIGHT\" width=\"$SURVEY_GWIDTH\"".
687 " src=\"$CFG->wwwroot/mod/survey/graph.php?$url\" alt=\"".get_string("surveygraph", "survey")."\" />";
691 * List the actions that correspond to a view of this module.
692 * This is used by the participation report.
694 * Note: This is not used by new logging system. Event with
695 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
696 * be considered as view action.
698 * @return array
700 function survey_get_view_actions() {
701 return array('download','view all','view form','view graph','view report');
705 * List the actions that correspond to a post of this module.
706 * This is used by the participation report.
708 * Note: This is not used by new logging system. Event with
709 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
710 * will be considered as post action.
712 * @return array
714 function survey_get_post_actions() {
715 return array('submit');
720 * Implementation of the function for printing the form elements that control
721 * whether the course reset functionality affects the survey.
723 * @param object $mform form passed by reference
725 function survey_reset_course_form_definition(&$mform) {
726 $mform->addElement('header', 'surveyheader', get_string('modulenameplural', 'survey'));
727 $mform->addElement('checkbox', 'reset_survey_answers', get_string('deleteallanswers','survey'));
728 $mform->addElement('checkbox', 'reset_survey_analysis', get_string('deleteanalysis','survey'));
729 $mform->disabledIf('reset_survey_analysis', 'reset_survey_answers', 'checked');
733 * Course reset form defaults.
734 * @return array
736 function survey_reset_course_form_defaults($course) {
737 return array('reset_survey_answers'=>1, 'reset_survey_analysis'=>1);
741 * Actual implementation of the reset course functionality, delete all the
742 * survey responses for course $data->courseid.
744 * @global object
745 * @param $data the data submitted from the reset course.
746 * @return array status array
748 function survey_reset_userdata($data) {
749 global $DB;
751 $componentstr = get_string('modulenameplural', 'survey');
752 $status = array();
754 $surveyssql = "SELECT ch.id
755 FROM {survey} ch
756 WHERE ch.course=?";
757 $params = array($data->courseid);
759 if (!empty($data->reset_survey_answers)) {
760 $DB->delete_records_select('survey_answers', "survey IN ($surveyssql)", $params);
761 $DB->delete_records_select('survey_analysis', "survey IN ($surveyssql)", $params);
762 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallanswers', 'survey'), 'error'=>false);
765 if (!empty($data->reset_survey_analysis)) {
766 $DB->delete_records_select('survey_analysis', "survey IN ($surveyssql)", $params);
767 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallanswers', 'survey'), 'error'=>false);
770 // No date shifting.
771 // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
772 // See MDL-9367.
774 return $status;
778 * @uses FEATURE_GROUPS
779 * @uses FEATURE_GROUPINGS
780 * @uses FEATURE_MOD_INTRO
781 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
782 * @uses FEATURE_GRADE_HAS_GRADE
783 * @uses FEATURE_GRADE_OUTCOMES
784 * @param string $feature FEATURE_xx constant for requested feature
785 * @return mixed True if module supports feature, false if not, null if doesn't know
787 function survey_supports($feature) {
788 switch($feature) {
789 case FEATURE_GROUPS: return true;
790 case FEATURE_GROUPINGS: return true;
791 case FEATURE_MOD_INTRO: return true;
792 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
793 case FEATURE_COMPLETION_HAS_RULES: return true;
794 case FEATURE_GRADE_HAS_GRADE: return false;
795 case FEATURE_GRADE_OUTCOMES: return false;
796 case FEATURE_BACKUP_MOODLE2: return true;
797 case FEATURE_SHOW_DESCRIPTION: return true;
799 default: return null;
804 * This function extends the settings navigation block for the site.
806 * It is safe to rely on PAGE here as we will only ever be within the module
807 * context when this is called
809 * @param navigation_node $settings
810 * @param navigation_node $surveynode
812 function survey_extend_settings_navigation($settings, $surveynode) {
813 global $PAGE;
815 if (has_capability('mod/survey:readresponses', $PAGE->cm->context)) {
816 $responsesnode = $surveynode->add(get_string("responsereports", "survey"));
818 $url = new moodle_url('/mod/survey/report.php', array('id' => $PAGE->cm->id, 'action'=>'summary'));
819 $responsesnode->add(get_string("summary", "survey"), $url);
821 $url = new moodle_url('/mod/survey/report.php', array('id' => $PAGE->cm->id, 'action'=>'scales'));
822 $responsesnode->add(get_string("scales", "survey"), $url);
824 $url = new moodle_url('/mod/survey/report.php', array('id' => $PAGE->cm->id, 'action'=>'questions'));
825 $responsesnode->add(get_string("question", "survey"), $url);
827 $url = new moodle_url('/mod/survey/report.php', array('id' => $PAGE->cm->id, 'action'=>'students'));
828 $responsesnode->add(get_string('participants'), $url);
830 if (has_capability('mod/survey:download', $PAGE->cm->context)) {
831 $url = new moodle_url('/mod/survey/report.php', array('id' => $PAGE->cm->id, 'action'=>'download'));
832 $surveynode->add(get_string('downloadresults', 'survey'), $url);
838 * Return a list of page types
839 * @param string $pagetype current page type
840 * @param stdClass $parentcontext Block's parent context
841 * @param stdClass $currentcontext Current context of block
843 function survey_page_type_list($pagetype, $parentcontext, $currentcontext) {
844 $module_pagetype = array('mod-survey-*'=>get_string('page-mod-survey-x', 'survey'));
845 return $module_pagetype;
849 * Mark the activity completed (if required) and trigger the course_module_viewed event.
851 * @param stdClass $survey survey object
852 * @param stdClass $course course object
853 * @param stdClass $cm course module object
854 * @param stdClass $context context object
855 * @param string $viewed which page viewed
856 * @since Moodle 3.0
858 function survey_view($survey, $course, $cm, $context, $viewed) {
860 // Trigger course_module_viewed event.
861 $params = array(
862 'context' => $context,
863 'objectid' => $survey->id,
864 'courseid' => $course->id,
865 'other' => array('viewed' => $viewed)
868 $event = \mod_survey\event\course_module_viewed::create($params);
869 $event->add_record_snapshot('course_modules', $cm);
870 $event->add_record_snapshot('course', $course);
871 $event->add_record_snapshot('survey', $survey);
872 $event->trigger();
874 // Completion.
875 $completion = new completion_info($course);
876 $completion->set_module_viewed($cm);
880 * Helper function for ordering a set of questions by the given ids.
882 * @param array $questions array of questions objects
883 * @param array $questionorder array of questions ids indicating the correct order
884 * @return array list of questions ordered
885 * @since Moodle 3.0
887 function survey_order_questions($questions, $questionorder) {
889 $finalquestions = array();
890 foreach ($questionorder as $qid) {
891 $finalquestions[] = $questions[$qid];
893 return $finalquestions;
897 * Translate the question texts and options.
899 * @param stdClass $question question object
900 * @return stdClass question object with all the text fields translated
901 * @since Moodle 3.0
903 function survey_translate_question($question) {
905 if ($question->text) {
906 $question->text = get_string($question->text, "survey");
909 if ($question->shorttext) {
910 $question->shorttext = get_string($question->shorttext, "survey");
913 if ($question->intro) {
914 $question->intro = get_string($question->intro, "survey");
917 if ($question->options) {
918 $question->options = get_string($question->options, "survey");
920 return $question;
924 * Returns the questions for a survey (ordered).
926 * @param stdClass $survey survey object
927 * @return array list of questions ordered
928 * @since Moodle 3.0
929 * @throws moodle_exception
931 function survey_get_questions($survey) {
932 global $DB;
934 $questionids = explode(',', $survey->questions);
935 if (! $questions = $DB->get_records_list("survey_questions", "id", $questionids)) {
936 throw new moodle_exception('cannotfindquestion', 'survey');
939 return survey_order_questions($questions, $questionids);
943 * Returns subquestions for a given question (ordered).
945 * @param stdClass $question questin object
946 * @return array list of subquestions ordered
947 * @since Moodle 3.0
949 function survey_get_subquestions($question) {
950 global $DB;
952 $questionids = explode(',', $question->multi);
953 $questions = $DB->get_records_list("survey_questions", "id", $questionids);
955 return survey_order_questions($questions, $questionids);
959 * Save the answer for the given survey
961 * @param stdClass $survey a survey object
962 * @param array $answersrawdata the answers to be saved
963 * @param stdClass $course a course object (required for trigger the submitted event)
964 * @param stdClass $context a context object (required for trigger the submitted event)
965 * @since Moodle 3.0
967 function survey_save_answers($survey, $answersrawdata, $course, $context) {
968 global $DB, $USER;
970 $answers = array();
972 // Sort through the data and arrange it.
973 // This is necessary because some of the questions may have two answers, eg Question 1 -> 1 and P1.
974 foreach ($answersrawdata as $key => $val) {
975 if ($key != "userid" && $key != "id") {
976 if (substr($key, 0, 1) == "q") {
977 $key = clean_param(substr($key, 1), PARAM_ALPHANUM); // Keep everything but the 'q', number or P number.
979 if (substr($key, 0, 1) == "P") {
980 $realkey = (int) substr($key, 1);
981 $answers[$realkey][1] = $val;
982 } else {
983 $answers[$key][0] = $val;
988 // Now store the data.
989 $timenow = time();
990 $answerstoinsert = array();
991 foreach ($answers as $key => $val) {
992 if ($key != 'sesskey') {
993 $newdata = new stdClass();
994 $newdata->time = $timenow;
995 $newdata->userid = $USER->id;
996 $newdata->survey = $survey->id;
997 $newdata->question = $key;
998 if (!empty($val[0])) {
999 $newdata->answer1 = $val[0];
1000 } else {
1001 $newdata->answer1 = "";
1003 if (!empty($val[1])) {
1004 $newdata->answer2 = $val[1];
1005 } else {
1006 $newdata->answer2 = "";
1009 $answerstoinsert[] = $newdata;
1013 if (!empty($answerstoinsert)) {
1014 $DB->insert_records("survey_answers", $answerstoinsert);
1017 // Update completion state.
1018 $cm = get_coursemodule_from_instance('survey', $survey->id, $course->id);
1019 $completion = new completion_info($course);
1020 if (isloggedin() && !isguestuser() && $completion->is_enabled($cm) && $survey->completionsubmit) {
1021 $completion->update_state($cm, COMPLETION_COMPLETE);
1024 $params = array(
1025 'context' => $context,
1026 'courseid' => $course->id,
1027 'other' => array('surveyid' => $survey->id)
1029 $event = \mod_survey\event\response_submitted::create($params);
1030 $event->trigger();
1034 * Check if the module has any update that affects the current user since a given time.
1036 * @param cm_info $cm course module data
1037 * @param int $from the time to check updates from
1038 * @param array $filter if we need to check only specific updates
1039 * @return stdClass an object with the different type of areas indicating if they were updated or not
1040 * @since Moodle 3.2
1042 function survey_check_updates_since(cm_info $cm, $from, $filter = array()) {
1043 global $DB, $USER;
1045 $updates = new stdClass();
1046 if (!has_capability('mod/survey:participate', $cm->context)) {
1047 return $updates;
1049 $updates = course_check_module_updates_since($cm, $from, array(), $filter);
1051 $updates->answers = (object) array('updated' => false);
1052 $select = 'survey = ? AND userid = ? AND time > ?';
1053 $params = array($cm->instance, $USER->id, $from);
1054 $answers = $DB->get_records_select('survey_answers', $select, $params, '', 'id');
1055 if (!empty($answers)) {
1056 $updates->answers->updated = true;
1057 $updates->answers->itemids = array_keys($answers);
1060 // Now, teachers should see other students updates.
1061 if (has_capability('mod/survey:readresponses', $cm->context)) {
1062 $select = 'survey = ? AND time > ?';
1063 $params = array($cm->instance, $from);
1065 if (groups_get_activity_groupmode($cm) == SEPARATEGROUPS) {
1066 $groupusers = array_keys(groups_get_activity_shared_group_members($cm));
1067 if (empty($groupusers)) {
1068 return $updates;
1070 list($insql, $inparams) = $DB->get_in_or_equal($groupusers);
1071 $select .= ' AND userid ' . $insql;
1072 $params = array_merge($params, $inparams);
1075 $updates->useranswers = (object) array('updated' => false);
1076 $answers = $DB->get_records_select('survey_answers', $select, $params, '', 'id');
1077 if (!empty($answers)) {
1078 $updates->useranswers->updated = true;
1079 $updates->useranswers->itemids = array_keys($answers);
1082 return $updates;
1086 * This function receives a calendar event and returns the action associated with it, or null if there is none.
1088 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
1089 * is not displayed on the block.
1091 * @param calendar_event $event
1092 * @param \core_calendar\action_factory $factory
1093 * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
1094 * @return \core_calendar\local\event\entities\action_interface|null
1096 function mod_survey_core_calendar_provide_event_action(calendar_event $event,
1097 \core_calendar\action_factory $factory,
1098 int $userid = 0) {
1099 global $USER;
1101 if (empty($userid)) {
1102 $userid = $USER->id;
1105 $cm = get_fast_modinfo($event->courseid, $userid)->instances['survey'][$event->instance];
1106 $context = context_module::instance($cm->id);
1108 if (!has_capability('mod/survey:participate', $context, $userid)) {
1109 return null;
1112 $completion = new \completion_info($cm->get_course());
1114 $completiondata = $completion->get_data($cm, false, $userid);
1116 if ($completiondata->completionstate != COMPLETION_INCOMPLETE) {
1117 return null;
1120 return $factory->create_instance(
1121 get_string('view'),
1122 new \moodle_url('/mod/survey/view.php', ['id' => $cm->id]),
1124 true
1129 * Add a get_coursemodule_info function in case any survey type wants to add 'extra' information
1130 * for the course (see resource).
1132 * Given a course_module object, this function returns any "extra" information that may be needed
1133 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
1135 * @param stdClass $coursemodule The coursemodule object (record).
1136 * @return cached_cm_info An object on information that the courses
1137 * will know about (most noticeably, an icon).
1139 function survey_get_coursemodule_info($coursemodule) {
1140 global $DB;
1142 $dbparams = ['id' => $coursemodule->instance];
1143 $fields = 'id, name, intro, introformat, completionsubmit';
1144 if (!$survey = $DB->get_record('survey', $dbparams, $fields)) {
1145 return false;
1148 $result = new cached_cm_info();
1149 $result->name = $survey->name;
1151 if ($coursemodule->showdescription) {
1152 // Convert intro to html. Do not filter cached version, filters run at display time.
1153 $result->content = format_module_intro('survey', $survey, $coursemodule->id, false);
1156 // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
1157 if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) {
1158 $result->customdata['customcompletionrules']['completionsubmit'] = $survey->completionsubmit;
1161 return $result;
1165 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
1167 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
1168 * @return array $descriptions the array of descriptions for the custom rules.
1170 function mod_survey_get_completion_active_rule_descriptions($cm) {
1171 // Values will be present in cm_info, and we assume these are up to date.
1172 if (empty($cm->customdata['customcompletionrules'])
1173 || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
1174 return [];
1177 $descriptions = [];
1178 foreach ($cm->customdata['customcompletionrules'] as $key => $val) {
1179 switch ($key) {
1180 case 'completionsubmit':
1181 if (!empty($val)) {
1182 $descriptions[] = get_string('completionsubmit', 'survey');
1184 break;
1185 default:
1186 break;
1189 return $descriptions;