MDL-10496:
[moodle-linuxchix.git] / mod / survey / save.php
blobacbeaa55bd9916642c4d8af33a6fe395ef93c3d3
1 <?php // $Id$
3 require_once('../../config.php');
4 require_once('lib.php');
7 // Make sure this is a legitimate posting
9 if (!$formdata = data_submitted("$CFG->wwwroot/mod/survey/view.php")) {
10 error("You are not supposed to use this script like that.");
13 $id = required_param('id', PARAM_INT); // Course Module ID
15 if (! $cm = get_coursemodule_from_id('survey', $id)) {
16 error("Course Module ID was incorrect");
19 if (! $course = get_record("course", "id", $cm->course)) {
20 error("Course is misconfigured");
23 require_login($course->id, false, $cm);
25 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
26 require_capability('mod/survey:participate', $context);
28 if (! $survey = get_record("survey", "id", $cm->instance)) {
29 error("Survey ID was incorrect");
32 add_to_log($course->id, "survey", "submit", "view.php?id=$cm->id", "$survey->id", "$cm->id");
34 $strsurveys = get_string("modulenameplural", "survey");
35 $strsurveysaved = get_string("surveysaved", "survey");
36 $navlinks = array();
37 $navlinks[] = array('name' => $strsurveys, 'link' => "index.php?id=$course->id", 'type' => 'activity');
38 $navlinks[] = array('name' => format_string($survey->name), 'link' => '', 'type' => 'activityinstance');
39 $navlinks[] = array('name' => $strsurveysaved, 'link' => '', 'type' => 'title');
40 $navigation = build_navigation($navlinks);
42 print_header_simple("$strsurveysaved", "", $navigation, "");
45 if (survey_already_done($survey->id, $USER->id)) {
46 notice(get_string("alreadysubmitted", "survey"), $_SERVER["HTTP_REFERER"]);
47 exit;
51 // Sort through the data and arrange it
52 // This is necessary because some of the questions
53 // may have two answers, eg Question 1 -> 1 and P1
55 $answers = array();
57 foreach ($formdata as $key => $val) {
58 if ($key <> "userid" && $key <> "id") {
59 if ( substr($key,0,1) == "q") {
60 $key = clean_param(substr($key,1), PARAM_ALPHANUM); // keep everything but the 'q', number or Pnumber
62 if ( substr($key,0,1) == "P") {
63 $realkey = (int) substr($key,1);
64 $answers[$realkey][1] = $val;
65 } else {
66 $answers[$key][0] = $val;
72 // Now store the data.
74 $timenow = time();
75 foreach ($answers as $key => $val) {
77 $newdata->time = $timenow;
78 $newdata->userid = $USER->id;
79 $newdata->survey = $survey->id;
80 $newdata->question = $key;
81 if (!empty($val[0])) {
82 $newdata->answer1 = $val[0];
83 } else {
84 $newdata->answer1 = "";
86 if (!empty($val[1])) {
87 $newdata->answer2 = $val[1];
88 } else {
89 $newdata->answer2 = "";
92 if (! insert_record("survey_answers", $newdata)) {
93 error("Encountered a problem trying to store your results. Sorry.");
97 // Print the page and finish up.
99 notice(get_string("thanksforanswers","survey", $USER->firstname), "$CFG->wwwroot/course/view.php?id=$course->id");
101 exit;