MDL-36754 core_files: Support tokens when rewriting text
[moodle.git] / mod / survey / lib.php
blob1f630ecabf976a8a93e358801730da5c9c8e2754
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");
59 // STANDARD FUNCTIONS ////////////////////////////////////////////////////////
60 /**
61 * Given an object containing all the necessary data,
62 * (defined by the form in mod_form.php) this function
63 * will create a new instance and return the id number
64 * of the new instance.
66 * @global object
67 * @param object $survey
68 * @return int|bool
70 function survey_add_instance($survey) {
71 global $DB;
73 if (!$template = $DB->get_record("survey", array("id"=>$survey->template))) {
74 return 0;
77 $survey->questions = $template->questions;
78 $survey->timecreated = time();
79 $survey->timemodified = $survey->timecreated;
81 $id = $DB->insert_record("survey", $survey);
83 $completiontimeexpected = !empty($survey->completionexpected) ? $survey->completionexpected : null;
84 \core_completion\api::update_completion_date_event($survey->coursemodule, 'survey', $id, $completiontimeexpected);
86 return $id;
90 /**
91 * Given an object containing all the necessary data,
92 * (defined by the form in mod_form.php) this function
93 * will update an existing instance with new data.
95 * @global object
96 * @param object $survey
97 * @return bool
99 function survey_update_instance($survey) {
100 global $DB;
102 if (!$template = $DB->get_record("survey", array("id"=>$survey->template))) {
103 return 0;
106 $survey->id = $survey->instance;
107 $survey->questions = $template->questions;
108 $survey->timemodified = time();
110 $completiontimeexpected = !empty($survey->completionexpected) ? $survey->completionexpected : null;
111 \core_completion\api::update_completion_date_event($survey->coursemodule, 'survey', $survey->id, $completiontimeexpected);
113 return $DB->update_record("survey", $survey);
117 * Given an ID of an instance of this module,
118 * this function will permanently delete the instance
119 * and any data that depends on it.
121 * @global object
122 * @param int $id
123 * @return bool
125 function survey_delete_instance($id) {
126 global $DB;
128 if (! $survey = $DB->get_record("survey", array("id"=>$id))) {
129 return false;
132 $cm = get_coursemodule_from_instance('survey', $id);
133 \core_completion\api::update_completion_date_event($cm->id, 'survey', $id, null);
135 $result = true;
137 if (! $DB->delete_records("survey_analysis", array("survey"=>$survey->id))) {
138 $result = false;
141 if (! $DB->delete_records("survey_answers", array("survey"=>$survey->id))) {
142 $result = false;
145 if (! $DB->delete_records("survey", array("id"=>$survey->id))) {
146 $result = false;
149 return $result;
153 * @global object
154 * @param object $course
155 * @param object $user
156 * @param object $mod
157 * @param object $survey
158 * @return $result
160 function survey_user_outline($course, $user, $mod, $survey) {
161 global $DB;
163 if ($answers = $DB->get_records("survey_answers", array('survey'=>$survey->id, 'userid'=>$user->id))) {
164 $lastanswer = array_pop($answers);
166 $result = new stdClass();
167 $result->info = get_string("done", "survey");
168 $result->time = $lastanswer->time;
169 return $result;
171 return NULL;
175 * @global stdObject
176 * @global object
177 * @uses SURVEY_CIQ
178 * @param object $course
179 * @param object $user
180 * @param object $mod
181 * @param object $survey
183 function survey_user_complete($course, $user, $mod, $survey) {
184 global $CFG, $DB, $OUTPUT;
186 if (survey_already_done($survey->id, $user->id)) {
187 if ($survey->template == SURVEY_CIQ) { // print out answers for critical incidents
188 $table = new html_table();
189 $table->align = array("left", "left");
191 $questions = $DB->get_records_list("survey_questions", "id", explode(',', $survey->questions));
192 $questionorder = explode(",", $survey->questions);
194 foreach ($questionorder as $key=>$val) {
195 $question = $questions[$val];
196 $questiontext = get_string($question->shorttext, "survey");
198 if ($answer = survey_get_user_answer($survey->id, $question->id, $user->id)) {
199 $answertext = "$answer->answer1";
200 } else {
201 $answertext = "No answer";
203 $table->data[] = array("<b>$questiontext</b>", s($answertext));
205 echo html_writer::table($table);
207 } else {
209 survey_print_graph("id=$mod->id&amp;sid=$user->id&amp;type=student.png");
212 } else {
213 print_string("notdone", "survey");
218 * @global stdClass
219 * @global object
220 * @param object $course
221 * @param mixed $viewfullnames
222 * @param int $timestamp
223 * @return bool
225 function survey_print_recent_activity($course, $viewfullnames, $timestart) {
226 global $CFG, $DB, $OUTPUT;
228 $modinfo = get_fast_modinfo($course);
229 $ids = array();
230 foreach ($modinfo->cms as $cm) {
231 if ($cm->modname != 'survey') {
232 continue;
234 if (!$cm->uservisible) {
235 continue;
237 $ids[$cm->instance] = $cm->instance;
240 if (!$ids) {
241 return false;
244 $slist = implode(',', $ids); // there should not be hundreds of glossaries in one course, right?
246 $allusernames = user_picture::fields('u');
247 $rs = $DB->get_recordset_sql("SELECT sa.userid, sa.survey, MAX(sa.time) AS time,
248 $allusernames
249 FROM {survey_answers} sa
250 JOIN {user} u ON u.id = sa.userid
251 WHERE sa.survey IN ($slist) AND sa.time > ?
252 GROUP BY sa.userid, sa.survey, $allusernames
253 ORDER BY time ASC", array($timestart));
254 if (!$rs->valid()) {
255 $rs->close(); // Not going to iterate (but exit), close rs
256 return false;
259 $surveys = array();
261 foreach ($rs as $survey) {
262 $cm = $modinfo->instances['survey'][$survey->survey];
263 $survey->name = $cm->name;
264 $survey->cmid = $cm->id;
265 $surveys[] = $survey;
267 $rs->close();
269 if (!$surveys) {
270 return false;
273 echo $OUTPUT->heading(get_string('newsurveyresponses', 'survey').':', 3);
274 foreach ($surveys as $survey) {
275 $url = $CFG->wwwroot.'/mod/survey/view.php?id='.$survey->cmid;
276 print_recent_activity_note($survey->time, $survey, $survey->name, $url, false, $viewfullnames);
279 return true;
282 // SQL FUNCTIONS ////////////////////////////////////////////////////////
285 * @global object
286 * @param sting $log
287 * @return array
289 function survey_log_info($log) {
290 global $DB;
291 return $DB->get_record_sql("SELECT s.name, u.firstname, u.lastname, u.picture
292 FROM {survey} s, {user} u
293 WHERE s.id = ? AND u.id = ?", array($log->info, $log->userid));
297 * @global object
298 * @param int $surveyid
299 * @param int $groupid
300 * @param int $groupingid
301 * @return array
303 function survey_get_responses($surveyid, $groupid, $groupingid) {
304 global $DB;
306 $params = array('surveyid'=>$surveyid, 'groupid'=>$groupid, 'groupingid'=>$groupingid);
308 if ($groupid) {
309 $groupsjoin = "JOIN {groups_members} gm ON u.id = gm.userid AND gm.groupid = :groupid ";
311 } else if ($groupingid) {
312 $groupsjoin = "JOIN {groups_members} gm ON u.id = gm.userid
313 JOIN {groupings_groups} gg ON gm.groupid = gg.groupid AND gg.groupingid = :groupingid ";
314 } else {
315 $groupsjoin = "";
318 $userfields = user_picture::fields('u');
319 return $DB->get_records_sql("SELECT $userfields, MAX(a.time) as time
320 FROM {survey_answers} a
321 JOIN {user} u ON a.userid = u.id
322 $groupsjoin
323 WHERE a.survey = :surveyid
324 GROUP BY $userfields
325 ORDER BY time ASC", $params);
329 * @global object
330 * @param int $survey
331 * @param int $user
332 * @return array
334 function survey_get_analysis($survey, $user) {
335 global $DB;
337 return $DB->get_record_sql("SELECT notes
338 FROM {survey_analysis}
339 WHERE survey=? AND userid=?", array($survey, $user));
343 * @global object
344 * @param int $survey
345 * @param int $user
346 * @param string $notes
348 function survey_update_analysis($survey, $user, $notes) {
349 global $DB;
351 return $DB->execute("UPDATE {survey_analysis}
352 SET notes=?
353 WHERE survey=?
354 AND userid=?", array($notes, $survey, $user));
358 * @global object
359 * @param int $surveyid
360 * @param int $groupid
361 * @param string $sort
362 * @return array
364 function survey_get_user_answers($surveyid, $questionid, $groupid, $sort="sa.answer1,sa.answer2 ASC") {
365 global $DB;
367 $params = array('surveyid'=>$surveyid, 'questionid'=>$questionid);
369 if ($groupid) {
370 $groupfrom = ', {groups_members} gm';
371 $groupsql = 'AND gm.groupid = :groupid AND u.id = gm.userid';
372 $params['groupid'] = $groupid;
373 } else {
374 $groupfrom = '';
375 $groupsql = '';
378 $userfields = user_picture::fields('u');
379 return $DB->get_records_sql("SELECT sa.*, $userfields
380 FROM {survey_answers} sa, {user} u $groupfrom
381 WHERE sa.survey = :surveyid
382 AND sa.question = :questionid
383 AND u.id = sa.userid $groupsql
384 ORDER BY $sort", $params);
388 * @global object
389 * @param int $surveyid
390 * @param int $questionid
391 * @param int $userid
392 * @return array
394 function survey_get_user_answer($surveyid, $questionid, $userid) {
395 global $DB;
397 return $DB->get_record_sql("SELECT sa.*
398 FROM {survey_answers} sa
399 WHERE sa.survey = ?
400 AND sa.question = ?
401 AND sa.userid = ?", array($surveyid, $questionid, $userid));
404 // MODULE FUNCTIONS ////////////////////////////////////////////////////////
406 * @global object
407 * @param int $survey
408 * @param int $user
409 * @param string $notes
410 * @return bool|int
412 function survey_add_analysis($survey, $user, $notes) {
413 global $DB;
415 $record = new stdClass();
416 $record->survey = $survey;
417 $record->userid = $user;
418 $record->notes = $notes;
420 return $DB->insert_record("survey_analysis", $record, false);
423 * @global object
424 * @param int $survey
425 * @param int $user
426 * @return bool
428 function survey_already_done($survey, $user) {
429 global $DB;
431 return $DB->record_exists("survey_answers", array("survey"=>$survey, "userid"=>$user));
434 * @param int $surveyid
435 * @param int $groupid
436 * @param int $groupingid
437 * @return int
439 function survey_count_responses($surveyid, $groupid, $groupingid) {
440 if ($responses = survey_get_responses($surveyid, $groupid, $groupingid)) {
441 return count($responses);
442 } else {
443 return 0;
448 * @param int $cmid
449 * @param array $results
450 * @param int $courseid
452 function survey_print_all_responses($cmid, $results, $courseid) {
453 global $OUTPUT;
454 $table = new html_table();
455 $table->head = array ("", get_string("name"), get_string("time"));
456 $table->align = array ("", "left", "left");
457 $table->size = array (35, "", "" );
459 foreach ($results as $a) {
460 $table->data[] = array($OUTPUT->user_picture($a, array('courseid'=>$courseid)),
461 html_writer::link("report.php?action=student&student=$a->id&id=$cmid", fullname($a)),
462 userdate($a->time));
465 echo html_writer::table($table);
469 * @global object
470 * @param int $templateid
471 * @return string
473 function survey_get_template_name($templateid) {
474 global $DB;
476 if ($templateid) {
477 if ($ss = $DB->get_record("surveys", array("id"=>$templateid))) {
478 return $ss->name;
480 } else {
481 return "";
487 * @param string $name
488 * @param array $numwords
489 * @return string
491 function survey_shorten_name ($name, $numwords) {
492 $words = explode(" ", $name);
493 $output = '';
494 for ($i=0; $i < $numwords; $i++) {
495 $output .= $words[$i]." ";
497 return $output;
501 * @todo Check this function
503 * @global object
504 * @global object
505 * @global int
506 * @global void This is never defined
507 * @global object This is defined twice?
508 * @param object $question
510 function survey_print_multi($question) {
511 global $USER, $DB, $qnum, $DB, $OUTPUT; //TODO: this is sloppy globals abuse
513 $stripreferthat = get_string("ipreferthat", "survey");
514 $strifoundthat = get_string("ifoundthat", "survey");
515 $strdefault = get_string('notyetanswered', 'survey');
516 $strresponses = get_string('responses', 'survey');
518 echo $OUTPUT->heading($question->text, 3);
519 echo "\n<table width=\"90%\" cellpadding=\"4\" cellspacing=\"1\" border=\"0\" class=\"surveytable\">";
521 $options = explode( ",", $question->options);
522 $numoptions = count($options);
524 // COLLES Actual (which is having questions of type 1) and COLLES Preferred (type 2)
525 // expect just one answer per question. COLLES Actual and Preferred (type 3) expects
526 // two answers per question. ATTLS (having a single question of type 1) expects one
527 // answer per question. CIQ is not using multiquestions (i.e. a question with subquestions).
528 // Note that the type of subquestions does not really matter, it's the type of the
529 // question itself that determines everything.
530 $oneanswer = ($question->type == 1 || $question->type == 2) ? true : false;
532 // COLLES Preferred (having questions of type 2) will use the radio elements with the name
533 // like qP1, qP2 etc. COLLES Actual and ATTLS have radios like q1, q2 etc.
534 if ($question->type == 2) {
535 $P = "P";
536 } else {
537 $P = "";
540 echo "<colgroup colspan=\"7\"></colgroup>";
541 echo "<tr class=\"smalltext\"><th scope=\"row\">$strresponses</th>";
542 echo "<th scope=\"col\" class=\"hresponse\">". get_string('notyetanswered', 'survey'). "</th>";
543 foreach ($options as $key => $val) {
544 echo "<th scope=\"col\" class=\"hresponse\">$val</th>\n";
546 echo "</tr>\n";
548 echo "<tr><th scope=\"colgroup\" colspan=\"7\">$question->intro</th></tr>\n";
550 $subquestions = survey_get_subquestions($question);
552 foreach ($subquestions as $q) {
553 $qnum++;
554 if ($oneanswer) {
555 $rowclass = survey_question_rowclass($qnum);
556 } else {
557 $rowclass = survey_question_rowclass(round($qnum / 2));
559 if ($q->text) {
560 $q->text = get_string($q->text, "survey");
563 echo "<tr class=\"$rowclass rblock\">";
564 if ($oneanswer) {
565 echo "<th scope=\"row\" class=\"optioncell\">";
566 echo "<b class=\"qnumtopcell\">$qnum</b> &nbsp; ";
567 echo $q->text ."</th>\n";
569 $default = get_accesshide($strdefault);
570 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>";
572 for ($i=1;$i<=$numoptions;$i++) {
573 $hiddentext = get_accesshide($options[$i-1]);
574 $id = "q$P" . $q->id . "_$i";
575 echo "<td><label for=\"$id\"><input type=\"radio\" name=\"q$P$q->id\" id=\"$id\" value=\"$i\" />$hiddentext</label></td>";
577 } else {
578 echo "<th scope=\"row\" class=\"optioncell\">";
579 echo "<b class=\"qnumtopcell\">$qnum</b> &nbsp; ";
580 $qnum++;
581 echo "<span class=\"preferthat\">$stripreferthat</span> &nbsp; ";
582 echo "<span class=\"option\">$q->text</span></th>\n";
584 $default = get_accesshide($strdefault);
585 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>';
588 for ($i=1;$i<=$numoptions;$i++) {
589 $hiddentext = get_accesshide($options[$i-1]);
590 $id = "qP" . $q->id . "_$i";
591 echo "<td><label for=\"$id\"><input type=\"radio\" name=\"qP$q->id\" id=\"$id\" value=\"$i\" />$hiddentext</label></td>";
593 echo "</tr>";
595 echo "<tr class=\"$rowclass rblock\">";
596 echo "<th scope=\"row\" class=\"optioncell\">";
597 echo "<b class=\"qnumtopcell\">$qnum</b> &nbsp; ";
598 echo "<span class=\"foundthat\">$strifoundthat</span> &nbsp; ";
599 echo "<span class=\"option\">$q->text</span></th>\n";
601 $default = get_accesshide($strdefault);
602 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>';
604 for ($i=1;$i<=$numoptions;$i++) {
605 $hiddentext = get_accesshide($options[$i-1]);
606 $id = "q" . $q->id . "_$i";
607 echo "<td><label for=\"$id\"><input type=\"radio\" name=\"q$q->id\" id=\"$id\" value=\"$i\" />$hiddentext</label></td>";
610 echo "</tr>\n";
612 echo "</table>";
617 * @global object
618 * @global int
619 * @param object $question
621 function survey_print_single($question) {
622 global $DB, $qnum, $OUTPUT;
624 $rowclass = survey_question_rowclass(0);
626 $qnum++;
628 echo "<br />\n";
629 echo "<table width=\"90%\" cellpadding=\"4\" cellspacing=\"0\">\n";
630 echo "<tr class=\"$rowclass\">";
631 echo "<th scope=\"row\" class=\"optioncell\"><label for=\"q$question->id\"><b class=\"qnumtopcell\">$qnum</b> &nbsp; ";
632 echo "<span class=\"questioncell\">$question->text</span></label></th>\n";
633 echo "<td class=\"questioncell smalltext\">\n";
636 if ($question->type == 0) { // Plain text field
637 echo "<textarea rows=\"3\" cols=\"30\" class=\"form-control\" name=\"q$question->id\" id=\"q$question->id\">$question->options</textarea>";
639 } else if ($question->type > 0) { // Choose one of a number
640 $strchoose = get_string("choose");
641 echo "<select name=\"q$question->id\" id=\"q$question->id\" class=\"custom-select\">";
642 echo "<option value=\"0\" selected=\"selected\">$strchoose...</option>";
643 $options = explode( ",", $question->options);
644 foreach ($options as $key => $val) {
645 $key++;
646 echo "<option value=\"$key\">$val</option>";
648 echo "</select>";
650 } else if ($question->type < 0) { // Choose several of a number
651 $options = explode( ",", $question->options);
652 echo $OUTPUT->notification("This question type not supported yet");
655 echo "</td></tr></table>";
661 * @param int $qnum
662 * @return string
664 function survey_question_rowclass($qnum) {
666 if ($qnum) {
667 return $qnum % 2 ? 'r0' : 'r1';
668 } else {
669 return 'r0';
674 * @global object
675 * @global int
676 * @global int
677 * @param string $url
679 function survey_print_graph($url) {
680 global $CFG, $SURVEY_GHEIGHT, $SURVEY_GWIDTH;
682 echo "<img class='resultgraph' height=\"$SURVEY_GHEIGHT\" width=\"$SURVEY_GWIDTH\"".
683 " src=\"$CFG->wwwroot/mod/survey/graph.php?$url\" alt=\"".get_string("surveygraph", "survey")."\" />";
687 * List the actions that correspond to a view of this module.
688 * This is used by the participation report.
690 * Note: This is not used by new logging system. Event with
691 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
692 * be considered as view action.
694 * @return array
696 function survey_get_view_actions() {
697 return array('download','view all','view form','view graph','view report');
701 * List the actions that correspond to a post of this module.
702 * This is used by the participation report.
704 * Note: This is not used by new logging system. Event with
705 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
706 * will be considered as post action.
708 * @return array
710 function survey_get_post_actions() {
711 return array('submit');
716 * Implementation of the function for printing the form elements that control
717 * whether the course reset functionality affects the survey.
719 * @param object $mform form passed by reference
721 function survey_reset_course_form_definition(&$mform) {
722 $mform->addElement('header', 'surveyheader', get_string('modulenameplural', 'survey'));
723 $mform->addElement('checkbox', 'reset_survey_answers', get_string('deleteallanswers','survey'));
724 $mform->addElement('checkbox', 'reset_survey_analysis', get_string('deleteanalysis','survey'));
725 $mform->disabledIf('reset_survey_analysis', 'reset_survey_answers', 'checked');
729 * Course reset form defaults.
730 * @return array
732 function survey_reset_course_form_defaults($course) {
733 return array('reset_survey_answers'=>1, 'reset_survey_analysis'=>1);
737 * Actual implementation of the reset course functionality, delete all the
738 * survey responses for course $data->courseid.
740 * @global object
741 * @param $data the data submitted from the reset course.
742 * @return array status array
744 function survey_reset_userdata($data) {
745 global $DB;
747 $componentstr = get_string('modulenameplural', 'survey');
748 $status = array();
750 $surveyssql = "SELECT ch.id
751 FROM {survey} ch
752 WHERE ch.course=?";
753 $params = array($data->courseid);
755 if (!empty($data->reset_survey_answers)) {
756 $DB->delete_records_select('survey_answers', "survey IN ($surveyssql)", $params);
757 $DB->delete_records_select('survey_analysis', "survey IN ($surveyssql)", $params);
758 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallanswers', 'survey'), 'error'=>false);
761 if (!empty($data->reset_survey_analysis)) {
762 $DB->delete_records_select('survey_analysis', "survey IN ($surveyssql)", $params);
763 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallanswers', 'survey'), 'error'=>false);
766 // No date shifting.
767 // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
768 // See MDL-9367.
770 return $status;
774 * Returns all other caps used in module
776 * @return array
778 function survey_get_extra_capabilities() {
779 return array('moodle/site:accessallgroups');
783 * @uses FEATURE_GROUPS
784 * @uses FEATURE_GROUPINGS
785 * @uses FEATURE_MOD_INTRO
786 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
787 * @uses FEATURE_GRADE_HAS_GRADE
788 * @uses FEATURE_GRADE_OUTCOMES
789 * @param string $feature FEATURE_xx constant for requested feature
790 * @return mixed True if module supports feature, false if not, null if doesn't know
792 function survey_supports($feature) {
793 switch($feature) {
794 case FEATURE_GROUPS: return true;
795 case FEATURE_GROUPINGS: return true;
796 case FEATURE_MOD_INTRO: return true;
797 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
798 case FEATURE_COMPLETION_HAS_RULES: return true;
799 case FEATURE_GRADE_HAS_GRADE: return false;
800 case FEATURE_GRADE_OUTCOMES: return false;
801 case FEATURE_BACKUP_MOODLE2: return true;
802 case FEATURE_SHOW_DESCRIPTION: return true;
804 default: return null;
809 * This function extends the settings navigation block for the site.
811 * It is safe to rely on PAGE here as we will only ever be within the module
812 * context when this is called
814 * @param navigation_node $settings
815 * @param navigation_node $surveynode
817 function survey_extend_settings_navigation($settings, $surveynode) {
818 global $PAGE;
820 if (has_capability('mod/survey:readresponses', $PAGE->cm->context)) {
821 $responsesnode = $surveynode->add(get_string("responsereports", "survey"));
823 $url = new moodle_url('/mod/survey/report.php', array('id' => $PAGE->cm->id, 'action'=>'summary'));
824 $responsesnode->add(get_string("summary", "survey"), $url);
826 $url = new moodle_url('/mod/survey/report.php', array('id' => $PAGE->cm->id, 'action'=>'scales'));
827 $responsesnode->add(get_string("scales", "survey"), $url);
829 $url = new moodle_url('/mod/survey/report.php', array('id' => $PAGE->cm->id, 'action'=>'questions'));
830 $responsesnode->add(get_string("question", "survey"), $url);
832 $url = new moodle_url('/mod/survey/report.php', array('id' => $PAGE->cm->id, 'action'=>'students'));
833 $responsesnode->add(get_string('participants'), $url);
835 if (has_capability('mod/survey:download', $PAGE->cm->context)) {
836 $url = new moodle_url('/mod/survey/report.php', array('id' => $PAGE->cm->id, 'action'=>'download'));
837 $surveynode->add(get_string('downloadresults', 'survey'), $url);
843 * Return a list of page types
844 * @param string $pagetype current page type
845 * @param stdClass $parentcontext Block's parent context
846 * @param stdClass $currentcontext Current context of block
848 function survey_page_type_list($pagetype, $parentcontext, $currentcontext) {
849 $module_pagetype = array('mod-survey-*'=>get_string('page-mod-survey-x', 'survey'));
850 return $module_pagetype;
854 * Mark the activity completed (if required) and trigger the course_module_viewed event.
856 * @param stdClass $survey survey object
857 * @param stdClass $course course object
858 * @param stdClass $cm course module object
859 * @param stdClass $context context object
860 * @param string $viewed which page viewed
861 * @since Moodle 3.0
863 function survey_view($survey, $course, $cm, $context, $viewed) {
865 // Trigger course_module_viewed event.
866 $params = array(
867 'context' => $context,
868 'objectid' => $survey->id,
869 'courseid' => $course->id,
870 'other' => array('viewed' => $viewed)
873 $event = \mod_survey\event\course_module_viewed::create($params);
874 $event->add_record_snapshot('course_modules', $cm);
875 $event->add_record_snapshot('course', $course);
876 $event->add_record_snapshot('survey', $survey);
877 $event->trigger();
879 // Completion.
880 $completion = new completion_info($course);
881 $completion->set_module_viewed($cm);
885 * Helper function for ordering a set of questions by the given ids.
887 * @param array $questions array of questions objects
888 * @param array $questionorder array of questions ids indicating the correct order
889 * @return array list of questions ordered
890 * @since Moodle 3.0
892 function survey_order_questions($questions, $questionorder) {
894 $finalquestions = array();
895 foreach ($questionorder as $qid) {
896 $finalquestions[] = $questions[$qid];
898 return $finalquestions;
902 * Translate the question texts and options.
904 * @param stdClass $question question object
905 * @return stdClass question object with all the text fields translated
906 * @since Moodle 3.0
908 function survey_translate_question($question) {
910 if ($question->text) {
911 $question->text = get_string($question->text, "survey");
914 if ($question->shorttext) {
915 $question->shorttext = get_string($question->shorttext, "survey");
918 if ($question->intro) {
919 $question->intro = get_string($question->intro, "survey");
922 if ($question->options) {
923 $question->options = get_string($question->options, "survey");
925 return $question;
929 * Returns the questions for a survey (ordered).
931 * @param stdClass $survey survey object
932 * @return array list of questions ordered
933 * @since Moodle 3.0
934 * @throws moodle_exception
936 function survey_get_questions($survey) {
937 global $DB;
939 $questionids = explode(',', $survey->questions);
940 if (! $questions = $DB->get_records_list("survey_questions", "id", $questionids)) {
941 throw new moodle_exception('cannotfindquestion', 'survey');
944 return survey_order_questions($questions, $questionids);
948 * Returns subquestions for a given question (ordered).
950 * @param stdClass $question questin object
951 * @return array list of subquestions ordered
952 * @since Moodle 3.0
954 function survey_get_subquestions($question) {
955 global $DB;
957 $questionids = explode(',', $question->multi);
958 $questions = $DB->get_records_list("survey_questions", "id", $questionids);
960 return survey_order_questions($questions, $questionids);
964 * Save the answer for the given survey
966 * @param stdClass $survey a survey object
967 * @param array $answersrawdata the answers to be saved
968 * @param stdClass $course a course object (required for trigger the submitted event)
969 * @param stdClass $context a context object (required for trigger the submitted event)
970 * @since Moodle 3.0
972 function survey_save_answers($survey, $answersrawdata, $course, $context) {
973 global $DB, $USER;
975 $answers = array();
977 // Sort through the data and arrange it.
978 // This is necessary because some of the questions may have two answers, eg Question 1 -> 1 and P1.
979 foreach ($answersrawdata as $key => $val) {
980 if ($key != "userid" && $key != "id") {
981 if (substr($key, 0, 1) == "q") {
982 $key = clean_param(substr($key, 1), PARAM_ALPHANUM); // Keep everything but the 'q', number or P number.
984 if (substr($key, 0, 1) == "P") {
985 $realkey = (int) substr($key, 1);
986 $answers[$realkey][1] = $val;
987 } else {
988 $answers[$key][0] = $val;
993 // Now store the data.
994 $timenow = time();
995 $answerstoinsert = array();
996 foreach ($answers as $key => $val) {
997 if ($key != 'sesskey') {
998 $newdata = new stdClass();
999 $newdata->time = $timenow;
1000 $newdata->userid = $USER->id;
1001 $newdata->survey = $survey->id;
1002 $newdata->question = $key;
1003 if (!empty($val[0])) {
1004 $newdata->answer1 = $val[0];
1005 } else {
1006 $newdata->answer1 = "";
1008 if (!empty($val[1])) {
1009 $newdata->answer2 = $val[1];
1010 } else {
1011 $newdata->answer2 = "";
1014 $answerstoinsert[] = $newdata;
1018 if (!empty($answerstoinsert)) {
1019 $DB->insert_records("survey_answers", $answerstoinsert);
1022 // Update completion state.
1023 $cm = get_coursemodule_from_instance('survey', $survey->id, $course->id);
1024 $completion = new completion_info($course);
1025 if (isloggedin() && !isguestuser() && $completion->is_enabled($cm) && $survey->completionsubmit) {
1026 $completion->update_state($cm, COMPLETION_COMPLETE);
1029 $params = array(
1030 'context' => $context,
1031 'courseid' => $course->id,
1032 'other' => array('surveyid' => $survey->id)
1034 $event = \mod_survey\event\response_submitted::create($params);
1035 $event->trigger();
1039 * Obtains the automatic completion state for this survey based on the condition
1040 * in feedback settings.
1042 * @param object $course Course
1043 * @param object $cm Course-module
1044 * @param int $userid User ID
1045 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
1046 * @return bool True if completed, false if not, $type if conditions not set.
1048 function survey_get_completion_state($course, $cm, $userid, $type) {
1049 global $DB;
1051 // Get survey details.
1052 $survey = $DB->get_record('survey', array('id' => $cm->instance), '*', MUST_EXIST);
1054 // If completion option is enabled, evaluate it and return true/false.
1055 if ($survey->completionsubmit) {
1056 $params = array('userid' => $userid, 'survey' => $survey->id);
1057 return $DB->record_exists('survey_answers', $params);
1058 } else {
1059 // Completion option is not enabled so just return $type.
1060 return $type;
1065 * Check if the module has any update that affects the current user since a given time.
1067 * @param cm_info $cm course module data
1068 * @param int $from the time to check updates from
1069 * @param array $filter if we need to check only specific updates
1070 * @return stdClass an object with the different type of areas indicating if they were updated or not
1071 * @since Moodle 3.2
1073 function survey_check_updates_since(cm_info $cm, $from, $filter = array()) {
1074 global $DB, $USER;
1076 $updates = new stdClass();
1077 if (!has_capability('mod/survey:participate', $cm->context)) {
1078 return $updates;
1080 $updates = course_check_module_updates_since($cm, $from, array(), $filter);
1082 $updates->answers = (object) array('updated' => false);
1083 $select = 'survey = ? AND userid = ? AND time > ?';
1084 $params = array($cm->instance, $USER->id, $from);
1085 $answers = $DB->get_records_select('survey_answers', $select, $params, '', 'id');
1086 if (!empty($answers)) {
1087 $updates->answers->updated = true;
1088 $updates->answers->itemids = array_keys($answers);
1091 // Now, teachers should see other students updates.
1092 if (has_capability('mod/survey:readresponses', $cm->context)) {
1093 $select = 'survey = ? AND time > ?';
1094 $params = array($cm->instance, $from);
1096 if (groups_get_activity_groupmode($cm) == SEPARATEGROUPS) {
1097 $groupusers = array_keys(groups_get_activity_shared_group_members($cm));
1098 if (empty($groupusers)) {
1099 return $updates;
1101 list($insql, $inparams) = $DB->get_in_or_equal($groupusers);
1102 $select .= ' AND userid ' . $insql;
1103 $params = array_merge($params, $inparams);
1106 $updates->useranswers = (object) array('updated' => false);
1107 $answers = $DB->get_records_select('survey_answers', $select, $params, '', 'id');
1108 if (!empty($answers)) {
1109 $updates->useranswers->updated = true;
1110 $updates->useranswers->itemids = array_keys($answers);
1113 return $updates;
1117 * This function receives a calendar event and returns the action associated with it, or null if there is none.
1119 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
1120 * is not displayed on the block.
1122 * @param calendar_event $event
1123 * @param \core_calendar\action_factory $factory
1124 * @return \core_calendar\local\event\entities\action_interface|null
1126 function mod_survey_core_calendar_provide_event_action(calendar_event $event,
1127 \core_calendar\action_factory $factory) {
1128 $cm = get_fast_modinfo($event->courseid)->instances['survey'][$event->instance];
1129 $context = context_module::instance($cm->id);
1131 if (!has_capability('mod/survey:participate', $context)) {
1132 return null;
1135 $completion = new \completion_info($cm->get_course());
1137 $completiondata = $completion->get_data($cm, false);
1139 if ($completiondata->completionstate != COMPLETION_INCOMPLETE) {
1140 return null;
1143 return $factory->create_instance(
1144 get_string('view'),
1145 new \moodle_url('/mod/survey/view.php', ['id' => $cm->id]),
1147 true
1152 * Add a get_coursemodule_info function in case any survey type wants to add 'extra' information
1153 * for the course (see resource).
1155 * Given a course_module object, this function returns any "extra" information that may be needed
1156 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
1158 * @param stdClass $coursemodule The coursemodule object (record).
1159 * @return cached_cm_info An object on information that the courses
1160 * will know about (most noticeably, an icon).
1162 function survey_get_coursemodule_info($coursemodule) {
1163 global $DB;
1165 $dbparams = ['id' => $coursemodule->instance];
1166 $fields = 'id, name, intro, introformat, completionsubmit';
1167 if (!$survey = $DB->get_record('survey', $dbparams, $fields)) {
1168 return false;
1171 $result = new cached_cm_info();
1172 $result->name = $survey->name;
1174 if ($coursemodule->showdescription) {
1175 // Convert intro to html. Do not filter cached version, filters run at display time.
1176 $result->content = format_module_intro('survey', $survey, $coursemodule->id, false);
1179 // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
1180 if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) {
1181 $result->customdata['customcompletionrules']['completionsubmit'] = $survey->completionsubmit;
1184 return $result;
1188 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
1190 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
1191 * @return array $descriptions the array of descriptions for the custom rules.
1193 function mod_survey_get_completion_active_rule_descriptions($cm) {
1194 // Values will be present in cm_info, and we assume these are up to date.
1195 if (empty($cm->customdata['customcompletionrules'])
1196 || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
1197 return [];
1200 $descriptions = [];
1201 foreach ($cm->customdata['customcompletionrules'] as $key => $val) {
1202 switch ($key) {
1203 case 'completionsubmit':
1204 if (empty($val)) {
1205 continue;
1207 $descriptions[] = get_string('completionsubmit', 'survey');
1208 break;
1209 default:
1210 break;
1213 return $descriptions;