]> git.mjollnir.org Git - moodle.git/commitdiff
COnverted from DOS format
authormoodler <moodler>
Tue, 2 May 2006 06:00:35 +0000 (06:00 +0000)
committermoodler <moodler>
Tue, 2 May 2006 06:00:35 +0000 (06:00 +0000)
mod/hotpot/attempt.php
mod/hotpot/defaults.php
mod/hotpot/view.php

index fd495c03d13c3b8cefc9761828f8eb558ac54bb7..b7d5e55a34222820e26b660dffd26a8af8db23ef 100644 (file)
-<?php \r
-       require_once("../../config.php");\r
-       require_once("lib.php");\r
-\r
-       $attemptid = required_param("attemptid");\r
-\r
-       // get attempt, hotpot, course and course_module records\r
-       if (! $attempt = get_record("hotpot_attempts", "id", $attemptid)) {\r
-               error("Hot Potatoes attempt record $attemptid could not be accessed: ".$db->ErrorMsg());\r
-       }\r
-       if ($attempt->userid != $USER->id) {\r
-               error("User ID is incorrect");\r
-       }\r
-       if (! $hotpot = get_record("hotpot", "id", $attempt->hotpot)) {\r
-               error("Hot Potatoes ID is incorrect (attempt id = $attempt->id)");\r
-       }\r
-       if (! $course = get_record("course", "id", $hotpot->course)) {\r
-               error("Course ID is incorrect (hotpot id = $hotpot->id)");\r
-       }\r
-       if (! $cm = get_coursemodule_from_instance("hotpot", $hotpot->id, $course->id)) {\r
-               error("Course Module ID is incorrect");\r
-       }\r
-\r
-       // make sure this user is enrolled in this course\r
-       require_login($course->id);\r
-\r
-       $next_url = "$CFG->wwwroot/course/view.php?id=$course->id";\r
-       $time = time();\r
-\r
-       // update attempt record fields using incoming data\r
-       $attempt->score = optional_param('mark', NULL, PARAM_INT);\r
-       $attempt->status = optional_param('status', NULL, PARAM_INT);\r
-       $attempt->details = optional_param('detail', NULL, PARAM_RAW);\r
-       $attempt->endtime = optional_param('endtime', NULL, PARAM_ALPHA);\r
-       $attempt->starttime = optional_param('starttime', NULL, PARAM_ALPHA);\r
-       $attempt->timefinish = $time;\r
-\r
-       // convert times, if necessary\r
-       if (empty($attempt->starttime)) {\r
-               $attempt->starttime = 0;\r
-       } else {\r
-                $attempt->starttime = strtotime($attempt->starttime);\r
-       }\r
-       if (empty($attempt->endtime)) {\r
-               $attempt->endtime = 0;\r
-       } else {\r
-                $attempt->endtime = strtotime($attempt->endtime);\r
-       }\r
-\r
-       // set clickreportid, (for click reporting)\r
-       $attempt->clickreportid = $attempt->id;\r
-\r
-       $quiztype = optional_param('quiztype', 0, PARAM_INT);\r
-\r
-       if (empty($attempt->details)) {\r
-               hotpot_set_attempt_details($attempt);\r
-               $javascript_is_off = true;\r
-       } else {\r
-               $javascript_is_off = false;\r
-       }\r
-\r
-       if (empty($attempt->status)) {\r
-               if (empty($attempt->endtime)) {\r
-                       $attempt->status = HOTPOT_STATUS_INPROGRESS;\r
-               } else {\r
-                       $attempt->status = HOTPOT_STATUS_COMPLETED;\r
-               }\r
-       }\r
-\r
-       // check if this is the second (or subsequent) click\r
-       if (get_field("hotpot_attempts", "timefinish", "id", $attempt->id)) {\r
-\r
-               if ($hotpot->clickreporting==HOTPOT_YES) {\r
-                       // add attempt record for each form submission\r
-                       // records are linked via the "clickreportid" field\r
-\r
-                       // update status in previous records in this group\r
-                       set_field("hotpot_attempts", "status", $attempt->status, "clickreportid", $attempt->clickreportid);\r
-\r
-                       // add new attempt record\r
-                       unset ($attempt->id);\r
-                       $attempt->id = insert_record("hotpot_attempts", $attempt);\r
-\r
-                       if (empty($attempt->id)) {\r
-                               error("Could not insert attempt record: ".$db->ErrorMsg(), $next_url);\r
-                       }\r
-\r
-                       // add attempt details record, if necessary\r
-                       if (!empty($attempt->details)) {\r
-                               unset($details);\r
-                               $details->attempt = $attempt->id;\r
-                               $details->details = $attempt->details;\r
-                               if (! insert_record("hotpot_details", $details, false)) {\r
-                                       error("Could not insert attempt details record: ".$db->ErrorMsg(), $next_url);\r
-                               }\r
-                       }\r
-               } else {\r
-                       // remove previous responses for this attempt, if required\r
-                       // (N.B. this does NOT remove the attempt record, just the responses)\r
-                       delete_records("hotpot_responses", "attempt", $attempt->id);\r
-               }\r
-       }\r
-\r
-       // remove slashes added by lib/setup.php\r
-       $attempt->details = stripslashes($attempt->details);\r
-\r
-       // add details of this attempt\r
-       hotpot_add_attempt_details($attempt);\r
-\r
-       // add slashes again, so the details can be added to the database\r
-       $attempt->details = addslashes($attempt->details);\r
-\r
-       // update the attempt record\r
-       if (! update_record("hotpot_attempts", $attempt)) {\r
-               error("Could not update attempt record: ".$db->ErrorMsg(), $next_url);\r
-       }\r
-\r
-       // get previous attempt details record, if any\r
-       $details_exist = record_exists("hotpot_details", "attempt", $attempt->id);\r
-\r
-       // delete/update/add the attempt details record\r
-       if (empty($attempt->details)) {\r
-               if ($details_exist) {\r
-                       delete_records("hotpot_details", "attempt", $attempt->id);\r
-               }\r
-       } else {\r
-               if ($details_exist) {\r
-                       set_field("hotpot_details", "details", $attempt->details, "attempt", $attempt->id);\r
-               } else {\r
-                       unset($details);\r
-                       $details->attempt = $attempt->id;\r
-                       $details->details = $attempt->details;\r
-                       if (! insert_record("hotpot_details", $details)) {\r
-                               error("Could not insert attempt details record: ".$db->ErrorMsg(), $next_url);\r
-                       }\r
-               }\r
-       }\r
-\r
-       if ($attempt->status==HOTPOT_STATUS_INPROGRESS) {\r
-               if ($javascript_is_off) {\r
-                       // regenerate HTML page\r
-                       define('HOTPOT_FIRST_ATTEMPT', false);\r
-                       include ("$CFG->hotpotroot/view.php");\r
-               } else {\r
-                       // continue without reloading the page\r
-                       header("Status: 204");\r
-                       header("HTTP/1.0 204 No Response");\r
-               }\r
-\r
-       } else { // quiz is finished\r
-\r
-               add_to_log($course->id, "hotpot", "submit", "review.php?id=$cm->id&attempt=$attempt->id", "$hotpot->id", "$cm->id");\r
-\r
-               if ($hotpot->shownextquiz==HOTPOT_YES) {\r
-                       if (is_numeric($next_cm = hotpot_get_next_cm($cm))) {\r
-                               $next_url = "$CFG->wwwroot/mod/hotpot/view.php?id=$next_cm";\r
-                       }\r
-               }\r
-\r
-               // redirect to the next quiz or the course page \r
-               redirect($next_url, get_string('resultssaved', 'hotpot'));\r
-       }\r
-\r
-// =================\r
-//     functions\r
-// =================\r
-\r
-function hotpot_get_next_cm(&$cm) {\r
-       // gets the next module in this section of the course\r
-       // that is the same type of module as the current module\r
-\r
-       $next_mod = false;\r
-\r
-       // get a list of $ids of modules in this section\r
-       if ($ids = get_field('course_sections', 'sequence', 'id', $cm->section)) {\r
-\r
-               $found = false;\r
-               $ids = explode(',', $ids);\r
-               foreach ($ids as $id) {\r
-                       if ($found && ($cm->module==get_field('course_modules', 'module', 'id', $id))) {\r
-                               $next_mod = $id;\r
-                               break;\r
-                       } else if ($cm->id==$id) {\r
-                               $found = true;\r
-                       }\r
-               }\r
-       }\r
-       return $next_mod;\r
-}\r
-function hotpot_set_attempt_details(&$attempt) {\r
-       global $CFG, $HOTPOT_QUIZTYPE;\r
-\r
-       // optional_param('showallquestions', 0, PARAM_INT);\r
-\r
-       $attempt->details = '';\r
-       $attempt->score = 0;\r
-       $attempt->status = HOTPOT_STATUS_COMPLETED;\r
-\r
-       $buttons = array('clues', 'hints', 'checks');\r
-       $textfields = array('correct', 'wrong', 'ignored');\r
-\r
-       $ok = false;\r
-       $quiztype = optional_param('quiztype', 0, PARAM_ALPHANUM);\r
-       if ($quiztype) {\r
-               if (is_numeric($quiztype)) {\r
-                       $ok = array_key_exists($quiztype, $HOTPOT_QUIZTYPE);\r
-               } else {\r
-                       $quiztype = array_search($quiztype, $HOTPOT_QUIZTYPE);\r
-                       $ok = is_numeric($quiztype);\r
-               }\r
-       }\r
-       if (!$ok) {\r
-               return;\r
-               // error('Quiz type is missing or invalid');\r
-               // error(get_string('error_invalidquiztype', 'hotpot'));\r
-               //\r
-               // script finishes here if quiztype is invalid\r
-               //\r
-       }\r
-\r
-       // special flag to detect jquiz multiselect\r
-       $is_jquiz_multiselect = false;\r
-\r
-       // set maximum question number\r
-       $q_max = 0;;\r
-       do {\r
-               switch ($quiztype) {\r
-                       case HOTPOT_JCLOZE:\r
-                       case HOTPOT_JQUIZ:\r
-                               $field="q{$q_max}_a0_text";\r
-                               break;\r
-                       case HOTPOT_JCB:\r
-                       case HOTPOT_JCROSS:\r
-                       case HOTPOT_JMATCH:\r
-                       case HOTPOT_JMIX:\r
-                       default:\r
-                               $field = '';\r
-               }\r
-       } while ($field && isset($_POST[$field]) && ($q_max = $q_max+1));\r
-\r
-       // check JQuiz navigation buttons\r
-       switch (true) {\r
-               case isset($_POST['ShowAllQuestionsButton']):\r
-                       $_POST['ShowAllQuestions'] = 1;\r
-                       break;\r
-               case isset($_POST['ShowOneByOneButton']):\r
-                       $_POST['ShowAllQuestions'] = 0;\r
-                       break;\r
-               case isset($_POST['PrevQButton']):\r
-                       $_POST['ThisQuestion']--;\r
-                       break;\r
-               case isset($_POST['NextQButton']):\r
-                       $_POST['ThisQuestion']++;\r
-                       break;\r
-       }\r
-\r
-       $q = 0;\r
-       while ($q<$q_max) {\r
-               $responsefield="q{$q}";\r
-\r
-               $questiontype = optional_param("{$responsefield}_questiontype", 0, PARAM_INT);\r
-               $is_jquiz_multiselect = ($quiztype==HOTPOT_JQUIZ && $questiontype==HOTPOT_JQUIZ_MULTISELECT);\r
-\r
-               if (isset($_POST[$responsefield]) && is_array($_POST[$responsefield])) {\r
-                       $responsevalue = array();\r
-                       foreach ($_POST[$responsefield] as $key=>$value) {\r
-                               $responsevalue[$key] = clean_param($value, PARAM_CLEAN);\r
-                       }\r
-               } else {\r
-                       $responsevalue = optional_param($responsefield, '');\r
-               }\r
-               if (is_array($responsevalue)) {\r
-                       // incomplete jquiz multi-select\r
-                       $responsevalues = $responsevalue;\r
-                       $responsevalue = implode('+', $responsevalue);\r
-               } else {\r
-                       $responsevalues = explode('+', $responsevalue);\r
-               }\r
-\r
-               // initialize $response object\r
-               $response = new stdClass();\r
-               $response->correct = array();\r
-               $response->wrong   = array();\r
-               $response->ignored = array();\r
-               $response->clues  = 0;\r
-               $response->hints  = 0;\r
-               $response->checks = 0;\r
-               $response->score  = 0;\r
-               $response->weighting = 0;\r
-\r
-               // create another empty object to hold all previous responses (from database)\r
-               $oldresponse = new stdClass();\r
-               $vars = get_object_vars($response);\r
-               foreach($vars as $name=>$value) {\r
-                       $oldresponse->$name = $value;\r
-               }\r
-\r
-               foreach ($buttons as $button) {\r
-                       if (($field = "q{$q}_{$button}_button") && isset($_POST[$field])) {\r
-                               $value = optional_param($field, '', PARAM_RAW);\r
-                               if (!empty($value)) {\r
-                                       $response->$button++;\r
-                               }\r
-                       }\r
-               }\r
-\r
-               // loop through possible answers to this question\r
-               $firstcorrectvalue = '';\r
-               $percents = array();\r
-               $a = 0;\r
-               while (($valuefield="q{$q}_a{$a}_text") && isset($_POST[$valuefield])) {\r
-                       $value = optional_param($valuefield, '', PARAM_RAW);\r
-\r
-                       if (($percentfield="q{$q}_a{$a}_percent") && isset($_POST[$percentfield])) {\r
-                               $percent = optional_param($percentfield, 0, PARAM_INT);\r
-                               if ($percent) {\r
-                                       $percents[$value] = $percent;\r
-                               }\r
-                       }\r
-\r
-                       if (($correctfield="q{$q}_a{$a}_correct") && isset($_POST[$correctfield])) {\r
-                               $correct = optional_param($correctfield, 0, PARAM_INT);\r
-                       } else {\r
-                               $correct = false;\r
-                       }\r
-\r
-                       if ($correct && empty($firstcorrectvalue)) {\r
-                               $firstcorrectvalue = $value;\r
-                       }\r
-\r
-                       if ($is_jquiz_multiselect) {\r
-                               $selected = in_array($value, $responsevalues);\r
-                               if ($correct) {\r
-                                       $response->correct[] = $value;\r
-                                       if (empty($selected)) {\r
-                                               $response->wrong[] = true;\r
-                                       }\r
-                               } else {\r
-                                       if ($selected) {\r
-                                               $response->wrong[] = true;\r
-                                       }\r
-                               }\r
-                       } else {\r
-                               // single answer only required\r
-                               if ($responsevalue==$value) {\r
-                                       if ($correct) {\r
-                                               $response->correct[] = $value;\r
-                                       } else {\r
-                                               $response->wrong[] = $value;\r
-                                       }\r
-                               } else {\r
-                                       $response->ignored[] = $value;\r
-                               }\r
-                       }\r
-                       $a++;\r
-               }\r
-\r
-               // number of answers for this question\r
-               $a_max = $a;\r
-\r
-               if ($is_jquiz_multiselect) {\r
-                       if (empty($response->wrong) && count($responsevalues)==count($response->correct)) {\r
-                               $response->wrong = array();\r
-                               $response->correct = array($responsevalue);\r
-                       } else {\r
-                               $response->correct = array();\r
-                               $response->wrong = array($responsevalue);\r
-                       }\r
-               } else {\r
-                       // if response did not match any answer, then this response is wrong\r
-                       if (empty($response->correct) && empty($response->wrong)) {\r
-                               $response->wrong[] = $responsevalue;\r
-                       }\r
-               }\r
-\r
-               // if this question has not been answered correctly, quiz is still in progress\r
-               if (empty($response->correct)) {\r
-\r
-                       if (isset($_POST["q{$q}_ShowAnswers_button"])) {\r
-                                       $_POST[$responsefield] = $firstcorrectvalue;\r
-                       } else {\r
-                               $attempt->status = HOTPOT_STATUS_INPROGRESS;\r
-\r
-                               if (isset($_POST["q{$q}_Hint_button"])) {\r
-                                       // a particular hint button in JQuiz shortanswer\r
-                                       $_POST['HintButton'] = true;\r
-                               }\r
-\r
-                               // give a hint, if necessary\r
-                               if (isset($_POST['HintButton']) && $firstcorrectvalue) {\r
-\r
-                                       // make sure we only come through here once\r
-                                       unset($_POST['HintButton']);\r
-\r
-                                       $correctlen = strlen($firstcorrectvalue);\r
-                                       $responselen = strlen($responsevalue);\r
-\r
-                                       // check how many letters are the same\r
-                                       $i = 0;\r
-                                       while ($i<$responselen && $i<$correctlen && $responsevalue{$i}==$firstcorrectvalue{$i}) {\r
-                                               $i++;\r
-                                       }\r
-\r
-                                       if ($i<$responselen) {\r
-                                               // remove incorrect characters on the end of the response\r
-                                               $responsevalue = substr($responsevalue, 0, $i);\r
-                                       }\r
-                                       if ($i<$correctlen) {\r
-                                               // append next correct letter\r
-                                               $responsevalue .= $firstcorrectvalue{$i};\r
-                                       }\r
-                                       $_POST[$responsefield] = $responsevalue;\r
-                                       $response->hints++;\r
-                               } // end if hint\r
-                       }\r
-               } // end if not correct\r
-\r
-               // get clue text, if any\r
-               if (($field="q{$q}_clue") && isset($_POST[$field])) {\r
-                       $response->clue_text = optional_param($field, '', PARAM_RAW);\r
-               }\r
-\r
-               // get question name\r
-               $qq = sprintf('%02d', $q); // (a padded, two-digit version of $q)\r
-               if (($field="q{$q}_name") && isset($_POST[$field])) {\r
-                       $questionname = optional_param($field, '',  PARAM_RAW);\r
-                       $questionname = strip_tags($questionname);\r
-               } else {\r
-                       $questionname = $qq;\r
-               }\r
-\r
-               // get previous responses to this question (if any)\r
-               $records = get_records_sql("\r
-                       SELECT\r
-                               r.*\r
-                       FROM\r
-                               {$CFG->prefix}hotpot_attempts AS a,\r
-                               {$CFG->prefix}hotpot_questions AS q,\r
-                               {$CFG->prefix}hotpot_responses AS r\r
-                       WHERE\r
-                               a.clickreportid = $attempt->clickreportid AND\r
-                               a.id = r.attempt AND\r
-                               r.question = q.id AND\r
-                               q.name = '$questionname' AND\r
-                               q.hotpot = $attempt->hotpot\r
-                       ORDER BY\r
-                               a.timefinish\r
-               ");\r
-\r
-               if ($records) {\r
-                       foreach ($records as $record) {\r
-                               foreach ($buttons as $button) {\r
-                                       $oldresponse->$button = max($oldresponse->$button, $record->$button);\r
-                               }\r
-                               foreach ($textfields as $field) {\r
-                                       if ($record->$field && ($field=='correct' || $field=='wrong')) {\r
-                                               $values = explode(',', hotpot_strings($record->$field));\r
-                                               $oldresponse->$field = array_merge($oldresponse->$field, $values);\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-\r
-               // remove "correct" and "wrong" values from "ignored" values\r
-               $response->ignored = array_diff($response->ignored, \r
-                       $response->correct, $response->wrong, $oldresponse->correct, $oldresponse->wrong\r
-               );\r
-\r
-               foreach ($buttons as $button) {\r
-                       $response->$button += $oldresponse->$button;\r
-               }\r
-\r
-               $value_has_changed = false;\r
-               foreach ($textfields as $field) {\r
-                       $response->$field = array_merge($oldresponse->$field, $response->$field);\r
-                       $response->$field = array_unique($response->$field);\r
-                       $response->$field  = implode(',', $response->$field);\r
-\r
-                       if ($field=='correct' || $field=='wrong') {\r
-                               $array = $oldresponse->$field;\r
-                               $array = array_unique($array);\r
-                               $oldresponse->$field  = implode(',', $array);\r
-                               if ($response->$field<>$oldresponse->$field) {\r
-                                       $value_has_changed = true;\r
-                               }\r
-                       }\r
-               }\r
-               if ($value_has_changed) {\r
-                       $response->checks++;\r
-               }\r
-\r
-               // $response now holds amalgamation of all responses so far to this question\r
-\r
-               // set question score and weighting\r
-               if ($response->correct) {\r
-                       switch ($quiztype) {\r
-                               case HOTPOT_JCB:\r
-                                       break;\r
-                               case HOTPOT_JCLOZE:\r
-                                       $strlen = strlen($response->correct);\r
-                                       $response->score = 100*($strlen-($response->checks-1))/$strlen;\r
-                                       $attempt->score += $response->score;\r
-                                       break;\r
-                               case HOTPOT_JCROSS:\r
-                                       break;\r
-                               case HOTPOT_JMATCH:\r
-                                       break;\r
-                               case HOTPOT_JMIX:\r
-                                       break;\r
-                               case HOTPOT_JQUIZ:\r
-                                       switch ($questiontype) {\r
-                                               case HOTPOT_JQUIZ_MULTICHOICE:\r
-                                                       $wrong = explode(',', $response->wrong);\r
-                                                       foreach ($wrong as $value) {\r
-                                                               if (isset($percents[$value])) {\r
-                                                                       $percent = $percents[$value];\r
-                                                               } else {\r
-                                                                       $percent = 0;\r
-                                                               }\r
-                                                       }\r
-                                               case HOTPOT_JQUIZ_SHORTANSWER:\r
-                                                       $strlen = strlen($response->correct);\r
-                                                       $response->score = 100*($strlen-($response->checks-1))/$strlen;\r
-                                                       break;\r
-                                               case HOTPOT_JQUIZ_MULTISELECT:\r
-                                                       if (isset($percents[$response->correct])) {\r
-                                                               $percent = $percents[$response->correct];\r
-                                                       } else {\r
-                                                               $percent = 0;\r
-                                                       }\r
-                                                       if ($a_max>0 && $response->checks>0 && $a_max>$response->checks) {\r
-                                                               $response->score = $percent*($a_max-($response->checks-1))/$a_max;\r
-                                                       }\r
-                                                       break;\r
-                                       }\r
-                                       $attempt->score += $response->score;\r
-                                       break;\r
-                       }\r
-               }\r
-\r
-               $fieldname = $HOTPOT_QUIZTYPE[$quiztype]."_q{$qq}_name";\r
-               $attempt->details .= "<field><fieldname>$fieldname</fieldname><fielddata>$questionname</fielddata></field>";\r
-\r
-               // encode $response fields as XML\r
-               $vars = get_object_vars($response);\r
-               foreach($vars as $name=>$value) {\r
-                       if (!empty($value)) {\r
-                               $fieldname = $HOTPOT_QUIZTYPE[$quiztype]."_q{$qq}_{$name}";\r
-                               $attempt->details .= "<field><fieldname>$fieldname</fieldname><fielddata>$value</fielddata></field>";\r
-                       }\r
-               }\r
-\r
-               $q++;\r
-       } // end main loop through $q(uestions)\r
-\r
-       // set attempt score\r
-       if ($q>0) {\r
-               switch ($quiztype) {\r
-                       case HOTPOT_JCB:\r
-                               break;\r
-                       case HOTPOT_JCLOZE:\r
-                               $attempt->score = floor($attempt->score / $q);\r
-                               break;\r
-                       case HOTPOT_JCROSS:\r
-                               break;\r
-                       case HOTPOT_JMATCH:\r
-                               break;\r
-                       case HOTPOT_JMIX:\r
-                               break;\r
-                       case HOTPOT_JQUIZ:\r
-                               break;\r
-               }\r
-       }\r
-\r
-       if ($attempt->details) {\r
-               $attempt->details = '<?xml version="1.0"?><hpjsresult><fields>'.$attempt->details.'</fields></hpjsresult>';\r
-       }\r
-\r
-//     print "forcing status to in progress ..<br>\n";\r
-//     $attempt->status = HOTPOT_STATUS_INPROGRESS;\r
-}\r
-\r
-?>
\ No newline at end of file
+<?php // $Id$
+       require_once("../../config.php");
+       require_once("lib.php");
+
+       $attemptid = required_param("attemptid");
+
+       // get attempt, hotpot, course and course_module records
+       if (! $attempt = get_record("hotpot_attempts", "id", $attemptid)) {
+               error("Hot Potatoes attempt record $attemptid could not be accessed: ".$db->ErrorMsg());
+       }
+       if ($attempt->userid != $USER->id) {
+               error("User ID is incorrect");
+       }
+       if (! $hotpot = get_record("hotpot", "id", $attempt->hotpot)) {
+               error("Hot Potatoes ID is incorrect (attempt id = $attempt->id)");
+       }
+       if (! $course = get_record("course", "id", $hotpot->course)) {
+               error("Course ID is incorrect (hotpot id = $hotpot->id)");
+       }
+       if (! $cm = get_coursemodule_from_instance("hotpot", $hotpot->id, $course->id)) {
+               error("Course Module ID is incorrect");
+       }
+
+       // make sure this user is enrolled in this course
+       require_login($course->id);
+
+       $next_url = "$CFG->wwwroot/course/view.php?id=$course->id";
+       $time = time();
+
+       // update attempt record fields using incoming data
+       $attempt->score = optional_param('mark', NULL, PARAM_INT);
+       $attempt->status = optional_param('status', NULL, PARAM_INT);
+       $attempt->details = optional_param('detail', NULL, PARAM_RAW);
+       $attempt->endtime = optional_param('endtime', NULL, PARAM_ALPHA);
+       $attempt->starttime = optional_param('starttime', NULL, PARAM_ALPHA);
+       $attempt->timefinish = $time;
+
+       // convert times, if necessary
+       if (empty($attempt->starttime)) {
+               $attempt->starttime = 0;
+       } else {
+                $attempt->starttime = strtotime($attempt->starttime);
+       }
+       if (empty($attempt->endtime)) {
+               $attempt->endtime = 0;
+       } else {
+                $attempt->endtime = strtotime($attempt->endtime);
+       }
+
+       // set clickreportid, (for click reporting)
+       $attempt->clickreportid = $attempt->id;
+
+       $quiztype = optional_param('quiztype', 0, PARAM_INT);
+
+       if (empty($attempt->details)) {
+               hotpot_set_attempt_details($attempt);
+               $javascript_is_off = true;
+       } else {
+               $javascript_is_off = false;
+       }
+
+       if (empty($attempt->status)) {
+               if (empty($attempt->endtime)) {
+                       $attempt->status = HOTPOT_STATUS_INPROGRESS;
+               } else {
+                       $attempt->status = HOTPOT_STATUS_COMPLETED;
+               }
+       }
+
+       // check if this is the second (or subsequent) click
+       if (get_field("hotpot_attempts", "timefinish", "id", $attempt->id)) {
+
+               if ($hotpot->clickreporting==HOTPOT_YES) {
+                       // add attempt record for each form submission
+                       // records are linked via the "clickreportid" field
+
+                       // update status in previous records in this group
+                       set_field("hotpot_attempts", "status", $attempt->status, "clickreportid", $attempt->clickreportid);
+
+                       // add new attempt record
+                       unset ($attempt->id);
+                       $attempt->id = insert_record("hotpot_attempts", $attempt);
+
+                       if (empty($attempt->id)) {
+                               error("Could not insert attempt record: ".$db->ErrorMsg(), $next_url);
+                       }
+
+                       // add attempt details record, if necessary
+                       if (!empty($attempt->details)) {
+                               unset($details);
+                               $details->attempt = $attempt->id;
+                               $details->details = $attempt->details;
+                               if (! insert_record("hotpot_details", $details, false)) {
+                                       error("Could not insert attempt details record: ".$db->ErrorMsg(), $next_url);
+                               }
+                       }
+               } else {
+                       // remove previous responses for this attempt, if required
+                       // (N.B. this does NOT remove the attempt record, just the responses)
+                       delete_records("hotpot_responses", "attempt", $attempt->id);
+               }
+       }
+
+       // remove slashes added by lib/setup.php
+       $attempt->details = stripslashes($attempt->details);
+
+       // add details of this attempt
+       hotpot_add_attempt_details($attempt);
+
+       // add slashes again, so the details can be added to the database
+       $attempt->details = addslashes($attempt->details);
+
+       // update the attempt record
+       if (! update_record("hotpot_attempts", $attempt)) {
+               error("Could not update attempt record: ".$db->ErrorMsg(), $next_url);
+       }
+
+       // get previous attempt details record, if any
+       $details_exist = record_exists("hotpot_details", "attempt", $attempt->id);
+
+       // delete/update/add the attempt details record
+       if (empty($attempt->details)) {
+               if ($details_exist) {
+                       delete_records("hotpot_details", "attempt", $attempt->id);
+               }
+       } else {
+               if ($details_exist) {
+                       set_field("hotpot_details", "details", $attempt->details, "attempt", $attempt->id);
+               } else {
+                       unset($details);
+                       $details->attempt = $attempt->id;
+                       $details->details = $attempt->details;
+                       if (! insert_record("hotpot_details", $details)) {
+                               error("Could not insert attempt details record: ".$db->ErrorMsg(), $next_url);
+                       }
+               }
+       }
+
+       if ($attempt->status==HOTPOT_STATUS_INPROGRESS) {
+               if ($javascript_is_off) {
+                       // regenerate HTML page
+                       define('HOTPOT_FIRST_ATTEMPT', false);
+                       include ("$CFG->hotpotroot/view.php");
+               } else {
+                       // continue without reloading the page
+                       header("Status: 204");
+                       header("HTTP/1.0 204 No Response");
+               }
+
+       } else { // quiz is finished
+
+               add_to_log($course->id, "hotpot", "submit", "review.php?id=$cm->id&attempt=$attempt->id", "$hotpot->id", "$cm->id");
+
+               if ($hotpot->shownextquiz==HOTPOT_YES) {
+                       if (is_numeric($next_cm = hotpot_get_next_cm($cm))) {
+                               $next_url = "$CFG->wwwroot/mod/hotpot/view.php?id=$next_cm";
+                       }
+               }
+
+               // redirect to the next quiz or the course page 
+               redirect($next_url, get_string('resultssaved', 'hotpot'));
+       }
+
+// =================
+//     functions
+// =================
+
+function hotpot_get_next_cm(&$cm) {
+       // gets the next module in this section of the course
+       // that is the same type of module as the current module
+
+       $next_mod = false;
+
+       // get a list of $ids of modules in this section
+       if ($ids = get_field('course_sections', 'sequence', 'id', $cm->section)) {
+
+               $found = false;
+               $ids = explode(',', $ids);
+               foreach ($ids as $id) {
+                       if ($found && ($cm->module==get_field('course_modules', 'module', 'id', $id))) {
+                               $next_mod = $id;
+                               break;
+                       } else if ($cm->id==$id) {
+                               $found = true;
+                       }
+               }
+       }
+       return $next_mod;
+}
+function hotpot_set_attempt_details(&$attempt) {
+       global $CFG, $HOTPOT_QUIZTYPE;
+
+       // optional_param('showallquestions', 0, PARAM_INT);
+
+       $attempt->details = '';
+       $attempt->score = 0;
+       $attempt->status = HOTPOT_STATUS_COMPLETED;
+
+       $buttons = array('clues', 'hints', 'checks');
+       $textfields = array('correct', 'wrong', 'ignored');
+
+       $ok = false;
+       $quiztype = optional_param('quiztype', 0, PARAM_ALPHANUM);
+       if ($quiztype) {
+               if (is_numeric($quiztype)) {
+                       $ok = array_key_exists($quiztype, $HOTPOT_QUIZTYPE);
+               } else {
+                       $quiztype = array_search($quiztype, $HOTPOT_QUIZTYPE);
+                       $ok = is_numeric($quiztype);
+               }
+       }
+       if (!$ok) {
+               return;
+               // error('Quiz type is missing or invalid');
+               // error(get_string('error_invalidquiztype', 'hotpot'));
+               //
+               // script finishes here if quiztype is invalid
+               //
+       }
+
+       // special flag to detect jquiz multiselect
+       $is_jquiz_multiselect = false;
+
+       // set maximum question number
+       $q_max = 0;;
+       do {
+               switch ($quiztype) {
+                       case HOTPOT_JCLOZE:
+                       case HOTPOT_JQUIZ:
+                               $field="q{$q_max}_a0_text";
+                               break;
+                       case HOTPOT_JCB:
+                       case HOTPOT_JCROSS:
+                       case HOTPOT_JMATCH:
+                       case HOTPOT_JMIX:
+                       default:
+                               $field = '';
+               }
+       } while ($field && isset($_POST[$field]) && ($q_max = $q_max+1));
+
+       // check JQuiz navigation buttons
+       switch (true) {
+               case isset($_POST['ShowAllQuestionsButton']):
+                       $_POST['ShowAllQuestions'] = 1;
+                       break;
+               case isset($_POST['ShowOneByOneButton']):
+                       $_POST['ShowAllQuestions'] = 0;
+                       break;
+               case isset($_POST['PrevQButton']):
+                       $_POST['ThisQuestion']--;
+                       break;
+               case isset($_POST['NextQButton']):
+                       $_POST['ThisQuestion']++;
+                       break;
+       }
+
+       $q = 0;
+       while ($q<$q_max) {
+               $responsefield="q{$q}";
+
+               $questiontype = optional_param("{$responsefield}_questiontype", 0, PARAM_INT);
+               $is_jquiz_multiselect = ($quiztype==HOTPOT_JQUIZ && $questiontype==HOTPOT_JQUIZ_MULTISELECT);
+
+               if (isset($_POST[$responsefield]) && is_array($_POST[$responsefield])) {
+                       $responsevalue = array();
+                       foreach ($_POST[$responsefield] as $key=>$value) {
+                               $responsevalue[$key] = clean_param($value, PARAM_CLEAN);
+                       }
+               } else {
+                       $responsevalue = optional_param($responsefield, '');
+               }
+               if (is_array($responsevalue)) {
+                       // incomplete jquiz multi-select
+                       $responsevalues = $responsevalue;
+                       $responsevalue = implode('+', $responsevalue);
+               } else {
+                       $responsevalues = explode('+', $responsevalue);
+               }
+
+               // initialize $response object
+               $response = new stdClass();
+               $response->correct = array();
+               $response->wrong   = array();
+               $response->ignored = array();
+               $response->clues  = 0;
+               $response->hints  = 0;
+               $response->checks = 0;
+               $response->score  = 0;
+               $response->weighting = 0;
+
+               // create another empty object to hold all previous responses (from database)
+               $oldresponse = new stdClass();
+               $vars = get_object_vars($response);
+               foreach($vars as $name=>$value) {
+                       $oldresponse->$name = $value;
+               }
+
+               foreach ($buttons as $button) {
+                       if (($field = "q{$q}_{$button}_button") && isset($_POST[$field])) {
+                               $value = optional_param($field, '', PARAM_RAW);
+                               if (!empty($value)) {
+                                       $response->$button++;
+                               }
+                       }
+               }
+
+               // loop through possible answers to this question
+               $firstcorrectvalue = '';
+               $percents = array();
+               $a = 0;
+               while (($valuefield="q{$q}_a{$a}_text") && isset($_POST[$valuefield])) {
+                       $value = optional_param($valuefield, '', PARAM_RAW);
+
+                       if (($percentfield="q{$q}_a{$a}_percent") && isset($_POST[$percentfield])) {
+                               $percent = optional_param($percentfield, 0, PARAM_INT);
+                               if ($percent) {
+                                       $percents[$value] = $percent;
+                               }
+                       }
+
+                       if (($correctfield="q{$q}_a{$a}_correct") && isset($_POST[$correctfield])) {
+                               $correct = optional_param($correctfield, 0, PARAM_INT);
+                       } else {
+                               $correct = false;
+                       }
+
+                       if ($correct && empty($firstcorrectvalue)) {
+                               $firstcorrectvalue = $value;
+                       }
+
+                       if ($is_jquiz_multiselect) {
+                               $selected = in_array($value, $responsevalues);
+                               if ($correct) {
+                                       $response->correct[] = $value;
+                                       if (empty($selected)) {
+                                               $response->wrong[] = true;
+                                       }
+                               } else {
+                                       if ($selected) {
+                                               $response->wrong[] = true;
+                                       }
+                               }
+                       } else {
+                               // single answer only required
+                               if ($responsevalue==$value) {
+                                       if ($correct) {
+                                               $response->correct[] = $value;
+                                       } else {
+                                               $response->wrong[] = $value;
+                                       }
+                               } else {
+                                       $response->ignored[] = $value;
+                               }
+                       }
+                       $a++;
+               }
+
+               // number of answers for this question
+               $a_max = $a;
+
+               if ($is_jquiz_multiselect) {
+                       if (empty($response->wrong) && count($responsevalues)==count($response->correct)) {
+                               $response->wrong = array();
+                               $response->correct = array($responsevalue);
+                       } else {
+                               $response->correct = array();
+                               $response->wrong = array($responsevalue);
+                       }
+               } else {
+                       // if response did not match any answer, then this response is wrong
+                       if (empty($response->correct) && empty($response->wrong)) {
+                               $response->wrong[] = $responsevalue;
+                       }
+               }
+
+               // if this question has not been answered correctly, quiz is still in progress
+               if (empty($response->correct)) {
+
+                       if (isset($_POST["q{$q}_ShowAnswers_button"])) {
+                                       $_POST[$responsefield] = $firstcorrectvalue;
+                       } else {
+                               $attempt->status = HOTPOT_STATUS_INPROGRESS;
+
+                               if (isset($_POST["q{$q}_Hint_button"])) {
+                                       // a particular hint button in JQuiz shortanswer
+                                       $_POST['HintButton'] = true;
+                               }
+
+                               // give a hint, if necessary
+                               if (isset($_POST['HintButton']) && $firstcorrectvalue) {
+
+                                       // make sure we only come through here once
+                                       unset($_POST['HintButton']);
+
+                                       $correctlen = strlen($firstcorrectvalue);
+                                       $responselen = strlen($responsevalue);
+
+                                       // check how many letters are the same
+                                       $i = 0;
+                                       while ($i<$responselen && $i<$correctlen && $responsevalue{$i}==$firstcorrectvalue{$i}) {
+                                               $i++;
+                                       }
+
+                                       if ($i<$responselen) {
+                                               // remove incorrect characters on the end of the response
+                                               $responsevalue = substr($responsevalue, 0, $i);
+                                       }
+                                       if ($i<$correctlen) {
+                                               // append next correct letter
+                                               $responsevalue .= $firstcorrectvalue{$i};
+                                       }
+                                       $_POST[$responsefield] = $responsevalue;
+                                       $response->hints++;
+                               } // end if hint
+                       }
+               } // end if not correct
+
+               // get clue text, if any
+               if (($field="q{$q}_clue") && isset($_POST[$field])) {
+                       $response->clue_text = optional_param($field, '', PARAM_RAW);
+               }
+
+               // get question name
+               $qq = sprintf('%02d', $q); // (a padded, two-digit version of $q)
+               if (($field="q{$q}_name") && isset($_POST[$field])) {
+                       $questionname = optional_param($field, '',  PARAM_RAW);
+                       $questionname = strip_tags($questionname);
+               } else {
+                       $questionname = $qq;
+               }
+
+               // get previous responses to this question (if any)
+               $records = get_records_sql("
+                       SELECT
+                               r.*
+                       FROM
+                               {$CFG->prefix}hotpot_attempts AS a,
+                               {$CFG->prefix}hotpot_questions AS q,
+                               {$CFG->prefix}hotpot_responses AS r
+                       WHERE
+                               a.clickreportid = $attempt->clickreportid AND
+                               a.id = r.attempt AND
+                               r.question = q.id AND
+                               q.name = '$questionname' AND
+                               q.hotpot = $attempt->hotpot
+                       ORDER BY
+                               a.timefinish
+               ");
+
+               if ($records) {
+                       foreach ($records as $record) {
+                               foreach ($buttons as $button) {
+                                       $oldresponse->$button = max($oldresponse->$button, $record->$button);
+                               }
+                               foreach ($textfields as $field) {
+                                       if ($record->$field && ($field=='correct' || $field=='wrong')) {
+                                               $values = explode(',', hotpot_strings($record->$field));
+                                               $oldresponse->$field = array_merge($oldresponse->$field, $values);
+                                       }
+                               }
+                       }
+               }
+
+               // remove "correct" and "wrong" values from "ignored" values
+               $response->ignored = array_diff($response->ignored, 
+                       $response->correct, $response->wrong, $oldresponse->correct, $oldresponse->wrong
+               );
+
+               foreach ($buttons as $button) {
+                       $response->$button += $oldresponse->$button;
+               }
+
+               $value_has_changed = false;
+               foreach ($textfields as $field) {
+                       $response->$field = array_merge($oldresponse->$field, $response->$field);
+                       $response->$field = array_unique($response->$field);
+                       $response->$field  = implode(',', $response->$field);
+
+                       if ($field=='correct' || $field=='wrong') {
+                               $array = $oldresponse->$field;
+                               $array = array_unique($array);
+                               $oldresponse->$field  = implode(',', $array);
+                               if ($response->$field<>$oldresponse->$field) {
+                                       $value_has_changed = true;
+                               }
+                       }
+               }
+               if ($value_has_changed) {
+                       $response->checks++;
+               }
+
+               // $response now holds amalgamation of all responses so far to this question
+
+               // set question score and weighting
+               if ($response->correct) {
+                       switch ($quiztype) {
+                               case HOTPOT_JCB:
+                                       break;
+                               case HOTPOT_JCLOZE:
+                                       $strlen = strlen($response->correct);
+                                       $response->score = 100*($strlen-($response->checks-1))/$strlen;
+                                       $attempt->score += $response->score;
+                                       break;
+                               case HOTPOT_JCROSS:
+                                       break;
+                               case HOTPOT_JMATCH:
+                                       break;
+                               case HOTPOT_JMIX:
+                                       break;
+                               case HOTPOT_JQUIZ:
+                                       switch ($questiontype) {
+                                               case HOTPOT_JQUIZ_MULTICHOICE:
+                                                       $wrong = explode(',', $response->wrong);
+                                                       foreach ($wrong as $value) {
+                                                               if (isset($percents[$value])) {
+                                                                       $percent = $percents[$value];
+                                                               } else {
+                                                                       $percent = 0;
+                                                               }
+                                                       }
+                                               case HOTPOT_JQUIZ_SHORTANSWER:
+                                                       $strlen = strlen($response->correct);
+                                                       $response->score = 100*($strlen-($response->checks-1))/$strlen;
+                                                       break;
+                                               case HOTPOT_JQUIZ_MULTISELECT:
+                                                       if (isset($percents[$response->correct])) {
+                                                               $percent = $percents[$response->correct];
+                                                       } else {
+                                                               $percent = 0;
+                                                       }
+                                                       if ($a_max>0 && $response->checks>0 && $a_max>$response->checks) {
+                                                               $response->score = $percent*($a_max-($response->checks-1))/$a_max;
+                                                       }
+                                                       break;
+                                       }
+                                       $attempt->score += $response->score;
+                                       break;
+                       }
+               }
+
+               $fieldname = $HOTPOT_QUIZTYPE[$quiztype]."_q{$qq}_name";
+               $attempt->details .= "<field><fieldname>$fieldname</fieldname><fielddata>$questionname</fielddata></field>";
+
+               // encode $response fields as XML
+               $vars = get_object_vars($response);
+               foreach($vars as $name=>$value) {
+                       if (!empty($value)) {
+                               $fieldname = $HOTPOT_QUIZTYPE[$quiztype]."_q{$qq}_{$name}";
+                               $attempt->details .= "<field><fieldname>$fieldname</fieldname><fielddata>$value</fielddata></field>";
+                       }
+               }
+
+               $q++;
+       } // end main loop through $q(uestions)
+
+       // set attempt score
+       if ($q>0) {
+               switch ($quiztype) {
+                       case HOTPOT_JCB:
+                               break;
+                       case HOTPOT_JCLOZE:
+                               $attempt->score = floor($attempt->score / $q);
+                               break;
+                       case HOTPOT_JCROSS:
+                               break;
+                       case HOTPOT_JMATCH:
+                               break;
+                       case HOTPOT_JMIX:
+                               break;
+                       case HOTPOT_JQUIZ:
+                               break;
+               }
+       }
+
+       if ($attempt->details) {
+               $attempt->details = '<?xml version="1.0"?><hpjsresult><fields>'.$attempt->details.'</fields></hpjsresult>';
+       }
+
+//     print "forcing status to in progress ..<br>\n";
+//     $attempt->status = HOTPOT_STATUS_INPROGRESS;
+}
+
+?>
index cd3373848b1e36ee2fd5f9abcfc76365215516b3..8e678f78c60f2a70475975b7c5a48f0869456aa8 100644 (file)
@@ -1,4 +1,4 @@
-<?php 
+<?php // $Id$
     if (empty($CFG->hotpot_initialdisable)) {
         if (!count_records('hotpot')) {
             set_field('modules', 'visible', 0, 'name', 'hotpot');  // Disable it by default
index 70b0dc8df1f9bb8e3284a55a0cefc90dd779ecbd..9d959d11fd633923a0c7c8e45a91d84119836f9a 100644 (file)
-<?PHP // $Id$\r
-       /// This page prints a hotpot quiz\r
-       if (defined('HOTPOT_FIRST_ATTEMPT') && HOTPOT_FIRST_ATTEMPT==false) {\r
-               // this script is being included (by attempt.php)\r
-       } else {\r
-               // this script is being called directly from the browser\r
-               define('HOTPOT_FIRST_ATTEMPT', true);\r
-               require_once("../../config.php");\r
-               require_once("lib.php");\r
-\r
-               $id = optional_param("id"); // Course Module ID, or\r
-               $hp = optional_param("hp"); // hotpot ID\r
-\r
-               if ($id) {\r
-                       if (! $cm = get_record("course_modules", "id", $id)) {\r
-                               error("Course Module ID was incorrect");\r
-                       }\r
-                       if (! $course = get_record("course", "id", $cm->course)) {\r
-                               error("Course is misconfigured");\r
-                       }\r
-                       if (! $hotpot = get_record("hotpot", "id", $cm->instance)) {\r
-                               error("Course module is incorrect");\r
-                       }\r
-\r
-               } else {\r
-                       if (! $hotpot = get_record("hotpot", "id", $hp)) {\r
-                               error("Course module is incorrect");\r
-                       }\r
-                       if (! $course = get_record("course", "id", $hotpot->course)) {\r
-                               error("Course is misconfigured");\r
-                       }\r
-                       if (! $cm = get_coursemodule_from_instance("hotpot", $hotpot->id, $course->id)) {\r
-                               error("Course Module ID was incorrect");\r
-                       }\r
-               }\r
-               require_login($course->id);\r
-       }\r
-       // set nextpage (for error messages)\r
-       $nextpage = "$CFG->wwwroot/course/view.php?id=$course->id";\r
-       // header strings\r
-       $title = strip_tags($course->shortname.': '.$hotpot->name);\r
-       $heading = "$course->fullname";\r
-       $target = empty($CFG->framename) ? '' : ' target="'.$CFG->framename.'"'; \r
-       $navigation = '<a'.$target.' href="'.$CFG->wwwroot.'/mod/hotpot/index.php?id='.$course->id.'">'.get_string("modulenameplural", "hotpot")."</a> -> $hotpot->name";\r
-       if ($course->category) {\r
-               $navigation = '<a'.$target.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.$course->shortname.'</a> -> '.$navigation;\r
-       }\r
-       $button = update_module_button($cm->id, $course->id, get_string("modulename", "hotpot").'" style="font-size:0.75em;');\r
-       $loggedinas = '<span class="logininfo">'.user_login_string($course, $USER).'</span>';\r
-       $time = time();\r
-       $hppassword = optional_param('hppassword');\r
-       if (HOTPOT_FIRST_ATTEMPT && !isteacher($course->id)) {\r
-               // check this quiz is available to this student\r
-               // error message, if quiz is unavailable\r
-               $error = '';\r
-               // check quiz is visible\r
-               if (!hotpot_is_visible($cm)) {\r
-                       $error = get_string("activityiscurrentlyhidden");\r
-               // check network address\r
-               } else if ($hotpot->subnet && !address_in_subnet($_SERVER['REMOTE_ADDR'], $hotpot->subnet)) {\r
-                       $error = get_string("subneterror", "quiz");\r
-               // check number of attempts\r
-               } else if ($hotpot->attempts && $hotpot->attempts <= count_records('hotpot_attempts', 'hotpot', $hotpot->id, 'userid', $USER->id)) {\r
-                       $error = get_string("nomoreattempts", "quiz");\r
-               // get password\r
-               } else if ($hotpot->password && empty($hppassword)) {\r
-                       print_header($title, $heading, $navigation, "", "", true, $button, $loggedinas, false);\r
-                       print_heading($hotpot->name);\r
-                       $boxalign = 'center';\r
-                       $boxwidth = 500;\r
-                       if (trim(strip_tags($hotpot->summary))) {\r
-                               print_simple_box_start($boxalign, $boxwidth);\r
-                               print '<div align="center">'.format_text($hotpot->summary)."</div>\n";\r
-                               print_simple_box_end();\r
-                               print "<br />\n";\r
-                       }\r
-                       print '<form name="passwordform" method="post" action="view.php?id='.$cm->id.'">'."\n";\r
-                       print_simple_box_start($boxalign, $boxwidth);\r
-                       print '<div align="center">';\r
-                       print get_string('requirepasswordmessage', 'quiz').'<br /><br />';\r
-                       print '<b>'.get_string('password').':</b> ';\r
-                       print '<input name="hppassword" type="password" value=""> ';\r
-                       print '<input type="submit" value="'.get_string("ok").'"> ';\r
-                       print "</div>\n";\r
-                       print_simple_box_end();\r
-                       print "</form>\n";\r
-                       print_footer();\r
-                       exit;\r
-               // check password\r
-               } else if ($hotpot->password && strcmp($hotpot->password, $hppassword)) {\r
-                       $error = get_string("passworderror", "quiz");\r
-                       $nextpage = "view.php?id=$cm->id";\r
-               // check quiz is open\r
-               } else if ($hotpot->timeopen && $hotpot->timeopen > $time) {\r
-                       $error = get_string("quiznotavailable", "quiz", userdate($hotpot->timeopen))."<br />\n";\r
-               // check quiz is not closed\r
-               } else if ($hotpot->timeclose && $hotpot->timeclose < $time) {\r
-                       $error = get_string("quizclosed", "quiz", userdate($hotpot->timeclose))."<br />\n";\r
-               }\r
-               if ($error) {\r
-                       print_header($title, $heading, $navigation, "", "", true, $button, $loggedinas, false);\r
-                       notice($error, $nextpage);\r
-                       //\r
-                       // script stops here, if quiz is unavailable to student\r
-                       //\r
-               }\r
-       }\r
-       $available_msg = '';\r
-       if (!empty($hotpot->timeclose) && $hotpot->timeclose > $time) {\r
-               // quiz is available until 'timeclose'\r
-               $available_msg = get_string("quizavailable", "quiz", userdate($hotpot->timeclose))."<br />\n";\r
-       }\r
-       // open and parse the source file\r
-       if(!$hp = new hotpot_xml_quiz($hotpot)) {\r
-               error("Quiz is unavailable at the moment");\r
-       }\r
-       $get_js = optional_param('js');\r
-       $get_css = optional_param('css');\r
-       $framename = optional_param('framename');\r
-       // look for <frameset> (HP5 v5)\r
-       $frameset = '';\r
-       $frameset_tags = '';\r
-       if (preg_match_all('|<frameset([^>]*)>(.*?)</frameset>|is', $hp->html, $matches)) {\r
-               $last = count($matches[0])-1;\r
-               $frameset = $matches[2][$last];\r
-               $frameset_tags = $matches[1][$last];\r
-       }\r
-       // if HTML is being requested ...\r
-       if (empty($get_js) && empty($get_css)) {\r
-               if (empty($frameset)) { \r
-                       // HP v6\r
-                       if ($hotpot->navigation==HOTPOT_NAVIGATION_FRAME || $hotpot->navigation==HOTPOT_NAVIGATION_IFRAME) {\r
-                               $get_html = ($framename=='main') ? true : false;\r
-                       } else {\r
-                               $get_html = true;\r
-                       }\r
-               } else { \r
-                       // HP5 v5\r
-                       $get_html = empty($framename) ? true : false;\r
-               }\r
-               if ($get_html) {\r
-               \r
-                       if (HOTPOT_FIRST_ATTEMPT) {\r
-                               add_to_log($course->id, "hotpot", "view", "view.php?id=$cm->id", "$hotpot->id", "$cm->id");\r
-\r
-                               $attemptid = hotpot_add_attempt($hotpot->id);\r
-                               if (! is_numeric($attemptid)) {\r
-                                       error('Could not insert attempt record: '.$db->ErrorMsg);\r
-                               }\r
-                       }\r
-                       $hp->adjust_media_urls();\r
-                       if (empty($frameset)) {\r
-                               // HP6 v6\r
-                               switch ($hotpot->navigation) {\r
-                                       case HOTPOT_NAVIGATION_BUTTONS:\r
-                                               // do nothing (i.e. leave buttons as they are)\r
-                                               break;\r
-                                       case HOTPOT_NAVIGATION_GIVEUP:\r
-                                               $hp->insert_giveup_form($attemptid, '<!-- BeginTopNavButtons -->', '<!-- EndTopNavButtons -->');\r
-                                               break;\r
-                                       default:\r
-                                               $hp->remove_nav_buttons();\r
-                               }\r
-                               if (isset($hp->real_outputformat) && $hp->real_outputformat==HOTPOT_OUTPUTFORMAT_MOBILE) {\r
-                                       $hp->insert_submission_form($attemptid, '<!-- BeginSubmissionForm -->', '<!-- EndSubmissionForm -->', true);\r
-                               } else {\r
-                                       $hp->insert_submission_form($attemptid, '<!-- BeginSubmissionForm -->', '<!-- EndSubmissionForm -->');\r
-                               }\r
-                       } else {\r
-                               // HP5 v5\r
-                               switch ($hotpot->navigation) {\r
-                                       case HOTPOT_NAVIGATION_BUTTONS:\r
-                                               // convert URLs in nav buttons\r
-                                               break;\r
-                                       case HOTPOT_NAVIGATION_GIVEUP:\r
-                                               //      $hp->insert_giveup_form($attemptid, '<!-- BeginTopNavButtons -->', '<!-- EndTopNavButtons -->');\r
-                                               break;\r
-                                       default:\r
-                                               // remove navigation buttons\r
-                                               $hp->html = preg_replace('#NavBar\+=(.*);#', '', $hp->html);\r
-                               }\r
-                               $hp->insert_submission_form($attemptid, "var NavBar='", "';");\r
-                       }\r
-               }\r
-       }\r
-       //FEEDBACK = new Array();\r
-       //FEEDBACK[0] = ''; // url of feedback page/script\r
-       //FEEDBACK[1] = ''; // array of array('teachername', 'value');\r
-       //FEEDBACK[2] = ''; // 'student name' [formmail only]\r
-       //FEEDBACK[3] = ''; // 'student email' [formmail only]\r
-       //FEEDBACK[4] = ''; // window width\r
-       //FEEDBACK[5] = ''; // window height\r
-       //FEEDBACK[6] = ''; // 'Send a message to teacher' [prompt/button text]\r
-       //FEEDBACK[7] = ''; // 'Title'\r
-       //FEEDBACK[8] = ''; // 'Teacher'\r
-       //FEEDBACK[9] = ''; // 'Message'\r
-       //FEEDBACK[10] = ''; // 'Close this window'\r
-       $feedback = array();\r
-       switch ($hotpot->studentfeedback) {\r
-               case HOTPOT_FEEDBACK_NONE:\r
-                       // do nothing\r
-                       break;\r
-               case HOTPOT_FEEDBACK_WEBPAGE:\r
-                       if (empty($hotpot->studentfeedbackurl)) {\r
-                               $hotpot->studentfeedback = HOTPOT_FEEDBACK_NONE;\r
-                       } else {\r
-                               $feedback[0] = "'$hotpot->studentfeedbackurl'";\r
-                       }\r
-                       break;\r
-               case HOTPOT_FEEDBACK_FORMMAIL:\r
-                       $teachers = hotpot_feedback_teachers($course, $hotpot);\r
-                       if (empty($teachers) || empty($hotpot->studentfeedbackurl)) {\r
-                               $hotpot->studentfeedback = HOTPOT_FEEDBACK_NONE;\r
-                       } else {\r
-                               $feedback[0] = "'$hotpot->studentfeedbackurl'";\r
-                               $feedback[1] = $teachers;\r
-                               $feedback[2] = "'".fullname($USER)."'";\r
-                               $feedback[3] = "'".$USER->email."'";\r
-                               $feedback[4] = 500; // width\r
-                               $feedback[5] = 300; // height\r
-                       }\r
-                       break;\r
-               case HOTPOT_FEEDBACK_MOODLEFORUM:\r
-                       $module = get_record('modules', 'name', 'forum');\r
-                       $forums = get_records('forum', 'course', "$course->id");\r
-                       if (empty($module) || empty($module->visible) || empty($forums)) {\r
-                               $hotpot->studentfeedback = HOTPOT_FEEDBACK_NONE;\r
-                       } else {\r
-                               $feedback[0] = "'$CFG->wwwroot/mod/forum/index.php?id=$course->id'";\r
-                       }\r
-                       break;\r
-               case HOTPOT_FEEDBACK_MOODLEMESSAGING:\r
-                       $teachers = hotpot_feedback_teachers($course, $hotpot);\r
-                       if (empty($CFG->messaging) || empty($teachers)) {\r
-                               $hotpot->studentfeedback = HOTPOT_FEEDBACK_NONE;\r
-                       } else {\r
-                               $feedback[0] = "'$CFG->wwwroot/message/discussion.php?id='";\r
-                               $feedback[1] = $teachers;\r
-                               $feedback[4] = 400; // width\r
-                               $feedback[5] = 500; // height\r
-                       }\r
-                       break;\r
-               default:\r
-                       // do nothing\r
-       }\r
-       if ($hotpot->studentfeedback != HOTPOT_FEEDBACK_NONE) {\r
-               $feedback[6] = "'Send a message to teacher'";\r
-               $feedback[7] = "'Title'";\r
-               $feedback[8] = "'Teacher'";\r
-               $feedback[9] = "'Message'";\r
-               $feedback[10] = "'Close this window'";\r
-               $js = '';\r
-               foreach ($feedback as $i=>$str) {\r
-                       $js .= 'FEEDBACK['.$i."] = $str;\n";\r
-               }\r
-               $js = '<script type="text/javascript" language="javascript">'."<!--\n"."FEEDBACK = new Array();\n".$js."//--></script>\n";\r
-               $hp->html = preg_replace('|</head>|i', "$js</head>", $hp->html, 1);\r
-       }\r
-       // insert hot-potatoes.js\r
-       $hp->insert_script(HOTPOT_JS);\r
-       // extract first <head> tag\r
-       $head = '';\r
-       $pattern = '|<head([^>]*)>(.*?)</head>|is';\r
-       if (preg_match($pattern, $hp->html, $matches)) {\r
-               $head = $matches[2];\r
-               // remove <title>\r
-               $head = preg_replace('|<title[^>]*>(.*?)</title>|is', '', $head);\r
-       }\r
-       // extract <style> tags (and remove from $head)\r
-       $styles = '';\r
-       $pattern = '|<style([^>]*)>(.*?)</style>|is';\r
-       if (preg_match_all($pattern, $head, $matches)) {\r
-               $count = count($matches[0]);\r
-               for ($i=0; $i<$count; $i++) {\r
-                       $styles .= $matches[0][$i]."\n";\r
-                       $head = str_replace($matches[0][$i], '', $head);\r
-               }\r
-       }\r
-       // extract <script> tags (and remove from $head)\r
-       $scripts = '';\r
-       $pattern = '|<script([^>]*)>(.*?)</script>|is';\r
-       if (preg_match_all($pattern, $head, $matches)) {\r
-               $count = count($matches[0]);\r
-               for ($i=0; $i<$count; $i++) {\r
-                       $scripts .= $matches[0][$i]."\n";\r
-                       $head = str_replace($matches[0][$i], '', $head);\r
-               }\r
-       }\r
-       // extract <body> tags\r
-       $body = '';\r
-       $body_tags = '';\r
-       $footer = '</html>';\r
-       // HP6 and some HP5 (v6 and v4) \r
-       if (preg_match('|<body'.'([^>]*'.'onLoad=(["\'])(.*?)(\\2)'.'[^>]*)'.'>(.*)</body>|is', $hp->html, $matches)) {\r
-               $body = $matches[5]; // contents of first <body onload="StartUp()">...</body> block\r
-               $body_tags = $matches[1];\r
-               // workaround to ensure javascript onload routine for quiz is always executed\r
-               //      $body_tags will only be inserted into the <body ...> tag\r
-               //      if it is included in the theme/$CFG->theme/header.html,\r
-               //      so some old or modified themes may not insert $body_tags\r
-               $body .= ""\r
-               .       '<script type="text/javascript">'."\n"\r
-               .       "<!--\n"\r
-               .       "       var s = (typeof(window.onload)=='function') ? onload.toString() : '';\n"\r
-               .       "       if (s.indexOf('".$matches[3]."')<0) {\n"\r
-               .       "               if (s=='') {\n" // no previous onload\r
-               .       "                       window.onload = new Function('".$matches[3]."');\n"\r
-               .       "               } else {\n"\r
-               .       "                       window.onload_hotpot = onload;\n"\r
-               .       "                       window.onload = new Function('window.onload_hotpot();'+'".$matches[3]."');\n"\r
-               .       "               }\n"\r
-               .       "        }\n"\r
-               .       "//-->\n"\r
-               .       "</script>\n"\r
-               ;\r
-               $footer = '</body>'.$footer;\r
-       } else if ($frameset) { // HP5 v5\r
-               switch ($framename) {\r
-                       case 'top':\r
-                               print_header($title, $heading, $navigation, "", "", true, $button, $loggedinas);\r
-                               print $footer;\r
-                       break;\r
-                       default:\r
-                               // add a HotPot navigation frame at the top of the page\r
-                               //$rows = empty($CFG->resource_framesize) ? 85 : $CFG->resource_framesize;\r
-                               //$frameset = "\n\t".'<frame src="view.php?id='.$cm->id.'&framename=top" frameborder="0" name="top"></frame>'.$frameset;\r
-                               //$frameset_tags = preg_replace('|rows="(.*?)"|', 'rows="'.$rows.',\\1"', $frameset_tags);\r
-                               // put navigation into var NavBar='';\r
-                               // add form to TopFrame in "WriteFeedback" function\r
-                               // OR add form to BottomFrame in "DisplayExercise" function\r
-                               // submission form: '<!-- BeginSubmissionForm -->', '<!-- EndSubmissionForm -->'\r
-                               // give up form: '<!-- BeginTopNavButtons -->', '<!-- EndTopNavButtons -->'\r
-                               print "<html>\n";\r
-                               print "<head>\n<title>$title</title>\n$styles\n$scripts</head>\n";\r
-                               print "<frameset$frameset_tags>$frameset</frameset>\n";\r
-                               print "</html>\n";\r
-                       break;\r
-               } // end switch $framename\r
-               exit;\r
-       // other files (maybe not even a HotPots)\r
-       } else if (preg_match('|<body'.'([^>]*)'.'>(.*)</body>|is', $hp->html, $matches)) {\r
-               $body = $matches[2];\r
-               $body_tags = $matches[1];\r
-       }\r
-       // print the quiz to the browser\r
-       if ($get_js) {\r
-               print($scripts);\r
-               exit;\r
-       }\r
-       if ($get_css) {\r
-               print($styles);\r
-               exit;\r
-       }\r
-       switch ($hotpot->navigation) {\r
-               case HOTPOT_NAVIGATION_BAR:\r
-                       //update_module_button($cm->id, $course->id, $strmodulename.'" style="font-size:0.8em')\r
-                       print_header(\r
-                               $title, $heading, $navigation,\r
-                               "", $head.$styles.$scripts, true, $button, \r
-                               $loggedinas, false, $body_tags\r
-                       );\r
-                       if (!empty($available_msg)) {\r
-                               notify($available_msg);\r
-                       }\r
-                       print $body.$footer;\r
-               break;\r
-               case HOTPOT_NAVIGATION_FRAME:\r
-                       switch ($framename) {\r
-                               case 'top':\r
-                                       print_header($title, $heading, $navigation, "", "", true, $button, $loggedinas);\r
-                                       print $footer;\r
-                               break;\r
-                               case 'main':\r
-                                       if (!empty($available_msg)) {\r
-                                               $hp->insert_message('<!-- BeginTopNavButtons -->', $available_msg);\r
-                                       }\r
-                                       print $hp->html;\r
-                               break;\r
-                               default:\r
-                                       $rows = empty($CFG->resource_framesize) ? 85 : $CFG->resource_framesize;\r
-                                       print "<html>\n";\r
-                                       print "<head><title>$title</title></head>\n";\r
-                                       print "<frameset rows=$rows,*>\n";\r
-                                       print "<frame src=\"view.php?id=$cm->id&framename=top\">\n";\r
-                                       print "<frame src=\"view.php?id=$cm->id&framename=main\">\n";\r
-                                       print "</frameset>\n";\r
-                                       print "</html>\n";\r
-                               break;\r
-                       } // end switch $framename\r
-               break;\r
-               case HOTPOT_NAVIGATION_IFRAME:\r
-                       switch ($framename) {\r
-                               case 'main':\r
-                                       print $hp->html;\r
-                               break;\r
-                               default:\r
-                                       $iframe_id = 'hotpot_iframe';\r
-                                       $body_tags = " onload=\"set_iframe_height('$iframe_id')\"";\r
-                                       $iframe_js = '<script src="iframe.js" type="text/javascript" language="javascript"></script>'."\n";\r
-                                       print_header(\r
-                                               $title, $heading, $navigation, \r
-                                               "", $head.$styles.$scripts.$iframe_js, true, $button, \r
-                                               $loggedinas, false, $body_tags\r
-                                       );\r
-                                       if (!empty($available_msg)) {\r
-                                               notify($available_msg);\r
-                                       }\r
-                                       print "<iframe id=\"$iframe_id\" src=\"view.php?id=$cm->id&framename=main\" height=\"100%\" width=\"100%\">";\r
-                                       print "<ilayer name=\"$iframe_id\" src=\"view.php?id=$cm->id&framename=main\" height=\"100%\" width=\"100%\">";\r
-                                       print "</ilayer>\n";\r
-                                       print "</iframe>\n";\r
-                                       print $footer;\r
-                               break;\r
-                       } // end switch $framename\r
-               break;\r
-               default:\r
-                       // HOTPOT_NAVIGATION_BUTTONS\r
-                       // HOTPOT_NAVIGATION_GIVEUP\r
-                       // HOTPOT_NAVIGATION_NONE\r
-                       if (!empty($available_msg)) {\r
-                               $hp->insert_message('<!-- BeginTopNavButtons -->', $available_msg);\r
-                       }\r
-                       print($hp->html);\r
-       }\r
-///////////////////////////////////\r
-///    functions\r
-///////////////////////////////////\r
-function hotpot_feedback_teachers(&$course, &$hotpot) {\r
-       global $CFG;\r
-       $teachers = get_records_sql("\r
-               SELECT \r
-                       u.*\r
-               FROM \r
-                       {$CFG->prefix}user AS u, \r
-                       {$CFG->prefix}user_teachers AS t\r
-               WHERE \r
-                       t.userid = u.id\r
-                       AND t.course = $course->id \r
-       ");\r
-       $teacherdetails = '';\r
-       if (!empty($teachers)) {\r
-               $details = array();\r
-               foreach ($teachers as $teacher) {\r
-                       if ($hotpot->studentfeedback==HOTPOT_FEEDBACK_MOODLEMESSAGING) {\r
-                               $detail = $teacher->id;\r
-                       } else {\r
-                               $detail =$teacher->email;\r
-                       }\r
-                       $details[] = "new Array('".fullname($teacher)."', '$detail')";\r
-               }\r
-               $teacherdetails = 'new Array('.implode(',', $details).");\n";\r
-       }\r
-       return $teacherdetails;\r
-}\r
-?>\r
+<?PHP // $Id$
+       /// This page prints a hotpot quiz
+       if (defined('HOTPOT_FIRST_ATTEMPT') && HOTPOT_FIRST_ATTEMPT==false) {
+               // this script is being included (by attempt.php)
+       } else {
+               // this script is being called directly from the browser
+               define('HOTPOT_FIRST_ATTEMPT', true);
+               require_once("../../config.php");
+               require_once("lib.php");
+
+               $id = optional_param("id"); // Course Module ID, or
+               $hp = optional_param("hp"); // hotpot ID
+
+               if ($id) {
+                       if (! $cm = get_record("course_modules", "id", $id)) {
+                               error("Course Module ID was incorrect");
+                       }
+                       if (! $course = get_record("course", "id", $cm->course)) {
+                               error("Course is misconfigured");
+                       }
+                       if (! $hotpot = get_record("hotpot", "id", $cm->instance)) {
+                               error("Course module is incorrect");
+                       }
+
+               } else {
+                       if (! $hotpot = get_record("hotpot", "id", $hp)) {
+                               error("Course module is incorrect");
+                       }
+                       if (! $course = get_record("course", "id", $hotpot->course)) {
+                               error("Course is misconfigured");
+                       }
+                       if (! $cm = get_coursemodule_from_instance("hotpot", $hotpot->id, $course->id)) {
+                               error("Course Module ID was incorrect");
+                       }
+               }
+               require_login($course->id);
+       }
+       // set nextpage (for error messages)
+       $nextpage = "$CFG->wwwroot/course/view.php?id=$course->id";
+       // header strings
+       $title = strip_tags($course->shortname.': '.$hotpot->name);
+       $heading = "$course->fullname";
+       $target = empty($CFG->framename) ? '' : ' target="'.$CFG->framename.'"'; 
+       $navigation = '<a'.$target.' href="'.$CFG->wwwroot.'/mod/hotpot/index.php?id='.$course->id.'">'.get_string("modulenameplural", "hotpot")."</a> -> $hotpot->name";
+       if ($course->category) {
+               $navigation = '<a'.$target.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.$course->shortname.'</a> -> '.$navigation;
+       }
+       $button = update_module_button($cm->id, $course->id, get_string("modulename", "hotpot").'" style="font-size:0.75em;');
+       $loggedinas = '<span class="logininfo">'.user_login_string($course, $USER).'</span>';
+       $time = time();
+       $hppassword = optional_param('hppassword');
+       if (HOTPOT_FIRST_ATTEMPT && !isteacher($course->id)) {
+               // check this quiz is available to this student
+               // error message, if quiz is unavailable
+               $error = '';
+               // check quiz is visible
+               if (!hotpot_is_visible($cm)) {
+                       $error = get_string("activityiscurrentlyhidden");
+               // check network address
+               } else if ($hotpot->subnet && !address_in_subnet($_SERVER['REMOTE_ADDR'], $hotpot->subnet)) {
+                       $error = get_string("subneterror", "quiz");
+               // check number of attempts
+               } else if ($hotpot->attempts && $hotpot->attempts <= count_records('hotpot_attempts', 'hotpot', $hotpot->id, 'userid', $USER->id)) {
+                       $error = get_string("nomoreattempts", "quiz");
+               // get password
+               } else if ($hotpot->password && empty($hppassword)) {
+                       print_header($title, $heading, $navigation, "", "", true, $button, $loggedinas, false);
+                       print_heading($hotpot->name);
+                       $boxalign = 'center';
+                       $boxwidth = 500;
+                       if (trim(strip_tags($hotpot->summary))) {
+                               print_simple_box_start($boxalign, $boxwidth);
+                               print '<div align="center">'.format_text($hotpot->summary)."</div>\n";
+                               print_simple_box_end();
+                               print "<br />\n";
+                       }
+                       print '<form name="passwordform" method="post" action="view.php?id='.$cm->id.'">'."\n";
+                       print_simple_box_start($boxalign, $boxwidth);
+                       print '<div align="center">';
+                       print get_string('requirepasswordmessage', 'quiz').'<br /><br />';
+                       print '<b>'.get_string('password').':</b> ';
+                       print '<input name="hppassword" type="password" value=""> ';
+                       print '<input type="submit" value="'.get_string("ok").'"> ';
+                       print "</div>\n";
+                       print_simple_box_end();
+                       print "</form>\n";
+                       print_footer();
+                       exit;
+               // check password
+               } else if ($hotpot->password && strcmp($hotpot->password, $hppassword)) {
+                       $error = get_string("passworderror", "quiz");
+                       $nextpage = "view.php?id=$cm->id";
+               // check quiz is open
+               } else if ($hotpot->timeopen && $hotpot->timeopen > $time) {
+                       $error = get_string("quiznotavailable", "quiz", userdate($hotpot->timeopen))."<br />\n";
+               // check quiz is not closed
+               } else if ($hotpot->timeclose && $hotpot->timeclose < $time) {
+                       $error = get_string("quizclosed", "quiz", userdate($hotpot->timeclose))."<br />\n";
+               }
+               if ($error) {
+                       print_header($title, $heading, $navigation, "", "", true, $button, $loggedinas, false);
+                       notice($error, $nextpage);
+                       //
+                       // script stops here, if quiz is unavailable to student
+                       //
+               }
+       }
+       $available_msg = '';
+       if (!empty($hotpot->timeclose) && $hotpot->timeclose > $time) {
+               // quiz is available until 'timeclose'
+               $available_msg = get_string("quizavailable", "quiz", userdate($hotpot->timeclose))."<br />\n";
+       }
+       // open and parse the source file
+       if(!$hp = new hotpot_xml_quiz($hotpot)) {
+               error("Quiz is unavailable at the moment");
+       }
+       $get_js = optional_param('js');
+       $get_css = optional_param('css');
+       $framename = optional_param('framename');
+       // look for <frameset> (HP5 v5)
+       $frameset = '';
+       $frameset_tags = '';
+       if (preg_match_all('|<frameset([^>]*)>(.*?)</frameset>|is', $hp->html, $matches)) {
+               $last = count($matches[0])-1;
+               $frameset = $matches[2][$last];
+               $frameset_tags = $matches[1][$last];
+       }
+       // if HTML is being requested ...
+       if (empty($get_js) && empty($get_css)) {
+               if (empty($frameset)) { 
+                       // HP v6
+                       if ($hotpot->navigation==HOTPOT_NAVIGATION_FRAME || $hotpot->navigation==HOTPOT_NAVIGATION_IFRAME) {
+                               $get_html = ($framename=='main') ? true : false;
+                       } else {
+                               $get_html = true;
+                       }
+               } else { 
+                       // HP5 v5
+                       $get_html = empty($framename) ? true : false;
+               }
+               if ($get_html) {
+               
+                       if (HOTPOT_FIRST_ATTEMPT) {
+                               add_to_log($course->id, "hotpot", "view", "view.php?id=$cm->id", "$hotpot->id", "$cm->id");
+
+                               $attemptid = hotpot_add_attempt($hotpot->id);
+                               if (! is_numeric($attemptid)) {
+                                       error('Could not insert attempt record: '.$db->ErrorMsg);
+                               }
+                       }
+                       $hp->adjust_media_urls();
+                       if (empty($frameset)) {
+                               // HP6 v6
+                               switch ($hotpot->navigation) {
+                                       case HOTPOT_NAVIGATION_BUTTONS:
+                                               // do nothing (i.e. leave buttons as they are)
+                                               break;
+                                       case HOTPOT_NAVIGATION_GIVEUP:
+                                               $hp->insert_giveup_form($attemptid, '<!-- BeginTopNavButtons -->', '<!-- EndTopNavButtons -->');
+                                               break;
+                                       default:
+                                               $hp->remove_nav_buttons();
+                               }
+                               if (isset($hp->real_outputformat) && $hp->real_outputformat==HOTPOT_OUTPUTFORMAT_MOBILE) {
+                                       $hp->insert_submission_form($attemptid, '<!-- BeginSubmissionForm -->', '<!-- EndSubmissionForm -->', true);
+                               } else {
+                                       $hp->insert_submission_form($attemptid, '<!-- BeginSubmissionForm -->', '<!-- EndSubmissionForm -->');
+                               }
+                       } else {
+                               // HP5 v5
+                               switch ($hotpot->navigation) {
+                                       case HOTPOT_NAVIGATION_BUTTONS:
+                                               // convert URLs in nav buttons
+                                               break;
+                                       case HOTPOT_NAVIGATION_GIVEUP:
+                                               //      $hp->insert_giveup_form($attemptid, '<!-- BeginTopNavButtons -->', '<!-- EndTopNavButtons -->');
+                                               break;
+                                       default:
+                                               // remove navigation buttons
+                                               $hp->html = preg_replace('#NavBar\+=(.*);#', '', $hp->html);
+                               }
+                               $hp->insert_submission_form($attemptid, "var NavBar='", "';");
+                       }
+               }
+       }
+       //FEEDBACK = new Array();
+       //FEEDBACK[0] = ''; // url of feedback page/script
+       //FEEDBACK[1] = ''; // array of array('teachername', 'value');
+       //FEEDBACK[2] = ''; // 'student name' [formmail only]
+       //FEEDBACK[3] = ''; // 'student email' [formmail only]
+       //FEEDBACK[4] = ''; // window width
+       //FEEDBACK[5] = ''; // window height
+       //FEEDBACK[6] = ''; // 'Send a message to teacher' [prompt/button text]
+       //FEEDBACK[7] = ''; // 'Title'
+       //FEEDBACK[8] = ''; // 'Teacher'
+       //FEEDBACK[9] = ''; // 'Message'
+       //FEEDBACK[10] = ''; // 'Close this window'
+       $feedback = array();
+       switch ($hotpot->studentfeedback) {
+               case HOTPOT_FEEDBACK_NONE:
+                       // do nothing
+                       break;
+               case HOTPOT_FEEDBACK_WEBPAGE:
+                       if (empty($hotpot->studentfeedbackurl)) {
+                               $hotpot->studentfeedback = HOTPOT_FEEDBACK_NONE;
+                       } else {
+                               $feedback[0] = "'$hotpot->studentfeedbackurl'";
+                       }
+                       break;
+               case HOTPOT_FEEDBACK_FORMMAIL:
+                       $teachers = hotpot_feedback_teachers($course, $hotpot);
+                       if (empty($teachers) || empty($hotpot->studentfeedbackurl)) {
+                               $hotpot->studentfeedback = HOTPOT_FEEDBACK_NONE;
+                       } else {
+                               $feedback[0] = "'$hotpot->studentfeedbackurl'";
+                               $feedback[1] = $teachers;
+                               $feedback[2] = "'".fullname($USER)."'";
+                               $feedback[3] = "'".$USER->email."'";
+                               $feedback[4] = 500; // width
+                               $feedback[5] = 300; // height
+                       }
+                       break;
+               case HOTPOT_FEEDBACK_MOODLEFORUM:
+                       $module = get_record('modules', 'name', 'forum');
+                       $forums = get_records('forum', 'course', "$course->id");
+                       if (empty($module) || empty($module->visible) || empty($forums)) {
+                               $hotpot->studentfeedback = HOTPOT_FEEDBACK_NONE;
+                       } else {
+                               $feedback[0] = "'$CFG->wwwroot/mod/forum/index.php?id=$course->id'";
+                       }
+                       break;
+               case HOTPOT_FEEDBACK_MOODLEMESSAGING:
+                       $teachers = hotpot_feedback_teachers($course, $hotpot);
+                       if (empty($CFG->messaging) || empty($teachers)) {
+                               $hotpot->studentfeedback = HOTPOT_FEEDBACK_NONE;
+                       } else {
+                               $feedback[0] = "'$CFG->wwwroot/message/discussion.php?id='";
+                               $feedback[1] = $teachers;
+                               $feedback[4] = 400; // width
+                               $feedback[5] = 500; // height
+                       }
+                       break;
+               default:
+                       // do nothing
+       }
+       if ($hotpot->studentfeedback != HOTPOT_FEEDBACK_NONE) {
+               $feedback[6] = "'Send a message to teacher'";
+               $feedback[7] = "'Title'";
+               $feedback[8] = "'Teacher'";
+               $feedback[9] = "'Message'";
+               $feedback[10] = "'Close this window'";
+               $js = '';
+               foreach ($feedback as $i=>$str) {
+                       $js .= 'FEEDBACK['.$i."] = $str;\n";
+               }
+               $js = '<script type="text/javascript" language="javascript">'."<!--\n"."FEEDBACK = new Array();\n".$js."//--></script>\n";
+               $hp->html = preg_replace('|</head>|i', "$js</head>", $hp->html, 1);
+       }
+       // insert hot-potatoes.js
+       $hp->insert_script(HOTPOT_JS);
+       // extract first <head> tag
+       $head = '';
+       $pattern = '|<head([^>]*)>(.*?)</head>|is';
+       if (preg_match($pattern, $hp->html, $matches)) {
+               $head = $matches[2];
+               // remove <title>
+               $head = preg_replace('|<title[^>]*>(.*?)</title>|is', '', $head);
+       }
+       // extract <style> tags (and remove from $head)
+       $styles = '';
+       $pattern = '|<style([^>]*)>(.*?)</style>|is';
+       if (preg_match_all($pattern, $head, $matches)) {
+               $count = count($matches[0]);
+               for ($i=0; $i<$count; $i++) {
+                       $styles .= $matches[0][$i]."\n";
+                       $head = str_replace($matches[0][$i], '', $head);
+               }
+       }
+       // extract <script> tags (and remove from $head)
+       $scripts = '';
+       $pattern = '|<script([^>]*)>(.*?)</script>|is';
+       if (preg_match_all($pattern, $head, $matches)) {
+               $count = count($matches[0]);
+               for ($i=0; $i<$count; $i++) {
+                       $scripts .= $matches[0][$i]."\n";
+                       $head = str_replace($matches[0][$i], '', $head);
+               }
+       }
+       // extract <body> tags
+       $body = '';
+       $body_tags = '';
+       $footer = '</html>';
+       // HP6 and some HP5 (v6 and v4) 
+       if (preg_match('|<body'.'([^>]*'.'onLoad=(["\'])(.*?)(\\2)'.'[^>]*)'.'>(.*)</body>|is', $hp->html, $matches)) {
+               $body = $matches[5]; // contents of first <body onload="StartUp()">...</body> block
+               $body_tags = $matches[1];
+               // workaround to ensure javascript onload routine for quiz is always executed
+               //      $body_tags will only be inserted into the <body ...> tag
+               //      if it is included in the theme/$CFG->theme/header.html,
+               //      so some old or modified themes may not insert $body_tags
+               $body .= ""
+               .       '<script type="text/javascript">'."\n"
+               .       "<!--\n"
+               .       "       var s = (typeof(window.onload)=='function') ? onload.toString() : '';\n"
+               .       "       if (s.indexOf('".$matches[3]."')<0) {\n"
+               .       "               if (s=='') {\n" // no previous onload
+               .       "                       window.onload = new Function('".$matches[3]."');\n"
+               .       "               } else {\n"
+               .       "                       window.onload_hotpot = onload;\n"
+               .       "                       window.onload = new Function('window.onload_hotpot();'+'".$matches[3]."');\n"
+               .       "               }\n"
+               .       "        }\n"
+               .       "//-->\n"
+               .       "</script>\n"
+               ;
+               $footer = '</body>'.$footer;
+       } else if ($frameset) { // HP5 v5
+               switch ($framename) {
+                       case 'top':
+                               print_header($title, $heading, $navigation, "", "", true, $button, $loggedinas);
+                               print $footer;
+                       break;
+                       default:
+                               // add a HotPot navigation frame at the top of the page
+                               //$rows = empty($CFG->resource_framesize) ? 85 : $CFG->resource_framesize;
+                               //$frameset = "\n\t".'<frame src="view.php?id='.$cm->id.'&framename=top" frameborder="0" name="top"></frame>'.$frameset;
+                               //$frameset_tags = preg_replace('|rows="(.*?)"|', 'rows="'.$rows.',\\1"', $frameset_tags);
+                               // put navigation into var NavBar='';
+                               // add form to TopFrame in "WriteFeedback" function
+                               // OR add form to BottomFrame in "DisplayExercise" function
+                               // submission form: '<!-- BeginSubmissionForm -->', '<!-- EndSubmissionForm -->'
+                               // give up form: '<!-- BeginTopNavButtons -->', '<!-- EndTopNavButtons -->'
+                               print "<html>\n";
+                               print "<head>\n<title>$title</title>\n$styles\n$scripts</head>\n";
+                               print "<frameset$frameset_tags>$frameset</frameset>\n";
+                               print "</html>\n";
+                       break;
+               } // end switch $framename
+               exit;
+       // other files (maybe not even a HotPots)
+       } else if (preg_match('|<body'.'([^>]*)'.'>(.*)</body>|is', $hp->html, $matches)) {
+               $body = $matches[2];
+               $body_tags = $matches[1];
+       }
+       // print the quiz to the browser
+       if ($get_js) {
+               print($scripts);
+               exit;
+       }
+       if ($get_css) {
+               print($styles);
+               exit;
+       }
+       switch ($hotpot->navigation) {
+               case HOTPOT_NAVIGATION_BAR:
+                       //update_module_button($cm->id, $course->id, $strmodulename.'" style="font-size:0.8em')
+                       print_header(
+                               $title, $heading, $navigation,
+                               "", $head.$styles.$scripts, true, $button, 
+                               $loggedinas, false, $body_tags
+                       );
+                       if (!empty($available_msg)) {
+                               notify($available_msg);
+                       }
+                       print $body.$footer;
+               break;
+               case HOTPOT_NAVIGATION_FRAME:
+                       switch ($framename) {
+                               case 'top':
+                                       print_header($title, $heading, $navigation, "", "", true, $button, $loggedinas);
+                                       print $footer;
+                               break;
+                               case 'main':
+                                       if (!empty($available_msg)) {
+                                               $hp->insert_message('<!-- BeginTopNavButtons -->', $available_msg);
+                                       }
+                                       print $hp->html;
+                               break;
+                               default:
+                                       $rows = empty($CFG->resource_framesize) ? 85 : $CFG->resource_framesize;
+                                       print "<html>\n";
+                                       print "<head><title>$title</title></head>\n";
+                                       print "<frameset rows=$rows,*>\n";
+                                       print "<frame src=\"view.php?id=$cm->id&framename=top\">\n";
+                                       print "<frame src=\"view.php?id=$cm->id&framename=main\">\n";
+                                       print "</frameset>\n";
+                                       print "</html>\n";
+                               break;
+                       } // end switch $framename
+               break;
+               case HOTPOT_NAVIGATION_IFRAME:
+                       switch ($framename) {
+                               case 'main':
+                                       print $hp->html;
+                               break;
+                               default:
+                                       $iframe_id = 'hotpot_iframe';
+                                       $body_tags = " onload=\"set_iframe_height('$iframe_id')\"";
+                                       $iframe_js = '<script src="iframe.js" type="text/javascript" language="javascript"></script>'."\n";
+                                       print_header(
+                                               $title, $heading, $navigation, 
+                                               "", $head.$styles.$scripts.$iframe_js, true, $button, 
+                                               $loggedinas, false, $body_tags
+                                       );
+                                       if (!empty($available_msg)) {
+                                               notify($available_msg);
+                                       }
+                                       print "<iframe id=\"$iframe_id\" src=\"view.php?id=$cm->id&framename=main\" height=\"100%\" width=\"100%\">";
+                                       print "<ilayer name=\"$iframe_id\" src=\"view.php?id=$cm->id&framename=main\" height=\"100%\" width=\"100%\">";
+                                       print "</ilayer>\n";
+                                       print "</iframe>\n";
+                                       print $footer;
+                               break;
+                       } // end switch $framename
+               break;
+               default:
+                       // HOTPOT_NAVIGATION_BUTTONS
+                       // HOTPOT_NAVIGATION_GIVEUP
+                       // HOTPOT_NAVIGATION_NONE
+                       if (!empty($available_msg)) {
+                               $hp->insert_message('<!-- BeginTopNavButtons -->', $available_msg);
+                       }
+                       print($hp->html);
+       }
+///////////////////////////////////
+///    functions
+///////////////////////////////////
+function hotpot_feedback_teachers(&$course, &$hotpot) {
+       global $CFG;
+       $teachers = get_records_sql("
+               SELECT 
+                       u.*
+               FROM 
+                       {$CFG->prefix}user AS u, 
+                       {$CFG->prefix}user_teachers AS t
+               WHERE 
+                       t.userid = u.id
+                       AND t.course = $course->id 
+       ");
+       $teacherdetails = '';
+       if (!empty($teachers)) {
+               $details = array();
+               foreach ($teachers as $teacher) {
+                       if ($hotpot->studentfeedback==HOTPOT_FEEDBACK_MOODLEMESSAGING) {
+                               $detail = $teacher->id;
+                       } else {
+                               $detail =$teacher->email;
+                       }
+                       $details[] = "new Array('".fullname($teacher)."', '$detail')";
+               }
+               $teacherdetails = 'new Array('.implode(',', $details).");\n";
+       }
+       return $teacherdetails;
+}
+?>