MDL-56846 mod_survey: Fix styles in boost
[moodle.git] / mod / survey / lib.php
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.
14 //
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
22  */
24 /**
25  * Graph size
26  * @global int $SURVEY_GHEIGHT
27  */
28 global $SURVEY_GHEIGHT;
29 $SURVEY_GHEIGHT = 500;
30 /**
31  * Graph size
32  * @global int $SURVEY_GWIDTH
33  */
34 global $SURVEY_GWIDTH;
35 $SURVEY_GWIDTH  = 900;
36 /**
37  * Question Type
38  * @global array $SURVEY_QTYPE
39  */
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",
49         );
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.
65  *
66  * @global object
67  * @param object $survey
68  * @return int|bool
69  */
70 function survey_add_instance($survey) {
71     global $DB;
73     if (!$template = $DB->get_record("survey", array("id"=>$survey->template))) {
74         return 0;
75     }
77     $survey->questions    = $template->questions;
78     $survey->timecreated  = time();
79     $survey->timemodified = $survey->timecreated;
81     return $DB->insert_record("survey", $survey);
83 }
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.
89  *
90  * @global object
91  * @param object $survey
92  * @return bool
93  */
94 function survey_update_instance($survey) {
95     global $DB;
97     if (!$template = $DB->get_record("survey", array("id"=>$survey->template))) {
98         return 0;
99     }
101     $survey->id           = $survey->instance;
102     $survey->questions    = $template->questions;
103     $survey->timemodified = time();
105     return $DB->update_record("survey", $survey);
108 /**
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.
112  *
113  * @global object
114  * @param int $id
115  * @return bool
116  */
117 function survey_delete_instance($id) {
118     global $DB;
120     if (! $survey = $DB->get_record("survey", array("id"=>$id))) {
121         return false;
122     }
124     $result = true;
126     if (! $DB->delete_records("survey_analysis", array("survey"=>$survey->id))) {
127         $result = false;
128     }
130     if (! $DB->delete_records("survey_answers", array("survey"=>$survey->id))) {
131         $result = false;
132     }
134     if (! $DB->delete_records("survey", array("id"=>$survey->id))) {
135         $result = false;
136     }
138     return $result;
141 /**
142  * @global object
143  * @param object $course
144  * @param object $user
145  * @param object $mod
146  * @param object $survey
147  * @return $result
148  */
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;
159     }
160     return NULL;
163 /**
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
171  */
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";
191                 }
192                 $table->data[] = array("<b>$questiontext</b>", s($answertext));
193             }
194             echo html_writer::table($table);
196         } else {
198             survey_print_graph("id=$mod->id&amp;sid=$user->id&amp;type=student.png");
199         }
201     } else {
202         print_string("notdone", "survey");
203     }
206 /**
207  * @global stdClass
208  * @global object
209  * @param object $course
210  * @param mixed $viewfullnames
211  * @param int $timestamp
212  * @return bool
213  */
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;
222         }
223         if (!$cm->uservisible) {
224             continue;
225         }
226         $ids[$cm->instance] = $cm->instance;
227     }
229     if (!$ids) {
230         return false;
231     }
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;
246     }
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;
255     }
256     $rs->close();
258     if (!$surveys) {
259         return false;
260     }
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);
266     }
268     return true;
271 // SQL FUNCTIONS ////////////////////////////////////////////////////////
273 /**
274  * @global object
275  * @param sting $log
276  * @return array
277  */
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));
285 /**
286  * @global object
287  * @param int $surveyid
288  * @param int $groupid
289  * @param int $groupingid
290  * @return array
291  */
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 = "";
305     }
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);
317 /**
318  * @global object
319  * @param int $survey
320  * @param int $user
321  * @return array
322  */
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));
331 /**
332  * @global object
333  * @param int $survey
334  * @param int $user
335  * @param string $notes
336  */
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));
346 /**
347  * @global object
348  * @param int $surveyid
349  * @param int $groupid
350  * @param string $sort
351  * @return array
352  */
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  = '';
365     }
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);
376 /**
377  * @global object
378  * @param int $surveyid
379  * @param int $questionid
380  * @param int $userid
381  * @return array
382  */
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 ////////////////////////////////////////////////////////
394 /**
395  * @global object
396  * @param int $survey
397  * @param int $user
398  * @param string $notes
399  * @return bool|int
400  */
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);
411 /**
412  * @global object
413  * @param int $survey
414  * @param int $user
415  * @return bool
416  */
417 function survey_already_done($survey, $user) {
418     global $DB;
420     return $DB->record_exists("survey_answers", array("survey"=>$survey, "userid"=>$user));
422 /**
423  * @param int $surveyid
424  * @param int $groupid
425  * @param int $groupingid
426  * @return int
427  */
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;
433     }
436 /**
437  * @param int $cmid
438  * @param array $results
439  * @param int $courseid
440  */
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));
452     }
454     echo html_writer::table($table);
457 /**
458  * @global object
459  * @param int $templateid
460  * @return string
461  */
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;
468         }
469     } else {
470         return "";
471     }
475 /**
476  * @param string $name
477  * @param array $numwords
478  * @return string
479  */
480 function survey_shorten_name ($name, $numwords) {
481     $words = explode(" ", $name);
482     $output = '';
483     for ($i=0; $i < $numwords; $i++) {
484         $output .= $words[$i]." ";
485     }
486     return $output;
489 /**
490  * @todo Check this function
491  *
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
498  */
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 = "";
527     }
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";
533     }
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));
546         }
547         if ($q->text) {
548             $q->text = get_string($q->text, "survey");
549         }
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>";
564             }
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>";
582             }
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>";
598             }
600             $checklist["qP$q->id"] = 0;
601             $checklist["q$q->id"] = 0;
602         }
603         echo "</tr>\n";
604     }
605     echo "</table>";
609 /**
610  * @global object
611  * @global int
612  * @param object $question
613  */
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\" class=\"form-control\" 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\" class=\"custom-select\">";
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>";
640         }
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");
646     }
648     echo "</td></tr></table>";
652 /**
653  *
654  * @param int $qnum
655  * @return string
656  */
657 function survey_question_rowclass($qnum) {
659     if ($qnum) {
660         return $qnum % 2 ? 'r0' : 'r1';
661     } else {
662         return 'r0';
663     }
666 /**
667  * @global object
668  * @global int
669  * @global int
670  * @param string $url
671  */
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")."\" />";
679 /**
680  * List the actions that correspond to a view of this module.
681  * This is used by the participation report.
682  *
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.
686  *
687  * @return array
688  */
689 function survey_get_view_actions() {
690     return array('download','view all','view form','view graph','view report');
693 /**
694  * List the actions that correspond to a post of this module.
695  * This is used by the participation report.
696  *
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.
700  *
701  * @return array
702  */
703 function survey_get_post_actions() {
704     return array('submit');
708 /**
709  * Implementation of the function for printing the form elements that control
710  * whether the course reset functionality affects the survey.
711  *
712  * @param object $mform form passed by reference
713  */
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');
721 /**
722  * Course reset form defaults.
723  * @return array
724  */
725 function survey_reset_course_form_defaults($course) {
726     return array('reset_survey_answers'=>1, 'reset_survey_analysis'=>1);
729 /**
730  * Actual implementation of the reset course functionality, delete all the
731  * survey responses for course $data->courseid.
732  *
733  * @global object
734  * @param $data the data submitted from the reset course.
735  * @return array status array
736  */
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);
752     }
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);
757     }
759     // no date shifting
760     return $status;
763 /**
764  * Returns all other caps used in module
765  *
766  * @return array
767  */
768 function survey_get_extra_capabilities() {
769     return array('moodle/site:accessallgroups');
772 /**
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
781  */
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_COMPLETION_HAS_RULES:    return true;
789         case FEATURE_GRADE_HAS_GRADE:         return false;
790         case FEATURE_GRADE_OUTCOMES:          return false;
791         case FEATURE_BACKUP_MOODLE2:          return true;
792         case FEATURE_SHOW_DESCRIPTION:        return true;
794         default: return null;
795     }
798 /**
799  * This function extends the settings navigation block for the site.
800  *
801  * It is safe to rely on PAGE here as we will only ever be within the module
802  * context when this is called
803  *
804  * @param navigation_node $settings
805  * @param navigation_node $surveynode
806  */
807 function survey_extend_settings_navigation($settings, $surveynode) {
808     global $PAGE;
810     if (has_capability('mod/survey:readresponses', $PAGE->cm->context)) {
811         $responsesnode = $surveynode->add(get_string("responsereports", "survey"));
813         $url = new moodle_url('/mod/survey/report.php', array('id' => $PAGE->cm->id, 'action'=>'summary'));
814         $responsesnode->add(get_string("summary", "survey"), $url);
816         $url = new moodle_url('/mod/survey/report.php', array('id' => $PAGE->cm->id, 'action'=>'scales'));
817         $responsesnode->add(get_string("scales", "survey"), $url);
819         $url = new moodle_url('/mod/survey/report.php', array('id' => $PAGE->cm->id, 'action'=>'questions'));
820         $responsesnode->add(get_string("question", "survey"), $url);
822         $url = new moodle_url('/mod/survey/report.php', array('id' => $PAGE->cm->id, 'action'=>'students'));
823         $responsesnode->add(get_string('participants'), $url);
825         if (has_capability('mod/survey:download', $PAGE->cm->context)) {
826             $url = new moodle_url('/mod/survey/report.php', array('id' => $PAGE->cm->id, 'action'=>'download'));
827             $surveynode->add(get_string('downloadresults', 'survey'), $url);
828         }
829     }
832 /**
833  * Return a list of page types
834  * @param string $pagetype current page type
835  * @param stdClass $parentcontext Block's parent context
836  * @param stdClass $currentcontext Current context of block
837  */
838 function survey_page_type_list($pagetype, $parentcontext, $currentcontext) {
839     $module_pagetype = array('mod-survey-*'=>get_string('page-mod-survey-x', 'survey'));
840     return $module_pagetype;
843 /**
844  * Mark the activity completed (if required) and trigger the course_module_viewed event.
845  *
846  * @param  stdClass $survey     survey object
847  * @param  stdClass $course     course object
848  * @param  stdClass $cm         course module object
849  * @param  stdClass $context    context object
850  * @param  string $viewed       which page viewed
851  * @since Moodle 3.0
852  */
853 function survey_view($survey, $course, $cm, $context, $viewed) {
855     // Trigger course_module_viewed event.
856     $params = array(
857         'context' => $context,
858         'objectid' => $survey->id,
859         'courseid' => $course->id,
860         'other' => array('viewed' => $viewed)
861     );
863     $event = \mod_survey\event\course_module_viewed::create($params);
864     $event->add_record_snapshot('course_modules', $cm);
865     $event->add_record_snapshot('course', $course);
866     $event->add_record_snapshot('survey', $survey);
867     $event->trigger();
869     // Completion.
870     $completion = new completion_info($course);
871     $completion->set_module_viewed($cm);
874 /**
875  * Helper function for ordering a set of questions by the given ids.
876  *
877  * @param  array $questions     array of questions objects
878  * @param  array $questionorder array of questions ids indicating the correct order
879  * @return array                list of questions ordered
880  * @since Moodle 3.0
881  */
882 function survey_order_questions($questions, $questionorder) {
884     $finalquestions = array();
885     foreach ($questionorder as $qid) {
886         $finalquestions[] = $questions[$qid];
887     }
888     return $finalquestions;
891 /**
892  * Translate the question texts and options.
893  *
894  * @param  stdClass $question question object
895  * @return stdClass question object with all the text fields translated
896  * @since Moodle 3.0
897  */
898 function survey_translate_question($question) {
900     if ($question->text) {
901         $question->text = get_string($question->text, "survey");
902     }
904     if ($question->shorttext) {
905         $question->shorttext = get_string($question->shorttext, "survey");
906     }
908     if ($question->intro) {
909         $question->intro = get_string($question->intro, "survey");
910     }
912     if ($question->options) {
913         $question->options = get_string($question->options, "survey");
914     }
915     return $question;
918 /**
919  * Returns the questions for a survey (ordered).
920  *
921  * @param  stdClass $survey survey object
922  * @return array list of questions ordered
923  * @since Moodle 3.0
924  * @throws  moodle_exception
925  */
926 function survey_get_questions($survey) {
927     global $DB;
929     $questionids = explode(',', $survey->questions);
930     if (! $questions = $DB->get_records_list("survey_questions", "id", $questionids)) {
931         throw new moodle_exception('cannotfindquestion', 'survey');
932     }
934     return survey_order_questions($questions, $questionids);
937 /**
938  * Returns subquestions for a given question (ordered).
939  *
940  * @param  stdClass $question questin object
941  * @return array list of subquestions ordered
942  * @since Moodle 3.0
943  */
944 function survey_get_subquestions($question) {
945     global $DB;
947     $questionids = explode(',', $question->multi);
948     $questions = $DB->get_records_list("survey_questions", "id", $questionids);
950     return survey_order_questions($questions, $questionids);
953 /**
954  * Save the answer for the given survey
955  *
956  * @param  stdClass $survey   a survey object
957  * @param  array $answersrawdata the answers to be saved
958  * @param  stdClass $course   a course object (required for trigger the submitted event)
959  * @param  stdClass $context  a context object (required for trigger the submitted event)
960  * @since Moodle 3.0
961  */
962 function survey_save_answers($survey, $answersrawdata, $course, $context) {
963     global $DB, $USER;
965     $answers = array();
967     // Sort through the data and arrange it.
968     // This is necessary because some of the questions may have two answers, eg Question 1 -> 1 and P1.
969     foreach ($answersrawdata as $key => $val) {
970         if ($key != "userid" && $key != "id") {
971             if (substr($key, 0, 1) == "q") {
972                 $key = clean_param(substr($key, 1), PARAM_ALPHANUM);   // Keep everything but the 'q', number or P number.
973             }
974             if (substr($key, 0, 1) == "P") {
975                 $realkey = (int) substr($key, 1);
976                 $answers[$realkey][1] = $val;
977             } else {
978                 $answers[$key][0] = $val;
979             }
980         }
981     }
983     // Now store the data.
984     $timenow = time();
985     $answerstoinsert = array();
986     foreach ($answers as $key => $val) {
987         if ($key != 'sesskey') {
988             $newdata = new stdClass();
989             $newdata->time = $timenow;
990             $newdata->userid = $USER->id;
991             $newdata->survey = $survey->id;
992             $newdata->question = $key;
993             if (!empty($val[0])) {
994                 $newdata->answer1 = $val[0];
995             } else {
996                 $newdata->answer1 = "";
997             }
998             if (!empty($val[1])) {
999                 $newdata->answer2 = $val[1];
1000             } else {
1001                 $newdata->answer2 = "";
1002             }
1004             $answerstoinsert[] = $newdata;
1005         }
1006     }
1008     if (!empty($answerstoinsert)) {
1009         $DB->insert_records("survey_answers", $answerstoinsert);
1010     }
1012     // Update completion state.
1013     $cm = get_coursemodule_from_instance('survey', $survey->id, $course->id);
1014     $completion = new completion_info($course);
1015     if (isloggedin() && !isguestuser() && $completion->is_enabled($cm) && $survey->completionsubmit) {
1016         $completion->update_state($cm, COMPLETION_COMPLETE);
1017     }
1019     $params = array(
1020         'context' => $context,
1021         'courseid' => $course->id,
1022         'other' => array('surveyid' => $survey->id)
1023     );
1024     $event = \mod_survey\event\response_submitted::create($params);
1025     $event->trigger();
1028 /**
1029  * Obtains the automatic completion state for this survey based on the condition
1030  * in feedback settings.
1031  *
1032  * @param object $course Course
1033  * @param object $cm Course-module
1034  * @param int $userid User ID
1035  * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
1036  * @return bool True if completed, false if not, $type if conditions not set.
1037  */
1038 function survey_get_completion_state($course, $cm, $userid, $type) {
1039     global $DB;
1041     // Get survey details.
1042     $survey = $DB->get_record('survey', array('id' => $cm->instance), '*', MUST_EXIST);
1044     // If completion option is enabled, evaluate it and return true/false.
1045     if ($survey->completionsubmit) {
1046         $params = array('userid' => $userid, 'survey' => $survey->id);
1047         return $DB->record_exists('survey_answers', $params);
1048     } else {
1049         // Completion option is not enabled so just return $type.
1050         return $type;
1051     }
1054 /**
1055  * Check if the module has any update that affects the current user since a given time.
1056  *
1057  * @param  cm_info $cm course module data
1058  * @param  int $from the time to check updates from
1059  * @param  array $filter  if we need to check only specific updates
1060  * @return stdClass an object with the different type of areas indicating if they were updated or not
1061  * @since Moodle 3.2
1062  */
1063 function survey_check_updates_since(cm_info $cm, $from, $filter = array()) {
1064     global $DB, $USER;
1066     $updates = new stdClass();
1067     if (!has_capability('mod/survey:participate', $cm->context)) {
1068         return $updates;
1069     }
1070     $updates = course_check_module_updates_since($cm, $from, array(), $filter);
1072     $updates->answers = (object) array('updated' => false);
1073     $select = 'survey = ? AND userid = ? AND time > ?';
1074     $params = array($cm->instance, $USER->id, $from);
1075     $answers = $DB->get_records_select('survey_answers', $select, $params, '', 'id');
1076     if (!empty($answers)) {
1077         $updates->answers->updated = true;
1078         $updates->answers->itemids = array_keys($answers);
1079     }
1080     return $updates;