MDL-51629 mod_survey: New WS mod_survey_submit_answers
[moodle.git] / mod / survey / lib.php
CommitLineData
e5cc530b 1<?php
2
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/>.
f9903ed0 17
e5cc530b 18/**
da9bddbe 19 * @package mod_survey
e5cc530b 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 */
23
24/**
25 * Graph size
26 * @global int $SURVEY_GHEIGHT
27 */
17da2e6f 28global $SURVEY_GHEIGHT;
551b0b98 29$SURVEY_GHEIGHT = 500;
e5cc530b 30/**
31 * Graph size
32 * @global int $SURVEY_GWIDTH
33 */
17da2e6f 34global $SURVEY_GWIDTH;
551b0b98 35$SURVEY_GWIDTH = 900;
e5cc530b 36/**
37 * Question Type
38 * @global array $SURVEY_QTYPE
39 */
17da2e6f 40global $SURVEY_QTYPE;
551b0b98 41$SURVEY_QTYPE = array (
f9903ed0 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 );
50
b6b3deb4 51
52define("SURVEY_COLLES_ACTUAL", "1");
53define("SURVEY_COLLES_PREFERRED", "2");
54define("SURVEY_COLLES_PREFERRED_ACTUAL", "3");
55define("SURVEY_ATTLS", "4");
56define("SURVEY_CIQ", "5");
57
58
66ea15f3 59// STANDARD FUNCTIONS ////////////////////////////////////////////////////////
e5cc530b 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 */
04eba58f 70function survey_add_instance($survey) {
c18269c7 71 global $DB;
04eba58f 72
c18269c7 73 if (!$template = $DB->get_record("survey", array("id"=>$survey->template))) {
04eba58f 74 return 0;
75 }
76
e5dd8e3b 77 $survey->questions = $template->questions;
04eba58f 78 $survey->timecreated = time();
79 $survey->timemodified = $survey->timecreated;
80
c18269c7 81 return $DB->insert_record("survey", $survey);
04eba58f 82
83}
84
e5cc530b 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 */
04eba58f 94function survey_update_instance($survey) {
c18269c7 95 global $DB;
04eba58f 96
c18269c7 97 if (!$template = $DB->get_record("survey", array("id"=>$survey->template))) {
04eba58f 98 return 0;
99 }
100
e5dd8e3b
PS
101 $survey->id = $survey->instance;
102 $survey->questions = $template->questions;
04eba58f 103 $survey->timemodified = time();
104
c18269c7 105 return $DB->update_record("survey", $survey);
04eba58f 106}
107
e5cc530b 108/**
109 * Given an ID of an instance of this module,
110 * this function will permanently delete the instance
e5dd8e3b 111 * and any data that depends on it.
e5cc530b 112 *
113 * @global object
114 * @param int $id
115 * @return bool
116 */
04eba58f 117function survey_delete_instance($id) {
c18269c7 118 global $DB;
04eba58f 119
c18269c7 120 if (! $survey = $DB->get_record("survey", array("id"=>$id))) {
04eba58f 121 return false;
122 }
123
124 $result = true;
125
c18269c7 126 if (! $DB->delete_records("survey_analysis", array("survey"=>$survey->id))) {
04eba58f 127 $result = false;
128 }
129
c18269c7 130 if (! $DB->delete_records("survey_answers", array("survey"=>$survey->id))) {
04eba58f 131 $result = false;
132 }
133
c18269c7 134 if (! $DB->delete_records("survey", array("id"=>$survey->id))) {
04eba58f 135 $result = false;
136 }
137
138 return $result;
139}
140
e5cc530b 141/**
142 * @global object
143 * @param object $course
144 * @param object $user
145 * @param object $mod
146 * @param object $survey
147 * @return $result
148 */
66ea15f3 149function survey_user_outline($course, $user, $mod, $survey) {
deb3a60d 150 global $DB;
66ea15f3 151
deb3a60d 152 if ($answers = $DB->get_records("survey_answers", array('survey'=>$survey->id, 'userid'=>$user->id))) {
66ea15f3 153 $lastanswer = array_pop($answers);
154
39790bd8 155 $result = new stdClass();
66ea15f3 156 $result->info = get_string("done", "survey");
157 $result->time = $lastanswer->time;
158 return $result;
159 }
160 return NULL;
161}
162
e5cc530b 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 */
66ea15f3 172function survey_user_complete($course, $user, $mod, $survey) {
02f78a26 173 global $CFG, $DB, $OUTPUT;
66ea15f3 174
175 if (survey_already_done($survey->id, $user->id)) {
b6b3deb4 176 if ($survey->template == SURVEY_CIQ) { // print out answers for critical incidents
02f78a26 177 $table = new html_table();
b6b3deb4 178 $table->align = array("left", "left");
179
44e1b7d7 180 $questions = $DB->get_records_list("survey_questions", "id", explode(',', $survey->questions));
b6b3deb4 181 $questionorder = explode(",", $survey->questions);
e5dd8e3b 182
b6b3deb4 183 foreach ($questionorder as $key=>$val) {
184 $question = $questions[$val];
185 $questiontext = get_string($question->shorttext, "survey");
e5dd8e3b 186
b6b3deb4 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>", $answertext);
193 }
16be8974 194 echo html_writer::table($table);
e5dd8e3b 195
b6b3deb4 196 } else {
e5dd8e3b 197
839f2456 198 survey_print_graph("id=$mod->id&amp;sid=$user->id&amp;type=student.png");
b6b3deb4 199 }
e5dd8e3b 200
66ea15f3 201 } else {
202 print_string("notdone", "survey");
203 }
204}
205
e5cc530b 206/**
207 * @global stdClass
208 * @global object
209 * @param object $course
210 * @param mixed $viewfullnames
211 * @param int $timestamp
212 * @return bool
213 */
dd97c328 214function survey_print_recent_activity($course, $viewfullnames, $timestart) {
11e0676a 215 global $CFG, $DB, $OUTPUT;
54634efc 216
dd97c328 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 }
54634efc 228
dd97c328 229 if (!$ids) {
1b5910c4 230 return false;
231 }
232
dd97c328 233 $slist = implode(',', $ids); // there should not be hundreds of glossaries in one course, right?
234
c4a8dce7 235 $allusernames = user_picture::fields('u');
a1d870aa 236 $rs = $DB->get_recordset_sql("SELECT sa.userid, sa.survey, MAX(sa.time) AS time,
c4a8dce7 237 $allusernames
a1d870aa
EL
238 FROM {survey_answers} sa
239 JOIN {user} u ON u.id = sa.userid
240 WHERE sa.survey IN ($slist) AND sa.time > ?
c4a8dce7 241 GROUP BY sa.userid, sa.survey, $allusernames
a1d870aa
EL
242 ORDER BY time ASC", array($timestart));
243 if (!$rs->valid()) {
244 $rs->close(); // Not going to iterate (but exit), close rs
dd97c328 245 return false;
54634efc 246 }
247
dd97c328 248 $surveys = array();
249
deb3a60d 250 foreach ($rs as $survey) {
dd97c328 251 $cm = $modinfo->instances['survey'][$survey->survey];
252 $survey->name = $cm->name;
253 $survey->cmid = $cm->id;
254 $surveys[] = $survey;
e5dd8e3b 255 }
deb3a60d 256 $rs->close();
dd97c328 257
258 if (!$surveys) {
259 return false;
260 }
261
5def24cf 262 echo $OUTPUT->heading(get_string('newsurveyresponses', 'survey').':', 3);
dd97c328 263 foreach ($surveys as $survey) {
d5edb961 264 $url = $CFG->wwwroot.'/mod/survey/view.php?id='.$survey->cmid;
dd97c328 265 print_recent_activity_note($survey->time, $survey, $survey->name, $url, false, $viewfullnames);
54634efc 266 }
e5dd8e3b 267
dd97c328 268 return true;
54634efc 269}
04eba58f 270
e323955d 271// SQL FUNCTIONS ////////////////////////////////////////////////////////
66ea15f3 272
e5cc530b 273/**
274 * @global object
275 * @param sting $log
276 * @return array
277 */
e323955d 278function survey_log_info($log) {
deb3a60d 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));
e323955d 283}
f9903ed0 284
e5cc530b 285/**
286 * @global object
287 * @param int $surveyid
288 * @param int $groupid
289 * @param int $groupingid
290 * @return array
291 */
07aa2057 292function survey_get_responses($surveyid, $groupid, $groupingid) {
deb3a60d 293 global $DB;
294
e5dd8e3b 295 $params = array('surveyid'=>$surveyid, 'groupid'=>$groupid, 'groupingid'=>$groupingid);
a9ccbf60 296
297 if ($groupid) {
deb3a60d 298 $groupsjoin = "JOIN {groups_members} gm ON u.id = gm.userid AND gm.groupid = :groupid ";
1d684195 299
07aa2057 300 } else if ($groupingid) {
deb3a60d 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 ";
a9ccbf60 303 } else {
07aa2057 304 $groupsjoin = "";
a9ccbf60 305 }
306
9b8b9b73
AD
307 $userfields = user_picture::fields('u');
308 return $DB->get_records_sql("SELECT $userfields, MAX(a.time) as time
deb3a60d 309 FROM {survey_answers} a
310 JOIN {user} u ON a.userid = u.id
311 $groupsjoin
312 WHERE a.survey = :surveyid
8e1e3c14 313 GROUP BY $userfields
deb3a60d 314 ORDER BY time ASC", $params);
e323955d 315}
316
e5cc530b 317/**
318 * @global object
319 * @param int $survey
320 * @param int $user
321 * @return array
322 */
e323955d 323function survey_get_analysis($survey, $user) {
deb3a60d 324 global $DB;
e323955d 325
e5dd8e3b 326 return $DB->get_record_sql("SELECT notes
deb3a60d 327 FROM {survey_analysis}
328 WHERE survey=? AND userid=?", array($survey, $user));
e323955d 329}
330
e5cc530b 331/**
332 * @global object
333 * @param int $survey
334 * @param int $user
335 * @param string $notes
336 */
e323955d 337function survey_update_analysis($survey, $user, $notes) {
deb3a60d 338 global $DB;
e323955d 339
deb3a60d 340 return $DB->execute("UPDATE {survey_analysis}
e5dd8e3b
PS
341 SET notes=?
342 WHERE survey=?
deb3a60d 343 AND userid=?", array($notes, $survey, $user));
e323955d 344}
345
e5cc530b 346/**
347 * @global object
348 * @param int $surveyid
349 * @param int $groupid
350 * @param string $sort
351 * @return array
352 */
a9ccbf60 353function survey_get_user_answers($surveyid, $questionid, $groupid, $sort="sa.answer1,sa.answer2 ASC") {
deb3a60d 354 global $DB;
355
62ab566e 356 $params = array('surveyid'=>$surveyid, 'questionid'=>$questionid);
e323955d 357
a9ccbf60 358 if ($groupid) {
62ab566e
EL
359 $groupfrom = ', {groups_members} gm';
360 $groupsql = 'AND gm.groupid = :groupid AND u.id = gm.userid';
361 $params['groupid'] = $groupid;
a9ccbf60 362 } else {
62ab566e
EL
363 $groupfrom = '';
364 $groupsql = '';
a9ccbf60 365 }
366
d04d8e96
AD
367 $userfields = user_picture::fields('u');
368 return $DB->get_records_sql("SELECT sa.*, $userfields
62ab566e 369 FROM {survey_answers} sa, {user} u $groupfrom
e5dd8e3b
PS
370 WHERE sa.survey = :surveyid
371 AND sa.question = :questionid
deb3a60d 372 AND u.id = sa.userid $groupsql
373 ORDER BY $sort", $params);
7c8c335f 374}
375
e5cc530b 376/**
377 * @global object
378 * @param int $surveyid
379 * @param int $questionid
380 * @param int $userid
381 * @return array
382 */
7c8c335f 383function survey_get_user_answer($surveyid, $questionid, $userid) {
deb3a60d 384 global $DB;
7c8c335f 385
e5dd8e3b 386 return $DB->get_record_sql("SELECT sa.*
deb3a60d 387 FROM {survey_answers} sa
e5dd8e3b
PS
388 WHERE sa.survey = ?
389 AND sa.question = ?
deb3a60d 390 AND sa.userid = ?", array($surveyid, $questionid, $userid));
e323955d 391}
392
393// MODULE FUNCTIONS ////////////////////////////////////////////////////////
e5cc530b 394/**
395 * @global object
396 * @param int $survey
397 * @param int $user
398 * @param string $notes
399 * @return bool|int
400 */
ebc3bd2b 401function survey_add_analysis($survey, $user, $notes) {
deb3a60d 402 global $DB;
ebc3bd2b 403
39790bd8 404 $record = new stdClass();
ebc3bd2b 405 $record->survey = $survey;
406 $record->userid = $user;
407 $record->notes = $notes;
408
deb3a60d 409 return $DB->insert_record("survey_analysis", $record, false);
ebc3bd2b 410}
e5cc530b 411/**
412 * @global object
413 * @param int $survey
414 * @param int $user
415 * @return bool
416 */
e323955d 417function survey_already_done($survey, $user) {
deb3a60d 418 global $DB;
419
420 return $DB->record_exists("survey_answers", array("survey"=>$survey, "userid"=>$user));
551b0b98 421}
e5cc530b 422/**
423 * @param int $surveyid
424 * @param int $groupid
425 * @param int $groupingid
426 * @return int
427 */
07aa2057 428function survey_count_responses($surveyid, $groupid, $groupingid) {
429 if ($responses = survey_get_responses($surveyid, $groupid, $groupingid)) {
551b0b98 430 return count($responses);
431 } else {
432 return 0;
433 }
f9903ed0 434}
435
e5cc530b 436/**
437 * @param int $cmid
438 * @param array $results
439 * @param int $courseid
440 */
7c8c335f 441function survey_print_all_responses($cmid, $results, $courseid) {
02f78a26 442 global $OUTPUT;
443 $table = new html_table();
a30f997e 444 $table->head = array ("", get_string("name"), get_string("time"));
445 $table->align = array ("", "left", "left");
446 $table->size = array (35, "", "" );
b416a1c3 447
448 foreach ($results as $a) {
812dbaf7 449 $table->data[] = array($OUTPUT->user_picture($a, array('courseid'=>$courseid)),
9bf16314 450 html_writer::link("report.php?action=student&student=$a->id&id=$cmid", fullname($a)),
a30f997e 451 userdate($a->time));
b416a1c3 452 }
7c8c335f 453
16be8974 454 echo html_writer::table($table);
b416a1c3 455}
456
e5cc530b 457/**
458 * @global object
459 * @param int $templateid
460 * @return string
461 */
551b0b98 462function survey_get_template_name($templateid) {
fd0e6640 463 global $DB;
f9903ed0 464
465 if ($templateid) {
deb3a60d 466 if ($ss = $DB->get_record("surveys", array("id"=>$templateid))) {
e323955d 467 return $ss->name;
f9903ed0 468 }
469 } else {
470 return "";
471 }
472}
473
0d22e7cc 474
e5cc530b 475/**
476 * @param string $name
477 * @param array $numwords
478 * @return string
479 */
0e30c987 480function survey_shorten_name ($name, $numwords) {
481 $words = explode(" ", $name);
92701024 482 $output = '';
0e30c987 483 for ($i=0; $i < $numwords; $i++) {
484 $output .= $words[$i]." ";
485 }
486 return $output;
487}
f9903ed0 488
e5cc530b 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 */
0e30c987 499function survey_print_multi($question) {
0a9d1b3b 500 global $USER, $DB, $qnum, $checklist, $DB, $OUTPUT; //TODO: this is sloppy globals abuse
0e30c987 501
98899fc0 502 $stripreferthat = get_string("ipreferthat", "survey");
503 $strifoundthat = get_string("ifoundthat", "survey");
6438c34f 504 $strdefault = get_string('notyetanswered', 'survey');
532f494d 505 $strresponses = get_string('responses', 'survey');
506
5def24cf 507 echo $OUTPUT->heading($question->text, 3);
90723839 508 echo "\n<table width=\"90%\" cellpadding=\"4\" cellspacing=\"1\" border=\"0\" class=\"surveytable\">";
0e30c987 509
510 $options = explode( ",", $question->options);
511 $numoptions = count($options);
512
de9a88cd
DM
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.
0e30c987 519 $oneanswer = ($question->type == 1 || $question->type == 2) ? true : false;
0e30c987 520
de9a88cd
DM
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 }
528
532f494d 529 echo "<tr class=\"smalltext\"><th scope=\"row\">$strresponses</th>";
6438c34f 530 echo "<th scope=\"col\" class=\"hresponse\">". get_string('notyetanswered', 'survey'). "</th>";
0e30c987 531 while (list ($key, $val) = each ($options)) {
532f494d 532 echo "<th scope=\"col\" class=\"hresponse\">$val</th>\n";
533 }
6438c34f 534 echo "</tr>\n";
532f494d 535
57c2052c 536 echo "<tr><th scope=\"col\" colspan=\"7\">$question->intro</th></tr>\n";
0e30c987 537
f772b515 538 $subquestions = survey_get_subquestions($question);
532f494d 539
0e30c987 540 foreach ($subquestions as $q) {
541 $qnum++;
7c517929
DM
542 if ($oneanswer) {
543 $rowclass = survey_question_rowclass($qnum);
544 } else {
545 $rowclass = survey_question_rowclass(round($qnum / 2));
546 }
f762c448 547 if ($q->text) {
548 $q->text = get_string($q->text, "survey");
5196df58
AD
549 }
550
532f494d 551 echo "<tr class=\"$rowclass rblock\">";
0e30c987 552 if ($oneanswer) {
532f494d 553 echo "<th scope=\"row\" class=\"optioncell\">";
554 echo "<b class=\"qnumtopcell\">$qnum</b> &nbsp; ";
555 echo $q->text ."</th>\n";
6438c34f
RW
556
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>";
559
532f494d 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>";
91421f3e
PS
564 }
565 $checklist["q$P$q->id"] = 0;
e5dd8e3b 566
91421f3e 567 } else {
532f494d 568 echo "<th scope=\"row\" class=\"optioncell\">";
569 echo "<b class=\"qnumtopcell\">$qnum</b> &nbsp; ";
5d1a5ef4 570 $qnum++;
7c517929 571 echo "<span class=\"preferthat\">$stripreferthat</span> &nbsp; ";
532f494d 572 echo "<span class=\"option\">$q->text</span></th>\n";
6438c34f
RW
573
574 $default = get_accesshide($strdefault);
57c2052c 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>';
6438c34f
RW
576
577
0e30c987 578 for ($i=1;$i<=$numoptions;$i++) {
532f494d 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>";
0e30c987 582 }
d1290cec 583 echo "</tr>";
0e30c987 584
532f494d 585 echo "<tr class=\"$rowclass rblock\">";
586 echo "<th scope=\"row\" class=\"optioncell\">";
587 echo "<b class=\"qnumtopcell\">$qnum</b> &nbsp; ";
7c517929 588 echo "<span class=\"foundthat\">$strifoundthat</span> &nbsp; ";
532f494d 589 echo "<span class=\"option\">$q->text</span></th>\n";
6438c34f
RW
590
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>';
91421f3e 593
0e30c987 594 for ($i=1;$i<=$numoptions;$i++) {
532f494d 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>";
0e30c987 598 }
91421f3e 599
6438c34f
RW
600 $checklist["qP$q->id"] = 0;
601 $checklist["q$q->id"] = 0;
0e30c987 602 }
d1290cec 603 echo "</tr>\n";
0e30c987 604 }
d1290cec 605 echo "</table>";
0e30c987 606}
607
608
e5cc530b 609/**
610 * @global object
611 * @global int
612 * @param object $question
613 */
0e30c987 614function survey_print_single($question) {
8b1b0382 615 global $DB, $qnum, $OUTPUT;
0e30c987 616
f1c1d2f1 617 $rowclass = survey_question_rowclass(0);
0e30c987 618
619 $qnum++;
620
caf261b0 621 echo "<br />\n";
795b56b3 622 echo "<table width=\"90%\" cellpadding=\"4\" cellspacing=\"0\">\n";
f1c1d2f1 623 echo "<tr class=\"$rowclass\">";
532f494d 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";
0e30c987 627
628
629 if ($question->type == 0) { // Plain text field
532f494d 630 echo "<textarea rows=\"3\" cols=\"30\" name=\"q$question->id\" id=\"q$question->id\">$question->options</textarea>";
0e30c987 631
632 } else if ($question->type > 0) { // Choose one of a number
98899fc0 633 $strchoose = get_string("choose");
532f494d 634 echo "<select name=\"q$question->id\" id=\"q$question->id\">";
e0b7b090 635 echo "<option value=\"0\" selected=\"selected\">$strchoose...</option>";
0e30c987 636 $options = explode( ",", $question->options);
637 foreach ($options as $key => $val) {
638 $key++;
d1290cec 639 echo "<option value=\"$key\">$val</option>";
0e30c987 640 }
d1290cec 641 echo "</select>";
0e30c987 642
643 } else if ($question->type < 0) { // Choose several of a number
644 $options = explode( ",", $question->options);
8b1b0382 645 echo $OUTPUT->notification("This question type not supported yet");
0e30c987 646 }
647
532f494d 648 echo "</td></tr></table>";
0e30c987 649
650}
651
e5cc530b 652/**
653 *
654 * @param int $qnum
655 * @return string
656 */
f1c1d2f1 657function survey_question_rowclass($qnum) {
0e30c987 658
659 if ($qnum) {
f1c1d2f1 660 return $qnum % 2 ? 'r0' : 'r1';
0e30c987 661 } else {
f1c1d2f1 662 return 'r0';
0e30c987 663 }
664}
665
e5cc530b 666/**
667 * @global object
668 * @global int
669 * @global int
670 * @param string $url
671 */
607809b3 672function survey_print_graph($url) {
673 global $CFG, $SURVEY_GHEIGHT, $SURVEY_GWIDTH;
674
689096bc
PS
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")."\" />";
607809b3 677}
678
e5cc530b 679/**
b2b4ec30
RT
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 *
e5cc530b 687 * @return array
688 */
f3221af9 689function survey_get_view_actions() {
cf051cc4 690 return array('download','view all','view form','view graph','view report');
f3221af9 691}
692
e5cc530b 693/**
b2b4ec30
RT
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 *
e5cc530b 701 * @return array
702 */
f3221af9 703function survey_get_post_actions() {
704 return array('submit');
705}
706
0b5a80a1 707
708/**
709 * Implementation of the function for printing the form elements that control
710 * whether the course reset functionality affects the survey.
e5dd8e3b 711 *
e5cc530b 712 * @param object $mform form passed by reference
0b5a80a1 713 */
714function 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');
719}
720
721/**
722 * Course reset form defaults.
e5cc530b 723 * @return array
0b5a80a1 724 */
725function survey_reset_course_form_defaults($course) {
726 return array('reset_survey_answers'=>1, 'reset_survey_analysis'=>1);
727}
728
729/**
72d2982e 730 * Actual implementation of the reset course functionality, delete all the
0b5a80a1 731 * survey responses for course $data->courseid.
e5cc530b 732 *
733 * @global object
0b5a80a1 734 * @param $data the data submitted from the reset course.
735 * @return array status array
736 */
737function survey_reset_userdata($data) {
deb3a60d 738 global $DB;
0b5a80a1 739
740 $componentstr = get_string('modulenameplural', 'survey');
741 $status = array();
742
743 $surveyssql = "SELECT ch.id
deb3a60d 744 FROM {survey} ch
745 WHERE ch.course=?";
746 $params = array($data->courseid);
0b5a80a1 747
748 if (!empty($data->reset_survey_answers)) {
deb3a60d 749 $DB->delete_records_select('survey_answers', "survey IN ($surveyssql)", $params);
750 $DB->delete_records_select('survey_analysis', "survey IN ($surveyssql)", $params);
0b5a80a1 751 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallanswers', 'survey'), 'error'=>false);
752 }
753
754 if (!empty($data->reset_survey_analysis)) {
deb3a60d 755 $DB->delete_records_select('survey_analysis', "survey IN ($surveyssql)", $params);
0b5a80a1 756 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallanswers', 'survey'), 'error'=>false);
757 }
758
759 // no date shifting
760 return $status;
761}
762
f432bebf 763/**
764 * Returns all other caps used in module
e5cc530b 765 *
766 * @return array
f432bebf 767 */
768function survey_get_extra_capabilities() {
769 return array('moodle/site:accessallgroups');
770}
771
42f103be 772/**
e5cc530b 773 * @uses FEATURE_GROUPS
774 * @uses FEATURE_GROUPINGS
e5cc530b 775 * @uses FEATURE_MOD_INTRO
776 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
777 * @uses FEATURE_GRADE_HAS_GRADE
778 * @uses FEATURE_GRADE_OUTCOMES
42f103be 779 * @param string $feature FEATURE_xx constant for requested feature
e5cc530b 780 * @return mixed True if module supports feature, false if not, null if doesn't know
42f103be 781 */
782function survey_supports($feature) {
783 switch($feature) {
784 case FEATURE_GROUPS: return true;
785 case FEATURE_GROUPINGS: return true;
dc5c2bd9 786 case FEATURE_MOD_INTRO: return true;
42f103be 787 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
1c79d7db
SM
788 case FEATURE_GRADE_HAS_GRADE: return false;
789 case FEATURE_GRADE_OUTCOMES: return false;
253063a2 790 case FEATURE_BACKUP_MOODLE2: return true;
3e4c2435 791 case FEATURE_SHOW_DESCRIPTION: return true;
42f103be 792
793 default: return null;
794 }
17da2e6f 795}
a5cb6242 796
a5cb6242 797/**
798 * This function extends the settings navigation block for the site.
799 *
800 * It is safe to rely on PAGE here as we will only ever be within the module
801 * context when this is called
802 *
803 * @param navigation_node $settings
0b29477b
SH
804 * @param navigation_node $surveynode
805 */
806function survey_extend_settings_navigation($settings, $surveynode) {
807 global $PAGE;
a5cb6242 808
809 if (has_capability('mod/survey:readresponses', $PAGE->cm->context)) {
3406acde 810 $responsesnode = $surveynode->add(get_string("responsereports", "survey"));
a5cb6242 811
a6855934 812 $url = new moodle_url('/mod/survey/report.php', array('id' => $PAGE->cm->id, 'action'=>'summary'));
3406acde 813 $responsesnode->add(get_string("summary", "survey"), $url);
a5cb6242 814
a6855934 815 $url = new moodle_url('/mod/survey/report.php', array('id' => $PAGE->cm->id, 'action'=>'scales'));
3406acde 816 $responsesnode->add(get_string("scales", "survey"), $url);
a5cb6242 817
a6855934 818 $url = new moodle_url('/mod/survey/report.php', array('id' => $PAGE->cm->id, 'action'=>'questions'));
3406acde 819 $responsesnode->add(get_string("question", "survey"), $url);
a5cb6242 820
a6855934 821 $url = new moodle_url('/mod/survey/report.php', array('id' => $PAGE->cm->id, 'action'=>'students'));
3406acde 822 $responsesnode->add(get_string('participants'), $url);
a5cb6242 823
824 if (has_capability('mod/survey:download', $PAGE->cm->context)) {
a6855934 825 $url = new moodle_url('/mod/survey/report.php', array('id' => $PAGE->cm->id, 'action'=>'download'));
0b29477b 826 $surveynode->add(get_string('downloadresults', 'survey'), $url);
a5cb6242 827 }
828 }
253063a2 829}
b1627a92
DC
830
831/**
832 * Return a list of page types
833 * @param string $pagetype current page type
834 * @param stdClass $parentcontext Block's parent context
835 * @param stdClass $currentcontext Current context of block
836 */
b38e2e28 837function survey_page_type_list($pagetype, $parentcontext, $currentcontext) {
b1627a92
DC
838 $module_pagetype = array('mod-survey-*'=>get_string('page-mod-survey-x', 'survey'));
839 return $module_pagetype;
840}
75516809
JL
841
842/**
843 * Mark the activity completed (if required) and trigger the course_module_viewed event.
844 *
845 * @param stdClass $survey survey object
846 * @param stdClass $course course object
847 * @param stdClass $cm course module object
848 * @param stdClass $context context object
849 * @param string $viewed which page viewed
850 * @since Moodle 3.0
851 */
852function survey_view($survey, $course, $cm, $context, $viewed) {
853
854 // Trigger course_module_viewed event.
855 $params = array(
856 'context' => $context,
857 'objectid' => $survey->id,
858 'courseid' => $course->id,
859 'other' => array('viewed' => $viewed)
860 );
861
862 $event = \mod_survey\event\course_module_viewed::create($params);
863 $event->add_record_snapshot('course_modules', $cm);
864 $event->add_record_snapshot('course', $course);
865 $event->add_record_snapshot('survey', $survey);
866 $event->trigger();
867
868 // Completion.
869 $completion = new completion_info($course);
870 $completion->set_module_viewed($cm);
871}
f772b515
JL
872
873/**
874 * Helper function for ordering a set of questions by the given ids.
875 *
876 * @param array $questions array of questions objects
877 * @param array $questionorder array of questions ids indicating the correct order
878 * @return array list of questions ordered
879 * @since Moodle 3.0
880 */
881function survey_order_questions($questions, $questionorder) {
882
883 $finalquestions = array();
884 foreach ($questionorder as $qid) {
885 $finalquestions[] = $questions[$qid];
886 }
887 return $finalquestions;
888}
889
890/**
891 * Translate the question texts and options.
892 *
893 * @param stdClass $question question object
894 * @return stdClass question object with all the text fields translated
895 * @since Moodle 3.0
896 */
897function survey_translate_question($question) {
898
899 if ($question->text) {
900 $question->text = get_string($question->text, "survey");
901 }
902
903 if ($question->shorttext) {
904 $question->shorttext = get_string($question->shorttext, "survey");
905 }
906
907 if ($question->intro) {
908 $question->intro = get_string($question->intro, "survey");
909 }
910
911 if ($question->options) {
912 $question->options = get_string($question->options, "survey");
913 }
914 return $question;
915}
916
917/**
918 * Returns the questions for a survey (ordered).
919 *
920 * @param stdClass $survey survey object
921 * @return array list of questions ordered
922 * @since Moodle 3.0
923 * @throws moodle_exception
924 */
925function survey_get_questions($survey) {
926 global $DB;
927
928 $questionids = explode(',', $survey->questions);
929 if (! $questions = $DB->get_records_list("survey_questions", "id", $questionids)) {
930 throw new moodle_exception('cannotfindquestion', 'survey');
931 }
932
933 return survey_order_questions($questions, $questionids);
934}
935
936/**
937 * Returns subquestions for a given question (ordered).
938 *
939 * @param stdClass $question questin object
940 * @return array list of subquestions ordered
941 * @since Moodle 3.0
942 */
943function survey_get_subquestions($question) {
944 global $DB;
945
946 $questionids = explode(',', $question->multi);
947 $questions = $DB->get_records_list("survey_questions", "id", $questionids);
948
949 return survey_order_questions($questions, $questionids);
950}
55dca60f
JL
951
952/**
953 * Save the answer for the given survey
954 *
955 * @param stdClass $survey a survey object
956 * @param array $answersrawdata the answers to be saved
957 * @param stdClass $course a course object (required for trigger the submitted event)
958 * @param stdClass $context a context object (required for trigger the submitted event)
959 * @since Moodle 3.0
960 */
961function survey_save_answers($survey, $answersrawdata, $course, $context) {
962 global $DB, $USER;
963
964 $answers = array();
965
966 // Sort through the data and arrange it.
967 // This is necessary because some of the questions may have two answers, eg Question 1 -> 1 and P1.
968 foreach ($answersrawdata as $key => $val) {
969 if ($key <> "userid" && $key <> "id") {
970 if (substr($key, 0, 1) == "q") {
971 $key = clean_param(substr($key, 1), PARAM_ALPHANUM); // Keep everything but the 'q', number or P number.
972 }
973 if (substr($key, 0, 1) == "P") {
974 $realkey = (int) substr($key, 1);
975 $answers[$realkey][1] = $val;
976 } else {
977 $answers[$key][0] = $val;
978 }
979 }
980 }
981
982 // Now store the data.
983 $timenow = time();
984 $answerstoinsert = array();
985 foreach ($answers as $key => $val) {
986 if ($key != 'sesskey') {
987 $newdata = new stdClass();
988 $newdata->time = $timenow;
989 $newdata->userid = $USER->id;
990 $newdata->survey = $survey->id;
991 $newdata->question = $key;
992 if (!empty($val[0])) {
993 $newdata->answer1 = $val[0];
994 } else {
995 $newdata->answer1 = "";
996 }
997 if (!empty($val[1])) {
998 $newdata->answer2 = $val[1];
999 } else {
1000 $newdata->answer2 = "";
1001 }
1002
1003 $answerstoinsert[] = $newdata;
1004 }
1005 }
1006
1007 if (!empty($answerstoinsert)) {
1008 $DB->insert_records("survey_answers", $answerstoinsert);
1009 }
1010
1011 $params = array(
1012 'context' => $context,
1013 'courseid' => $course->id,
1014 'other' => array('surveyid' => $survey->id)
1015 );
1016 $event = \mod_survey\event\response_submitted::create($params);
1017 $event->trigger();
1018}