MDL-49940 mod_survey: Fix XSS on survey module
[moodle.git] / mod / survey / lib.php
blob9d57fb36df048e827473761617f36c8c83ccf646
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 return $DB->insert_record("survey", $survey);
85 /**
86 * Given an object containing all the necessary data,
87 * (defined by the form in mod_form.php) this function
88 * will update an existing instance with new data.
90 * @global object
91 * @param object $survey
92 * @return bool
94 function survey_update_instance($survey) {
95 global $DB;
97 if (!$template = $DB->get_record("survey", array("id"=>$survey->template))) {
98 return 0;
101 $survey->id = $survey->instance;
102 $survey->questions = $template->questions;
103 $survey->timemodified = time();
105 return $DB->update_record("survey", $survey);
109 * Given an ID of an instance of this module,
110 * this function will permanently delete the instance
111 * and any data that depends on it.
113 * @global object
114 * @param int $id
115 * @return bool
117 function survey_delete_instance($id) {
118 global $DB;
120 if (! $survey = $DB->get_record("survey", array("id"=>$id))) {
121 return false;
124 $result = true;
126 if (! $DB->delete_records("survey_analysis", array("survey"=>$survey->id))) {
127 $result = false;
130 if (! $DB->delete_records("survey_answers", array("survey"=>$survey->id))) {
131 $result = false;
134 if (! $DB->delete_records("survey", array("id"=>$survey->id))) {
135 $result = false;
138 return $result;
142 * @global object
143 * @param object $course
144 * @param object $user
145 * @param object $mod
146 * @param object $survey
147 * @return $result
149 function survey_user_outline($course, $user, $mod, $survey) {
150 global $DB;
152 if ($answers = $DB->get_records("survey_answers", array('survey'=>$survey->id, 'userid'=>$user->id))) {
153 $lastanswer = array_pop($answers);
155 $result = new stdClass();
156 $result->info = get_string("done", "survey");
157 $result->time = $lastanswer->time;
158 return $result;
160 return NULL;
164 * @global stdObject
165 * @global object
166 * @uses SURVEY_CIQ
167 * @param object $course
168 * @param object $user
169 * @param object $mod
170 * @param object $survey
172 function survey_user_complete($course, $user, $mod, $survey) {
173 global $CFG, $DB, $OUTPUT;
175 if (survey_already_done($survey->id, $user->id)) {
176 if ($survey->template == SURVEY_CIQ) { // print out answers for critical incidents
177 $table = new html_table();
178 $table->align = array("left", "left");
180 $questions = $DB->get_records_list("survey_questions", "id", explode(',', $survey->questions));
181 $questionorder = explode(",", $survey->questions);
183 foreach ($questionorder as $key=>$val) {
184 $question = $questions[$val];
185 $questiontext = get_string($question->shorttext, "survey");
187 if ($answer = survey_get_user_answer($survey->id, $question->id, $user->id)) {
188 $answertext = "$answer->answer1";
189 } else {
190 $answertext = "No answer";
192 $table->data[] = array("<b>$questiontext</b>", s($answertext));
194 echo html_writer::table($table);
196 } else {
198 survey_print_graph("id=$mod->id&amp;sid=$user->id&amp;type=student.png");
201 } else {
202 print_string("notdone", "survey");
207 * @global stdClass
208 * @global object
209 * @param object $course
210 * @param mixed $viewfullnames
211 * @param int $timestamp
212 * @return bool
214 function survey_print_recent_activity($course, $viewfullnames, $timestart) {
215 global $CFG, $DB, $OUTPUT;
217 $modinfo = get_fast_modinfo($course);
218 $ids = array();
219 foreach ($modinfo->cms as $cm) {
220 if ($cm->modname != 'survey') {
221 continue;
223 if (!$cm->uservisible) {
224 continue;
226 $ids[$cm->instance] = $cm->instance;
229 if (!$ids) {
230 return false;
233 $slist = implode(',', $ids); // there should not be hundreds of glossaries in one course, right?
235 $allusernames = user_picture::fields('u');
236 $rs = $DB->get_recordset_sql("SELECT sa.userid, sa.survey, MAX(sa.time) AS time,
237 $allusernames
238 FROM {survey_answers} sa
239 JOIN {user} u ON u.id = sa.userid
240 WHERE sa.survey IN ($slist) AND sa.time > ?
241 GROUP BY sa.userid, sa.survey, $allusernames
242 ORDER BY time ASC", array($timestart));
243 if (!$rs->valid()) {
244 $rs->close(); // Not going to iterate (but exit), close rs
245 return false;
248 $surveys = array();
250 foreach ($rs as $survey) {
251 $cm = $modinfo->instances['survey'][$survey->survey];
252 $survey->name = $cm->name;
253 $survey->cmid = $cm->id;
254 $surveys[] = $survey;
256 $rs->close();
258 if (!$surveys) {
259 return false;
262 echo $OUTPUT->heading(get_string('newsurveyresponses', 'survey').':', 3);
263 foreach ($surveys as $survey) {
264 $url = $CFG->wwwroot.'/mod/survey/view.php?id='.$survey->cmid;
265 print_recent_activity_note($survey->time, $survey, $survey->name, $url, false, $viewfullnames);
268 return true;
271 // SQL FUNCTIONS ////////////////////////////////////////////////////////
274 * @global object
275 * @param sting $log
276 * @return array
278 function survey_log_info($log) {
279 global $DB;
280 return $DB->get_record_sql("SELECT s.name, u.firstname, u.lastname, u.picture
281 FROM {survey} s, {user} u
282 WHERE s.id = ? AND u.id = ?", array($log->info, $log->userid));
286 * @global object
287 * @param int $surveyid
288 * @param int $groupid
289 * @param int $groupingid
290 * @return array
292 function survey_get_responses($surveyid, $groupid, $groupingid) {
293 global $DB;
295 $params = array('surveyid'=>$surveyid, 'groupid'=>$groupid, 'groupingid'=>$groupingid);
297 if ($groupid) {
298 $groupsjoin = "JOIN {groups_members} gm ON u.id = gm.userid AND gm.groupid = :groupid ";
300 } else if ($groupingid) {
301 $groupsjoin = "JOIN {groups_members} gm ON u.id = gm.userid
302 JOIN {groupings_groups} gg ON gm.groupid = gg.groupid AND gg.groupingid = :groupingid ";
303 } else {
304 $groupsjoin = "";
307 $userfields = user_picture::fields('u');
308 return $DB->get_records_sql("SELECT $userfields, MAX(a.time) as time
309 FROM {survey_answers} a
310 JOIN {user} u ON a.userid = u.id
311 $groupsjoin
312 WHERE a.survey = :surveyid
313 GROUP BY $userfields
314 ORDER BY time ASC", $params);
318 * @global object
319 * @param int $survey
320 * @param int $user
321 * @return array
323 function survey_get_analysis($survey, $user) {
324 global $DB;
326 return $DB->get_record_sql("SELECT notes
327 FROM {survey_analysis}
328 WHERE survey=? AND userid=?", array($survey, $user));
332 * @global object
333 * @param int $survey
334 * @param int $user
335 * @param string $notes
337 function survey_update_analysis($survey, $user, $notes) {
338 global $DB;
340 return $DB->execute("UPDATE {survey_analysis}
341 SET notes=?
342 WHERE survey=?
343 AND userid=?", array($notes, $survey, $user));
347 * @global object
348 * @param int $surveyid
349 * @param int $groupid
350 * @param string $sort
351 * @return array
353 function survey_get_user_answers($surveyid, $questionid, $groupid, $sort="sa.answer1,sa.answer2 ASC") {
354 global $DB;
356 $params = array('surveyid'=>$surveyid, 'questionid'=>$questionid);
358 if ($groupid) {
359 $groupfrom = ', {groups_members} gm';
360 $groupsql = 'AND gm.groupid = :groupid AND u.id = gm.userid';
361 $params['groupid'] = $groupid;
362 } else {
363 $groupfrom = '';
364 $groupsql = '';
367 $userfields = user_picture::fields('u');
368 return $DB->get_records_sql("SELECT sa.*, $userfields
369 FROM {survey_answers} sa, {user} u $groupfrom
370 WHERE sa.survey = :surveyid
371 AND sa.question = :questionid
372 AND u.id = sa.userid $groupsql
373 ORDER BY $sort", $params);
377 * @global object
378 * @param int $surveyid
379 * @param int $questionid
380 * @param int $userid
381 * @return array
383 function survey_get_user_answer($surveyid, $questionid, $userid) {
384 global $DB;
386 return $DB->get_record_sql("SELECT sa.*
387 FROM {survey_answers} sa
388 WHERE sa.survey = ?
389 AND sa.question = ?
390 AND sa.userid = ?", array($surveyid, $questionid, $userid));
393 // MODULE FUNCTIONS ////////////////////////////////////////////////////////
395 * @global object
396 * @param int $survey
397 * @param int $user
398 * @param string $notes
399 * @return bool|int
401 function survey_add_analysis($survey, $user, $notes) {
402 global $DB;
404 $record = new stdClass();
405 $record->survey = $survey;
406 $record->userid = $user;
407 $record->notes = $notes;
409 return $DB->insert_record("survey_analysis", $record, false);
412 * @global object
413 * @param int $survey
414 * @param int $user
415 * @return bool
417 function survey_already_done($survey, $user) {
418 global $DB;
420 return $DB->record_exists("survey_answers", array("survey"=>$survey, "userid"=>$user));
423 * @param int $surveyid
424 * @param int $groupid
425 * @param int $groupingid
426 * @return int
428 function survey_count_responses($surveyid, $groupid, $groupingid) {
429 if ($responses = survey_get_responses($surveyid, $groupid, $groupingid)) {
430 return count($responses);
431 } else {
432 return 0;
437 * @param int $cmid
438 * @param array $results
439 * @param int $courseid
441 function survey_print_all_responses($cmid, $results, $courseid) {
442 global $OUTPUT;
443 $table = new html_table();
444 $table->head = array ("", get_string("name"), get_string("time"));
445 $table->align = array ("", "left", "left");
446 $table->size = array (35, "", "" );
448 foreach ($results as $a) {
449 $table->data[] = array($OUTPUT->user_picture($a, array('courseid'=>$courseid)),
450 html_writer::link("report.php?action=student&student=$a->id&id=$cmid", fullname($a)),
451 userdate($a->time));
454 echo html_writer::table($table);
458 * @global object
459 * @param int $templateid
460 * @return string
462 function survey_get_template_name($templateid) {
463 global $DB;
465 if ($templateid) {
466 if ($ss = $DB->get_record("surveys", array("id"=>$templateid))) {
467 return $ss->name;
469 } else {
470 return "";
476 * @param string $name
477 * @param array $numwords
478 * @return string
480 function survey_shorten_name ($name, $numwords) {
481 $words = explode(" ", $name);
482 $output = '';
483 for ($i=0; $i < $numwords; $i++) {
484 $output .= $words[$i]." ";
486 return $output;
490 * @todo Check this function
492 * @global object
493 * @global object
494 * @global int
495 * @global void This is never defined
496 * @global object This is defined twice?
497 * @param object $question
499 function survey_print_multi($question) {
500 global $USER, $DB, $qnum, $checklist, $DB, $OUTPUT; //TODO: this is sloppy globals abuse
502 $stripreferthat = get_string("ipreferthat", "survey");
503 $strifoundthat = get_string("ifoundthat", "survey");
504 $strdefault = get_string('notyetanswered', 'survey');
505 $strresponses = get_string('responses', 'survey');
507 echo $OUTPUT->heading($question->text, 3);
508 echo "\n<table width=\"90%\" cellpadding=\"4\" cellspacing=\"1\" border=\"0\" class=\"surveytable\">";
510 $options = explode( ",", $question->options);
511 $numoptions = count($options);
513 // COLLES Actual (which is having questions of type 1) and COLLES Preferred (type 2)
514 // expect just one answer per question. COLLES Actual and Preferred (type 3) expects
515 // two answers per question. ATTLS (having a single question of type 1) expects one
516 // answer per question. CIQ is not using multiquestions (i.e. a question with subquestions).
517 // Note that the type of subquestions does not really matter, it's the type of the
518 // question itself that determines everything.
519 $oneanswer = ($question->type == 1 || $question->type == 2) ? true : false;
521 // COLLES Preferred (having questions of type 2) will use the radio elements with the name
522 // like qP1, qP2 etc. COLLES Actual and ATTLS have radios like q1, q2 etc.
523 if ($question->type == 2) {
524 $P = "P";
525 } else {
526 $P = "";
529 echo "<tr class=\"smalltext\"><th scope=\"row\">$strresponses</th>";
530 echo "<th scope=\"col\" class=\"hresponse\">". get_string('notyetanswered', 'survey'). "</th>";
531 while (list ($key, $val) = each ($options)) {
532 echo "<th scope=\"col\" class=\"hresponse\">$val</th>\n";
534 echo "</tr>\n";
536 echo "<tr><th scope=\"col\" colspan=\"7\">$question->intro</th></tr>\n";
538 $subquestions = survey_get_subquestions($question);
540 foreach ($subquestions as $q) {
541 $qnum++;
542 if ($oneanswer) {
543 $rowclass = survey_question_rowclass($qnum);
544 } else {
545 $rowclass = survey_question_rowclass(round($qnum / 2));
547 if ($q->text) {
548 $q->text = get_string($q->text, "survey");
551 echo "<tr class=\"$rowclass rblock\">";
552 if ($oneanswer) {
553 echo "<th scope=\"row\" class=\"optioncell\">";
554 echo "<b class=\"qnumtopcell\">$qnum</b> &nbsp; ";
555 echo $q->text ."</th>\n";
557 $default = get_accesshide($strdefault);
558 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\" />$default</label></td>";
560 for ($i=1;$i<=$numoptions;$i++) {
561 $hiddentext = get_accesshide($options[$i-1]);
562 $id = "q$P" . $q->id . "_$i";
563 echo "<td><label for=\"$id\"><input type=\"radio\" name=\"q$P$q->id\" id=\"$id\" value=\"$i\" />$hiddentext</label></td>";
565 $checklist["q$P$q->id"] = 0;
567 } else {
568 echo "<th scope=\"row\" class=\"optioncell\">";
569 echo "<b class=\"qnumtopcell\">$qnum</b> &nbsp; ";
570 $qnum++;
571 echo "<span class=\"preferthat\">$stripreferthat</span> &nbsp; ";
572 echo "<span class=\"option\">$q->text</span></th>\n";
574 $default = get_accesshide($strdefault);
575 echo '<td class="whitecell"><label for="qP'.$q->id.'"><input type="radio" name="qP'.$q->id.'" id="qP'.$q->id.'" value="0" checked="checked" />'.$default.'</label></td>';
578 for ($i=1;$i<=$numoptions;$i++) {
579 $hiddentext = get_accesshide($options[$i-1]);
580 $id = "qP" . $q->id . "_$i";
581 echo "<td><label for=\"$id\"><input type=\"radio\" name=\"qP$q->id\" id=\"$id\" value=\"$i\" />$hiddentext</label></td>";
583 echo "</tr>";
585 echo "<tr class=\"$rowclass rblock\">";
586 echo "<th scope=\"row\" class=\"optioncell\">";
587 echo "<b class=\"qnumtopcell\">$qnum</b> &nbsp; ";
588 echo "<span class=\"foundthat\">$strifoundthat</span> &nbsp; ";
589 echo "<span class=\"option\">$q->text</span></th>\n";
591 $default = get_accesshide($strdefault);
592 echo '<td class="whitecell"><label for="q'. $q->id .'"><input type="radio" name="q'.$q->id. '" id="q'. $q->id .'" value="0" checked="checked" />'.$default.'</label></td>';
594 for ($i=1;$i<=$numoptions;$i++) {
595 $hiddentext = get_accesshide($options[$i-1]);
596 $id = "q" . $q->id . "_$i";
597 echo "<td><label for=\"$id\"><input type=\"radio\" name=\"q$q->id\" id=\"$id\" value=\"$i\" />$hiddentext</label></td>";
600 $checklist["qP$q->id"] = 0;
601 $checklist["q$q->id"] = 0;
603 echo "</tr>\n";
605 echo "</table>";
610 * @global object
611 * @global int
612 * @param object $question
614 function survey_print_single($question) {
615 global $DB, $qnum, $OUTPUT;
617 $rowclass = survey_question_rowclass(0);
619 $qnum++;
621 echo "<br />\n";
622 echo "<table width=\"90%\" cellpadding=\"4\" cellspacing=\"0\">\n";
623 echo "<tr class=\"$rowclass\">";
624 echo "<th scope=\"row\" class=\"optioncell\"><label for=\"q$question->id\"><b class=\"qnumtopcell\">$qnum</b> &nbsp; ";
625 echo "<span class=\"questioncell\">$question->text</span></label></th>\n";
626 echo "<td class=\"questioncell smalltext\">\n";
629 if ($question->type == 0) { // Plain text field
630 echo "<textarea rows=\"3\" cols=\"30\" name=\"q$question->id\" id=\"q$question->id\">$question->options</textarea>";
632 } else if ($question->type > 0) { // Choose one of a number
633 $strchoose = get_string("choose");
634 echo "<select name=\"q$question->id\" id=\"q$question->id\">";
635 echo "<option value=\"0\" selected=\"selected\">$strchoose...</option>";
636 $options = explode( ",", $question->options);
637 foreach ($options as $key => $val) {
638 $key++;
639 echo "<option value=\"$key\">$val</option>";
641 echo "</select>";
643 } else if ($question->type < 0) { // Choose several of a number
644 $options = explode( ",", $question->options);
645 echo $OUTPUT->notification("This question type not supported yet");
648 echo "</td></tr></table>";
654 * @param int $qnum
655 * @return string
657 function survey_question_rowclass($qnum) {
659 if ($qnum) {
660 return $qnum % 2 ? 'r0' : 'r1';
661 } else {
662 return 'r0';
667 * @global object
668 * @global int
669 * @global int
670 * @param string $url
672 function survey_print_graph($url) {
673 global $CFG, $SURVEY_GHEIGHT, $SURVEY_GWIDTH;
675 echo "<img class='resultgraph' height=\"$SURVEY_GHEIGHT\" width=\"$SURVEY_GWIDTH\"".
676 " src=\"$CFG->wwwroot/mod/survey/graph.php?$url\" alt=\"".get_string("surveygraph", "survey")."\" />";
680 * List the actions that correspond to a view of this module.
681 * This is used by the participation report.
683 * Note: This is not used by new logging system. Event with
684 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
685 * be considered as view action.
687 * @return array
689 function survey_get_view_actions() {
690 return array('download','view all','view form','view graph','view report');
694 * List the actions that correspond to a post of this module.
695 * This is used by the participation report.
697 * Note: This is not used by new logging system. Event with
698 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
699 * will be considered as post action.
701 * @return array
703 function survey_get_post_actions() {
704 return array('submit');
709 * Implementation of the function for printing the form elements that control
710 * whether the course reset functionality affects the survey.
712 * @param object $mform form passed by reference
714 function survey_reset_course_form_definition(&$mform) {
715 $mform->addElement('header', 'surveyheader', get_string('modulenameplural', 'survey'));
716 $mform->addElement('checkbox', 'reset_survey_answers', get_string('deleteallanswers','survey'));
717 $mform->addElement('checkbox', 'reset_survey_analysis', get_string('deleteanalysis','survey'));
718 $mform->disabledIf('reset_survey_analysis', 'reset_survey_answers', 'checked');
722 * Course reset form defaults.
723 * @return array
725 function survey_reset_course_form_defaults($course) {
726 return array('reset_survey_answers'=>1, 'reset_survey_analysis'=>1);
730 * Actual implementation of the reset course functionality, delete all the
731 * survey responses for course $data->courseid.
733 * @global object
734 * @param $data the data submitted from the reset course.
735 * @return array status array
737 function survey_reset_userdata($data) {
738 global $DB;
740 $componentstr = get_string('modulenameplural', 'survey');
741 $status = array();
743 $surveyssql = "SELECT ch.id
744 FROM {survey} ch
745 WHERE ch.course=?";
746 $params = array($data->courseid);
748 if (!empty($data->reset_survey_answers)) {
749 $DB->delete_records_select('survey_answers', "survey IN ($surveyssql)", $params);
750 $DB->delete_records_select('survey_analysis', "survey IN ($surveyssql)", $params);
751 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallanswers', 'survey'), 'error'=>false);
754 if (!empty($data->reset_survey_analysis)) {
755 $DB->delete_records_select('survey_analysis', "survey IN ($surveyssql)", $params);
756 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallanswers', 'survey'), 'error'=>false);
759 // no date shifting
760 return $status;
764 * Returns all other caps used in module
766 * @return array
768 function survey_get_extra_capabilities() {
769 return array('moodle/site:accessallgroups');
773 * @uses FEATURE_GROUPS
774 * @uses FEATURE_GROUPINGS
775 * @uses FEATURE_MOD_INTRO
776 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
777 * @uses FEATURE_GRADE_HAS_GRADE
778 * @uses FEATURE_GRADE_OUTCOMES
779 * @param string $feature FEATURE_xx constant for requested feature
780 * @return mixed True if module supports feature, false if not, null if doesn't know
782 function survey_supports($feature) {
783 switch($feature) {
784 case FEATURE_GROUPS: return true;
785 case FEATURE_GROUPINGS: return true;
786 case FEATURE_MOD_INTRO: return true;
787 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
788 case FEATURE_GRADE_HAS_GRADE: return false;
789 case FEATURE_GRADE_OUTCOMES: return false;
790 case FEATURE_BACKUP_MOODLE2: return true;
791 case FEATURE_SHOW_DESCRIPTION: return true;
793 default: return null;
798 * This function extends the settings navigation block for the site.
800 * It is safe to rely on PAGE here as we will only ever be within the module
801 * context when this is called
803 * @param navigation_node $settings
804 * @param navigation_node $surveynode
806 function survey_extend_settings_navigation($settings, $surveynode) {
807 global $PAGE;
809 if (has_capability('mod/survey:readresponses', $PAGE->cm->context)) {
810 $responsesnode = $surveynode->add(get_string("responsereports", "survey"));
812 $url = new moodle_url('/mod/survey/report.php', array('id' => $PAGE->cm->id, 'action'=>'summary'));
813 $responsesnode->add(get_string("summary", "survey"), $url);
815 $url = new moodle_url('/mod/survey/report.php', array('id' => $PAGE->cm->id, 'action'=>'scales'));
816 $responsesnode->add(get_string("scales", "survey"), $url);
818 $url = new moodle_url('/mod/survey/report.php', array('id' => $PAGE->cm->id, 'action'=>'questions'));
819 $responsesnode->add(get_string("question", "survey"), $url);
821 $url = new moodle_url('/mod/survey/report.php', array('id' => $PAGE->cm->id, 'action'=>'students'));
822 $responsesnode->add(get_string('participants'), $url);
824 if (has_capability('mod/survey:download', $PAGE->cm->context)) {
825 $url = new moodle_url('/mod/survey/report.php', array('id' => $PAGE->cm->id, 'action'=>'download'));
826 $surveynode->add(get_string('downloadresults', 'survey'), $url);
832 * Return a list of page types
833 * @param string $pagetype current page type
834 * @param stdClass $parentcontext Block's parent context
835 * @param stdClass $currentcontext Current context of block
837 function survey_page_type_list($pagetype, $parentcontext, $currentcontext) {
838 $module_pagetype = array('mod-survey-*'=>get_string('page-mod-survey-x', 'survey'));
839 return $module_pagetype;
843 * Mark the activity completed (if required) and trigger the course_module_viewed event.
845 * @param stdClass $survey survey object
846 * @param stdClass $course course object
847 * @param stdClass $cm course module object
848 * @param stdClass $context context object
849 * @param string $viewed which page viewed
850 * @since Moodle 3.0
852 function survey_view($survey, $course, $cm, $context, $viewed) {
854 // Trigger course_module_viewed event.
855 $params = array(
856 'context' => $context,
857 'objectid' => $survey->id,
858 'courseid' => $course->id,
859 'other' => array('viewed' => $viewed)
862 $event = \mod_survey\event\course_module_viewed::create($params);
863 $event->add_record_snapshot('course_modules', $cm);
864 $event->add_record_snapshot('course', $course);
865 $event->add_record_snapshot('survey', $survey);
866 $event->trigger();
868 // Completion.
869 $completion = new completion_info($course);
870 $completion->set_module_viewed($cm);
874 * Helper function for ordering a set of questions by the given ids.
876 * @param array $questions array of questions objects
877 * @param array $questionorder array of questions ids indicating the correct order
878 * @return array list of questions ordered
879 * @since Moodle 3.0
881 function survey_order_questions($questions, $questionorder) {
883 $finalquestions = array();
884 foreach ($questionorder as $qid) {
885 $finalquestions[] = $questions[$qid];
887 return $finalquestions;
891 * Translate the question texts and options.
893 * @param stdClass $question question object
894 * @return stdClass question object with all the text fields translated
895 * @since Moodle 3.0
897 function survey_translate_question($question) {
899 if ($question->text) {
900 $question->text = get_string($question->text, "survey");
903 if ($question->shorttext) {
904 $question->shorttext = get_string($question->shorttext, "survey");
907 if ($question->intro) {
908 $question->intro = get_string($question->intro, "survey");
911 if ($question->options) {
912 $question->options = get_string($question->options, "survey");
914 return $question;
918 * Returns the questions for a survey (ordered).
920 * @param stdClass $survey survey object
921 * @return array list of questions ordered
922 * @since Moodle 3.0
923 * @throws moodle_exception
925 function survey_get_questions($survey) {
926 global $DB;
928 $questionids = explode(',', $survey->questions);
929 if (! $questions = $DB->get_records_list("survey_questions", "id", $questionids)) {
930 throw new moodle_exception('cannotfindquestion', 'survey');
933 return survey_order_questions($questions, $questionids);
937 * Returns subquestions for a given question (ordered).
939 * @param stdClass $question questin object
940 * @return array list of subquestions ordered
941 * @since Moodle 3.0
943 function survey_get_subquestions($question) {
944 global $DB;
946 $questionids = explode(',', $question->multi);
947 $questions = $DB->get_records_list("survey_questions", "id", $questionids);
949 return survey_order_questions($questions, $questionids);
953 * Save the answer for the given survey
955 * @param stdClass $survey a survey object
956 * @param array $answersrawdata the answers to be saved
957 * @param stdClass $course a course object (required for trigger the submitted event)
958 * @param stdClass $context a context object (required for trigger the submitted event)
959 * @since Moodle 3.0
961 function survey_save_answers($survey, $answersrawdata, $course, $context) {
962 global $DB, $USER;
964 $answers = array();
966 // Sort through the data and arrange it.
967 // This is necessary because some of the questions may have two answers, eg Question 1 -> 1 and P1.
968 foreach ($answersrawdata as $key => $val) {
969 if ($key != "userid" && $key != "id") {
970 if (substr($key, 0, 1) == "q") {
971 $key = clean_param(substr($key, 1), PARAM_ALPHANUM); // Keep everything but the 'q', number or P number.
973 if (substr($key, 0, 1) == "P") {
974 $realkey = (int) substr($key, 1);
975 $answers[$realkey][1] = $val;
976 } else {
977 $answers[$key][0] = $val;
982 // Now store the data.
983 $timenow = time();
984 $answerstoinsert = array();
985 foreach ($answers as $key => $val) {
986 if ($key != 'sesskey') {
987 $newdata = new stdClass();
988 $newdata->time = $timenow;
989 $newdata->userid = $USER->id;
990 $newdata->survey = $survey->id;
991 $newdata->question = $key;
992 if (!empty($val[0])) {
993 $newdata->answer1 = $val[0];
994 } else {
995 $newdata->answer1 = "";
997 if (!empty($val[1])) {
998 $newdata->answer2 = $val[1];
999 } else {
1000 $newdata->answer2 = "";
1003 $answerstoinsert[] = $newdata;
1007 if (!empty($answerstoinsert)) {
1008 $DB->insert_records("survey_answers", $answerstoinsert);
1011 $params = array(
1012 'context' => $context,
1013 'courseid' => $course->id,
1014 'other' => array('surveyid' => $survey->id)
1016 $event = \mod_survey\event\response_submitted::create($params);
1017 $event->trigger();