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");
57 // Question length to wrap.
58 define("SURVEY_QLENGTH_WRAP", "80");
60 require_once(__DIR__
. '/deprecatedlib.php');
62 // STANDARD FUNCTIONS ////////////////////////////////////////////////////////
64 * Given an object containing all the necessary data,
65 * (defined by the form in mod_form.php) this function
66 * will create a new instance and return the id number
67 * of the new instance.
70 * @param object $survey
73 function survey_add_instance($survey) {
76 if (!$template = $DB->get_record("survey", array("id"=>$survey->template
))) {
80 $survey->questions
= $template->questions
;
81 $survey->timecreated
= time();
82 $survey->timemodified
= $survey->timecreated
;
84 $id = $DB->insert_record("survey", $survey);
86 $completiontimeexpected = !empty($survey->completionexpected
) ?
$survey->completionexpected
: null;
87 \core_completion\api
::update_completion_date_event($survey->coursemodule
, 'survey', $id, $completiontimeexpected);
94 * Given an object containing all the necessary data,
95 * (defined by the form in mod_form.php) this function
96 * will update an existing instance with new data.
99 * @param object $survey
102 function survey_update_instance($survey) {
105 if (!$template = $DB->get_record("survey", array("id"=>$survey->template
))) {
109 $survey->id
= $survey->instance
;
110 $survey->questions
= $template->questions
;
111 $survey->timemodified
= time();
113 $completiontimeexpected = !empty($survey->completionexpected
) ?
$survey->completionexpected
: null;
114 \core_completion\api
::update_completion_date_event($survey->coursemodule
, 'survey', $survey->id
, $completiontimeexpected);
116 return $DB->update_record("survey", $survey);
120 * Given an ID of an instance of this module,
121 * this function will permanently delete the instance
122 * and any data that depends on it.
128 function survey_delete_instance($id) {
131 if (! $survey = $DB->get_record("survey", array("id"=>$id))) {
135 $cm = get_coursemodule_from_instance('survey', $id);
136 \core_completion\api
::update_completion_date_event($cm->id
, 'survey', $id, null);
140 if (! $DB->delete_records("survey_analysis", array("survey"=>$survey->id
))) {
144 if (! $DB->delete_records("survey_answers", array("survey"=>$survey->id
))) {
148 if (! $DB->delete_records("survey", array("id"=>$survey->id
))) {
157 * @param object $course
158 * @param object $user
160 * @param object $survey
163 function survey_user_outline($course, $user, $mod, $survey) {
166 if ($answers = $DB->get_records("survey_answers", array('survey'=>$survey->id
, 'userid'=>$user->id
))) {
167 $lastanswer = array_pop($answers);
169 $result = new stdClass();
170 $result->info
= get_string("done", "survey");
171 $result->time
= $lastanswer->time
;
181 * @param object $course
182 * @param object $user
184 * @param object $survey
186 function survey_user_complete($course, $user, $mod, $survey) {
187 global $CFG, $DB, $OUTPUT;
189 if (survey_already_done($survey->id
, $user->id
)) {
190 if ($survey->template
== SURVEY_CIQ
) { // print out answers for critical incidents
191 $table = new html_table();
192 $table->align
= array("left", "left");
194 $questions = $DB->get_records_list("survey_questions", "id", explode(',', $survey->questions
));
195 $questionorder = explode(",", $survey->questions
);
197 foreach ($questionorder as $key=>$val) {
198 $question = $questions[$val];
199 $questiontext = get_string($question->shorttext
, "survey");
201 if ($answer = survey_get_user_answer($survey->id
, $question->id
, $user->id
)) {
202 $answertext = "$answer->answer1";
204 $answertext = "No answer";
206 $table->data
[] = array("<b>$questiontext</b>", s($answertext));
208 echo html_writer
::table($table);
212 survey_print_graph("id=$mod->id&sid=$user->id&type=student.png");
216 print_string("notdone", "survey");
223 * @param object $course
224 * @param mixed $viewfullnames
225 * @param int $timestamp
228 function survey_print_recent_activity($course, $viewfullnames, $timestart) {
229 global $CFG, $DB, $OUTPUT;
231 $modinfo = get_fast_modinfo($course);
233 foreach ($modinfo->cms
as $cm) {
234 if ($cm->modname
!= 'survey') {
237 if (!$cm->uservisible
) {
240 $ids[$cm->instance
] = $cm->instance
;
247 $slist = implode(',', $ids); // there should not be hundreds of glossaries in one course, right?
249 $userfieldsapi = \core_user\fields
::for_userpic();
250 $allusernames = $userfieldsapi->get_sql('u', false, '', '', false)->selects
;
251 $rs = $DB->get_recordset_sql("SELECT sa.userid, sa.survey, MAX(sa.time) AS time,
253 FROM {survey_answers} sa
254 JOIN {user} u ON u.id = sa.userid
255 WHERE sa.survey IN ($slist) AND sa.time > ?
256 GROUP BY sa.userid, sa.survey, $allusernames
257 ORDER BY time ASC", array($timestart));
259 $rs->close(); // Not going to iterate (but exit), close rs
265 foreach ($rs as $survey) {
266 $cm = $modinfo->instances
['survey'][$survey->survey
];
267 $survey->name
= $cm->name
;
268 $survey->cmid
= $cm->id
;
269 $surveys[] = $survey;
277 echo $OUTPUT->heading(get_string('newsurveyresponses', 'survey') . ':', 6);
278 foreach ($surveys as $survey) {
279 $url = $CFG->wwwroot
.'/mod/survey/view.php?id='.$survey->cmid
;
280 print_recent_activity_note($survey->time
, $survey, $survey->name
, $url, false, $viewfullnames);
286 // SQL FUNCTIONS ////////////////////////////////////////////////////////
293 function survey_log_info($log) {
295 return $DB->get_record_sql("SELECT s.name, u.firstname, u.lastname, u.picture
296 FROM {survey} s, {user} u
297 WHERE s.id = ? AND u.id = ?", array($log->info
, $log->userid
));
302 * @param int $surveyid
303 * @param int $groupid
304 * @param int $groupingid
307 function survey_get_responses($surveyid, $groupid, $groupingid) {
310 $params = array('surveyid'=>$surveyid, 'groupid'=>$groupid, 'groupingid'=>$groupingid);
313 $groupsjoin = "JOIN {groups_members} gm ON u.id = gm.userid AND gm.groupid = :groupid ";
315 } else if ($groupingid) {
316 $groupsjoin = "JOIN {groups_members} gm ON u.id = gm.userid
317 JOIN {groupings_groups} gg ON gm.groupid = gg.groupid AND gg.groupingid = :groupingid ";
322 $userfieldsapi = \core_user\fields
::for_userpic();
323 $userfields = $userfieldsapi->get_sql('u', false, '', '', false)->selects
;
324 return $DB->get_records_sql("SELECT $userfields, MAX(a.time) as time
325 FROM {survey_answers} a
326 JOIN {user} u ON a.userid = u.id
328 WHERE a.survey = :surveyid
330 ORDER BY time ASC", $params);
339 function survey_get_analysis($survey, $user) {
342 return $DB->get_record_sql("SELECT notes
343 FROM {survey_analysis}
344 WHERE survey=? AND userid=?", array($survey, $user));
351 * @param string $notes
353 function survey_update_analysis($survey, $user, $notes) {
356 return $DB->execute("UPDATE {survey_analysis}
359 AND userid=?", array($notes, $survey, $user));
364 * @param int $surveyid
365 * @param int $groupid
366 * @param string $sort
369 function survey_get_user_answers($surveyid, $questionid, $groupid, $sort="sa.answer1,sa.answer2 ASC") {
372 $params = array('surveyid'=>$surveyid, 'questionid'=>$questionid);
375 $groupfrom = ', {groups_members} gm';
376 $groupsql = 'AND gm.groupid = :groupid AND u.id = gm.userid';
377 $params['groupid'] = $groupid;
383 $userfieldsapi = \core_user\fields
::for_userpic();
384 $userfields = $userfieldsapi->get_sql('u', false, '', '', false)->selects
;
385 return $DB->get_records_sql("SELECT sa.*, $userfields
386 FROM {survey_answers} sa, {user} u $groupfrom
387 WHERE sa.survey = :surveyid
388 AND sa.question = :questionid
389 AND u.id = sa.userid $groupsql
390 ORDER BY $sort", $params);
395 * @param int $surveyid
396 * @param int $questionid
398 * @return stdClass|false
400 function survey_get_user_answer($surveyid, $questionid, $userid) {
403 return $DB->get_record_sql("SELECT sa.*
404 FROM {survey_answers} sa
407 AND sa.userid = ?", array($surveyid, $questionid, $userid));
410 // MODULE FUNCTIONS ////////////////////////////////////////////////////////
415 * @param string $notes
418 function survey_add_analysis($survey, $user, $notes) {
421 $record = new stdClass();
422 $record->survey
= $survey;
423 $record->userid
= $user;
424 $record->notes
= $notes;
426 return $DB->insert_record("survey_analysis", $record, false);
434 function survey_already_done($survey, $user) {
437 return $DB->record_exists("survey_answers", array("survey"=>$survey, "userid"=>$user));
440 * @param int $surveyid
441 * @param int $groupid
442 * @param int $groupingid
445 function survey_count_responses($surveyid, $groupid, $groupingid) {
446 if ($responses = survey_get_responses($surveyid, $groupid, $groupingid)) {
447 return count($responses);
455 * @param array $results
456 * @param int $courseid
458 function survey_print_all_responses($cmid, $results, $courseid) {
460 $table = new html_table();
461 $table->head
= array ("", get_string("name"), get_string("time"));
462 $table->align
= array ("", "left", "left");
463 $table->size
= array (35, "", "" );
465 foreach ($results as $a) {
466 $table->data
[] = array($OUTPUT->user_picture($a, array('courseid'=>$courseid)),
467 html_writer
::link("report.php?action=student&student=$a->id&id=$cmid", fullname($a)),
471 echo html_writer
::table($table);
476 * @param int $templateid
479 function survey_get_template_name($templateid) {
483 if ($ss = $DB->get_record("surveys", array("id"=>$templateid))) {
493 * @param string $name
494 * @param array $numwords
497 function survey_shorten_name ($name, $numwords) {
498 $words = explode(" ", $name);
500 for ($i=0; $i < $numwords; $i++
) {
501 $output .= $words[$i]." ";
507 * @todo Check this function
512 * @global void This is never defined
513 * @global object This is defined twice?
514 * @param object $question
516 function survey_print_multi($question) {
517 global $USER, $DB, $qnum, $DB, $OUTPUT; //TODO: this is sloppy globals abuse
519 $stripreferthat = get_string("ipreferthat", "survey");
520 $strifoundthat = get_string("ifoundthat", "survey");
521 $strdefault = get_string('notyetanswered', 'survey');
522 $strresponses = get_string('responses', 'survey');
524 echo $OUTPUT->heading($question->text
, 3);
525 echo "\n<table width=\"90%\" cellpadding=\"4\" cellspacing=\"1\" border=\"0\" class=\"surveytable\">";
527 $options = explode( ",", $question->options
);
528 $numoptions = count($options);
530 // COLLES Actual (which is having questions of type 1) and COLLES Preferred (type 2)
531 // expect just one answer per question. COLLES Actual and Preferred (type 3) expects
532 // two answers per question. ATTLS (having a single question of type 1) expects one
533 // answer per question. CIQ is not using multiquestions (i.e. a question with subquestions).
534 // Note that the type of subquestions does not really matter, it's the type of the
535 // question itself that determines everything.
536 $oneanswer = ($question->type
== 1 ||
$question->type
== 2) ?
true : false;
538 // COLLES Preferred (having questions of type 2) will use the radio elements with the name
539 // like qP1, qP2 etc. COLLES Actual and ATTLS have radios like q1, q2 etc.
540 if ($question->type
== 2) {
546 echo "<colgroup colspan=\"7\"></colgroup>";
547 echo "<tr class=\"smalltext\"><th scope=\"row\">$strresponses</th>";
548 echo "<th scope=\"col\" class=\"hresponse\">". get_string('notyetanswered', 'survey'). "</th>";
549 foreach ($options as $key => $val) {
550 echo "<th scope=\"col\" class=\"hresponse\">$val</th>\n";
554 echo "<tr><th scope=\"colgroup\" colspan=\"7\">$question->intro</th></tr>\n";
556 $subquestions = survey_get_subquestions($question);
558 foreach ($subquestions as $q) {
561 $rowclass = survey_question_rowclass($qnum);
563 $rowclass = survey_question_rowclass(round($qnum / 2));
566 $q->text
= get_string($q->text
, "survey");
569 echo "<tr class=\"$rowclass rblock\">";
571 echo "<th scope=\"row\" class=\"optioncell\">";
572 echo "<b class=\"qnumtopcell\">$qnum</b> ";
573 echo $q->text
."</th>\n";
575 $default = get_accesshide($strdefault);
576 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>";
578 for ($i=1;$i<=$numoptions;$i++
) {
579 $hiddentext = get_accesshide($options[$i-1]);
580 $id = "q$P" . $q->id
. "_$i";
581 echo "<td><label for=\"$id\"><input type=\"radio\" name=\"q$P$q->id\" id=\"$id\" value=\"$i\" />$hiddentext</label></td>";
584 echo "<th scope=\"row\" class=\"optioncell\">";
585 echo "<b class=\"qnumtopcell\">$qnum</b> ";
587 echo "<span class=\"preferthat\">$stripreferthat</span> ";
588 echo "<span class=\"option\">$q->text</span></th>\n";
590 $default = get_accesshide($strdefault);
591 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>';
594 for ($i=1;$i<=$numoptions;$i++
) {
595 $hiddentext = get_accesshide($options[$i-1]);
596 $id = "qP" . $q->id
. "_$i";
597 echo "<td><label for=\"$id\"><input type=\"radio\" name=\"qP$q->id\" id=\"$id\" value=\"$i\" />$hiddentext</label></td>";
601 echo "<tr class=\"$rowclass rblock\">";
602 echo "<th scope=\"row\" class=\"optioncell\">";
603 echo "<b class=\"qnumtopcell\">$qnum</b> ";
604 echo "<span class=\"foundthat\">$strifoundthat</span> ";
605 echo "<span class=\"option\">$q->text</span></th>\n";
607 $default = get_accesshide($strdefault);
608 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>';
610 for ($i=1;$i<=$numoptions;$i++
) {
611 $hiddentext = get_accesshide($options[$i-1]);
612 $id = "q" . $q->id
. "_$i";
613 echo "<td><label for=\"$id\"><input type=\"radio\" name=\"q$q->id\" id=\"$id\" value=\"$i\" />$hiddentext</label></td>";
625 * @param object $question
627 function survey_print_single($question) {
628 global $DB, $qnum, $OUTPUT;
630 $rowclass = survey_question_rowclass(0);
635 echo "<table width=\"90%\" cellpadding=\"4\" cellspacing=\"0\">\n";
636 echo "<tr class=\"$rowclass\">";
637 echo "<th scope=\"row\" class=\"optioncell\"><label for=\"q$question->id\"><b class=\"qnumtopcell\">$qnum</b> ";
638 echo "<span class=\"questioncell\">$question->text</span></label></th>\n";
639 echo "<td class=\"questioncell smalltext\">\n";
642 if ($question->type
== 0) { // Plain text field
643 echo "<textarea rows=\"3\" cols=\"30\" class=\"form-control\" name=\"q$question->id\" id=\"q$question->id\">$question->options</textarea>";
645 } else if ($question->type
> 0) { // Choose one of a number
646 $strchoose = get_string("choose");
647 echo "<select name=\"q$question->id\" id=\"q$question->id\" class=\"custom-select\">";
648 echo "<option value=\"0\" selected=\"selected\">$strchoose...</option>";
649 $options = explode( ",", $question->options
);
650 foreach ($options as $key => $val) {
652 echo "<option value=\"$key\">$val</option>";
656 } else if ($question->type
< 0) { // Choose several of a number
657 $options = explode( ",", $question->options
);
658 echo $OUTPUT->notification("This question type not supported yet");
661 echo "</td></tr></table>";
670 function survey_question_rowclass($qnum) {
673 return $qnum %
2 ?
'r0' : 'r1';
685 function survey_print_graph($url) {
686 global $CFG, $SURVEY_GHEIGHT, $SURVEY_GWIDTH;
688 echo "<img class='resultgraph' height=\"$SURVEY_GHEIGHT\" width=\"$SURVEY_GWIDTH\"".
689 " src=\"$CFG->wwwroot/mod/survey/graph.php?$url\" alt=\"".get_string("surveygraph", "survey")."\" />";
693 * List the actions that correspond to a view of this module.
694 * This is used by the participation report.
696 * Note: This is not used by new logging system. Event with
697 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
698 * be considered as view action.
702 function survey_get_view_actions() {
703 return array('download','view all','view form','view graph','view report');
707 * List the actions that correspond to a post of this module.
708 * This is used by the participation report.
710 * Note: This is not used by new logging system. Event with
711 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
712 * will be considered as post action.
716 function survey_get_post_actions() {
717 return array('submit');
722 * Implementation of the function for printing the form elements that control
723 * whether the course reset functionality affects the survey.
725 * @param MoodleQuickForm $mform form passed by reference
727 function survey_reset_course_form_definition(&$mform) {
728 $mform->addElement('header', 'surveyheader', get_string('modulenameplural', 'survey'));
729 $mform->addElement('checkbox', 'reset_survey_answers', get_string('deleteallanswers','survey'));
730 $mform->addElement('checkbox', 'reset_survey_analysis', get_string('deleteanalysis','survey'));
731 $mform->disabledIf('reset_survey_analysis', 'reset_survey_answers', 'checked');
735 * Course reset form defaults.
738 function survey_reset_course_form_defaults($course) {
739 return array('reset_survey_answers'=>1, 'reset_survey_analysis'=>1);
743 * Actual implementation of the reset course functionality, delete all the
744 * survey responses for course $data->courseid.
747 * @param $data the data submitted from the reset course.
748 * @return array status array
750 function survey_reset_userdata($data) {
753 $componentstr = get_string('modulenameplural', 'survey');
756 $surveyssql = "SELECT ch.id
759 $params = array($data->courseid
);
761 if (!empty($data->reset_survey_answers
)) {
762 $DB->delete_records_select('survey_answers', "survey IN ($surveyssql)", $params);
763 $DB->delete_records_select('survey_analysis', "survey IN ($surveyssql)", $params);
764 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallanswers', 'survey'), 'error'=>false);
767 if (!empty($data->reset_survey_analysis
)) {
768 $DB->delete_records_select('survey_analysis', "survey IN ($surveyssql)", $params);
769 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallanswers', 'survey'), 'error'=>false);
773 // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
780 * @uses FEATURE_GROUPS
781 * @uses FEATURE_GROUPINGS
782 * @uses FEATURE_MOD_INTRO
783 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
784 * @uses FEATURE_GRADE_HAS_GRADE
785 * @uses FEATURE_GRADE_OUTCOMES
786 * @param string $feature FEATURE_xx constant for requested feature
787 * @return mixed True if module supports feature, false if not, null if doesn't know or string for the module purpose.
789 function survey_supports($feature) {
791 case FEATURE_GROUPS
: return true;
792 case FEATURE_GROUPINGS
: return true;
793 case FEATURE_MOD_INTRO
: return true;
794 case FEATURE_COMPLETION_TRACKS_VIEWS
: return true;
795 case FEATURE_COMPLETION_HAS_RULES
: return true;
796 case FEATURE_GRADE_HAS_GRADE
: return false;
797 case FEATURE_GRADE_OUTCOMES
: return false;
798 case FEATURE_BACKUP_MOODLE2
: return true;
799 case FEATURE_SHOW_DESCRIPTION
: return true;
800 case FEATURE_MOD_PURPOSE
: return MOD_PURPOSE_COMMUNICATION
;
802 default: return null;
807 * This function extends the settings navigation block for the site.
809 * It is safe to rely on PAGE here as we will only ever be within the module
810 * context when this is called
812 * @param settings_navigation $settings
813 * @param navigation_node $surveynode
815 function survey_extend_settings_navigation(settings_navigation
$settings, navigation_node
$surveynode) {
817 if (has_capability('mod/survey:readresponses', $settings->get_page()->cm
->context
)) {
818 $cm = get_coursemodule_from_id('survey', $settings->get_page()->cm
->id
);
819 $survey = $DB->get_record("survey", ["id" => $cm->instance
]);
820 $url = new moodle_url('/mod/survey/report.php', ['id' => $settings->get_page()->cm
->id
]);
821 if ($survey && ($survey->template
!= SURVEY_CIQ
)) {
822 $url->param('action', 'summary');
824 $url->param('action', 'questions');
826 $surveynode->add(get_string("responsereports", "survey"), $url);
831 * Return a list of page types
832 * @param string $pagetype current page type
833 * @param stdClass $parentcontext Block's parent context
834 * @param stdClass $currentcontext Current context of block
836 function survey_page_type_list($pagetype, $parentcontext, $currentcontext) {
837 $module_pagetype = array('mod-survey-*'=>get_string('page-mod-survey-x', 'survey'));
838 return $module_pagetype;
842 * Mark the activity completed (if required) and trigger the course_module_viewed event.
844 * @param stdClass $survey survey object
845 * @param stdClass $course course object
846 * @param stdClass $cm course module object
847 * @param stdClass $context context object
848 * @param string $viewed which page viewed
851 function survey_view($survey, $course, $cm, $context, $viewed) {
853 // Trigger course_module_viewed event.
855 'context' => $context,
856 'objectid' => $survey->id
,
857 'courseid' => $course->id
,
858 'other' => array('viewed' => $viewed)
861 $event = \mod_survey\event\course_module_viewed
::create($params);
862 $event->add_record_snapshot('course_modules', $cm);
863 $event->add_record_snapshot('course', $course);
864 $event->add_record_snapshot('survey', $survey);
868 $completion = new completion_info($course);
869 $completion->set_module_viewed($cm);
873 * Helper function for ordering a set of questions by the given ids.
875 * @param array $questions array of questions objects
876 * @param array $questionorder array of questions ids indicating the correct order
877 * @return array list of questions ordered
880 function survey_order_questions($questions, $questionorder) {
882 $finalquestions = array();
883 foreach ($questionorder as $qid) {
884 $finalquestions[] = $questions[$qid];
886 return $finalquestions;
890 * Translate the question texts and options.
892 * @param stdClass $question question object
893 * @return stdClass question object with all the text fields translated
896 function survey_translate_question($question) {
898 if ($question->text
) {
899 $question->text
= get_string($question->text
, "survey");
902 if ($question->shorttext
) {
903 $question->shorttext
= get_string($question->shorttext
, "survey");
906 if ($question->intro
) {
907 $question->intro
= get_string($question->intro
, "survey");
910 if ($question->options
) {
911 $question->options
= get_string($question->options
, "survey");
917 * Returns the questions for a survey (ordered).
919 * @param stdClass $survey survey object
920 * @return array list of questions ordered
922 * @throws moodle_exception
924 function survey_get_questions($survey) {
927 $questionids = explode(',', $survey->questions
);
928 if (! $questions = $DB->get_records_list("survey_questions", "id", $questionids)) {
929 throw new moodle_exception('cannotfindquestion', 'survey');
932 return survey_order_questions($questions, $questionids);
936 * Returns subquestions for a given question (ordered).
938 * @param stdClass $question questin object
939 * @return array list of subquestions ordered
942 function survey_get_subquestions($question) {
945 $questionids = explode(',', $question->multi
);
946 $questions = $DB->get_records_list("survey_questions", "id", $questionids);
948 return survey_order_questions($questions, $questionids);
952 * Save the answer for the given survey
954 * @param stdClass $survey a survey object
955 * @param array $answersrawdata the answers to be saved
956 * @param stdClass $course a course object (required for trigger the submitted event)
957 * @param stdClass $context a context object (required for trigger the submitted event)
960 function survey_save_answers($survey, $answersrawdata, $course, $context) {
965 // Sort through the data and arrange it.
966 // This is necessary because some of the questions may have two answers, eg Question 1 -> 1 and P1.
967 foreach ($answersrawdata as $key => $val) {
968 if ($key != "userid" && $key != "id") {
969 if (substr($key, 0, 1) == "q") {
970 $key = clean_param(substr($key, 1), PARAM_ALPHANUM
); // Keep everything but the 'q', number or P number.
972 if (substr($key, 0, 1) == "P") {
973 $realkey = (int) substr($key, 1);
974 $answers[$realkey][1] = $val;
976 $answers[$key][0] = $val;
981 // Now store the data.
983 $answerstoinsert = array();
984 foreach ($answers as $key => $val) {
985 if ($key != 'sesskey') {
986 $newdata = new stdClass();
987 $newdata->time
= $timenow;
988 $newdata->userid
= $USER->id
;
989 $newdata->survey
= $survey->id
;
990 $newdata->question
= $key;
991 if (!empty($val[0])) {
992 $newdata->answer1
= $val[0];
994 $newdata->answer1
= "";
996 if (!empty($val[1])) {
997 $newdata->answer2
= $val[1];
999 $newdata->answer2
= "";
1002 $answerstoinsert[] = $newdata;
1006 if (!empty($answerstoinsert)) {
1007 $DB->insert_records("survey_answers", $answerstoinsert);
1010 // Update completion state.
1011 $cm = get_coursemodule_from_instance('survey', $survey->id
, $course->id
);
1012 $completion = new completion_info($course);
1013 if (isloggedin() && !isguestuser() && $completion->is_enabled($cm) && $survey->completionsubmit
) {
1014 $completion->update_state($cm, COMPLETION_COMPLETE
);
1018 'context' => $context,
1019 'courseid' => $course->id
,
1020 'other' => array('surveyid' => $survey->id
)
1022 $event = \mod_survey\event\response_submitted
::create($params);
1027 * Check if the module has any update that affects the current user since a given time.
1029 * @param cm_info $cm course module data
1030 * @param int $from the time to check updates from
1031 * @param array $filter if we need to check only specific updates
1032 * @return stdClass an object with the different type of areas indicating if they were updated or not
1035 function survey_check_updates_since(cm_info
$cm, $from, $filter = array()) {
1038 $updates = new stdClass();
1039 if (!has_capability('mod/survey:participate', $cm->context
)) {
1042 $updates = course_check_module_updates_since($cm, $from, array(), $filter);
1044 $updates->answers
= (object) array('updated' => false);
1045 $select = 'survey = ? AND userid = ? AND time > ?';
1046 $params = array($cm->instance
, $USER->id
, $from);
1047 $answers = $DB->get_records_select('survey_answers', $select, $params, '', 'id');
1048 if (!empty($answers)) {
1049 $updates->answers
->updated
= true;
1050 $updates->answers
->itemids
= array_keys($answers);
1053 // Now, teachers should see other students updates.
1054 if (has_capability('mod/survey:readresponses', $cm->context
)) {
1055 $select = 'survey = ? AND time > ?';
1056 $params = array($cm->instance
, $from);
1058 if (groups_get_activity_groupmode($cm) == SEPARATEGROUPS
) {
1059 $groupusers = array_keys(groups_get_activity_shared_group_members($cm));
1060 if (empty($groupusers)) {
1063 list($insql, $inparams) = $DB->get_in_or_equal($groupusers);
1064 $select .= ' AND userid ' . $insql;
1065 $params = array_merge($params, $inparams);
1068 $updates->useranswers
= (object) array('updated' => false);
1069 $answers = $DB->get_records_select('survey_answers', $select, $params, '', 'id');
1070 if (!empty($answers)) {
1071 $updates->useranswers
->updated
= true;
1072 $updates->useranswers
->itemids
= array_keys($answers);
1079 * This function receives a calendar event and returns the action associated with it, or null if there is none.
1081 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
1082 * is not displayed on the block.
1084 * @param calendar_event $event
1085 * @param \core_calendar\action_factory $factory
1086 * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
1087 * @return \core_calendar\local\event\entities\action_interface|null
1089 function mod_survey_core_calendar_provide_event_action(calendar_event
$event,
1090 \core_calendar\action_factory
$factory,
1094 if (empty($userid)) {
1095 $userid = $USER->id
;
1098 $cm = get_fast_modinfo($event->courseid
, $userid)->instances
['survey'][$event->instance
];
1099 $context = context_module
::instance($cm->id
);
1101 if (!has_capability('mod/survey:participate', $context, $userid)) {
1105 $completion = new \
completion_info($cm->get_course());
1107 $completiondata = $completion->get_data($cm, false, $userid);
1109 if ($completiondata->completionstate
!= COMPLETION_INCOMPLETE
) {
1113 return $factory->create_instance(
1115 new \
moodle_url('/mod/survey/view.php', ['id' => $cm->id
]),
1122 * Add a get_coursemodule_info function in case any survey type wants to add 'extra' information
1123 * for the course (see resource).
1125 * Given a course_module object, this function returns any "extra" information that may be needed
1126 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
1128 * @param stdClass $coursemodule The coursemodule object (record).
1129 * @return cached_cm_info An object on information that the courses
1130 * will know about (most noticeably, an icon).
1132 function survey_get_coursemodule_info($coursemodule) {
1135 $dbparams = ['id' => $coursemodule->instance
];
1136 $fields = 'id, name, intro, introformat, completionsubmit';
1137 if (!$survey = $DB->get_record('survey', $dbparams, $fields)) {
1141 $result = new cached_cm_info();
1142 $result->name
= $survey->name
;
1144 if ($coursemodule->showdescription
) {
1145 // Convert intro to html. Do not filter cached version, filters run at display time.
1146 $result->content
= format_module_intro('survey', $survey, $coursemodule->id
, false);
1149 // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
1150 if ($coursemodule->completion
== COMPLETION_TRACKING_AUTOMATIC
) {
1151 $result->customdata
['customcompletionrules']['completionsubmit'] = $survey->completionsubmit
;
1158 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
1160 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
1161 * @return array $descriptions the array of descriptions for the custom rules.
1163 function mod_survey_get_completion_active_rule_descriptions($cm) {
1164 // Values will be present in cm_info, and we assume these are up to date.
1165 if (empty($cm->customdata
['customcompletionrules'])
1166 ||
$cm->completion
!= COMPLETION_TRACKING_AUTOMATIC
) {
1171 foreach ($cm->customdata
['customcompletionrules'] as $key => $val) {
1173 case 'completionsubmit':
1175 $descriptions[] = get_string('completionsubmit', 'survey');
1182 return $descriptions;