3 // This file is part of Moodle - http://moodle.org/
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.
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/>.
20 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
21 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 * @global int $SURVEY_GHEIGHT
28 global $SURVEY_GHEIGHT;
29 $SURVEY_GHEIGHT = 500;
32 * @global int $SURVEY_GWIDTH
34 global $SURVEY_GWIDTH;
38 * @global array $SURVEY_QTYPE
41 $SURVEY_QTYPE = array (
42 "-3" => "Virtual Actual and Preferred",
43 "-2" => "Virtual Preferred",
44 "-1" => "Virtual Actual",
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 ////////////////////////////////////////////////////////
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.
67 * @param object $survey
70 function survey_add_instance($survey) {
73 if (!$template = $DB->get_record("survey", array("id"=>$survey->template
))) {
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);
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.
96 * @param object $survey
99 function survey_update_instance($survey) {
102 if (!$template = $DB->get_record("survey", array("id"=>$survey->template
))) {
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.
125 function survey_delete_instance($id) {
128 if (! $survey = $DB->get_record("survey", array("id"=>$id))) {
132 $cm = get_coursemodule_from_instance('survey', $id);
133 \core_completion\api
::update_completion_date_event($cm->id
, 'survey', $id, null);
137 if (! $DB->delete_records("survey_analysis", array("survey"=>$survey->id
))) {
141 if (! $DB->delete_records("survey_answers", array("survey"=>$survey->id
))) {
145 if (! $DB->delete_records("survey", array("id"=>$survey->id
))) {
154 * @param object $course
155 * @param object $user
157 * @param object $survey
160 function survey_user_outline($course, $user, $mod, $survey) {
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
;
178 * @param object $course
179 * @param object $user
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";
201 $answertext = "No answer";
203 $table->data
[] = array("<b>$questiontext</b>", s($answertext));
205 echo html_writer
::table($table);
209 survey_print_graph("id=$mod->id&sid=$user->id&type=student.png");
213 print_string("notdone", "survey");
220 * @param object $course
221 * @param mixed $viewfullnames
222 * @param int $timestamp
225 function survey_print_recent_activity($course, $viewfullnames, $timestart) {
226 global $CFG, $DB, $OUTPUT;
228 $modinfo = get_fast_modinfo($course);
230 foreach ($modinfo->cms
as $cm) {
231 if ($cm->modname
!= 'survey') {
234 if (!$cm->uservisible
) {
237 $ids[$cm->instance
] = $cm->instance
;
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,
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));
255 $rs->close(); // Not going to iterate (but exit), close rs
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;
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);
282 // SQL FUNCTIONS ////////////////////////////////////////////////////////
289 function survey_log_info($log) {
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
));
298 * @param int $surveyid
299 * @param int $groupid
300 * @param int $groupingid
303 function survey_get_responses($surveyid, $groupid, $groupingid) {
306 $params = array('surveyid'=>$surveyid, 'groupid'=>$groupid, 'groupingid'=>$groupingid);
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 ";
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
323 WHERE a.survey = :surveyid
325 ORDER BY time ASC", $params);
334 function survey_get_analysis($survey, $user) {
337 return $DB->get_record_sql("SELECT notes
338 FROM {survey_analysis}
339 WHERE survey=? AND userid=?", array($survey, $user));
346 * @param string $notes
348 function survey_update_analysis($survey, $user, $notes) {
351 return $DB->execute("UPDATE {survey_analysis}
354 AND userid=?", array($notes, $survey, $user));
359 * @param int $surveyid
360 * @param int $groupid
361 * @param string $sort
364 function survey_get_user_answers($surveyid, $questionid, $groupid, $sort="sa.answer1,sa.answer2 ASC") {
367 $params = array('surveyid'=>$surveyid, 'questionid'=>$questionid);
370 $groupfrom = ', {groups_members} gm';
371 $groupsql = 'AND gm.groupid = :groupid AND u.id = gm.userid';
372 $params['groupid'] = $groupid;
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);
389 * @param int $surveyid
390 * @param int $questionid
394 function survey_get_user_answer($surveyid, $questionid, $userid) {
397 return $DB->get_record_sql("SELECT sa.*
398 FROM {survey_answers} sa
401 AND sa.userid = ?", array($surveyid, $questionid, $userid));
404 // MODULE FUNCTIONS ////////////////////////////////////////////////////////
409 * @param string $notes
412 function survey_add_analysis($survey, $user, $notes) {
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);
428 function survey_already_done($survey, $user) {
431 return $DB->record_exists("survey_answers", array("survey"=>$survey, "userid"=>$user));
434 * @param int $surveyid
435 * @param int $groupid
436 * @param int $groupingid
439 function survey_count_responses($surveyid, $groupid, $groupingid) {
440 if ($responses = survey_get_responses($surveyid, $groupid, $groupingid)) {
441 return count($responses);
449 * @param array $results
450 * @param int $courseid
452 function survey_print_all_responses($cmid, $results, $courseid) {
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)),
465 echo html_writer
::table($table);
470 * @param int $templateid
473 function survey_get_template_name($templateid) {
477 if ($ss = $DB->get_record("surveys", array("id"=>$templateid))) {
487 * @param string $name
488 * @param array $numwords
491 function survey_shorten_name ($name, $numwords) {
492 $words = explode(" ", $name);
494 for ($i=0; $i < $numwords; $i++
) {
495 $output .= $words[$i]." ";
501 * @todo Check this function
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) {
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";
548 echo "<tr><th scope=\"colgroup\" colspan=\"7\">$question->intro</th></tr>\n";
550 $subquestions = survey_get_subquestions($question);
552 foreach ($subquestions as $q) {
555 $rowclass = survey_question_rowclass($qnum);
557 $rowclass = survey_question_rowclass(round($qnum / 2));
560 $q->text
= get_string($q->text
, "survey");
563 echo "<tr class=\"$rowclass rblock\">";
565 echo "<th scope=\"row\" class=\"optioncell\">";
566 echo "<b class=\"qnumtopcell\">$qnum</b> ";
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>";
578 echo "<th scope=\"row\" class=\"optioncell\">";
579 echo "<b class=\"qnumtopcell\">$qnum</b> ";
581 echo "<span class=\"preferthat\">$stripreferthat</span> ";
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>";
595 echo "<tr class=\"$rowclass rblock\">";
596 echo "<th scope=\"row\" class=\"optioncell\">";
597 echo "<b class=\"qnumtopcell\">$qnum</b> ";
598 echo "<span class=\"foundthat\">$strifoundthat</span> ";
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>";
619 * @param object $question
621 function survey_print_single($question) {
622 global $DB, $qnum, $OUTPUT;
624 $rowclass = survey_question_rowclass(0);
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> ";
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) {
646 echo "<option value=\"$key\">$val</option>";
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>";
664 function survey_question_rowclass($qnum) {
667 return $qnum %
2 ?
'r0' : 'r1';
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.
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.
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.
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.
741 * @param $data the data submitted from the reset course.
742 * @return array status array
744 function survey_reset_userdata($data) {
747 $componentstr = get_string('modulenameplural', 'survey');
750 $surveyssql = "SELECT ch.id
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);
767 // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
774 * @uses FEATURE_GROUPS
775 * @uses FEATURE_GROUPINGS
776 * @uses FEATURE_MOD_INTRO
777 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
778 * @uses FEATURE_GRADE_HAS_GRADE
779 * @uses FEATURE_GRADE_OUTCOMES
780 * @param string $feature FEATURE_xx constant for requested feature
781 * @return mixed True if module supports feature, false if not, null if doesn't know
783 function survey_supports($feature) {
785 case FEATURE_GROUPS
: return true;
786 case FEATURE_GROUPINGS
: return true;
787 case FEATURE_MOD_INTRO
: return true;
788 case FEATURE_COMPLETION_TRACKS_VIEWS
: return true;
789 case FEATURE_COMPLETION_HAS_RULES
: return true;
790 case FEATURE_GRADE_HAS_GRADE
: return false;
791 case FEATURE_GRADE_OUTCOMES
: return false;
792 case FEATURE_BACKUP_MOODLE2
: return true;
793 case FEATURE_SHOW_DESCRIPTION
: return true;
795 default: return null;
800 * This function extends the settings navigation block for the site.
802 * It is safe to rely on PAGE here as we will only ever be within the module
803 * context when this is called
805 * @param navigation_node $settings
806 * @param navigation_node $surveynode
808 function survey_extend_settings_navigation($settings, $surveynode) {
811 if (has_capability('mod/survey:readresponses', $PAGE->cm
->context
)) {
812 $responsesnode = $surveynode->add(get_string("responsereports", "survey"));
814 $url = new moodle_url('/mod/survey/report.php', array('id' => $PAGE->cm
->id
, 'action'=>'summary'));
815 $responsesnode->add(get_string("summary", "survey"), $url);
817 $url = new moodle_url('/mod/survey/report.php', array('id' => $PAGE->cm
->id
, 'action'=>'scales'));
818 $responsesnode->add(get_string("scales", "survey"), $url);
820 $url = new moodle_url('/mod/survey/report.php', array('id' => $PAGE->cm
->id
, 'action'=>'questions'));
821 $responsesnode->add(get_string("question", "survey"), $url);
823 $url = new moodle_url('/mod/survey/report.php', array('id' => $PAGE->cm
->id
, 'action'=>'students'));
824 $responsesnode->add(get_string('participants'), $url);
826 if (has_capability('mod/survey:download', $PAGE->cm
->context
)) {
827 $url = new moodle_url('/mod/survey/report.php', array('id' => $PAGE->cm
->id
, 'action'=>'download'));
828 $surveynode->add(get_string('downloadresults', 'survey'), $url);
834 * Return a list of page types
835 * @param string $pagetype current page type
836 * @param stdClass $parentcontext Block's parent context
837 * @param stdClass $currentcontext Current context of block
839 function survey_page_type_list($pagetype, $parentcontext, $currentcontext) {
840 $module_pagetype = array('mod-survey-*'=>get_string('page-mod-survey-x', 'survey'));
841 return $module_pagetype;
845 * Mark the activity completed (if required) and trigger the course_module_viewed event.
847 * @param stdClass $survey survey object
848 * @param stdClass $course course object
849 * @param stdClass $cm course module object
850 * @param stdClass $context context object
851 * @param string $viewed which page viewed
854 function survey_view($survey, $course, $cm, $context, $viewed) {
856 // Trigger course_module_viewed event.
858 'context' => $context,
859 'objectid' => $survey->id
,
860 'courseid' => $course->id
,
861 'other' => array('viewed' => $viewed)
864 $event = \mod_survey\event\course_module_viewed
::create($params);
865 $event->add_record_snapshot('course_modules', $cm);
866 $event->add_record_snapshot('course', $course);
867 $event->add_record_snapshot('survey', $survey);
871 $completion = new completion_info($course);
872 $completion->set_module_viewed($cm);
876 * Helper function for ordering a set of questions by the given ids.
878 * @param array $questions array of questions objects
879 * @param array $questionorder array of questions ids indicating the correct order
880 * @return array list of questions ordered
883 function survey_order_questions($questions, $questionorder) {
885 $finalquestions = array();
886 foreach ($questionorder as $qid) {
887 $finalquestions[] = $questions[$qid];
889 return $finalquestions;
893 * Translate the question texts and options.
895 * @param stdClass $question question object
896 * @return stdClass question object with all the text fields translated
899 function survey_translate_question($question) {
901 if ($question->text
) {
902 $question->text
= get_string($question->text
, "survey");
905 if ($question->shorttext
) {
906 $question->shorttext
= get_string($question->shorttext
, "survey");
909 if ($question->intro
) {
910 $question->intro
= get_string($question->intro
, "survey");
913 if ($question->options
) {
914 $question->options
= get_string($question->options
, "survey");
920 * Returns the questions for a survey (ordered).
922 * @param stdClass $survey survey object
923 * @return array list of questions ordered
925 * @throws moodle_exception
927 function survey_get_questions($survey) {
930 $questionids = explode(',', $survey->questions
);
931 if (! $questions = $DB->get_records_list("survey_questions", "id", $questionids)) {
932 throw new moodle_exception('cannotfindquestion', 'survey');
935 return survey_order_questions($questions, $questionids);
939 * Returns subquestions for a given question (ordered).
941 * @param stdClass $question questin object
942 * @return array list of subquestions ordered
945 function survey_get_subquestions($question) {
948 $questionids = explode(',', $question->multi
);
949 $questions = $DB->get_records_list("survey_questions", "id", $questionids);
951 return survey_order_questions($questions, $questionids);
955 * Save the answer for the given survey
957 * @param stdClass $survey a survey object
958 * @param array $answersrawdata the answers to be saved
959 * @param stdClass $course a course object (required for trigger the submitted event)
960 * @param stdClass $context a context object (required for trigger the submitted event)
963 function survey_save_answers($survey, $answersrawdata, $course, $context) {
968 // Sort through the data and arrange it.
969 // This is necessary because some of the questions may have two answers, eg Question 1 -> 1 and P1.
970 foreach ($answersrawdata as $key => $val) {
971 if ($key != "userid" && $key != "id") {
972 if (substr($key, 0, 1) == "q") {
973 $key = clean_param(substr($key, 1), PARAM_ALPHANUM
); // Keep everything but the 'q', number or P number.
975 if (substr($key, 0, 1) == "P") {
976 $realkey = (int) substr($key, 1);
977 $answers[$realkey][1] = $val;
979 $answers[$key][0] = $val;
984 // Now store the data.
986 $answerstoinsert = array();
987 foreach ($answers as $key => $val) {
988 if ($key != 'sesskey') {
989 $newdata = new stdClass();
990 $newdata->time
= $timenow;
991 $newdata->userid
= $USER->id
;
992 $newdata->survey
= $survey->id
;
993 $newdata->question
= $key;
994 if (!empty($val[0])) {
995 $newdata->answer1
= $val[0];
997 $newdata->answer1
= "";
999 if (!empty($val[1])) {
1000 $newdata->answer2
= $val[1];
1002 $newdata->answer2
= "";
1005 $answerstoinsert[] = $newdata;
1009 if (!empty($answerstoinsert)) {
1010 $DB->insert_records("survey_answers", $answerstoinsert);
1013 // Update completion state.
1014 $cm = get_coursemodule_from_instance('survey', $survey->id
, $course->id
);
1015 $completion = new completion_info($course);
1016 if (isloggedin() && !isguestuser() && $completion->is_enabled($cm) && $survey->completionsubmit
) {
1017 $completion->update_state($cm, COMPLETION_COMPLETE
);
1021 'context' => $context,
1022 'courseid' => $course->id
,
1023 'other' => array('surveyid' => $survey->id
)
1025 $event = \mod_survey\event\response_submitted
::create($params);
1030 * Obtains the automatic completion state for this survey based on the condition
1031 * in feedback settings.
1033 * @param object $course Course
1034 * @param object $cm Course-module
1035 * @param int $userid User ID
1036 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
1037 * @return bool True if completed, false if not, $type if conditions not set.
1039 function survey_get_completion_state($course, $cm, $userid, $type) {
1042 // Get survey details.
1043 $survey = $DB->get_record('survey', array('id' => $cm->instance
), '*', MUST_EXIST
);
1045 // If completion option is enabled, evaluate it and return true/false.
1046 if ($survey->completionsubmit
) {
1047 $params = array('userid' => $userid, 'survey' => $survey->id
);
1048 return $DB->record_exists('survey_answers', $params);
1050 // Completion option is not enabled so just return $type.
1056 * Check if the module has any update that affects the current user since a given time.
1058 * @param cm_info $cm course module data
1059 * @param int $from the time to check updates from
1060 * @param array $filter if we need to check only specific updates
1061 * @return stdClass an object with the different type of areas indicating if they were updated or not
1064 function survey_check_updates_since(cm_info
$cm, $from, $filter = array()) {
1067 $updates = new stdClass();
1068 if (!has_capability('mod/survey:participate', $cm->context
)) {
1071 $updates = course_check_module_updates_since($cm, $from, array(), $filter);
1073 $updates->answers
= (object) array('updated' => false);
1074 $select = 'survey = ? AND userid = ? AND time > ?';
1075 $params = array($cm->instance
, $USER->id
, $from);
1076 $answers = $DB->get_records_select('survey_answers', $select, $params, '', 'id');
1077 if (!empty($answers)) {
1078 $updates->answers
->updated
= true;
1079 $updates->answers
->itemids
= array_keys($answers);
1082 // Now, teachers should see other students updates.
1083 if (has_capability('mod/survey:readresponses', $cm->context
)) {
1084 $select = 'survey = ? AND time > ?';
1085 $params = array($cm->instance
, $from);
1087 if (groups_get_activity_groupmode($cm) == SEPARATEGROUPS
) {
1088 $groupusers = array_keys(groups_get_activity_shared_group_members($cm));
1089 if (empty($groupusers)) {
1092 list($insql, $inparams) = $DB->get_in_or_equal($groupusers);
1093 $select .= ' AND userid ' . $insql;
1094 $params = array_merge($params, $inparams);
1097 $updates->useranswers
= (object) array('updated' => false);
1098 $answers = $DB->get_records_select('survey_answers', $select, $params, '', 'id');
1099 if (!empty($answers)) {
1100 $updates->useranswers
->updated
= true;
1101 $updates->useranswers
->itemids
= array_keys($answers);
1108 * This function receives a calendar event and returns the action associated with it, or null if there is none.
1110 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
1111 * is not displayed on the block.
1113 * @param calendar_event $event
1114 * @param \core_calendar\action_factory $factory
1115 * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
1116 * @return \core_calendar\local\event\entities\action_interface|null
1118 function mod_survey_core_calendar_provide_event_action(calendar_event
$event,
1119 \core_calendar\action_factory
$factory,
1123 if (empty($userid)) {
1124 $userid = $USER->id
;
1127 $cm = get_fast_modinfo($event->courseid
, $userid)->instances
['survey'][$event->instance
];
1128 $context = context_module
::instance($cm->id
);
1130 if (!has_capability('mod/survey:participate', $context, $userid)) {
1134 $completion = new \
completion_info($cm->get_course());
1136 $completiondata = $completion->get_data($cm, false, $userid);
1138 if ($completiondata->completionstate
!= COMPLETION_INCOMPLETE
) {
1142 return $factory->create_instance(
1144 new \
moodle_url('/mod/survey/view.php', ['id' => $cm->id
]),
1151 * Add a get_coursemodule_info function in case any survey type wants to add 'extra' information
1152 * for the course (see resource).
1154 * Given a course_module object, this function returns any "extra" information that may be needed
1155 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
1157 * @param stdClass $coursemodule The coursemodule object (record).
1158 * @return cached_cm_info An object on information that the courses
1159 * will know about (most noticeably, an icon).
1161 function survey_get_coursemodule_info($coursemodule) {
1164 $dbparams = ['id' => $coursemodule->instance
];
1165 $fields = 'id, name, intro, introformat, completionsubmit';
1166 if (!$survey = $DB->get_record('survey', $dbparams, $fields)) {
1170 $result = new cached_cm_info();
1171 $result->name
= $survey->name
;
1173 if ($coursemodule->showdescription
) {
1174 // Convert intro to html. Do not filter cached version, filters run at display time.
1175 $result->content
= format_module_intro('survey', $survey, $coursemodule->id
, false);
1178 // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
1179 if ($coursemodule->completion
== COMPLETION_TRACKING_AUTOMATIC
) {
1180 $result->customdata
['customcompletionrules']['completionsubmit'] = $survey->completionsubmit
;
1187 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
1189 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
1190 * @return array $descriptions the array of descriptions for the custom rules.
1192 function mod_survey_get_completion_active_rule_descriptions($cm) {
1193 // Values will be present in cm_info, and we assume these are up to date.
1194 if (empty($cm->customdata
['customcompletionrules'])
1195 ||
$cm->completion
!= COMPLETION_TRACKING_AUTOMATIC
) {
1200 foreach ($cm->customdata
['customcompletionrules'] as $key => $val) {
1202 case 'completionsubmit':
1204 $descriptions[] = get_string('completionsubmit', 'survey');
1211 return $descriptions;