Removed tabs
authormoodler <moodler>
Wed, 9 Aug 2006 13:45:49 +0000 (13:45 +0000)
committermoodler <moodler>
Wed, 9 Aug 2006 13:45:49 +0000 (13:45 +0000)
67 files changed:
mod/assignment/lib.php
mod/assignment/mod.html
mod/chat/gui_header_js/index.php
mod/chat/lib.php
mod/chat/report.php
mod/chat/view.php
mod/choice/lib.php
mod/choice/report.php
mod/choice/view.php
mod/data/comment.php
mod/data/field.php
mod/data/import.php
mod/data/lib.php
mod/data/restorelib.php
mod/data/tabs.php
mod/data/templates.php
mod/data/view.php
mod/exercise/assessments.php
mod/exercise/view.php
mod/glossary/approve.php
mod/glossary/comment.php
mod/glossary/comments.php
mod/glossary/deleteentry.php
mod/glossary/edit.php
mod/glossary/editcategories.php
mod/glossary/export.php
mod/glossary/exportentry.php
mod/glossary/exportfile.php
mod/glossary/import.php
mod/glossary/lib.php
mod/glossary/report.php
mod/glossary/tabs.html
mod/glossary/view.php
mod/hotpot/attempt.php
mod/hotpot/config.html
mod/hotpot/db/mysql.php
mod/hotpot/db/update_to_v2.php
mod/hotpot/index.php
mod/hotpot/lib.php
mod/hotpot/mod.html
mod/hotpot/report.php
mod/hotpot/report/default.php
mod/hotpot/review.php
mod/hotpot/show.php
mod/hotpot/template/default.php
mod/hotpot/template/v6.php
mod/hotpot/view.php
mod/lesson/mediafile.php
mod/lesson/mod.html
mod/quiz/attempt.php
mod/quiz/db/mysql.php
mod/quiz/db/postgres7.php
mod/quiz/defaults.php
mod/quiz/styles.php
mod/scorm/api.php
mod/scorm/coefficientconfirm.php
mod/scorm/coefficientsetting.php
mod/scorm/datamodels/scorm1_3.js.php
mod/scorm/db/mysql.php
mod/scorm/db/postgres7.php
mod/scorm/index.php
mod/scorm/lib.php
mod/scorm/loadSCO.php
mod/scorm/mod.html
mod/scorm/report.php
mod/wiki/ewiki/ewiki.php
mod/wiki/view.php

index b8bd546..6d3e4e0 100644 (file)
@@ -107,10 +107,10 @@ class assignment_base {
      */
     function view() {
       
-               $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
+        $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
         has_capability('mod/assignment:view', $context->id, true);
         
-               add_to_log($this->course->id, "assignment", "view", "view.php?id={$this->cm->id}", 
+        add_to_log($this->course->id, "assignment", "view", "view.php?id={$this->cm->id}", 
                    $this->assignment->id, $this->cm->id);
 
         $this->view_header();
@@ -281,7 +281,7 @@ class assignment_base {
 
         // if this user can mark and is put in a group
         // then he can only see/mark submission in his own groups
-            if (user_group($this->course->id, $USER->id)) {                    
+            if (user_group($this->course->id, $USER->id)) {             
                 $count = $this->count_real_submissions($this->currentgroup);  // Only their groups
             } else {
                 $count = $this->count_real_submissions();                     // Everyone
index 891f57a..0d5e4dc 100644 (file)
@@ -35,7 +35,7 @@
     var availableitems = ['availableday','availablemonth','availableyear','availablehour', 'availableminute'];
 </script>
 
-<form name="form" method="post" action="../mod/assignment/details.php">        
+<form name="form" method="post" action="../mod/assignment/details.php"> 
 <table cellpadding="5">
 <tr valign="top">
     <td align="right"><b><?php print_string("assignmentname", "assignment") ?>:</b></td>
index ddd1d74..6c35be3 100644 (file)
     if (!$cm = get_coursemodule_from_instance('chat', $chat->id, $course->id)) {
         error('Course Module ID was incorrect');
     }
-       
-       $context = get_context_instance(CONTEXT_MODULE, $cm->id);
     
-       require_login($course->id, false, $cm);
+    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
+    
+    require_login($course->id, false, $cm);
 
-       has_capability('mod/chat:chat',$context->id, true);
-       /*
+    has_capability('mod/chat:chat',$context->id, true);
+    /*
     if (isguest()) {
         error('Guest does not have access to chat rooms');
     }
-       */
+    */
     if (!$cm->visible and !isteacher($course->id)) {
         print_header();
         notice(get_string("activityiscurrentlyhidden"));
index d963d5c..0052d55 100644 (file)
@@ -200,17 +200,17 @@ function chat_print_recent_activity($course, $isteacher, $timestart) {
             }
             if ($chat = get_record('chat', 'id', $chatuser->chatid)) {
               
-               // we find the course module id
-               $chatmod = get_record('modules', 'name', 'chat');
-               $SQL = "select * from {$CFG->prefix}course_modules where
-                               course = $course->id 
-                                               and module = $chatmod->id
-                               and instance = $chat->id";
-               $cm = get_records_sql($SQL);
-               $context = get_context_instance(CONTEXT_MODULE, $cm->id);
+                // we find the course module id
+                $chatmod = get_record('modules', 'name', 'chat');
+                $SQL = "select * from {$CFG->prefix}course_modules where
+                        course = $course->id 
+                        and module = $chatmod->id
+                        and instance = $chat->id";
+                $cm = get_records_sql($SQL);
+                $context = get_context_instance(CONTEXT_MODULE, $cm->id);
               
-               // needs to be fixed
-                               if (!(has_capability('mod/chat:readlog', $context->id) or instance_is_visible('chat', $chat))) {  // Chat hidden to students
+                // needs to be fixed
+                if (!(has_capability('mod/chat:readlog', $context->id) or instance_is_visible('chat', $chat))) {  // Chat hidden to students
                 //if (!($isteacher or instance_is_visible('chat', $chat))) {  // Chat hidden to students
                     continue;
                 }
index 5bcf6a6..8f9ec6a 100644 (file)
         error('Course is misconfigured');
     }
 
-       $context = get_context_instance(CONTEXT_MODULE, $cm->id);
+    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
     require_login($course->id, false, $cm);
 
     $isteacher     = isteacher($course->id);
     $isteacheredit = isteacheredit($course->id);
 
     //if (isguest() or (!$isteacher and !$chat->studentlogs)) {
-       //error('You can not view these chat reports');
+        //error('You can not view these chat reports');
     //}
-       has_capability('mod/chat:readlog', $context->id, true); // if can't even read, kill
+    has_capability('mod/chat:readlog', $context->id, true); // if can't even read, kill
 
     add_to_log($course->id, 'chat', 'report', "report.php?id=$cm->id", $chat->id, $cm->id);
 
@@ -89,7 +89,7 @@
             print_simple_box_end('center');
         }
 
-               if (!$deletesession or !has_capability('mod/chat:deletelog', $context->id)) {
+        if (!$deletesession or !has_capability('mod/chat:deletelog', $context->id)) {
         //if (!$deletesession or !$isteacheredit) {
             print_continue("report.php?id=$cm->id");
         }
 
 /// Delete a session if one has been specified
 
-       if ($deletesession and has_capability('mod/chat:deletelog', $context->id) and $confirmdelete and $start and $end and confirm_sesskey()) {
+    if ($deletesession and has_capability('mod/chat:deletelog', $context->id) and $confirmdelete and $start and $end and confirm_sesskey()) {
     //if ($deletesession and $isteacheredit and $confirmdelete and $start and $end and confirm_sesskey()) {
         delete_records_select('chat_messages', "chatid = $chat->id AND
                                             timestamp >= '$start' AND
                 echo '<p align="right">';
                 echo "<a href=\"report.php?id=$cm->id&amp;start=$sessionstart&amp;end=$sessionend\">$strseesession</a>";
                 //if ($isteacheredit)
-                               if (has_capability('mod/chat:deletelog', $context->id)) {
+                if (has_capability('mod/chat:deletelog', $context->id)) {
                     echo "<br /><a href=\"report.php?id=$cm->id&amp;start=$sessionstart&amp;end=$sessionend&amp;deletesession=1\">$strdeletesession</a>";
                 }
                 echo '</p>';
index 5a125ed..5d96bd9 100644 (file)
@@ -43,9 +43,9 @@
 
     require_course_login($course, true, $cm);
     
-       $context = get_context_instance(CONTEXT_MODULE, $cm->id);
+    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
     
-       add_to_log($course->id, 'chat', 'view', "view.php?id=$cm->id", $chat->id, $cm->id);
+    add_to_log($course->id, 'chat', 'view', "view.php?id=$cm->id", $chat->id, $cm->id);
 
 // Initialize $PAGE, compute blocks
 
@@ -76,7 +76,7 @@
 
     echo '<td id="middle-column">';
     
-       if ($chat->studentlogs or has_capability('mod/chat:readlog',$context->id)) {
+    if ($chat->studentlogs or has_capability('mod/chat:readlog',$context->id)) {
     //if (($chat->studentlogs or isteacher($course->id)) and !isguest()) {
         echo '<div class="reportlink">';
         echo "<a href=\"report.php?id=$cm->id\">".
index d7051a9..4ed0247 100644 (file)
@@ -144,7 +144,7 @@ function choice_update_instance($choice) {
 }
 
 function choice_show_form($choice, $user, $cm) {
-       
+    
 //$cdisplay is an array of the display info for a choice $cdisplay[$optionid]->text  - text name of option.
 //                                                                            ->maxanswers -maxanswers for this option
 //                                                                            ->full - whether this option is full or not. 0=not full, 1=full
@@ -157,9 +157,9 @@ $cdisplay = array();
             $countans = 0;           
             $context = get_context_instance(CONTEXT_MODULE, $cm->id);
             if (!empty($countanswers)) {
-                foreach ($countanswers as $ca) { //only return enrolled users.                                 
-                                   if (has_capability('mod/choice:choose', $context->id)) {
-                                       //if (isstudent($cm->course, $ca->userid) or isteacher($cm->course, $ca->userid)) {     
+                foreach ($countanswers as $ca) { //only return enrolled users.                  
+                    if (has_capability('mod/choice:choose', $context->id)) {
+                    //if (isstudent($cm->course, $ca->userid) or isteacher($cm->course, $ca->userid)) { 
                         $countans = $countans+1;
                     }
                 }
@@ -171,21 +171,21 @@ $cdisplay = array();
             }
             $maxans = $choice->maxanswers[$optionid];
 
-               $cdisplay[$aid]->optionid = $optionid;
-                   $cdisplay[$aid]->text = $text;
-                   $cdisplay[$aid]->maxanswers = $maxans;
-                   $cdisplay[$aid]->countanswers = $countans;
+            $cdisplay[$aid]->optionid = $optionid;
+            $cdisplay[$aid]->text = $text;
+            $cdisplay[$aid]->maxanswers = $maxans;
+            $cdisplay[$aid]->countanswers = $countans;
 
-                   if ($current = get_record('choice_answers', 'choiceid', $choice->id, 'userid', $user->id, 'optionid', $optionid)) {
-                       $cdisplay[$aid]->checked = ' checked="checked" ';       
-                   } else {
-                       $cdisplay[$aid]->checked = '';  
-               }
+            if ($current = get_record('choice_answers', 'choiceid', $choice->id, 'userid', $user->id, 'optionid', $optionid)) {
+                $cdisplay[$aid]->checked = ' checked="checked" ';   
+            } else {
+                $cdisplay[$aid]->checked = '';  
+            }
             if ($choice->limitanswers && ($countans >= $maxans) && (empty($cdisplay[$aid]->checked)) ) {
-                               $cdisplay[$aid]->disabled = ' disabled="disabled" ';    
-                       } else {
-                               $cdisplay[$aid]->disabled = ''; 
-                   }
+                $cdisplay[$aid]->disabled = ' disabled="disabled" ';    
+            } else {
+                $cdisplay[$aid]->disabled = ''; 
+            }
             $aid++;
         }
     }
@@ -193,13 +193,13 @@ $cdisplay = array();
         switch ($choice->display) {
             case CHOICE_DISPLAY_HORIZONTAL:
                 echo "<table cellpadding=\"20\" cellspacing=\"20\" align=\"center\"><tr>";
-                                                   
+                                    
                 foreach ($cdisplay as $cd) { 
                     echo "<td align=\"center\" valign=\"top\">";
                     echo "<input type=\"radio\" name=\"answer\" value=\"".$cd->optionid."\" alt=\"".strip_tags(format_text($cd->text))."\"". $cd->checked.$cd->disabled." />";                    
                     if (!empty($cd->disabled)) {               
-                            echo format_text($cd->text."<br /><strong>".get_string('full', 'choice')."</strong>");                                 
-                                   } else {
+                            echo format_text($cd->text."<br /><strong>".get_string('full', 'choice')."</strong>");                  
+                    } else {
                         echo format_text($cd->text);
                     }
                         echo "</td>";                    
@@ -222,8 +222,8 @@ $cdisplay = array();
                             
                             if (!empty($cd->disabled)) {
                                 echo get_string('full', 'choice');
-                                                   } elseif(!empty($cd->checked)) {
-                                                           //currently do nothing - maybe some text could be added here to signfy that the choice has been 'selected'
+                            } elseif(!empty($cd->checked)) {
+                                //currently do nothing - maybe some text could be added here to signfy that the choice has been 'selected'
                             } elseif ($cd->maxanswers-$cd->countanswers==1) {
                                 echo ($cd->maxanswers - $cd->countanswers);
                                 echo " ".get_string('spaceleft', 'choice');
@@ -256,26 +256,26 @@ $cdisplay = array();
 function choice_user_submit_response($formanswer, $choice, $userid, $courseid, $cm) {
 
 $current = get_record('choice_answers', 'choiceid', $choice->id, 'userid', $userid);
-       $context = get_context_instance(CONTEXT_MODULE, $cm->id);
-       $countanswers = get_records("choice_answers", "optionid", $formanswer);
+    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
+    $countanswers = get_records("choice_answers", "optionid", $formanswer);
             if ($countanswers) {
             $countans = 0;
             foreach ($countanswers as $ca) { //only return enrolled users.
-                               if (has_capability('mod/choice:choose', $context->id)) {
-                               //if (isstudent($courseid, $ca->userid) or isteacher($courseid, $ca->userid)) { 
-                                   $countans = $countans+1;
-                           }
-                       }                               
-                               
+                if (has_capability('mod/choice:choose', $context->id)) {
+                //if (isstudent($courseid, $ca->userid) or isteacher($courseid, $ca->userid)) { 
+                    $countans = $countans+1;
+                }
+            }               
+                
                 $countanswers = count($countans);
                 } else {
                     $countanswers = 0;
                 }
             $maxans = $choice->maxanswers[$formanswer];
             
-            if (!($choice->limitanswers && ($countanswers >= $maxans) )) {                             
+            if (!($choice->limitanswers && ($countanswers >= $maxans) )) {              
                 if ($current) {
-                                       
+                    
                     $newanswer = $current;
                     $newanswer->optionid = $formanswer;
                     $newanswer->timemodified = time();
@@ -304,11 +304,11 @@ $current = get_record('choice_answers', 'choiceid', $choice->id, 'userid', $user
 
 function choice_show_reportlink($choice, $courseid, $cmid) {
         $context = get_context_instance(CONTEXT_MODULE, $cmid);
-           if ( $allanswers = get_records("choice_answers", "choiceid", $choice->id)) {
+        if ( $allanswers = get_records("choice_answers", "choiceid", $choice->id)) {
             $responsecount = 0;
             foreach ($allanswers as $aa) {
                 if (has_capability('mod/choice:readresponses', $context->id)) {
-                               //if (isstudent($courseid, $aa->userid) or isteacher($courseid, $aa->userid)) { //check to make sure user is enrolled in course.
+                //if (isstudent($courseid, $aa->userid) or isteacher($courseid, $aa->userid)) { //check to make sure user is enrolled in course.
                     $responsecount++;
                 }
             }
@@ -323,12 +323,12 @@ function choice_show_reportlink($choice, $courseid, $cmid) {
 function choice_show_results($choice, $course, $cm, $forcepublish='') {
             
         global $CFG, $COLUMN_HEIGHT, $USER;
-               $context = get_context_instance(CONTEXT_MODULE, $cm->id);
+        $context = get_context_instance(CONTEXT_MODULE, $cm->id);
         print_heading(get_string("responses", "choice"));        
         if (empty($forcepublish)) { //alow the publish setting to be overridden
-                       $forcepublish = $choice->publish;
-               }               
-                       
+            $forcepublish = $choice->publish;
+        }       
+                
         /// Check to see if groups are being used in this choice
     if ($groupmode = groupmode($course, $cm)) {   // Groups are being used
         $currentgroup = setup_and_print_groups($course, $groupmode, $_SERVER['PHP_SELF']."?id=$cm->id");
@@ -383,9 +383,9 @@ function choice_show_results($choice, $course, $cm, $forcepublish='') {
             //$isteacher = isteacher($course->id);
 
             $tablewidth = (int) (100.0 / count($useranswer));
-                       if (has_capability('mod/choice:readresponses', $context->id)) {
+            if (has_capability('mod/choice:readresponses', $context->id)) {
             //if (isteacher($course->id, $USER->id)) {
-                               echo '<div id="tablecontainer">';
+                echo '<div id="tablecontainer">';
                 echo '<form id="attemptsform" method="post" action="'.$_SERVER['PHP_SELF'].'" onsubmit="var menu = document.getElementById(\'menuaction\'); return (menu.options[menu.selectedIndex].value == \'delete\' ? \''.addslashes(get_string('deleteattemptcheck','quiz')).'\' : true);">';
                 echo '<input type="hidden" name="id" value="'.$cm->id.'" />';
                 echo '<input type="hidden" name="mode" value="overview" />';
@@ -420,7 +420,7 @@ function choice_show_results($choice, $course, $cm, $forcepublish='') {
 
                 echo "<table width=\"100%\">";
                 foreach ($userlist as $user) {
-                       // this needs to be fixed
+                    // this needs to be fixed
                     if (!($optionid==0 && isadmin($user->id)) && !($optionid==0 && isteacher($course->id, $user->id) && !(isteacheredit($course->id, $user->id)) )  ) { //make sure admins and hidden teachers are not shown in not answered yet column.
                         echo "<tr>";
                         if (isteacher($course->id, $USER->id) && !($optionid==0)) {
@@ -450,12 +450,12 @@ function choice_show_results($choice, $course, $cm, $forcepublish='') {
                 $countanswers = get_records("choice_answers", "optionid", $optionid);                
                 $countans = 0;  
                 if (!empty($countanswers)) {              
-                    foreach ($countanswers as $ca) { //only return enrolled users.             
-                                               // needs fixing too                                     
-                                       if (isstudent($course->id, $ca->userid) or isteacher($course->id, $ca->userid)) {                                                       
-                                          $countans = $countans+1;
-                                   }                           
-                               }
+                    foreach ($countanswers as $ca) { //only return enrolled users.      
+                        // needs fixing too                         
+                        if (isstudent($course->id, $ca->userid) or isteacher($course->id, $ca->userid)) {                           
+                           $countans = $countans+1;
+                        }                   
+                    }
                 }
                 if ($choice->limitanswers && !$optionid==0) {
                     echo get_string("taken", "choice").":";
@@ -490,8 +490,8 @@ function choice_show_results($choice, $course, $cm, $forcepublish='') {
             echo "</tr></table>";
             //if (isteacher($course->id, $USER->id)) {
             if (has_capability('mod/choice:readresponses', $context->id)) {
-                           echo "</form></div>";
-                       }
+                echo "</form></div>";
+            }
             break;
 
 
@@ -572,13 +572,13 @@ function choice_show_results($choice, $course, $cm, $forcepublish='') {
             echo "</tr></table>";
 
             break;
-        }      
+        }   
 }
 
 
 function choice_delete_responses($attemptids) {
-       
-       if(!is_array($attemptids) || empty($attemptids)) {
+    
+    if(!is_array($attemptids) || empty($attemptids)) {
         return false;
     }
 
index c813d58..bb56faa 100644 (file)
 
     require_login($course->id, false, $cm);
     
-       $context = get_context_instance(CONTEXT_MODULE, $cm->id);
+    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
     
     has_capability('mod/choice:readresponses', $context->id, true);
     
-       //if (!isteacher($course->id)) {
+    //if (!isteacher($course->id)) {
     //    error("Only teachers can look at this page");
     //}
 
@@ -40,7 +40,7 @@
     //if ($action == 'delete') { //some responses need to be deleted
         $attemptids = isset($_POST['attemptid']) ? $_POST['attemptid'] : array(); //get array of repsonses to delete.
         choice_delete_responses($attemptids); //delete responses.
-        redirect("report.php?id=$cm->id");                                 
+        redirect("report.php?id=$cm->id");                      
     }
         
     if ($download <> "xls" and $download <> "txt" ) {
                     $ug2 = '';
                     if ($usergrps = user_group($course->id, $user->id)) {
                         foreach ($usergrps as $ug) {
-                                                   $ug2 = $ug2. $ug->name;
-                                           }
-                               }
+                            $ug2 = $ug2. $ug->name;
+                        }
+                    }
                     $myxls->write_string($row,3,$ug2);
                     
                     $useroption = choice_get_option_text($choice, $answers[$user->id]->optionid);
         exit;
     } 
     // print text file  
-       //if ($download == "txt") {   
+    //if ($download == "txt") {   
     if ($download == "txt" && has_capability('mod/choice:downloadresponses', $context->id, true)) {
         $filename = clean_filename("$course->shortname ".strip_tags(format_string($choice->name,true))).'.txt';
             
               echo "\t".$user->firstname;
               $studentid = " ";
               if (!empty($user->idnumber)) {
-                             $studentid = $user->idnumber;
-                         }              
+                  $studentid = $user->idnumber;
+              }              
               echo "\t". $studentid."\t";
               $ug2 = '';
               if ($usergrps = user_group($course->id, $user->id)) {
                   foreach ($usergrps as $ug) {
-                                 $ug2 = $ug2. $ug->name;
-                             }
-                         }
+                      $ug2 = $ug2. $ug->name;
+                  }
+              }
               echo $ug2. "\t";
               echo format_string(choice_get_option_text($choice, $answers[$user->id]->optionid),true). "\n";
           }
index ff052f7..fa6849a 100644 (file)
@@ -33,7 +33,7 @@
 
     if ($form = data_submitted()) {
         $timenow = time();
-               if (has_capability('mod/choice:deleteresponses', $context->id)) {
+        if (has_capability('mod/choice:deleteresponses', $context->id)) {
         //if (isteacher($course->id, $USER->id)) {
             if ($action == 'delete') { //some responses need to be deleted     
                 choice_delete_responses($attemptids); //delete responses.
@@ -59,7 +59,7 @@
                  "<a href=\"index.php?id=$course->id\">$strchoices</a> -> ".format_string($choice->name), "", "", true,
                   update_module_button($cm->id, $course->id, $strchoice), navmenu($course, $cm));
                                                       
-       if (has_capability('mod/choice:readresponses', $context->id)) {
+    if (has_capability('mod/choice:readresponses', $context->id)) {
     //if (isteacher($course->id)) {
         choice_show_reportlink($choice, $course->id, $cm->id);
     } else if (!$cm->visible) {
         ( $choice->showresults == CHOICE_SHOWRESULTS_AFTER_ANSWER and $current ) or
         ( $choice->showresults == CHOICE_SHOWRESULTS_AFTER_CLOSE and $choice->timeclose <= time() ) )  {
 
-               choice_show_results($choice, $course, $cm);
+        choice_show_results($choice, $course, $cm);
     }
 
     print_footer($course);
index 2a79131..34a8837 100755 (executable)
     }
 
     require_login($course->id);
-       
-       $cm = data_get_cm($data);
-       $context = get_context_instance(CONTEXT_MODULE, $cm->id);
     
-       if ($commentid) {
+    $cm = data_get_cm($data);
+    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
+    
+    if ($commentid) {
         if (! $comment = get_record('data_comments', 'id', $commentid)) {
             error('Comment ID is misconfigured');
         }
index 4cd279c..b129a74 100755 (executable)
@@ -65,8 +65,8 @@
 
     require_course_login($course, true, $cm);
 
-       $context = get_context_instance(CONTEXT_MODULE, $cm->id);
-       has_capability('mod/data:managetemplates', $context->id, true);
+    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
+    has_capability('mod/data:managetemplates', $context->id, true);
 
 
     if (!isteacheredit($course->id)){
index d299115..2c7e922 100755 (executable)
@@ -57,8 +57,8 @@
         }
     }
     
-       $context = get_context_instance(CONTEXT_MODULE, $cm->id);
-       has_capability('mod/data:uploadentries', $context->id, true);
+    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
+    has_capability('mod/data:uploadentries', $context->id, true);
     
     if (has_capability('mod/data:managetemplates', $context->id)) {
         if (!count_records('data_fields','dataid',$data->id)) {      // Brand new database!
index 17fc862..b0b827a 100755 (executable)
@@ -557,7 +557,7 @@ function data_add_record($data, $groupid=0){
     $record->groupid = $groupid;
     $record->timecreated = $record->timemodified = time();
     if (has_capability('mod/data:approve', $context->id)) {
-       //if (isteacher($data->course)) {
+    //if (isteacher($data->course)) {
         $record->approved = 1;
     } else {
         $record->approved = 0;
@@ -839,8 +839,8 @@ function data_get_coursemodule_info($coursemodule) {
 function data_print_template($template, $records, $data, $search='',$page=0, $return=false) {
     global $CFG;
 
-       $cm = data_get_cm($data);
-       $context = get_context_instance(CONTEXT_MODULE, $cm->id);
+    $cm = data_get_cm($data);
+    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
 
     static $fields = NULL;
     static $isteacher;
@@ -991,9 +991,9 @@ function data_print_preference_form($data, $perpage, $search, $sort='', $order='
 function data_print_ratings($data, $record) {
     global $USER;
 
-       $cm = data_get_cm($data);
-       $context = get_context_instance(CONTEXT_MODULE, $cm->id);
-       
+    $cm = data_get_cm($data);
+    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
+    
     $ratingsmenuused = false;
     if ($data->ratings and !empty($USER->id)) {
         if ($ratings->scale = make_grades_menu($data->scale)) {
@@ -1165,10 +1165,10 @@ function data_print_comment($data, $comment, $page=0) {
 
     global $USER, $CFG;
     
-       $cm = data_get_cm($data);
-       $context = get_context_instance(CONTEXT_MODULE, $cm->id);
+    $cm = data_get_cm($data);
+    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
     
-       $stredit = get_string('edit');
+    $stredit = get_string('edit');
     $strdelete = get_string('delete');
 
     $user = get_record('user','id',$comment->userid);
@@ -1254,13 +1254,13 @@ function data_convert_arrays_to_strings(&$fieldinput) {
 
 // returns the $cm given $data
 function data_get_cm($data) {
-       global $CFG, $course;
-       $datamod = get_record('modules', 'name', 'data');
-       $SQL = "select * from {$CFG->prefix}course_modules
-                       where course = $course->id and
-                       module = $datamod->id and
-                       instance = $data->id";
-       return get_record_sql($SQL);
+    global $CFG, $course;
+    $datamod = get_record('modules', 'name', 'data');
+    $SQL = "select * from {$CFG->prefix}course_modules
+            where course = $course->id and
+            module = $datamod->id and
+            instance = $data->id";
+    return get_record_sql($SQL);
 }
 
 ?>
index 1adf4d4..80b149c 100644 (file)
@@ -92,11 +92,11 @@ function data_restore_mods($mod,$restore) {
                              $mod->id, $newid);
             //Now check if want to restore user data and do it.
             if (function_exists('restore_userdata_selected')) {
-               // Moodle 1.6
-                   $restore_userdata_selected = restore_userdata_selected($restore, 'data', $mod->id);
+                // Moodle 1.6
+                $restore_userdata_selected = restore_userdata_selected($restore, 'data', $mod->id);
             } else {
                 // Moodle 1.5
-                   $restore_userdata_selected = $restore->mods['data']->userinfo;
+                $restore_userdata_selected = $restore->mods['data']->userinfo;
             }
             if ($restore_userdata_selected) {
                 //Restore data_fields first!!! need to hold an array of [oldid]=>newid due to double dependencies
index b35cf31..82e5e8c 100755 (executable)
@@ -30,7 +30,7 @@
     }
     
     $cm = data_get_cm($data);
-       $context = get_context_instance(CONTEXT_MODULE, $cm->id);
+    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
 
     $inactive = NULL;
     $row = array();
@@ -46,7 +46,7 @@
     //if (isloggedin() and !isguest()) {
     if (isloggedin()) {
         if (has_capability('mod/data:writeentry', $context->id)) { // took out participation list here!
-                       $addstring = empty($editentry) ? get_string('add', 'data') : get_string('editentry', 'data');
+            $addstring = empty($editentry) ? get_string('add', 'data') : get_string('editentry', 'data');
             $row[] = new tabobject('add', $CFG->wwwroot.'/mod/data/edit.php?d='.$data->id, $addstring, '', true);
         }
         if (has_capability('mod/data:managetemplates', $context->id)) {
index 9c6c92f..4931b7e 100755 (executable)
@@ -56,9 +56,9 @@
     }
 
     require_course_login($course, true, $cm);
-       $context = get_context_instance(CONTEXT_MODULE, $cm->id);
-       has_capability('mod/data:managetemplates', $context->id, true);
-/*     
+    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
+    has_capability('mod/data:managetemplates', $context->id, true);
+/*  
     if (!isteacheredit($course->id)){
         error(get_string('noaccess','data'));
     }
index 9621ba2..10dd24c 100755 (executable)
@@ -82,9 +82,9 @@
     }
 
     require_course_login($course, true, $cm);
-       
-       $context = get_context_instance(CONTEXT_MODULE, $cm->id);
-       has_capability('mod/data:readentry', $context->id, true);
+    
+    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
+    has_capability('mod/data:readentry', $context->id, true);
 
 /// If it's hidden then it's don't show anything.  :)
     if (empty($cm->visible) and !has_capability('mod/data:managetemplates', $context->id)) {
index 4ebeab3..27fae00 100644 (file)
@@ -55,7 +55,7 @@
 
     require_login($course->id, false, $cm);
 
-       $context = get_context_instance(CONTEXT_MODULE, $cm->id);
+    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
 
     $strexercises = get_string("modulenameplural", "exercise");
     $strexercise  = get_string("modulename", "exercise");
index aa7a0af..e10dbba 100644 (file)
@@ -38,7 +38,7 @@
 
     require_login($course->id, false, $cm);
 
-       $context = get_context_instance(CONTEXT_MODULE, $cm->id);
+    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
 
     // ...log activity...
     add_to_log($course->id, "exercise", "view", "view.php?id=$cm->id", $exercise->id, $cm->id);
index 5448d92..364886f 100644 (file)
@@ -22,9 +22,9 @@
     }
 
     require_login($course->id, false, $cm);    
-       
-       $context = get_context_instance(CONTEXT_MODULE, $cm->id);
-       has_capability('mod/glossary:approve', $context->id, true);
+    
+    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
+    has_capability('mod/glossary:approve', $context->id, true);
 
     $newentry->id = $eid;
     $newentry->approved = 1;
index 3161431..365f658 100644 (file)
@@ -38,9 +38,9 @@
 
     require_login($course->id, false, $cm);
     
-       $context = get_context_instance(CONTEXT_MODULE, $cm->id);
+    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
     
-       if (isguest()) {
+    if (isguest()) {
         error('Guests are not allowed to post comments', $_SERVER['HTTP_REFERER']);
     }
     add_to_log($course->id, 'glossary', 'view', "view.php?id=$cm->id", "$glossary->id",$cm->id);
index 38a5463..176fced 100644 (file)
@@ -25,7 +25,7 @@
         error("Entry is incorrect");
     }
 
-       $context = get_context_instance(CONTEXT_MODULE, $cm->id);
+    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
 
     require_login($course->id, false, $cm);
 
index 3d20b81..b66d841 100644 (file)
@@ -29,8 +29,8 @@
     }
 
     require_login($course->id, false, $cm);
-       $context = get_context_instance(CONTEXT_MODULE, $cm->id);
-       
+    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
+    
     if (isguest()) {
         error("Guests are not allowed to edit or delete entries", $_SERVER["HTTP_REFERER"]);
     }
index 95e6623..5e07395 100644 (file)
@@ -166,7 +166,7 @@ if ( $confirm ) {
             error("Could not update this glossary entry because this concept already exist.");
         }
     } else {
-               
+        
         $newentry->userid = $USER->id;
         $newentry->timecreated = $timenow;
         $newentry->sourceglossaryid = 0;
@@ -332,7 +332,7 @@ $tab = GLOSSARY_ADDENTRY_VIEW;
 include("tabs.html");
 
 if (!$e) {
-       has_capability('glossary_write', $context->id, true);  
+    has_capability('glossary_write', $context->id, true);  
 }
 
 include("edit.html");
index 83d6dd5..94d3f47 100644 (file)
@@ -44,7 +44,7 @@
     require_login($course->id, false);
 
     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
-       has_capability('mod/glossary:managecategories', $context->id, true);
+    has_capability('mod/glossary:managecategories', $context->id, true);
 
     $strglossaries   = get_string("modulenameplural", "glossary");
     $strglossary     = get_string("modulename", "glossary");
index 712cf75..cbe03fe 100644 (file)
         error("Course module is incorrect");
     }
 
-    require_login($course->id, false); 
-       
-       $context = get_context_instance(CONTEXT_MODULE, $cm->id);
-       has_capability('mod/glossary:export', $context->id, true);
+    require_login($course->id, false);  
+    
+    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
+    has_capability('mod/glossary:export', $context->id, true);
 
     $strglossaries = get_string("modulenameplural", "glossary");
     $strglossary = get_string("modulename", "glossary");
index 8619cc6..735eec4 100644 (file)
@@ -29,8 +29,8 @@
             $lcase = 'lcase';
     }
 
-       $context = get_context_instance(CONTEXT_MODULE, $cm->id);
-       has_capability('mod/glossary:export', $context->id, true);
+    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
+    has_capability('mod/glossary:export', $context->id, true);
 
     if (! $course = get_record('course', 'id', $cm->course)) {
         error('Course is misconfigured');
index e4f163d..ca3338c 100644 (file)
     }
 
     require_login($course->id, false);
-       
-       $context = get_context_instance(CONTEXT_MODULE, $cm->id);
-       has_capability('mod/glossary:export', $context->id, true);
-       
+    
+    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
+    has_capability('mod/glossary:export', $context->id, true);
+    
     $filename = clean_filename(strip_tags(format_string($glossary->name,true)).'.xml');
     $content = glossary_generate_export_file($glossary,$l,$cat);
     
index 0f1c029..ad2f018 100644 (file)
@@ -18,7 +18,7 @@
     if (! $cm = get_coursemodule_from_id('glossary', $id)) {
         error("Course Module ID was incorrect");
     }
-       
+    
     if (! $course = get_record("course", "id", $cm->course)) {
         error("Course is misconfigured");
     }
         error("Course module is incorrect");
     }
 
-    require_login($course->id, false); 
-       
-       $context = get_context_instance(CONTEXT_MODULE, $cm->id);
-       has_capability('mod/glossary:import', $context->id, true);
+    require_login($course->id, false);  
+    
+    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
+    has_capability('mod/glossary:import', $context->id, true);
 
     if ($dest != 'new' and $dest != 'current') {
         $dest = 'current';
index 5df9c68..0185ab0 100644 (file)
@@ -738,8 +738,8 @@ function  glossary_print_entry_aliases($course, $cm, $glossary, $entry,$mode='',
 
 function glossary_print_entry_icons($course, $cm, $glossary, $entry, $mode='',$hook='', $type = 'print') {
     global $USER, $CFG;
-       
-       $context = get_context_instance(CONTEXT_MODULE, $cm->id);
+    
+    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
 
     $output = false;   //To decide if we must really return text in "return". Activate when needed only!
     $importedentry = ($entry->sourceglossaryid == $glossary->id);
@@ -754,15 +754,15 @@ function glossary_print_entry_icons($course, $cm, $glossary, $entry, $mode='',$h
     $return .= glossary_print_entry_commentslink($course, $cm, $glossary, $entry,$mode,$hook,'html');
     
     if (has_capability('mod/glossary:comment', $context->id)) {
-           $output = true;
+        $output = true;
         $return .= ' <a title="' . get_string('addcomment','glossary') . '" href="comment.php?id='.$cm->id.'&amp;eid='.$entry->id.'"><img src="comment.gif" height="11" width="11" border="0" alt="'.get_string('addcomment','glossary').'" /></a>';
     }
 
 
     if (has_capability('mod/glossary:write', $context->id) or (!empty($USER->id) and $glossary->studentcanpost and $entry->userid == $USER->id)) {
         // only teachers can export entries so check it out
-       if (has_capability('mod/glossary:export', $context->id) and !$ismainglossary and !$importedentry) {
-               $mainglossary = get_record('glossary','mainglossary',1,'course',$course->id);
+        if (has_capability('mod/glossary:export', $context->id) and !$ismainglossary and !$importedentry) {
+            $mainglossary = get_record('glossary','mainglossary',1,'course',$course->id);
             if ( $mainglossary ) {  // if there is a main glossary defined, allow to export the current entry
                 $output = true;
                 $return .= ' <a title="'.get_string('exporttomainglossary','glossary') . '" href="exportentry.php?id='.$cm->id.'&amp;entry='.$entry->id.'&amp;mode='.$mode.'&amp;hook='.$hook.'"><img src="export.gif" height="11" width="11" border="0" alt="'.get_string('exporttomainglossary','glossary').'" /></a>';
@@ -1303,9 +1303,9 @@ function glossary_print_author_menu($cm, $glossary,$mode, $hook, $sortkey = '',
 
 function glossary_print_categories_menu($cm, $glossary, $hook, $category) {
      
-        global $CFG;
-        
-        $context = get_context_instance(CONTEXT_MODULE, $cm->id);
+     global $CFG;
+     
+     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
 
      echo '<table border="0" width="100%">';
      echo '<tr>';
@@ -1563,8 +1563,8 @@ function  glossary_print_entry_ratings($course, $entry, $ratings = NULL) {
     $glossary = get_record('glossary', 'id', $entry->glossaryid);
     $glossarymod = get_record('modules','name','glossary');
     $cm = get_record_sql("select * from {$CFG->prefix}course_modules where course = $course->id 
-                                         and module = $glossarymod->id and instance = $glossary->id");
-                                         
+                          and module = $glossarymod->id and instance = $glossary->id");
+                          
     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
 
     $ratingsmenuused = false;
index 2492525..8ac786f 100644 (file)
@@ -21,8 +21,8 @@
     
     $module = get_record("modules","name","glossary");
     $cm = get_record("course_modules","module",$module->id,"instance",$entry->glossaryid);
-       $context = get_context_instance(CONTEXT_MODULE, $cm->id);
-       
+    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
+    
     if (!has_capability('mod/glossary:manageentries', $context->id) and $USER->id != $entry->userid) {
         error("You can only look at results for your own entries");
     }
index ad1ed73..6ada25b 100644 (file)
@@ -23,8 +23,8 @@
     }
     if (has_capability('mod/glossary:import', $context->id)) {
         $data[GLOSSARY_IMPORT_VIEW]->caption = get_string("importentries", "glossary");
-       $data[GLOSSARY_IMPORT_VIEW]->link = "import.php?id=$cm->id";
-       }
+        $data[GLOSSARY_IMPORT_VIEW]->link = "import.php?id=$cm->id";
+    }
         
     if (has_capability('mod/glossary:export', $context->id)) {
         $data[GLOSSARY_EXPORT_VIEW]->caption = get_string("exportentries", "glossary");     
@@ -39,8 +39,8 @@
     $data[GLOSSARY_CATEGORY_VIEW]->link = "view.php?id=$id&amp;mode=cat";
     $data[GLOSSARY_AUTHOR_VIEW]->link = "view.php?id=$id&amp;mode=author";
 
-       if (has_capability('mod/glossary:approve', $context->id)) {
-           $data[GLOSSARY_APPROVAL_VIEW]->caption = get_string("waitingapproval", "glossary");
+    if (has_capability('mod/glossary:approve', $context->id)) {
+        $data[GLOSSARY_APPROVAL_VIEW]->caption = get_string("waitingapproval", "glossary");
         $data[GLOSSARY_APPROVAL_VIEW]->link = "";
 
         $hiddenentries = get_records_select("glossary_entries","glossaryid  = $glossary->id and approved = 0");
index d013974..71f2796 100644 (file)
@@ -44,8 +44,8 @@
         error("Must specify glossary ID or course module ID");
     }
 
-       $context = get_context_instance(CONTEXT_MODULE, $cm->id);
-       has_capability('mod/glossary:view', $context->id, true); // kill the page if user can't even read
+    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
+    has_capability('mod/glossary:view', $context->id, true); // kill the page if user can't even read
 
     if ($CFG->forcelogin) {
         require_login();
index b7d5e55..68c612c 100644 (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'));
-       }
+    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
+//  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;
+    // 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;
+    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 48585a7..a783402 100644 (file)
@@ -2,24 +2,24 @@
 <INPUT type="hidden" name="sesskey" value="<?PHP print isset($USER->sesskey) ? $USER->sesskey : '' ?>">
 
 <TABLE cellpadding="9" cellspacing="0">
-       <TR valign="top">
-               <TD align="right"><P>hotpot_showtimes:</TD>
-               <TD><?PHP 
-                       unset($choices);
-                       $choices["0"] = get_string("no");
-                       $choices["1"] = get_string("yes");
-                       choose_from_menu ($choices, "hotpot_showtimes", $CFG->hotpot_showtimes, "");
-               ?></TD>
-               <TD><?PHP print_string("configshowtimes", "hotpot") ?></TD>
-       </TR>
-       <TR valign=top>
-               <TD align="right"><P>hotpot_excelencodings:</TD>
-               <TD><INPUT name=hotpot_excelencodings type=text size=30 value="<?PHP p($CFG->hotpot_excelencodings) ?>"></TD>
-               <TD><?PHP print_string("configexcelencodings", "hotpot") ?></TD>
-       </TR>
-       <TR>
-               <TD colspan="3" align="center"><INPUT type="submit" value="<?PHP print_string("savechanges") ?>"></TD>
-       </TR>
+    <TR valign="top">
+        <TD align="right"><P>hotpot_showtimes:</TD>
+        <TD><?PHP 
+            unset($choices);
+            $choices["0"] = get_string("no");
+            $choices["1"] = get_string("yes");
+            choose_from_menu ($choices, "hotpot_showtimes", $CFG->hotpot_showtimes, "");
+        ?></TD>
+        <TD><?PHP print_string("configshowtimes", "hotpot") ?></TD>
+    </TR>
+    <TR valign=top>
+        <TD align="right"><P>hotpot_excelencodings:</TD>
+        <TD><INPUT name=hotpot_excelencodings type=text size=30 value="<?PHP p($CFG->hotpot_excelencodings) ?>"></TD>
+        <TD><?PHP print_string("configexcelencodings", "hotpot") ?></TD>
+    </TR>
+    <TR>
+        <TD colspan="3" align="center"><INPUT type="submit" value="<?PHP print_string("savechanges") ?>"></TD>
+    </TR>
 </TABLE>
 
 </FORM>
index 561f626..ab75b1e 100644 (file)
@@ -1,43 +1,43 @@
 <?PHP
 function hotpot_upgrade($oldversion) {
-       global $CFG;
-       $ok = true;
+    global $CFG;
+    $ok = true;
 
-       if ($oldversion < 2004021400) {
-               execute_sql(" ALTER TABLE `{$CFG->prefix}hotpot_events` ADD `starttime` INT(10) unsigned NOT NULL DEFAULT '0' AFTER `time`");
-               execute_sql(" ALTER TABLE `{$CFG->prefix}hotpot_events` ADD `endtime` INT(10) unsigned NOT NULL DEFAULT '0' AFTER `time`");
-       }
+    if ($oldversion < 2004021400) {
+        execute_sql(" ALTER TABLE `{$CFG->prefix}hotpot_events` ADD `starttime` INT(10) unsigned NOT NULL DEFAULT '0' AFTER `time`");
+        execute_sql(" ALTER TABLE `{$CFG->prefix}hotpot_events` ADD `endtime` INT(10) unsigned NOT NULL DEFAULT '0' AFTER `time`");
+    }
 
-       // set path to update functions
-       $update_to_v2 = "$CFG->dirroot/mod/hotpot/db/update_to_v2.php";
+    // set path to update functions
+    $update_to_v2 = "$CFG->dirroot/mod/hotpot/db/update_to_v2.php";
 
-       // update from HotPot v1 to HotPot v2
-       if ($oldversion < 2005031400) {
-               require_once $update_to_v2;
-               $ok = $ok && hotpot_update_to_v2_from_v1();
-       }
-       if ($oldversion < 2005090700) {
-               require_once $update_to_v2;
-               $ok = $ok && hotpot_update_to_v2_1();
-       }
-       if ($oldversion > 2005031419 && $oldversion < 2005090702) {
-               // update to from HotPot v2.1.0 or v2.1.1
-               require_once $update_to_v2;
-               $ok = $ok && hotpot_update_to_v2_1_2();
-       }
-       if ($oldversion < 2006042103) {
-               require_once $update_to_v2;
-               $ok = $ok && hotpot_update_to_v2_1_16();
-       }
-       if ($oldversion < 2006042601) {
-               require_once $update_to_v2;
-               $ok = $ok && hotpot_update_to_v2_1_17();
-       }
-       if ($oldversion < 2006042803) {
-               require_once $update_to_v2;
-               $ok = $ok && hotpot_update_to_v2_1_18();
-       }
+    // update from HotPot v1 to HotPot v2
+    if ($oldversion < 2005031400) {
+        require_once $update_to_v2;
+        $ok = $ok && hotpot_update_to_v2_from_v1();
+    }
+    if ($oldversion < 2005090700) {
+        require_once $update_to_v2;
+        $ok = $ok && hotpot_update_to_v2_1();
+    }
+    if ($oldversion > 2005031419 && $oldversion < 2005090702) {
+        // update to from HotPot v2.1.0 or v2.1.1
+        require_once $update_to_v2;
+        $ok = $ok && hotpot_update_to_v2_1_2();
+    }
+    if ($oldversion < 2006042103) {
+        require_once $update_to_v2;
+        $ok = $ok && hotpot_update_to_v2_1_16();
+    }
+    if ($oldversion < 2006042601) {
+        require_once $update_to_v2;
+        $ok = $ok && hotpot_update_to_v2_1_17();
+    }
+    if ($oldversion < 2006042803) {
+        require_once $update_to_v2;
+        $ok = $ok && hotpot_update_to_v2_1_18();
+    }
 
-       return $ok;
+    return $ok;
 }
 ?>
index 9c8eb45..b8eb14a 100644 (file)
@@ -3,7 +3,7 @@ function hotpot_update_to_v2_1_21() {
     global $CFG;
     $ok = true;
 
-       if (strtolower($CFG->dbtype)=='postgres7') {
+    if (strtolower($CFG->dbtype)=='postgres7') {
         // ensure setting of default values on certain fields
         // this was originally done in postgres7.php, but was found to be incompatible with PG7 :-(
         $table="hotpot";
@@ -36,1293 +36,1293 @@ function hotpot_update_to_v2_1_21() {
     return $ok;
 }
 function hotpot_update_to_v2_1_18() {
-       $ok = true;
+    $ok = true;
 
-       // remove all orphan records (there shouldn't be any, but if there are they can mess up the utfdbmigrate)
+    // remove all orphan records (there shouldn't be any, but if there are they can mess up the utfdbmigrate)
 
-       $ok = $ok && hotpot_remove_orphans('hotpot_attempts', 'hotpot', 'hotpot');
-       $ok = $ok && hotpot_remove_orphans('hotpot_questions', 'hotpot', 'hotpot');
-       $ok = $ok && hotpot_remove_orphans('hotpot_responses', 'attempt', 'hotpot_attempts');
-       $ok = $ok && hotpot_remove_orphans('hotpot_responses', 'question', 'hotpot_questions');
-       $ok = $ok && hotpot_remove_orphans('hotpot_details', 'attempt', 'hotpot_attempts');
+    $ok = $ok && hotpot_remove_orphans('hotpot_attempts', 'hotpot', 'hotpot');
+    $ok = $ok && hotpot_remove_orphans('hotpot_questions', 'hotpot', 'hotpot');
+    $ok = $ok && hotpot_remove_orphans('hotpot_responses', 'attempt', 'hotpot_attempts');
+    $ok = $ok && hotpot_remove_orphans('hotpot_responses', 'question', 'hotpot_questions');
+    $ok = $ok && hotpot_remove_orphans('hotpot_details', 'attempt', 'hotpot_attempts');
 
-       // allow negative weighting and scores
+    // allow negative weighting and scores
 
-       $ok = $ok && hotpot_denull_int_field('hotpot_responses', 'weighting', '6', false);
-       $ok = $ok && hotpot_denull_int_field('hotpot_responses', 'score', '6', false);
+    $ok = $ok && hotpot_denull_int_field('hotpot_responses', 'weighting', '6', false);
+    $ok = $ok && hotpot_denull_int_field('hotpot_responses', 'score', '6', false);
 
-       return $ok;
+    return $ok;
 }
 function hotpot_remove_orphans($secondarytable, $secondarykeyfield, $primarytable, $primarykeyfield='id') {
-       global $CFG,$db;
-       $ok = true;
+    global $CFG,$db;
+    $ok = true;
 
-       // save and switch off SQL message echo
-       $debug = $db->debug;
-       $db->debug = false;
+    // save and switch off SQL message echo
+    $debug = $db->debug;
+    $db->debug = false;
 
-       $records = get_records_sql("
-               SELECT 
-                       t2.$secondarykeyfield, t2.$secondarykeyfield
-               FROM 
-                       {$CFG->prefix}$secondarytable AS t2 LEFT JOIN {$CFG->prefix}$primarytable AS t1 
-                       ON (t2.$secondarykeyfield = t1.id)
-               WHERE 
-                       t1.$primarykeyfield IS NULL
-       ");
+    $records = get_records_sql("
+        SELECT 
+            t2.$secondarykeyfield, t2.$secondarykeyfield
+        FROM 
+            {$CFG->prefix}$secondarytable AS t2 LEFT JOIN {$CFG->prefix}$primarytable AS t1 
+            ON (t2.$secondarykeyfield = t1.id)
+        WHERE 
+            t1.$primarykeyfield IS NULL
+    ");
 
-       // restore SQL message echo setting
-       $db->debug = $debug;
+    // restore SQL message echo setting
+    $db->debug = $debug;
 
-       if ($records) {
-               $keys = implode(',', array_keys($records));
-               print "removing orphan record(s) from {$CFG->prefix}$secondarytable<br>";
-               $ok = $ok && execute_sql("DELETE FROM {$CFG->prefix}$secondarytable WHERE $secondarykeyfield IN ($keys)");
-       }
+    if ($records) {
+        $keys = implode(',', array_keys($records));
+        print "removing orphan record(s) from {$CFG->prefix}$secondarytable<br>";
+        $ok = $ok && execute_sql("DELETE FROM {$CFG->prefix}$secondarytable WHERE $secondarykeyfield IN ($keys)");
+    }
 
-       return $ok;
+    return $ok;
 }
 function hotpot_update_to_v2_1_17() {
-       global $CFG;
-       $ok = true;
+    global $CFG;
+    $ok = true;
 
-       // convert and disable null values on certain numeric fields
+    // convert and disable null values on certain numeric fields
 
-       $ok = $ok && hotpot_denull_int_field('hotpot_attempts', 'starttime', '10');
-       $ok = $ok && hotpot_denull_int_field('hotpot_attempts', 'endtime', '10');
-       $ok = $ok && hotpot_denull_int_field('hotpot_attempts', 'score', '6');
-       $ok = $ok && hotpot_denull_int_field('hotpot_attempts', 'penalties',  '6');
-       $ok = $ok && hotpot_denull_int_field('hotpot_attempts', 'timestart', '10');
-       $ok = $ok && hotpot_denull_int_field('hotpot_attempts', 'timefinish', '10');
-       $ok = $ok && hotpot_denull_int_field('hotpot_attempts', 'clickreportid', '10');
+    $ok = $ok && hotpot_denull_int_field('hotpot_attempts', 'starttime', '10');
+    $ok = $ok && hotpot_denull_int_field('hotpot_attempts', 'endtime', '10');
+    $ok = $ok && hotpot_denull_int_field('hotpot_attempts', 'score', '6');
+    $ok = $ok && hotpot_denull_int_field('hotpot_attempts', 'penalties',  '6');
+    $ok = $ok && hotpot_denull_int_field('hotpot_attempts', 'timestart', '10');
+    $ok = $ok && hotpot_denull_int_field('hotpot_attempts', 'timefinish', '10');
+    $ok = $ok && hotpot_denull_int_field('hotpot_attempts', 'clickreportid', '10');
 
-       $ok = $ok && hotpot_denull_int_field('hotpot_questions', 'type', '4');
-       $ok = $ok && hotpot_denull_int_field('hotpot_questions', 'text', '10');
+    $ok = $ok && hotpot_denull_int_field('hotpot_questions', 'type', '4');
+    $ok = $ok && hotpot_denull_int_field('hotpot_questions', 'text', '10');
 
-       $ok = $ok && hotpot_denull_int_field('hotpot_responses', 'weighting', '6', false);
-       $ok = $ok && hotpot_denull_int_field('hotpot_responses', 'score', '6', false);
-       $ok = $ok && hotpot_denull_int_field('hotpot_responses', 'hints', '6');
-       $ok = $ok && hotpot_denull_int_field('hotpot_responses', 'clues', '6');
-       $ok = $ok && hotpot_denull_int_field('hotpot_responses', 'checks', '6');
-       return $ok;
+    $ok = $ok && hotpot_denull_int_field('hotpot_responses', 'weighting', '6', false);
+    $ok = $ok && hotpot_denull_int_field('hotpot_responses', 'score', '6', false);
+    $ok = $ok && hotpot_denull_int_field('hotpot_responses', 'hints', '6');
+    $ok = $ok && hotpot_denull_int_field('hotpot_responses', 'clues', '6');
+    $ok = $ok && hotpot_denull_int_field('hotpot_responses', 'checks', '6');
+    return $ok;
 }
 function hotpot_denull_int_field($table, $field, $size, $unsigned=true) {
-       global $CFG;
-       $ok = true;
+    global $CFG;
+    $ok = true;
 
-       $ok = $ok && execute_sql("UPDATE {$CFG->prefix}$table SET $field=0 WHERE $field IS NULL", false);
-       if ($unsigned) {
-               $ok = $ok && execute_sql("UPDATE {$CFG->prefix}$table SET $field=0 WHERE $field<0", false);
-       }
-       $ok = $ok && hotpot_db_update_field_type($table, $field, $field, 'INTEGER', $size, $unsigned, 'NOT NULL', 0);
+    $ok = $ok && execute_sql("UPDATE {$CFG->prefix}$table SET $field=0 WHERE $field IS NULL", false);
+    if ($unsigned) {
+        $ok = $ok && execute_sql("UPDATE {$CFG->prefix}$table SET $field=0 WHERE $field<0", false);
+    }
+    $ok = $ok && hotpot_db_update_field_type($table, $field, $field, 'INTEGER', $size, $unsigned, 'NOT NULL', 0);
 
-       return $ok;
+    return $ok;
 }
 function hotpot_update_to_v2_1_16() {
-       global $CFG;
-       $ok = true;
+    global $CFG;
+    $ok = true;
 
-       // settings for the "hotpot_questions_name_idx" index
-       $length = 20;
-       $field = 'name';
-       $table = 'hotpot_questions';
-       $index = "{$table}_{$field}_idx";
+    // settings for the "hotpot_questions_name_idx" index
+    $length = 20;
+    $field = 'name';
+    $table = 'hotpot_questions';
+    $index = "{$table}_{$field}_idx";
 
-       // remove the index
-       hotpot_db_delete_index("{$CFG->prefix}$table", $index);
-       hotpot_db_delete_index("{$CFG->prefix}$table", "{$CFG->prefix}$index");
+    // remove the index
+    hotpot_db_delete_index("{$CFG->prefix}$table", $index);
+    hotpot_db_delete_index("{$CFG->prefix}$table", "{$CFG->prefix}$index");
 
-       // make sure type of 'name' is a text field (not varchar 255)
-       $ok = $ok && hotpot_db_update_field_type($table, $field, $field, 'TEXT',   '',  '', 'NOT NULL', '');
+    // make sure type of 'name' is a text field (not varchar 255)
+    $ok = $ok && hotpot_db_update_field_type($table, $field, $field, 'TEXT',   '',  '', 'NOT NULL', '');
 
-       // restore the index
-       $ok = $ok && hotpot_db_add_index($table, $field, $length);
+    // restore the index
+    $ok = $ok && hotpot_db_add_index($table, $field, $length);
 
-       if (strtolower($CFG->dbtype)=='mysql') {
+    if (strtolower($CFG->dbtype)=='mysql') {
 
-               // set default values on certain VARCHAR(255) fields
-               $varchar_fields = array(
-                       'hotpot.studentfeedbackurl',
-                       'hotpot_responses.correct',
-                       'hotpot_responses.wrong',
-                       'hotpot_responses.ignored'
-               );
-               foreach ($varchar_fields as $varchar_field) {
-                       list ($table, $field) = explode('.', $varchar_field);
-                       execute_sql("UPDATE {$CFG->prefix}$table SET $field='' WHERE $field IS NULL");
-                       $ok = $ok && hotpot_db_update_field_type($table, $field, $field, 'VARCHAR', 255, '', 'NOT NULL', '');
-               }
+        // set default values on certain VARCHAR(255) fields
+        $varchar_fields = array(
+            'hotpot.studentfeedbackurl',
+            'hotpot_responses.correct',
+            'hotpot_responses.wrong',
+            'hotpot_responses.ignored'
+        );
+        foreach ($varchar_fields as $varchar_field) {
+            list ($table, $field) = explode('.', $varchar_field);
+            execute_sql("UPDATE {$CFG->prefix}$table SET $field='' WHERE $field IS NULL");
+            $ok = $ok && hotpot_db_update_field_type($table, $field, $field, 'VARCHAR', 255, '', 'NOT NULL', '');
+        }
 
-               // remove $CFG->prefix from all index names
-               $ok = $ok && hotpot_index_remove_prefix('hotpot_attempts', 'hotpot');
-               $ok = $ok && hotpot_index_remove_prefix('hotpot_attempts', 'userid');
-               $ok = $ok && hotpot_index_remove_prefix('hotpot_details', 'attempt');
-               $ok = $ok && hotpot_index_remove_prefix('hotpot_questions', 'hotpot');
-               //$ok = $ok && hotpot_index_remove_prefix('hotpot_questions', 'name', 20);
-               $ok = $ok && hotpot_index_remove_prefix('hotpot_responses', 'attempt');
-               $ok = $ok && hotpot_index_remove_prefix('hotpot_responses', 'question');
-               $ok = $ok && hotpot_index_remove_prefix('hotpot_strings', 'string', 20);
-       }
-       return $ok;
+        // remove $CFG->prefix from all index names
+        $ok = $ok && hotpot_index_remove_prefix('hotpot_attempts', 'hotpot');
+        $ok = $ok && hotpot_index_remove_prefix('hotpot_attempts', 'userid');
+        $ok = $ok && hotpot_index_remove_prefix('hotpot_details', 'attempt');
+        $ok = $ok && hotpot_index_remove_prefix('hotpot_questions', 'hotpot');
+        //$ok = $ok && hotpot_index_remove_prefix('hotpot_questions', 'name', 20);
+        $ok = $ok && hotpot_index_remove_prefix('hotpot_responses', 'attempt');
+        $ok = $ok && hotpot_index_remove_prefix('hotpot_responses', 'question');
+        $ok = $ok && hotpot_index_remove_prefix('hotpot_strings', 'string', 20);
+    }
+    return $ok;
 }
 function hotpot_index_remove_prefix($table, $field, $length=0) {
-       global $CFG;
-       $index = "{$table}_{$field}_idx";
-       hotpot_db_delete_index("{$CFG->prefix}$table", "{$CFG->prefix}$index");
-       hotpot_db_delete_index("{$CFG->prefix}$table", $index);
-       return hotpot_db_add_index($table, $field, $length);
+    global $CFG;
+    $index = "{$table}_{$field}_idx";
+    hotpot_db_delete_index("{$CFG->prefix}$table", "{$CFG->prefix}$index");
+    hotpot_db_delete_index("{$CFG->prefix}$table", $index);
+    return hotpot_db_add_index($table, $field, $length);
 }
 
 function hotpot_update_to_v2_1_8() {
-       global $CFG;
-       $ok = true;
-       if (strtolower($CFG->dbtype)=='postgres7') {
-               // add, delete and rename certain fields and indexes
-               // that were not correctly setup by postgres7.sql
+    global $CFG;
+    $ok = true;
+    if (strtolower($CFG->dbtype)=='postgres7') {
+        // add, delete and rename certain fields and indexes
+        // that were not correctly setup by postgres7.sql
 
-               // hotpot
-               $table = 'hotpot';
-               if (hotpot_db_field_exists($table, 'microreporting')) {
-                       $ok = $ok && hotpot_db_update_field_type($table, 'microreporting', 'clickreporting', 'INTEGER', 4, 'UNSIGNED', 'NOT NULL', '0');
-               }
-       }
-       return $ok;
+        // hotpot
+        $table = 'hotpot';
+        if (hotpot_db_field_exists($table, 'microreporting')) {
+            $ok = $ok && hotpot_db_update_field_type($table, 'microreporting', 'clickreporting', 'INTEGER', 4, 'UNSIGNED', 'NOT NULL', '0');
+        }
+    }
+    return $ok;
 }
 function hotpot_update_to_v2_1_6() {
-       global $CFG;
-       $ok = true;
+    global $CFG;
+    $ok = true;
 
-       if (strtolower($CFG->dbtype)=='postgres7') {
-               // add, delete and rename certain fields and indexes
-               // that were not correctly setup by postgres7.sql
+    if (strtolower($CFG->dbtype)=='postgres7') {
+        // add, delete and rename certain fields and indexes
+        // that were not correctly setup by postgres7.sql
 
-               // hotpot
-               $table = 'hotpot';
-               if (hotpot_db_field_exists($table, 'studentfeedback') && !hotpot_db_field_exists($table, 'studentfeedbackurl')) {
-                       $ok = $ok && hotpot_db_update_field_type($table, 'studentfeedback', 'studentfeedbackurl', 'VARCHAR', 255, '', 'NULL');
-                       $ok = $ok && hotpot_db_update_field_type($table, '', 'studentfeedback', 'INTEGER', 4, 'UNSIGNED', 'NOT NULL', '0');
-               }
+        // hotpot
+        $table = 'hotpot';
+        if (hotpot_db_field_exists($table, 'studentfeedback') && !hotpot_db_field_exists($table, 'studentfeedbackurl')) {
+            $ok = $ok && hotpot_db_update_field_type($table, 'studentfeedback', 'studentfeedbackurl', 'VARCHAR', 255, '', 'NULL');
+            $ok = $ok && hotpot_db_update_field_type($table, '', 'studentfeedback', 'INTEGER', 4, 'UNSIGNED', 'NOT NULL', '0');
+        }
 
-               // hotpot_attempts
-               $table = 'hotpot_attempts';
-               $ok = $ok && hotpot_db_remove_field($table, 'groupid');
-               if (hotpot_db_field_exists($table, 'microreportid') && !hotpot_db_field_exists($table, 'clickreportid')) {
-                       $ok = $ok && hotpot_db_update_field_type($table, 'microreportid', 'clickreportid', 'INTEGER', 10, 'UNSIGNED', 'NULL');
-               }
+        // hotpot_attempts
+        $table = 'hotpot_attempts';
+        $ok = $ok && hotpot_db_remove_field($table, 'groupid');
+        if (hotpot_db_field_exists($table, 'microreportid') && !hotpot_db_field_exists($table, 'clickreportid')) {
+            $ok = $ok && hotpot_db_update_field_type($table, 'microreportid', 'clickreportid', 'INTEGER', 10, 'UNSIGNED', 'NULL');
+        }
 
-               // hotpot_questions (add index on question "name")
-               $table = 'hotpot_questions';
-               $field = 'name';
-               $index = "{$table}_{$field}_idx";
-               if (!hotpot_db_index_exists("{$CFG->prefix}$table", "{$CFG->prefix}$index")) {
-                       hotpot_db_add_index($table, $field, '20');
-               }
+        // hotpot_questions (add index on question "name")
+        $table = 'hotpot_questions';
+        $field = 'name';
+        $index = "{$table}_{$field}_idx";
+        if (!hotpot_db_index_exists("{$CFG->prefix}$table", "{$CFG->prefix}$index")) {
+            hotpot_db_add_index($table, $field, '20');
+        }
 
-               // hotpot_strings (add index on "string")
-               $table = "hotpot_strings";
-               $field = 'string';
-               $index = "{$table}_{$field}_idx";
-               if (!hotpot_db_index_exists("{$CFG->prefix}$table", "{$CFG->prefix}$index")) {
-                       hotpot_db_add_index($table, $field, '20');
-               }
-       }
+        // hotpot_strings (add index on "string")
+        $table = "hotpot_strings";
+        $field = 'string';
+        $index = "{$table}_{$field}_idx";
+        if (!hotpot_db_index_exists("{$CFG->prefix}$table", "{$CFG->prefix}$index")) {
+            hotpot_db_add_index($table, $field, '20');
+        }
+    }
 
-       return $ok;
+    return $ok;
 }
 function hotpot_update_to_v2_1_2() {
-       global $CFG, $db;
-       $ok = true;
+    global $CFG, $db;
+    $ok = true;
 
-       // save and switch off SQL message echo
-       $debug = $db->debug;
-       $db->debug = false;
+    // save and switch off SQL message echo
+    $debug = $db->debug;
+    $db->debug = false;
 
-       // extract info about attempts by each user on each hotpot (cases where 
-       // the user has only one attempt, or no "in progess" attempt are ignored)
-       $rs = $db->Execute("
-               SELECT userid, hotpot, COUNT(*), MIN(status)
-               FROM {$CFG->prefix}hotpot_attempts
-               GROUP BY userid, hotpot
-               HAVING COUNT(*)>1 AND MIN(status)=1
-       ");
-       if ($rs && $rs->RecordCount()) {
-               $records = $rs->GetArray();
+    // extract info about attempts by each user on each hotpot (cases where 
+    // the user has only one attempt, or no "in progess" attempt are ignored)
+    $rs = $db->Execute("
+        SELECT userid, hotpot, COUNT(*), MIN(status)
+        FROM {$CFG->prefix}hotpot_attempts
+        GROUP BY userid, hotpot
+        HAVING COUNT(*)>1 AND MIN(status)=1
+    ");
+    if ($rs && $rs->RecordCount()) {
+        $records = $rs->GetArray();
 
-               // start message to browser
-               print "adjusting status of ".count($records)." &quot;in progress&quot; attempts ... ";
+        // start message to browser
+        print "adjusting status of ".count($records)." &quot;in progress&quot; attempts ... ";
 
-               // loop through records
-               foreach ($records as $record) {
+        // loop through records
+        foreach ($records as $record) {
 
-                       // get all attempts by this user at this hotpot
-                       $attempts = get_records_sql("
-                               SELECT id, userid, hotpot, score, timestart, timefinish, status 
-                               FROM {$CFG->prefix}hotpot_attempts 
-                               WHERE userid = ".$record['userid']." AND hotpot=".$record['hotpot']."
-                               ORDER BY timestart DESC, id DESC
-                       ");
+            // get all attempts by this user at this hotpot
+            $attempts = get_records_sql("
+                SELECT id, userid, hotpot, score, timestart, timefinish, status 
+                FROM {$CFG->prefix}hotpot_attempts 
+                WHERE userid = ".$record['userid']." AND hotpot=".$record['hotpot']."
+                ORDER BY timestart DESC, id DESC
+            ");
 
-                       unset($previous_timestart);
+            unset($previous_timestart);
 
-                       foreach ($attempts as $attempt) {
-                               // if this attempt has a status of "in progress" and is not 
-                               // the most recent one in the group, set the status to "abandoned"
-                               if ($attempt->status==1 && isset($previous_timestart)) {
-                                       $values = 'status=3';
-                                       if (empty($attempt->score)) {
-                                               $values .= ',score=0';
-                                       }
-                                       if (empty($attempt->timefinish)) {
-                                               $values .= ",timefinish=$previous_timestart";
-                                       }
-                                       execute_sql("UPDATE {$CFG->prefix}hotpot_attempts SET $values WHERE id=$attempt->id", false);
-                                       print ".";
-                                       hotpot_flush(300);
-                               }
-                               $previous_timestart = $attempt->timestart;
-                       } // end foreach $attempts
-               } // end foreach $records
+            foreach ($attempts as $attempt) {
+                // if this attempt has a status of "in progress" and is not 
+                // the most recent one in the group, set the status to "abandoned"
+                if ($attempt->status==1 && isset($previous_timestart)) {
+                    $values = 'status=3';
+                    if (empty($attempt->score)) {
+                        $values .= ',score=0';
+                    }
+                    if (empty($attempt->timefinish)) {
+                        $values .= ",timefinish=$previous_timestart";
+                    }
+                    execute_sql("UPDATE {$CFG->prefix}hotpot_attempts SET $values WHERE id=$attempt->id", false);
+                    print ".";
+                    hotpot_flush(300);
+                }
+                $previous_timestart = $attempt->timestart;
+            } // end foreach $attempts
+        } // end foreach $records
 
-               // finish message to browser
-               print $ok ? get_string('success') : 'failed';
-               print "<br />\n";
-       }
+        // finish message to browser
+        print $ok ? get_string('success') : 'failed';
+        print "<br />\n";
+    }
 
-       // restore SQL message echo setting
-       $db->debug = $debug;
+    // restore SQL message echo setting
+    $db->debug = $debug;
 
-       return $ok;
+    return $ok;
 }
 function hotpot_update_to_v2_1() {
-       global $CFG, $db;
-       $ok = true;
-       // hotpot_questions: reduce size of "type" field to "4"
-       $ok = $ok && hotpot_db_update_field_type('hotpot_questions', 'type', 'type', 'INTEGER', 4,  'UNSIGNED', 'NULL');
-       // hotpot_questions: change type of "name" field to "text"
-       $ok = $ok && hotpot_db_update_field_type('hotpot_questions', 'name', 'name', 'TEXT',   '',  '', 'NOT NULL', '');
-       // hotpot_questions: nullify empty and non-numeric (shouldn't be any) values in "text" field
-       switch (strtolower($CFG->dbtype)) {
-               case 'mysql' : 
-                       $NOT_REGEXP = 'NOT REGEXP';
-               break;
-               case 'postgres7' :
-                       $NOT_REGEXP = '!~';
-               break;
-               default:
-                       $NOT_REGEXP = '';
-               break;
-       }
-       if ($NOT_REGEXP) {
-               $ok = $ok && execute_sql("UPDATE {$CFG->prefix}hotpot_questions SET text=NULL WHERE text $NOT_REGEXP '^[0-9]+$'");
-       }
-       // hotpot_questions: change type of "text" field to "INT(10)"
-       $ok = $ok && hotpot_db_update_field_type('hotpot_questions', 'text', 'text', 'INTEGER', 10, 'UNSIGNED', 'NULL');
-       // hotpot_attempts
-       // hotpot_attempts: move "details" to separate table
-       $table = 'hotpot_details';
-       if (hotpot_db_table_exists($table)) {
-               // do nothing
-       } else {
-               $ok = $ok && hotpot_create_table($table);
-               switch (strtolower($CFG->dbtype)) {
-                       case 'mysql' : 
-                       case 'postgres7' :
-                               $sql = "
-                                       INSERT INTO {$CFG->prefix}$table (attempt, details) 
-                                       SELECT a.id AS attempt, a.details AS details
-                                               FROM {$CFG->prefix}hotpot_attempts AS a
-                                               WHERE 
-                                                       a.details IS NOT NULL AND a.details <> ''
-                                                       AND a.details LIKE '<?xml%' AND a.details LIKE '%</hpjsresult>'
-                               ";
-                       break;
-                       default:
-                               $sql = '';
-                       break;
-               }
-               if ($sql) {
-                       $ok = $ok && execute_sql($sql);
-               }
-       }
-       // hotpot_attempts: remove the "details" field
-       $ok = $ok && hotpot_db_remove_field('hotpot_attempts', 'details');
-       // hotpot_attempts: create and set status field (1=in-progress, 2=timed-out, 3=abandoned, 4=completed)
-       $ok = $ok && hotpot_db_update_field_type('hotpot_attempts', '', 'status', 'INTEGER', 4, 'UNSIGNED', 'NOT NULL', 1);
-       $ok = $ok && execute_sql("UPDATE {$CFG->prefix}hotpot_attempts SET status=1 WHERE timefinish=0 AND SCORE IS NULL");
-       $ok = $ok && execute_sql("UPDATE {$CFG->prefix}hotpot_attempts SET status=3 WHERE timefinish>0 AND SCORE IS NULL");
-       $ok = $ok && execute_sql("UPDATE {$CFG->prefix}hotpot_attempts SET status=4 WHERE timefinish>0 AND SCORE IS NOT NULL");
-       // hotpot_attempts: create and set clickreport fields
-       $ok = $ok && hotpot_db_update_field_type('hotpot', '', 'clickreporting', 'INTEGER', 4, 'UNSIGNED', 'NOT NULL', 0);
-       $ok = $ok && hotpot_db_update_field_type('hotpot_attempts', '', 'clickreportid', 'INTEGER', 10, 'UNSIGNED', 'NULL');
-       $ok = $ok && execute_sql("UPDATE {$CFG->prefix}hotpot_attempts SET clickreportid=id WHERE clickreportid IS NULL");
-       // hotpot_attempts: create and set studentfeedback field (0=none, 1=formmail, 2=moodleforum, 3=moodlemessaging)
-       $ok = $ok && hotpot_db_update_field_type('hotpot', '', 'studentfeedback', 'INTEGER', 4, 'UNSIGNED', 'NOT NULL', '0');
-       $ok = $ok && hotpot_db_update_field_type('hotpot', '', 'studentfeedbackurl', 'VARCHAR', 255, '', 'NULL');
-       // add indexes
-       $ok = $ok && hotpot_db_add_index('hotpot_attempts', 'hotpot');
-       $ok = $ok && hotpot_db_add_index('hotpot_attempts', 'userid');
-       $ok = $ok && hotpot_db_add_index('hotpot_details', 'attempt');
-       $ok = $ok && hotpot_db_add_index('hotpot_questions', 'name', 20);
-       $ok = $ok && hotpot_db_add_index('hotpot_questions', 'hotpot');
-       $ok = $ok && hotpot_db_add_index('hotpot_responses', 'attempt');
-       $ok = $ok && hotpot_db_add_index('hotpot_responses', 'question');
-       $ok = $ok && hotpot_db_add_index('hotpot_strings', 'string', 20);
-       // hotpot_string: correct double-encoded HTML entities
-       $ok = $ok && execute_sql("
-               UPDATE {$CFG->prefix}hotpot_strings 
-               SET string = REPLACE(string, '&amp;','&') 
-               WHERE string LIKE '%&amp;#%' 
-               AND (string LIKE '<' OR string LIKE '>')
-       ");
-       // hotpot_question: remove questions which refer to deleted hotpots
-       if ($ok) {
-               // try and get all hotpot records
-               if ($records = get_records('hotpot')) {
-                       $ids = implode(',', array_keys($records));
-                       $sql = "DELETE FROM {$CFG->prefix}hotpot_questions WHERE hotpot NOT IN ($ids)";
-               } else {
-                       // remove all question records (because there are no valid hotpot ids)
-                       $sql = "TRUNCATE {$CFG->prefix}hotpot_questions";
-               }
-               print "Removing unused question records ...";
-               execute_sql($sql);
-       }
-       if ($ok) {
-               // remove old 'v6' templates folder (replaced by 'template' folder)
-               $ds = DIRECTORY_SEPARATOR;
-               $dir = "mod{$ds}hotpot{$ds}v6";
-               print "removing old templates ($dir) ... ";
-               if (hotpot_rm("$CFG->dirroot{$ds}$dir", false)) {
-                       print get_string('success');
-               } else {
-                       print "failed<br>Please remove '$CFG->dirroot{$ds}$dir' manually";
-               }
-               print "<br />\n";
-       }
-       return $ok;
+    global $CFG, $db;
+    $ok = true;
+    // hotpot_questions: reduce size of "type" field to "4"
+    $ok = $ok && hotpot_db_update_field_type('hotpot_questions', 'type', 'type', 'INTEGER', 4,  'UNSIGNED', 'NULL');
+    // hotpot_questions: change type of "name" field to "text"
+    $ok = $ok && hotpot_db_update_field_type('hotpot_questions', 'name', 'name', 'TEXT',   '',  '', 'NOT NULL', '');
+    // hotpot_questions: nullify empty and non-numeric (shouldn't be any) values in "text" field
+    switch (strtolower($CFG->dbtype)) {
+        case 'mysql' : 
+            $NOT_REGEXP = 'NOT REGEXP';
+        break;
+        case 'postgres7' :
+            $NOT_REGEXP = '!~';
+        break;
+        default:
+            $NOT_REGEXP = '';
+        break;
+    }
+    if ($NOT_REGEXP) {
+        $ok = $ok && execute_sql("UPDATE {$CFG->prefix}hotpot_questions SET text=NULL WHERE text $NOT_REGEXP '^[0-9]+$'");
+    }
+    // hotpot_questions: change type of "text" field to "INT(10)"
+    $ok = $ok && hotpot_db_update_field_type('hotpot_questions', 'text', 'text', 'INTEGER', 10, 'UNSIGNED', 'NULL');
+    // hotpot_attempts
+    // hotpot_attempts: move "details" to separate table
+    $table = 'hotpot_details';
+    if (hotpot_db_table_exists($table)) {
+        // do nothing
+    } else {
+        $ok = $ok && hotpot_create_table($table);
+        switch (strtolower($CFG->dbtype)) {
+            case 'mysql' : 
+            case 'postgres7' :
+                $sql = "
+                    INSERT INTO {$CFG->prefix}$table (attempt, details) 
+                    SELECT a.id AS attempt, a.details AS details
+                        FROM {$CFG->prefix}hotpot_attempts AS a
+                        WHERE 
+                            a.details IS NOT NULL AND a.details <> ''
+                            AND a.details LIKE '<?xml%' AND a.details LIKE '%</hpjsresult>'
+                ";
+            break;
+            default:
+                $sql = '';
+            break;
+        }
+        if ($sql) {
+            $ok = $ok && execute_sql($sql);
+        }
+    }
+    // hotpot_attempts: remove the "details" field
+    $ok = $ok && hotpot_db_remove_field('hotpot_attempts', 'details');
+    // hotpot_attempts: create and set status field (1=in-progress, 2=timed-out, 3=abandoned, 4=completed)
+    $ok = $ok && hotpot_db_update_field_type('hotpot_attempts', '', 'status', 'INTEGER', 4, 'UNSIGNED', 'NOT NULL', 1);
+    $ok = $ok && execute_sql("UPDATE {$CFG->prefix}hotpot_attempts SET status=1 WHERE timefinish=0 AND SCORE IS NULL");
+    $ok = $ok && execute_sql("UPDATE {$CFG->prefix}hotpot_attempts SET status=3 WHERE timefinish>0 AND SCORE IS NULL");
+    $ok = $ok && execute_sql("UPDATE {$CFG->prefix}hotpot_attempts SET status=4 WHERE timefinish>0 AND SCORE IS NOT NULL");
+    // hotpot_attempts: create and set clickreport fields
+    $ok = $ok && hotpot_db_update_field_type('hotpot', '', 'clickreporting', 'INTEGER', 4, 'UNSIGNED', 'NOT NULL', 0);
+    $ok = $ok && hotpot_db_update_field_type('hotpot_attempts', '', 'clickreportid', 'INTEGER', 10, 'UNSIGNED', 'NULL');
+    $ok = $ok && execute_sql("UPDATE {$CFG->prefix}hotpot_attempts SET clickreportid=id WHERE clickreportid IS NULL");
+    // hotpot_attempts: create and set studentfeedback field (0=none, 1=formmail, 2=moodleforum, 3=moodlemessaging)
+    $ok = $ok && hotpot_db_update_field_type('hotpot', '', 'studentfeedback', 'INTEGER', 4, 'UNSIGNED', 'NOT NULL', '0');
+    $ok = $ok && hotpot_db_update_field_type('hotpot', '', 'studentfeedbackurl', 'VARCHAR', 255, '', 'NULL');
+    // add indexes
+    $ok = $ok && hotpot_db_add_index('hotpot_attempts', 'hotpot');
+    $ok = $ok && hotpot_db_add_index('hotpot_attempts', 'userid');
+    $ok = $ok && hotpot_db_add_index('hotpot_details', 'attempt');
+    $ok = $ok && hotpot_db_add_index('hotpot_questions', 'name', 20);
+    $ok = $ok && hotpot_db_add_index('hotpot_questions', 'hotpot');
+    $ok = $ok && hotpot_db_add_index('hotpot_responses', 'attempt');
+    $ok = $ok && hotpot_db_add_index('hotpot_responses', 'question');
+    $ok = $ok && hotpot_db_add_index('hotpot_strings', 'string', 20);
+    // hotpot_string: correct double-encoded HTML entities
+    $ok = $ok && execute_sql("
+        UPDATE {$CFG->prefix}hotpot_strings 
+        SET string = REPLACE(string, '&amp;','&') 
+        WHERE string LIKE '%&amp;#%' 
+        AND (string LIKE '<' OR string LIKE '>')
+    ");
+    // hotpot_question: remove questions which refer to deleted hotpots
+    if ($ok) {
+        // try and get all hotpot records
+        if ($records = get_records('hotpot')) {
+            $ids = implode(',', array_keys($records));
+            $sql = "DELETE FROM {$CFG->prefix}hotpot_questions WHERE hotpot NOT IN ($ids)";
+        } else {
+            // remove all question records (because there are no valid hotpot ids)
+            $sql = "TRUNCATE {$CFG->prefix}hotpot_questions";
+        }
+        print "Removing unused question records ...";
+        execute_sql($sql);
+    }
+    if ($ok) {
+        // remove old 'v6' templates folder (replaced by 'template' folder)
+        $ds = DIRECTORY_SEPARATOR;
+        $dir = "mod{$ds}hotpot{$ds}v6";
+        print "removing old templates ($dir) ... ";
+        if (hotpot_rm("$CFG->dirroot{$ds}$dir", false)) {
+            print get_string('success');
+        } else {
+            print "failed<br>Please remove '$CFG->dirroot{$ds}$dir' manually";
+        }
+        print "<br />\n";
+    }
+    return $ok;
 }
 function hotpot_update_to_v2_from_v1() {
-       global $CFG;
-       $ok = true;
-       // remove, alter and add fields in database
-       $table = 'hotpot';
-       if (hotpot_db_table_exists($table)) {
-               $ok = $ok && hotpot_update_fields($table);
-       } else {
-               $ok = $ok && hotpot_create_table($table);
-       }
-       $table = 'hotpot_attempts';
-       $oldtable = 'hotpot_events';
-       if (hotpot_db_table_exists($oldtable)) {
-               $ok = $ok && hotpot_update_fields($oldtable);
-               $ok = $ok && hotpot_db_append_table($oldtable, $table);
-       } else {
-               $ok = $ok && hotpot_create_table($table);
-       }
-       // create new tables (from mysql.sql)
-       $ok = $ok && hotpot_create_table('hotpot_questions');
-       $ok = $ok && hotpot_create_table('hotpot_responses');
-       $ok = $ok && hotpot_create_table('hotpot_strings');
-       // remove redundant scripts
-       $files = array('coursefiles.php', 'details.php', 'dummy.html', 'hotpot.php', 'hotpot2db.php');
-       foreach ($files as $file) {
-               $filepath = "$CFG->dirroot/mod/hotpot/$file";
-               if (file_exists($filepath)) {
-                       @unlink($filepath); // don't worry about errors
-               }
-       }
-       return $ok;
+    global $CFG;
+    $ok = true;
+    // remove, alter and add fields in database
+    $table = 'hotpot';
+    if (hotpot_db_table_exists($table)) {
+        $ok = $ok && hotpot_update_fields($table);
+    } else {
+        $ok = $ok && hotpot_create_table($table);
+    }
+    $table = 'hotpot_attempts';
+    $oldtable = 'hotpot_events';
+    if (hotpot_db_table_exists($oldtable)) {
+        $ok = $ok && hotpot_update_fields($oldtable);
+        $ok = $ok && hotpot_db_append_table($oldtable, $table);
+    } else {
+        $ok = $ok && hotpot_create_table($table);
+    }
+    // create new tables (from mysql.sql)
+    $ok = $ok && hotpot_create_table('hotpot_questions');
+    $ok = $ok && hotpot_create_table('hotpot_responses');
+    $ok = $ok && hotpot_create_table('hotpot_strings');
+    // remove redundant scripts
+    $files = array('coursefiles.php', 'details.php', 'dummy.html', 'hotpot.php', 'hotpot2db.php');
+    foreach ($files as $file) {
+        $filepath = "$CFG->dirroot/mod/hotpot/$file";
+        if (file_exists($filepath)) {
+            @unlink($filepath); // don't worry about errors
+        }
+    }
+    return $ok;
 }
 function hotpot_update_to_v2_from_hotpotatoes() {
-       global $CFG;
-       $ok = true; // hope for the best!
-       // check we have the minimum required hotpot module
-       $minimum = 2005031400; 
-       $module = get_record("modules", "name", "hotpot");
-       if (empty($module) || $module->version<$minimum) {
-               if ($module) {
-                       print ("<p>The update to the HotPotatoes module requires at least version $minimum of the HotPot module.</p>");
-                       print ("<p>The current version of the HotPot module on this site is $module->version.</p>");
-               }
-               print ("<p>Please install the latest version of the HotPot module and then try the update again.</p>");
-               $ok = false;
-       } else {
-               // arrays to map foreign keys
-               $new = array();
-               $new['hotpot'] = array();
-               $new['attempt'] = array();
-               $new['question'] = array();
-               $new['string'] = array();
-               // save and switch off SQL message echo
-               global $db;
-               $debug = $db->debug;
-               $db->debug = false;
-               // import hotpotatoes (and save old ids)
-               $ok = $ok && hotpot_update_fields('hotpotatoes');
-               $ok = $ok && hotpot_transfer_records('hotpotatoes', 'hotpot', array(), 'hotpot', $new);
-               // update course modules and logs
-               $ok = $ok && hotpot_update_course_modules('hotpotatoes', 'hotpot', $new);
-               // import hotpotatoes_strings (and save old ids)
-               $ok = $ok && hotpot_transfer_records('hotpotatoes_strings', 'hotpot_strings', array(), 'string', $new);
-               // import hotpotatoes_attempts (and save old ids)
-               $ok = $ok && hotpot_transfer_records('hotpotatoes_attempts', 'hotpot_attempts', array('hotpotatoes'=>'hotpot'), 'attempt', $new);
-               // import hotpotatoes_questions (and save old ids)
-               $ok = $ok && hotpot_transfer_records('hotpotatoes_questions', 'hotpot_questions', array('hotpotatoes'=>'hotpot'), 'question', $new);
-               // import hotpotatoes_responses
-               $ok = $ok && hotpot_transfer_records('hotpotatoes_responses', 'hotpot_responses', array('attempt'=>'attempt', 'question'=>'question'), 'response', $new);
-               // restore SQL message echo setting
-               $db->debug = $debug;
-               // remove the hotpotatoes tables, if the update went ok
-               if ($ok) {
-               //      hotpot_db_remove_table('hotpotatoes');
-               //      hotpot_db_remove_table('hotpotatoes_attempts');
-               //      hotpot_db_remove_table('hotpotatoes_questions');
-               //      hotpot_db_remove_table('hotpotatoes_responses');
-               //      hotpot_db_remove_table('hotpotatoes_strings');
-               }
-               // hide the hotpotatoes module (see admin/modules.php))
-               if ($ok && ($module = get_record("modules", "name", "hotpotatoes"))) {
-                       set_field("modules", "visible", "0", "id", $module->id);
-                       print '<p>All HotPotatoes activities have been imported to the HotPot module.<br />'."\n";
-                       print 'The HotPotatoes module has been hidden and can safely be deleted from this Moodle site.<br />'."\n";
-                       print ' &nbsp; &nbsp; <a href="'.$CFG->wwwroot.'/'.$CFG->admin.'/modules.php">Configuration -> Modules</A>, then click &quot;Delete&quot; for &quot;Hot Potatoes XML Quiz&quot;</p>'."\n";
-               }
-       }
-       if ($ok) {
-               print '<p align="center">Thank you for using the HotPotatoes module.<br />';
-               print 'The HotPotatoes module has been replaced by<br />version 2 of the HotPot module. Enjoy!</p>';
-       }
-       return $ok;
+    global $CFG;
+    $ok = true; // hope for the best!
+    // check we have the minimum required hotpot module
+    $minimum = 2005031400; 
+    $module = get_record("modules", "name", "hotpot");
+    if (empty($module) || $module->version<$minimum) {
+        if ($module) {
+            print ("<p>The update to the HotPotatoes module requires at least version $minimum of the HotPot module.</p>");
+            print ("<p>The current version of the HotPot module on this site is $module->version.</p>");
+        }
+        print ("<p>Please install the latest version of the HotPot module and then try the update again.</p>");
+        $ok = false;
+    } else {
+        // arrays to map foreign keys
+        $new = array();
+        $new['hotpot'] = array();
+        $new['attempt'] = array();
+        $new['question'] = array();
+        $new['string'] = array();
+        // save and switch off SQL message echo
+        global $db;
+        $debug = $db->debug;
+        $db->debug = false;
+        // import hotpotatoes (and save old ids)
+        $ok = $ok && hotpot_update_fields('hotpotatoes');
+        $ok = $ok && hotpot_transfer_records('hotpotatoes', 'hotpot', array(), 'hotpot', $new);
+        // update course modules and logs
+        $ok = $ok && hotpot_update_course_modules('hotpotatoes', 'hotpot', $new);
+        // import hotpotatoes_strings (and save old ids)
+        $ok = $ok && hotpot_transfer_records('hotpotatoes_strings', 'hotpot_strings', array(), 'string', $new);
+        // import hotpotatoes_attempts (and save old ids)
+        $ok = $ok && hotpot_transfer_records('hotpotatoes_attempts', 'hotpot_attempts', array('hotpotatoes'=>'hotpot'), 'attempt', $new);
+        // import hotpotatoes_questions (and save old ids)
+        $ok = $ok && hotpot_transfer_records('hotpotatoes_questions', 'hotpot_questions', array('hotpotatoes'=>'hotpot'), 'question', $new);
+        // import hotpotatoes_responses
+        $ok = $ok && hotpot_transfer_records('hotpotatoes_responses', 'hotpot_responses', array('attempt'=>'attempt', 'question'=>'question'), 'response', $new);
+        // restore SQL message echo setting
+        $db->debug = $debug;
+        // remove the hotpotatoes tables, if the update went ok
+        if ($ok) {
+        //  hotpot_db_remove_table('hotpotatoes');
+        //  hotpot_db_remove_table('hotpotatoes_attempts');
+        //  hotpot_db_remove_table('hotpotatoes_questions');
+        //  hotpot_db_remove_table('hotpotatoes_responses');
+        //  hotpot_db_remove_table('hotpotatoes_strings');
+        }
+        // hide the hotpotatoes module (see admin/modules.php))
+        if ($ok && ($module = get_record("modules", "name", "hotpotatoes"))) {
+            set_field("modules", "visible", "0", "id", $module->id);
+            print '<p>All HotPotatoes activities have been imported to the HotPot module.<br />'."\n";
+            print 'The HotPotatoes module has been hidden and can safely be deleted from this Moodle site.<br />'."\n";
+            print ' &nbsp; &nbsp; <a href="'.$CFG->wwwroot.'/'.$CFG->admin.'/modules.php">Configuration -> Modules</A>, then click &quot;Delete&quot; for &quot;Hot Potatoes XML Quiz&quot;</p>'."\n";
+        }
+    }
+    if ($ok) {
+        print '<p align="center">Thank you for using the HotPotatoes module.<br />';
+        print 'The HotPotatoes module has been replaced by<br />version 2 of the HotPot module. Enjoy!</p>';
+    }
+    return $ok;
 }
 function hotpot_create_table($table) {
-       global $CFG;
-       $ok = true;
-       static $sql;
-       if (empty($sql)) { // first time only
-               $filepath = "$CFG->dirroot/mod/hotpot/db/$CFG->dbtype.sql";
-               if (function_exists('file_get_contents')) {
-                       $sql = file_get_contents($filepath);
-               } else { // PHP < 4.3
-                       $sql = file($filepath);
-                       if (is_array($sql)) {
-                                $sql = implode('', $sql);
-                       }
-               }
-               if(empty($sql)) { // $sql==false
-                        $sql = '';
-               }
-       }
-       // check table does not already exist
-       if (!hotpot_db_table_exists($table)) {
-               // extract and execute all CREATE statements relating to this table
-               if (preg_match_all("/CREATE (TABLE|INDEX)(\s[^;]*)? prefix_{$table}(\s[^;]*)?;/s", $sql, $strings)) {
-                       foreach ($strings[0] as $string) {
-                               $ok = $ok && modify_database('', $string);
-                       }
-               } else {
-                       // no CREATE statements found for this $table
-                       $ok = false;
-               }
-       }
-       return $ok;
+    global $CFG;
+    $ok = true;
+    static $sql;
+    if (empty($sql)) { // first time only
+        $filepath = "$CFG->dirroot/mod/hotpot/db/$CFG->dbtype.sql";
+        if (function_exists('file_get_contents')) {
+            $sql = file_get_contents($filepath);
+        } else { // PHP < 4.3
+            $sql = file($filepath);
+            if (is_array($sql)) {
+                 $sql = implode('', $sql);
+            }
+        }
+        if(empty($sql)) { // $sql==false
+             $sql = '';
+        }
+    }
+    // check table does not already exist
+    if (!hotpot_db_table_exists($table)) {
+        // extract and execute all CREATE statements relating to this table
+        if (preg_match_all("/CREATE (TABLE|INDEX)(\s[^;]*)? prefix_{$table}(\s[^;]*)?;/s", $sql, $strings)) {
+            foreach ($strings[0] as $string) {
+                $ok = $ok && modify_database('', $string);
+            }
+        } else {
+            // no CREATE statements found for this $table
+            $ok = false;
+        }
+    }
+    return $ok;
 }
 function hotpot_transfer_records($oldtable, $table, $foreignkeys, $primarykey, &$new) {
-       global $db;
-       $ok = true;
-       // get the records, if any
-       if (hotpot_db_table_exists($oldtable) && ($records = get_records($oldtable))) {
-               // start progress report
-               $i = 0;
-               $count = count($records);
-               hotpot_update_print("Transferring $count records from &quot;$oldtable&quot; to &quot;$table&quot; ... ");
-               // transfer all $records
-               foreach ($records as $record) {
-                       switch ($table) {
-                               case 'hotpot' :
-                                       $record->summary = addslashes($record->summary);
-                                       break;
-                               case 'hotpot_attempts' :
-                                       $record->details = addslashes($record->details);
-                                       break;
-                               case 'hotpot_questions' :
-                                       $record->name = addslashes($record->name);
-                                       hotpot_update_string_id_list($table, $record, 'TEXT', $new);
-                                       break;
-                               case 'hotpot_responses' :
-                                       hotpot_update_string_id_list($table, $record, 'correct', $new);
-                                       hotpot_update_string_id_list($table, $record, 'ignored', $new);
-                                       hotpot_update_string_id_list($table, $record, 'wrong', $new);
-                                       break;
-                               case 'hotpot_strings' :
-                                       $record->string = addslashes($record->string);
-                                       break;
-                       }
-                       // update foreign keys, if any
-                       foreach ($foreignkeys as $oldkey=>$key) {
-                               // transfer (and update) key
-                               $value = $record->$oldkey;
-                               if (isset($new[$key][$value])) {
-                                       $record->$key = $new[$key][$value];
-                               } else {
-                                       // foreign key could not be updated
-                                       $ok = hotpot_update_print_warning($key, $value, $oldtable, $record->id) && $ok;
-                                       unset($record->id);
-                               }
-                       }
-                       if ($ok && isset($record->id)) {
-                               // store and remove old primary key
-                               $id = $record->id;
-                               unset($record->id);
-                               // add the updated record and store the new id
-                               $new[$primarykey][$id] = insert_record($table, $record, true);
-                               // check id is numeric
-                               if (!is_numeric($new[$primarykey][$id])) {
-                                       hotpot_update_print("<li>Record could not added to $table table ($oldtable id=$id)</li>\n");
-                                       //$ok = false;
-                               }
-                       }
-                       $i++;
-                       hotpot_update_print_progress($i);
-               }
-               // finish progress report
-               hotpot_update_print_ok($ok);
-       }
-       return $ok;
+    global $db;
+    $ok = true;
+    // get the records, if any
+    if (hotpot_db_table_exists($oldtable) && ($records = get_records($oldtable))) {
+        // start progress report
+        $i = 0;
+        $count = count($records);
+        hotpot_update_print("Transferring $count records from &quot;$oldtable&quot; to &quot;$table&quot; ... ");
+        // transfer all $records
+        foreach ($records as $record) {
+            switch ($table) {
+                case 'hotpot' :
+                    $record->summary = addslashes($record->summary);
+                    break;
+                case 'hotpot_attempts' :
+                    $record->details = addslashes($record->details);
+                    break;
+                case 'hotpot_questions' :
+                    $record->name = addslashes($record->name);
+                    hotpot_update_string_id_list($table, $record, 'TEXT', $new);
+                    break;
+                case 'hotpot_responses' :
+                    hotpot_update_string_id_list($table, $record, 'correct', $new);
+                    hotpot_update_string_id_list($table, $record, 'ignored', $new);
+                    hotpot_update_string_id_list($table, $record, 'wrong', $new);
+                    break;
+                case 'hotpot_strings' :
+                    $record->string = addslashes($record->string);
+                    break;
+            }
+            // update foreign keys, if any
+            foreach ($foreignkeys as $oldkey=>$key) {
+                // transfer (and update) key
+                $value = $record->$oldkey;
+                if (isset($new[$key][$value])) {
+                    $record->$key = $new[$key][$value];
+                } else {
+                    // foreign key could not be updated
+                    $ok = hotpot_update_print_warning($key, $value, $oldtable, $record->id) && $ok;
+                    unset($record->id);
+                }
+            }
+            if ($ok && isset($record->id)) {
+                // store and remove old primary key
+                $id = $record->id;
+                unset($record->id);
+                // add the updated record and store the new id
+                $new[$primarykey][$id] = insert_record($table, $record, true);
+                // check id is numeric
+                if (!is_numeric($new[$primarykey][$id])) {
+                    hotpot_update_print("<li>Record could not added to $table table ($oldtable id=$id)</li>\n");
+                    //$ok = false;
+                }
+            }
+            $i++;
+            hotpot_update_print_progress($i);
+        }
+        // finish progress report
+        hotpot_update_print_ok($ok);
+    }
+    return $ok;
 }
 function hotpot_update_course_modules($oldmodulename, $modulename, &$new) {
-       $ok = true;
-       $oldmoduleid = get_field('modules', 'id', 'name', $oldmodulename);
-       $moduleid = get_field('modules', 'id', 'name', $modulename);
-       if (is_numeric($oldmoduleid) && is_numeric($moduleid)) {
-               // get module records
-               if ($records = get_records('course_modules', 'module', $oldmoduleid)) {
-                       // start progress report
-                       $count = count($records);
-                       hotpot_update_print("Updating $count course modules from &quot;$oldmodulename&quot; to &quot;$modulename&quot; ... ");
-                       // update foreign keys in all $records
-                       foreach ($records as $record) {
-                               // update instance
-                               $instance = $record->instance;
-                               if (isset($new[$modulename][$instance])) {
-                                       $record->instance = $new[$modulename][$instance];
-                               } else if ($record->deleted) {
-                                       unset($record->id);
-                               } else {
-                                       // could not find new id of course module
-                                       $ok = hotpot_update_print_warning("$modulename instance", $instance, 'course_modules', $record->id) && $ok;
-                                       unset($record->id);
-                               }
-                               // update module id
-                               if ($ok && isset($record->id)) {
-                                       $record->module = $moduleid;
-                                       $ok = update_record('course_modules', $record);
-                               }
-                       }
-                       // finish progress report
-                       hotpot_update_print_ok($ok);
-               }
-               // update logs
-               $ok = $ok && hotpot_update_logs($oldmodulename, $modulename, $moduleid, $new);
-       }
-       return $ok;
+    $ok = true;
+    $oldmoduleid = get_field('modules', 'id', 'name', $oldmodulename);
+    $moduleid = get_field('modules', 'id', 'name', $modulename);
+    if (is_numeric($oldmoduleid) && is_numeric($moduleid)) {
+        // get module records
+        if ($records = get_records('course_modules', 'module', $oldmoduleid)) {
+            // start progress report
+            $count = count($records);
+            hotpot_update_print("Updating $count course modules from &quot;$oldmodulename&quot; to &quot;$modulename&quot; ... ");
+            // update foreign keys in all $records
+            foreach ($records as $record) {
+                // update instance
+                $instance = $record->instance;
+                if (isset($new[$modulename][$instance])) {
+                    $record->instance = $new[$modulename][$instance];
+                } else if ($record->deleted) {
+                    unset($record->id);
+                } else {
+                    // could not find new id of course module
+                    $ok = hotpot_update_print_warning("$modulename instance", $instance, 'course_modules', $record->id) && $ok;
+                    unset($record->id);
+                }
+                // update module id
+                if ($ok && isset($record->id)) {
+                    $record->module = $moduleid;
+                    $ok = update_record('course_modules', $record);
+                }
+            }
+            // finish progress report
+            hotpot_update_print_ok($ok);
+        }
+        // update logs
+        $ok = $ok && hotpot_update_logs($oldmodulename, $modulename, $moduleid, $new);
+    }
+    return $ok;
 }
 function hotpot_update_logs($oldmodulename, $modulename, $moduleid, &$new) {
-       $table = 'log';
-       $ok = true;
-       // get log records for the oldmodule
-       if ($records = get_records($table, 'module', $oldmodulename)) {
-               // start progress report
-               $i = 0;
-               $count = count($records);
-               hotpot_update_print("Updating $count log records ... ");
-               // update foreign keys in all $records
-               foreach ($records as $record) {
-                       // update course module name
-                       $record->module = $modulename;
-                       // check if module id was given (usually it is)
-                       if ($record->cmid) {
-                               // update course module id, if necessary
-                               if (isset($new[$modulename][$record->cmid])) {
-                                       $record->cmid = $new[$modulename][$record->cmid];
-                               } else {
-                                       // could not update course module id
-                                       $ok = hotpot_update_print_warning('cmid', $record->cmid, 'log', $record->id) && $ok;
-                                       unset($record->id);
-                               }
-                               // update url and info
-                               switch ($record->action) {
-                                       case "add":
-                                       case "update":
-                                       case "view":
-                                               $record->url = "view.php?id=".$record->cmid;
-                                               $record->info = $moduleid;
-                                               break;
-                                       case "view all":
-                                               // do nothing
-                                               break;
-                                       case "report":
-                                               $record->url = "report.php?id=".$record->cmid;
-                                               $record->info = $moduleid;
-                                               break;
-                                       case "attempt":
-                                       case "submit":
-                                       case "review": 
-                                               $id = substr(strrchr($record->url,"="),1);
-                                               if (isset($new->attempt[$id])) { 
-                                                       $id = $new->attempt[$id];
-                                               }
-                                               $record->url = "review.php?id=".$record->cmid."&attempt=$id";
-                                               $record->info = $moduleid;
-                                               break;
-                                       default:
-                                               // unknown log action
-                                               $ok = hotpot_update_print_warning('action', $record->action, 'log', $record->id) && $ok;
-                                               unset($record->id);
-                               } // end switch
-                       }
-                       if (isset($record->id)) {
-                               $ok = $ok && update_record($table, $record);
-                       }
-                       $i++;
-                       hotpot_update_print_progress($i);
-               } // end foreach
-               // finish progress report
-               hotpot_update_print_ok($ok);
-       }
-       return $ok;
+    $table = 'log';
+    $ok = true;
+    // get log records for the oldmodule
+    if ($records = get_records($table, 'module', $oldmodulename)) {
+        // start progress report
+        $i = 0;
+        $count = count($records);
+        hotpot_update_print("Updating $count log records ... ");
+        // update foreign keys in all $records
+        foreach ($records as $record) {
+            // update course module name
+            $record->module = $modulename;
+            // check if module id was given (usually it is)
+            if ($record->cmid) {
+                // update course module id, if necessary
+                if (isset($new[$modulename][$record->cmid])) {
+                    $record->cmid = $new[$modulename][$record->cmid];
+                } else {
+                    // could not update course module id
+                    $ok = hotpot_update_print_warning('cmid', $record->cmid, 'log', $record->id) && $ok;
+                    unset($record->id);
+                }
+                // update url and info
+                switch ($record->action) {
+                    case "add":
+                    case "update":
+                    case "view":
+                        $record->url = "view.php?id=".$record->cmid;
+                        $record->info = $moduleid;
+                        break;
+                    case "view all":
+                        // do nothing
+                        break;
+                    case "report":
+                        $record->url = "report.php?id=".$record->cmid;
+                        $record->info = $moduleid;
+                        break;
+                    case "attempt":
+                    case "submit":
+                    case "review": 
+                        $id = substr(strrchr($record->url,"="),1);
+                        if (isset($new->attempt[$id])) { 
+                            $id = $new->attempt[$id];
+                        }
+                        $record->url = "review.php?id=".$record->cmid."&attempt=$id";
+                        $record->info = $moduleid;
+                        break;
+                    default:
+                        // unknown log action
+                        $ok = hotpot_update_print_warning('action', $record->action, 'log', $record->id) && $ok;
+                        unset($record->id);
+                } // end switch
+            }
+            if (isset($record->id)) {
+                $ok = $ok && update_record($table, $record);
+            }
+            $i++;
+            hotpot_update_print_progress($i);
+        } // end foreach
+        // finish progress report
+        hotpot_update_print_ok($ok);
+    }
+    return $ok;
 }
 function hotpot_update_fields($table, $feedback=false) {
-       global $CFG, $db;
-       $ok = true;
-       // check the table exists
-       if (hotpot_db_table_exists($table)) {
-               switch ($table) {
-                       case 'hotpot' :
-                               // == ADD ==
-                               hotpot_db_update_field_type($table, '', 'location',     'INTEGER', 4, 'UNSIGNED', 'NOT NULL', 0);
-                               hotpot_db_update_field_type($table, '', 'navigation',   'INTEGER', 4, 'UNSIGNED', 'NOT NULL', 1);
-                               hotpot_db_update_field_type($table, '', 'outputformat', 'INTEGER', 4, 'UNSIGNED', 'NOT NULL', 1);
-                               hotpot_db_update_field_type($table, '', 'shownextquiz', 'INTEGER', 4, 'UNSIGNED', 'NOT NULL', 0);
-                               hotpot_db_update_field_type($table, '', 'forceplugins', 'INTEGER', 4, 'UNSIGNED', 'NOT NULL', 0);
-                               hotpot_db_update_field_type($table, '', 'password',     'VARCHAR', 255, '',       'NOT NULL', '');
-                               hotpot_db_update_field_type($table, '', 'subnet',       'VARCHAR', 255, '',       'NOT NULL', '');
-                               // == ALTER ==
-                               hotpot_db_update_field_type($table, 'summary',   'summary',   'TEXT',    '',  '', 'NOT NULL', '');
-                               hotpot_db_update_field_type($table, 'reference', 'reference', 'VARCHAR', 255, '', 'NOT NULL', '');
-                               // == REMOVE ==
-                               hotpot_db_remove_field($table, 'intro');
-                               hotpot_db_remove_field($table, 'attemptonlast');
-                               hotpot_db_remove_field($table, 'sumgrades');
-                               hotpot_db_set_table_comment($table, 'details about Hot Potatoes quizzes');
-                       break;
-                       case 'hotpot_events' :
-                               // == ADD ==
-                               hotpot_db_update_field_type($table, '', 'hotpot',     'INTEGER', 10, 'UNSIGNED', 'NOT NULL');
-                               hotpot_db_update_field_type($table, '', 'attempt',    'INTEGER', 6,  'UNSIGNED', 'NOT NULL');
-                               hotpot_db_update_field_type($table, '', 'details',    'TEXT',    '', '', '', '');
-                               hotpot_db_update_field_type($table, '', 'timestart',  'INTEGER', 10, 'UNSIGNED', 'NOT NULL', 0);
-                               hotpot_db_update_field_type($table, '', 'timefinish', 'INTEGER', 10, 'UNSIGNED', 'NOT NULL', 0);
-                               // == ALTER ==
-                               hotpot_db_update_field_type($table, 'score',     'score',      'INTEGER', 6,  'UNSIGNED', 'NULL');
-                               hotpot_db_update_field_type($table, 'wrong',     'penalties',  'INTEGER', 6,  'UNSIGNED', 'NULL');
-                               hotpot_db_update_field_type($table, 'starttime', 'starttime',  'INTEGER', 10, 'UNSIGNED', 'NULL');
-                               hotpot_db_update_field_type($table, 'endtime',   'endtime',    'INTEGER', 10, 'UNSIGNED', 'NULL');
-                               // save and switch off SQL message echo
-                               $debug = $db->debug;
-                               $db->debug = $feedback;
-                               // get array mapping course module ids to hotpot ids
-                               $hotpotmoduleid = get_field('modules', 'id', 'name', 'hotpot');
-                               $coursemodules = get_records('course_modules', 'module', $hotpotmoduleid, 'id', 'id, instance');
-                               // get all event records
-                               if (hotpot_db_field_exists($table, 'hotpotid')) {
-                                       $records = get_records($table, '', '', 'userid,hotpotid,time');
-                               } else {
-                                       $records = false; // table has already been updated
-                               }
-                               if ($records) {
-                                       $count = count($records);
-                                       hotpot_update_print("Updating $count records in $table ... ");
-                                       $ids = array_keys($records);
-                                       foreach ($ids as $i=>$id) {
-                                               // reference to current record
-                                               $record = &$records[$id];
-                                               // set timestart and timefinish (the times recorded by Moodle)
-                                               if (empty($record->timestart) && $record->time) {
-                                                       $record->timestart = $record->time;
-                                               }
-                                               if (empty($record->timefinish) && $record->timestart) {
-                                                       if ($record->starttime && $record->endtime) {
-                                                               $duration = ($record->endtime - $record->starttime);
-                                                       } else {
-                                                               if (($i+1)>=$count) {
-                                                                       $nextrecord = NULL;
-                                                               } else {
-                                                                       $nextrecord = &$records[$ids[$i+1]];
-                                                               }
-                                                               if (isset($nextrecord) && $nextrecord->userid==$record->userid && $nextrecord->hotpotid==$record->hotpotid) {
-                                                                       $duration = $nextrecord->time - $record->time;
-                                                               } else {
-                                                                       $duration = NULL;
-                                                               }
-                                                       }
-                                                       if (isset($duration)) {
-                                                               $record->timefinish = $record->timestart + $duration;
-                                                       }
-                                               }
-                                               // unset score and penalties, if quiz was abandoned
-                                               if (empty($record->endtime) || (empty($record->penalties) && empty($record->score))) {
-                                                       unset($record->score);
-                                                       unset($record->penalties);
-                                               }
-                                               // get last (=previous) record
-                                               if ($i==0) {
-                                                       $lastrecord = NULL;
-                                               } else {
-                                                       $lastrecord = &$records[$ids[$i-1]];
-                                               }
-                                               // increment or reset $attempt number
-                                               if (isset($lastrecord) && $lastrecord->userid==$record->userid && $lastrecord->hotpotid==$record->hotpotid) {
-                                                       $attempt++;
-                                               } else {
-                                                       $attempt = 1;
-                                               }
-                                               // set $record->$attempt, if necessary
-                                               if (empty($record->attempt) || $record->attempt<$attempt) {
-                                                       $record->attempt = $attempt;
-                                               } else {
-                                                       $attempt = $record->attempt;
-                                               }
-                                               // set hotpot id and update record
-                                               if (isset($record->hotpotid) && isset($record->id)) {
-                                                       if (isset($coursemodules[$record->hotpotid])) {
-                                                               $record->hotpot = $coursemodules[$record->hotpotid]->instance;
-                                                               hotpot_db_update_record($table, $record, true);
-                                                       } else {
-                                                               // hotpotid is invalid (shouldn't happen)
-                                                               $ok = hotpot_update_print_warning('hotpotid', $record->hotpotid, $table, $record->id) && $ok;
-                                                               delete_records($table, 'id', $record->id);
-                                                       }
-                                               } else {
-                                                               // empty record (shouldn't happen)
-                                               }
-                                               hotpot_update_print_progress($i);
-                                       }
-                                       // finish progress report
-                                       hotpot_update_print_ok($ok);
-                               }
-                               // restore SQL message echo setting
-                               $db->debug = $debug;
-                               // == REMOVE ==
-                               hotpot_db_remove_field($table, 'hotpotid');
-                               hotpot_db_remove_field($table, 'course');
-                               hotpot_db_remove_field($table, 'time');
-                               hotpot_db_remove_field($table, 'event');
-                               hotpot_db_set_table_comment($table, 'details about Hot Potatoes quiz attempts');
-                       break;
-                       case 'hotpotatoes' :
-                               // == ALTER ==
-                               hotpot_db_update_field_type($table, 'intro', 'summary', 'TEXT', '', '', '', 'NULL');
-                       break;
-               }
-       }
-       return $ok;
+    global $CFG, $db;
+    $ok = true;
+    // check the table exists
+    if (hotpot_db_table_exists($table)) {
+        switch ($table) {
+            case 'hotpot' :
+                // == ADD ==
+                hotpot_db_update_field_type($table, '', 'location',     'INTEGER', 4, 'UNSIGNED', 'NOT NULL', 0);
+                hotpot_db_update_field_type($table, '', 'navigation',   'INTEGER', 4, 'UNSIGNED', 'NOT NULL', 1);
+                hotpot_db_update_field_type($table, '', 'outputformat', 'INTEGER', 4, 'UNSIGNED', 'NOT NULL', 1);
+                hotpot_db_update_field_type($table, '', 'shownextquiz', 'INTEGER', 4, 'UNSIGNED', 'NOT NULL', 0);
+                hotpot_db_update_field_type($table, '', 'forceplugins', 'INTEGER', 4, 'UNSIGNED', 'NOT NULL', 0);
+                hotpot_db_update_field_type($table, '', 'password',     'VARCHAR', 255, '',       'NOT NULL', '');
+                hotpot_db_update_field_type($table, '', 'subnet',       'VARCHAR', 255, '',       'NOT NULL', '');
+                // == ALTER ==
+                hotpot_db_update_field_type($table, 'summary',   'summary',   'TEXT',    '',  '', 'NOT NULL', '');
+                hotpot_db_update_field_type($table, 'reference', 'reference', 'VARCHAR', 255, '', 'NOT NULL', '');
+                // == REMOVE ==
+                hotpot_db_remove_field($table, 'intro');
+                hotpot_db_remove_field($table, 'attemptonlast');
+                hotpot_db_remove_field($table, 'sumgrades');
+                hotpot_db_set_table_comment($table, 'details about Hot Potatoes quizzes');
+            break;
+            case 'hotpot_events' :
+                // == ADD ==
+                hotpot_db_update_field_type($table, '', 'hotpot',     'INTEGER', 10, 'UNSIGNED', 'NOT NULL');
+                hotpot_db_update_field_type($table, '', 'attempt',    'INTEGER', 6,  'UNSIGNED', 'NOT NULL');
+                hotpot_db_update_field_type($table, '', 'details',    'TEXT',    '', '', '', '');
+                hotpot_db_update_field_type($table, '', 'timestart',  'INTEGER', 10, 'UNSIGNED', 'NOT NULL', 0);
+                hotpot_db_update_field_type($table, '', 'timefinish', 'INTEGER', 10, 'UNSIGNED', 'NOT NULL', 0);
+                // == ALTER ==
+                hotpot_db_update_field_type($table, 'score',     'score',      'INTEGER', 6,  'UNSIGNED', 'NULL');
+                hotpot_db_update_field_type($table, 'wrong',     'penalties',  'INTEGER', 6,  'UNSIGNED', 'NULL');
+                hotpot_db_update_field_type($table, 'starttime', 'starttime',  'INTEGER', 10, 'UNSIGNED', 'NULL');
+                hotpot_db_update_field_type($table, 'endtime',   'endtime',    'INTEGER', 10, 'UNSIGNED', 'NULL');
+                // save and switch off SQL message echo
+                $debug = $db->debug;
+                $db->debug = $feedback;
+                // get array mapping course module ids to hotpot ids
+                $hotpotmoduleid = get_field('modules', 'id', 'name', 'hotpot');
+                $coursemodules = get_records('course_modules', 'module', $hotpotmoduleid, 'id', 'id, instance');
+                // get all event records
+                if (hotpot_db_field_exists($table, 'hotpotid')) {
+                    $records = get_records($table, '', '', 'userid,hotpotid,time');
+                } else {
+                    $records = false; // table has already been updated
+                }
+                if ($records) {
+                    $count = count($records);
+                    hotpot_update_print("Updating $count records in $table ... ");
+                    $ids = array_keys($records);
+                    foreach ($ids as $i=>$id) {
+                        // reference to current record
+                        $record = &$records[$id];
+                        // set timestart and timefinish (the times recorded by Moodle)
+                        if (empty($record->timestart) && $record->time) {
+                            $record->timestart = $record->time;
+                        }
+                        if (empty($record->timefinish) && $record->timestart) {
+                            if ($record->starttime && $record->endtime) {
+                                $duration = ($record->endtime - $record->starttime);
+                            } else {
+                                if (($i+1)>=$count) {
+                                    $nextrecord = NULL;
+                                } else {
+                                    $nextrecord = &$records[$ids[$i+1]];
+                                }
+                                if (isset($nextrecord) && $nextrecord->userid==$record->userid && $nextrecord->hotpotid==$record->hotpotid) {
+                                    $duration = $nextrecord->time - $record->time;
+                                } else {
+                                    $duration = NULL;
+                                }
+                            }
+                            if (isset($duration)) {
+                                $record->timefinish = $record->timestart + $duration;
+                            }
+                        }
+                        // unset score and penalties, if quiz was abandoned
+                        if (empty($record->endtime) || (empty($record->penalties) && empty($record->score))) {
+                            unset($record->score);
+                            unset($record->penalties);
+                        }
+                        // get last (=previous) record
+                        if ($i==0) {
+                            $lastrecord = NULL;
+                        } else {
+                            $lastrecord = &$records[$ids[$i-1]];
+                        }
+                        // increment or reset $attempt number
+                        if (isset($lastrecord) && $lastrecord->userid==$record->userid && $lastrecord->hotpotid==$record->hotpotid) {
+                            $attempt++;
+                        } else {
+                            $attempt = 1;
+                        }
+                        // set $record->$attempt, if necessary
+                        if (empty($record->attempt) || $record->attempt<$attempt) {
+                            $record->attempt = $attempt;
+                        } else {
+                            $attempt = $record->attempt;
+                        }
+                        // set hotpot id and update record
+                        if (isset($record->hotpotid) && isset($record->id)) {
+                            if (isset($coursemodules[$record->hotpotid])) {
+                                $record->hotpot = $coursemodules[$record->hotpotid]->instance;
+                                hotpot_db_update_record($table, $record, true);
+                            } else {
+                                // hotpotid is invalid (shouldn't happen)
+                                $ok = hotpot_update_print_warning('hotpotid', $record->hotpotid, $table, $record->id) && $ok;
+                                delete_records($table, 'id', $record->id);
+                            }
+                        } else {
+                                // empty record (shouldn't happen)
+                        }
+                        hotpot_update_print_progress($i);
+                    }
+                    // finish progress report
+                    hotpot_update_print_ok($ok);
+                }
+                // restore SQL message echo setting
+                $db->debug = $debug;
+                // == REMOVE ==
+                hotpot_db_remove_field($table, 'hotpotid');
+                hotpot_db_remove_field($table, 'course');
+                hotpot_db_remove_field($table, 'time');
+                hotpot_db_remove_field($table, 'event');
+                hotpot_db_set_table_comment($table, 'details about Hot Potatoes quiz attempts');
+            break;
+            case 'hotpotatoes' :
+                // == ALTER ==
+                hotpot_db_update_field_type($table, 'intro', 'summary', 'TEXT', '', '', '', 'NULL');
+            break;
+        }
+    }
+    return $ok;
 }
 function hotpot_update_string_id_list($table, &$record, $field, &$new) {
-       $ok = true;
-       if (isset($record->$field)) {
-               $oldids = explode(',', $record->$field);
-               $newids = array();
-               foreach ($oldids as $id) {
-                       if (isset($new['string'][$id])) {
-                               $newids[] = $new['string'][$id];
-                       } else if (is_numeric($id)) {
-                               // string id could not be updated
-                               $ok = hotpot_update_print_warning("string id in $field", $id, $table, $record->id) && $ok;
-                       } else {
-                               // ignore non-numeric ids (e.g. blanks)
-                       }
-               }
-               if ($ok) {
-                       $record->$field = implode(',', $newids);
-               }
-       }
-       return $ok;
+    $ok = true;
+    if (isset($record->$field)) {
+        $oldids = explode(',', $record->$field);
+        $newids = array();
+        foreach ($oldids as $id) {
+            if (isset($new['string'][$id])) {
+                $newids[] = $new['string'][$id];
+            } else if (is_numeric($id)) {
+                // string id could not be updated
+                $ok = hotpot_update_print_warning("string id in $field", $id, $table, $record->id) && $ok;
+            } else {
+                // ignore non-numeric ids (e.g. blanks)
+            }
+        }
+        if ($ok) {
+            $record->$field = implode(',', $newids);
+        }
+    }
+    return $ok;
 }
 ///////////////////////////
 //     print functions
 ///////////////////////////
 function hotpot_update_print($msg=false, $n=300) {
-       // this function prints $msg and flush output buffer
-       if ($msg) {
-               if (is_string($msg)) {
-                       print $msg;
-               } else {
-                       print strftime("%X", time());
-               }
-       }
-       // fill output buffer
-       if ($n) {
-               print str_repeat(" ", $n);
-       }
-       // some browser's require newline to flush
-       print "\n";
-       // flush PHP's output buffer
-       flush();
+    // this function prints $msg and flush output buffer
+    if ($msg) {
+        if (is_string($msg)) {
+            print $msg;
+        } else {
+            print strftime("%X", time());
+        }
+    }
+    // fill output buffer
+    if ($n) {
+        print str_repeat(" ", $n);
+    }
+    // some browser's require newline to flush
+    print "\n";
+    // flush PHP's output buffer
+    flush();
 }
 function hotpot_update_print_progress($i) {
-       if ($i%10==0) {
-               $msg = '.';
-               hotpot_update_print($msg);
-       }
+    if ($i%10==0) {
+        $msg = '.';
+        hotpot_update_print($msg);
+    }
 }
 function hotpot_update_print_ok($ok) {
-       if ($ok) {
-               hotpot_update_print('<font color="green">'.get_string('success')."</font><br />\n");
-       } else {
-               hotpot_update_print('<font color="red">'.get_string('error')."</font><br />\n");
-       }
+    if ($ok) {
+        hotpot_update_print('<font color="green">'.get_string('success')."</font><br />\n");
+    } else {
+        hotpot_update_print('<font color="red">'.get_string('error')."</font><br />\n");
+    }
 }
 function hotpot_update_print_warning($field, $value, $table, $id) {
-       hotpot_update_print("<li><b>Warning:</b> invalid $field field (value=$value) in $table (id=$id)</li>\n");
-       return true;
+    hotpot_update_print("<li><b>Warning:</b> invalid $field field (value=$value) in $table (id=$id)</li>\n");
+    return true;
 }
 ///////////////////////////
 //     database functions
 ///////////////////////////
 function hotpot_db_index_exists($table, $index, $feedback=false) {
-       global $CFG, $db;
-       $exists = false;
-       // save and switch off SQL message echo
-       $debug = $db->debug;
-       $db->debug = $feedback;
-       switch (strtolower($CFG->dbtype)) {
-               case 'mysql' : 
-                       $rs = $db->Execute("SHOW INDEX FROM `$table`");
-                       if ($rs && $rs->RecordCount()>0) {
-                               $records = $rs->GetArray();
-                               foreach ($records as $record) {
-                                       if (isset($record['Key_name']) && $record['Key_name']==$index) {
-                                               $exists = true;
-                                               break;
-                                       }
-                               }
-                       }
-               break;
-               case 'postgres7' :
-                       $rs = $db->Execute("SELECT relname FROM pg_class WHERE relname = '$index' AND relkind='i'");
-                       if ($rs && $rs->RecordCount()>0) {
-                               $exists = true;
-                       }
-               break;
-       }
-       // restore SQL message echo
-       $db->debug = $debug;
-       return $exists;
+    global $CFG, $db;
+    $exists = false;
+    // save and switch off SQL message echo
+    $debug = $db->debug;
+    $db->debug = $feedback;
+    switch (strtolower($CFG->dbtype)) {
+        case 'mysql' : 
+            $rs = $db->Execute("SHOW INDEX FROM `$table`");
+            if ($rs && $rs->RecordCount()>0) {
+                $records = $rs->GetArray();
+                foreach ($records as $record) {
+                    if (isset($record['Key_name']) && $record['Key_name']==$index) {
+                        $exists = true;
+                        break;
+                    }
+                }
+            }
+        break;
+        case 'postgres7' :
+            $rs = $db->Execute("SELECT relname FROM pg_class WHERE relname = '$index' AND relkind='i'");
+            if ($rs && $rs->RecordCount()>0) {
+                $exists = true;
+            }
+        break;
+    }
+    // restore SQL message echo
+    $db->debug = $debug;
+    return $exists;
 }
 function hotpot_db_delete_index($table, $index, $feedback=false) {
-       global $CFG, $db;
-       $ok = true;
-       // check index exists
-       if (hotpot_db_index_exists($table, $index)) {
-               switch (strtolower($CFG->dbtype)) {
-                       case 'mysql' : 
-                               $sql = "ALTER TABLE `$table` DROP INDEX `$index`";
-                       break;
-                       case 'postgres7' :
-                               $sql = "DROP INDEX $index";
-                       break;
-                       default: // unknown database type
-                               $sql = '';
-                       break;
-               }
-               if ($sql) {
-                       // save and switch off SQL message echo
-                       $debug = $db->debug;
-                       $db->debug = $feedback;
-                       $ok = $db->Execute($sql) ? true : false;
-                       // restore SQL message echo
-                       $db->debug = $debug;
-               } else { // unknown database type
-                       $ok = false;
-               }
-       }
-       return $ok;
+    global $CFG, $db;
+    $ok = true;
+    // check index exists
+    if (hotpot_db_index_exists($table, $index)) {
+        switch (strtolower($CFG->dbtype)) {
+            case 'mysql' : 
+                $sql = "ALTER TABLE `$table` DROP INDEX `$index`";
+            break;
+            case 'postgres7' :
+                $sql = "DROP INDEX $index";
+            break;
+            default: // unknown database type
+                $sql = '';
+            break;
+        }
+        if ($sql) {
+            // save and switch off SQL message echo
+            $debug = $db->debug;
+            $db->debug = $feedback;
+            $ok = $db->Execute($sql) ? true : false;
+            // restore SQL message echo
+            $db->debug = $debug;
+        } else { // unknown database type
+            $ok = false;
+        }
+    }
+    return $ok;
 }
 function hotpot_db_add_index($table, $field, $length='') {
-       global $CFG, $db;
+    global $CFG, $db;
 
-       if (strtolower($CFG->dbtype)=='postgres7') {
-               $index = "{$CFG->prefix}{$table}_{$field}_idx";
-       } else {
-               // mysql (and others)
-               $index = "{$table}_{$field}_idx";
-       }
-       $table = "{$CFG->prefix}$table";
+    if (strtolower($CFG->dbtype)=='postgres7') {
+        $index = "{$CFG->prefix}{$table}_{$field}_idx";
+    } else {
+        // mysql (and others)
+        $index = "{$table}_{$field}_idx";
+    }
+    $table = "{$CFG->prefix}$table";
 
-       // delete $index if it already exists
-       $ok = hotpot_db_delete_index($table, $index);
+    // delete $index if it already exists
+    $ok = hotpot_db_delete_index($table, $index);
 
-       switch (strtolower($CFG->dbtype)) {
-               case 'mysql' :
-                       $length = empty($length) ? '' : " ($length)";
-                       $ok = $ok && $db->Execute("ALTER TABLE `$table` ADD INDEX `$index` (`$field`$length)");
-               break;
-               case 'postgres7' :
-                       if ($length) {
-                               $field = "SUBSTR(\"$field\",$length)";
-                       }
-                       $ok = $ok && $db->Execute("CREATE INDEX $index ON $table ($field)");
-               break;
-               default: // unknown database type
-                       $ok = false;
-               break;
-       }
-       return $ok;
+    switch (strtolower($CFG->dbtype)) {
+        case 'mysql' :
+            $length = empty($length) ? '' : " ($length)";
+            $ok = $ok && $db->Execute("ALTER TABLE `$table` ADD INDEX `$index` (`$field`$length)");
+        break;
+        case 'postgres7' :
+            if ($length) {
+                $field = "SUBSTR(\"$field\",$length)";
+            }
+            $ok = $ok && $db->Execute("CREATE INDEX $index ON $table ($field)");
+        break;
+        default: // unknown database type
+            $ok = false;
+        break;
+    }
+    return $ok;
 }
 function hotpot_db_table_exists($table, $feedback=false) {
-       return hotpot_db_object_exists($table, '', $feedback);
+    return hotpot_db_object_exists($table, '', $feedback);
 }
 function hotpot_db_field_exists($table, $field, $feedback=false) {
-       return 
-               hotpot_db_object_exists($table, '', $feedback) &&
-               hotpot_db_object_exists($table, $field, $feedback)
-       ;
+    return 
+        hotpot_db_object_exists($table, '', $feedback) &&
+        hotpot_db_object_exists($table, $field, $feedback)
+    ;
 }
 function hotpot_db_object_exists($table, $field='', $feedback=false) {
-       global $CFG,$db;
-       // expand table name
-       $table = "{$CFG->prefix}$table";
-       // set $sql
-       switch (strtolower($CFG->dbtype)) {
-               case 'mysql' : 
-                       if (empty($field)) {
-                               $sql = "SHOW TABLES LIKE '$table'";
-                       } else {
-                               $sql = "SHOW COLUMNS FROM `$table` LIKE '$field'";
-                       }
-               break;
-               case 'postgres7' :
-                       if (empty($field)) {
-                               $sql = "SELECT relname FROM pg_class WHERE relname = '$table' AND relkind='r'";
-                       } else {
-                               $sql = "
-                                       SELECT attname FROM pg_attribute WHERE attname = '$field' 
-                                       AND attrelid = (SELECT oid FROM pg_class WHERE relname = '$table')
-                               ";
-                       }
-               break;
-       }
-       // save and switch off SQL message echo
-       $debug = $db->debug;
-       $db->debug = $feedback;
-       // execute sql
-       $rs = $db->Execute($sql);
-       // restore SQL message echo setting
-       $db->debug = $debug;
-       // report error if required
-       if (empty($rs) && isset($CFG->debug) and $CFG->debug > 7) {
-               notify($db->ErrorMsg()."<br /><br />$sql");
-       }
-       return ($rs && $rs->RecordCount()>0);
+    global $CFG,$db;
+    // expand table name
+    $table = "{$CFG->prefix}$table";
+    // set $sql
+    switch (strtolower($CFG->dbtype)) {
+        case 'mysql' : 
+            if (empty($field)) {
+                $sql = "SHOW TABLES LIKE '$table'";
+            } else {
+                $sql = "SHOW COLUMNS FROM `$table` LIKE '$field'";
+            }
+        break;
+        case 'postgres7' :
+            if (empty($field)) {
+                $sql = "SELECT relname FROM pg_class WHERE relname = '$table' AND relkind='r'";
+            } else {
+                $sql = "
+                    SELECT attname FROM pg_attribute WHERE attname = '$field' 
+                    AND attrelid = (SELECT oid FROM pg_class WHERE relname = '$table')
+                ";
+            }
+        break;
+    }
+    // save and switch off SQL message echo
+    $debug = $db->debug;
+    $db->debug = $feedback;
+    // execute sql
+    $rs = $db->Execute($sql);
+    // restore SQL message echo setting
+    $db->debug = $debug;
+    // report error if required
+    if (empty($rs) && isset($CFG->debug) and $CFG->debug > 7) {
+        notify($db->ErrorMsg()."<br /><br />$sql");
+    }
+    return ($rs && $rs->RecordCount()>0);
 }
 function hotpot_db_remove_table($table, $feedback=true) {
-       global $CFG;
-       if (hotpot_db_table_exists($table)) {
-               $ok = execute_sql("DROP TABLE {$CFG->prefix}$table", $feedback);
-       } else {
-               $ok = true;
-       }
-       return $ok;
+    global $CFG;
+    if (hotpot_db_table_exists($table)) {
+        $ok = execute_sql("DROP TABLE {$CFG->prefix}$table", $feedback);
+    } else {
+        $ok = true;
+    }
+    return $ok;
 }
 function hotpot_db_rename_table($oldtable, $table, $feedback=true) {
-       global $CFG;
-       if (hotpot_db_table_exists($oldtable)) {
-               $ok = execute_sql("ALTER TABLE {$CFG->prefix}$oldtable RENAME TO {$CFG->prefix}$table", $feedback);
-       } else {
-               $ok = true;
-       }
-       return $ok;
+    global $CFG;
+    if (hotpot_db_table_exists($oldtable)) {
+        $ok = execute_sql("ALTER TABLE {$CFG->prefix}$oldtable RENAME TO {$CFG->prefix}$table", $feedback);
+    } else {
+        $ok = true;
+    }
+    return $ok;
 }
 function hotpot_db_append_table($oldtable, $table, $feedback=true) {
-       global $CFG, $db;
-       if (hotpot_db_table_exists($oldtable)) {
-               if (hotpot_db_table_exists($table)) {
-                       // expand table names
-                       $table = "{$CFG->prefix}$table";
-                       $oldtable = "{$CFG->prefix}$oldtable";
-                       // get field info
-                       $fields = $db->MetaColumns($table);
-                       $oldfields = $db->MetaColumns($oldtable);
-                       $fieldnames = array();
-                       if (!empty($fields) || !empty($oldfields)) {
-                               foreach ($fields as $field) {
-                                       if ($field->name!='id' && isset($oldfields[strtoupper($field->name)])) {
-                                               $fieldnames[] = $field->name;
-                                       }
-                               }
-                       }
-                       $fieldnames = implode(',', $fieldnames);
-                       if (empty($fieldnames)) {
-                               $ok = false;
-                       } else {
-                               switch (strtolower($CFG->dbtype)) {
-                                       case 'mysql':
-                                               $ok = execute_sql("INSERT INTO `$table` ($fieldnames) SELECT $fieldnames FROM `$oldtable` WHERE 1");
-                                               break;
-                                       case 'postgres7':
-                                               $ok = execute_sql("INSERT INTO $table ($fieldnames) SELECT $fieldnames FROM $oldtable");
-                                               break;
-                                       default:
-                                               $ok = false;
-                                               break;
-                               }
-                       }
-               } else { // $table does not exist
-                       $ok = hotpot_db_rename_table($oldtable, $table, $feedback);
-               }
-       } else { // $oldtable does not exist
-               $ok = hotpot_db_table_exists($table, $feedback);
-       }
-       return $ok;
+    global $CFG, $db;
+    if (hotpot_db_table_exists($oldtable)) {
+        if (hotpot_db_table_exists($table)) {
+            // expand table names
+            $table = "{$CFG->prefix}$table";
+            $oldtable = "{$CFG->prefix}$oldtable";
+            // get field info
+            $fields = $db->MetaColumns($table);
+            $oldfields = $db->MetaColumns($oldtable);
+            $fieldnames = array();
+            if (!empty($fields) || !empty($oldfields)) {
+                foreach ($fields as $field) {
+                    if ($field->name!='id' && isset($oldfields[strtoupper($field->name)])) {
+                        $fieldnames[] = $field->name;
+                    }
+                }
+            }
+            $fieldnames = implode(',', $fieldnames);
+            if (empty($fieldnames)) {
+                $ok = false;
+            } else {
+                switch (strtolower($CFG->dbtype)) {
+                    case 'mysql':
+                        $ok = execute_sql("INSERT INTO `$table` ($fieldnames) SELECT $fieldnames FROM `$oldtable` WHERE 1");
+                        break;
+                    case 'postgres7':
+                        $ok = execute_sql("INSERT INTO $table ($fieldnames) SELECT $fieldnames FROM $oldtable");
+                        break;
+                    default:
+                        $ok = false;
+                        break;
+                }
+            }
+        } else { // $table does not exist
+            $ok = hotpot_db_rename_table($oldtable, $table, $feedback);
+        }
+    } else { // $oldtable does not exist
+        $ok = hotpot_db_table_exists($table, $feedback);
+    }
+    return $ok;
 }
 function hotpot_db_set_table_comment($table, $comment, $feedback=true) {
-       global $CFG;
-       $ok = true;
-       switch (strtolower($CFG->dbtype)) {
-               case 'mysql' :
-                       $ok = execute_sql("ALTER TABLE {$CFG->prefix}$table COMMENT='$comment'");
-                       break;
-               case 'postgres7' :
-                       $ok = execute_sql("COMMENT ON TABLE {$CFG->prefix}$table IS '$comment'");
-                       break;
-       }
-       return $ok;
+    global $CFG;
+    $ok = true;
+    switch (strtolower($CFG->dbtype)) {
+        case 'mysql' :
+            $ok = execute_sql("ALTER TABLE {$CFG->prefix}$table COMMENT='$comment'");
+            break;
+        case 'postgres7' :
+            $ok = execute_sql("COMMENT ON TABLE {$CFG->prefix}$table IS '$comment'");
+            break;
+    }
+    return $ok;
 }
 function hotpot_db_remove_field($table, $field, $feedback=true) {
-       global $CFG;
-       if (hotpot_db_field_exists($table, $field)) {
-               $ok = execute_sql("ALTER TABLE {$CFG->prefix}$table DROP COLUMN $field", $feedback);
-       } else {
-               $ok = true;
-       }
-       return $ok;
+    global $CFG;
+    if (hotpot_db_field_exists($table, $field)) {
+        $ok = execute_sql("ALTER TABLE {$CFG->prefix}$table DROP COLUMN $field", $feedback);
+    } else {
+        $ok = true;
+    }
+    return $ok;
 }
 function hotpot_db_update_field_type($table, $oldfield, $field, $type, $size, $unsigned, $notnull, $default=NULL, $after=NULL) {
-       $ok = true;
-       global $CFG,$db;
-       // check validity of arguments, and adjust if necessary
-       if ($oldfield && !hotpot_db_field_exists($table, $oldfield)) {
-               $oldfield = '';
-       }
-       if (empty($oldfield) && hotpot_db_field_exists($table, $field)) {
-               $oldfield = $field;
-       
-       if (is_string($unsigned)) {
-               $unsigned = (strtoupper($unsigned)=='UNSIGNED');
-       }
-       if (is_string($notnull)) {
-               $notnull = (strtoupper($notnull)=='NOT NULL');
-       }
-       if (isset($default)) {
-               if (!is_numeric($default) && strtoupper($default)!='NULL' && !preg_match("|^'.*'$|", $default)) {
-                       $default = "'$default'";
-               }
-       }
-       // set full table name
-       $table = "{$CFG->prefix}$table";
-       // update the field in the database
-       switch (strtolower($CFG->dbtype)) {
-               case 'mysql':
-                       // optimize integer types
-                       switch (strtoupper($type)) {
-                               case 'TEXT':
-                                       $size = '';
-                                       $unsigned = false;
-                               break;
-                               case 'INTEGER' :
-                                       if (!is_numeric($size)) {
-                                               $size = '';
-                                       } else if ($size <= 4) {
-                                               $type = "TINYINT";   // 1 byte
-                                       } else if ($size <= 6) {
-                                               $type = "SMALLINT";  // 2 bytes
-                                       } else if ($size <= 8) {
-                                               $type = "MEDIUMINT"; // 3 bytes
-                                       } else if ($size <= 10) {
-                                               $type = "INTEGER";   // 4 bytes (=INT)
-                                       } else if ($size > 10) {
-                                               $type = "BIGINT";    // 8 bytes
-                                       }
-                               break;
-                               case 'VARCHAR':
-                                       $unsigned = false;
-                               break;
-                       }
-                       // set action
-                       if (empty($oldfield)) {
-                               $action = "ADD";
-                       } else {
-                               $action = "CHANGE `$oldfield`";
-                       }
-                       // set fieldtype
-                       $fieldtype = $type;
-                       if ($size) {
-                               $fieldtype .= "($size)";
-                       }
-                       if ($unsigned) {
-                               $fieldtype .= ' UNSIGNED';
-                       }
-                       if ($notnull) {
-                               $fieldtype .= ' NOT NULL';
-                       }
-                       if (isset($default)) {
-                               $fieldtype .= " DEFAULT $default";
-                       }
-                       if (!empty($after)) {
-                               $fieldtype .= " AFTER `$after`";
-                       }
-                       $ok = $ok && execute_sql("ALTER TABLE `$table` $action `$field` $fieldtype");
-               break;
-               case 'postgres7':
-                       // get db version
-                       $dbinfo = $db->ServerInfo();
-                       $dbversion = substr($dbinfo['version'],0,3);
-                       // prevent conflicts with reserved words
-                       $tmpfield = "\"temporary_{$field}_".time()."\"";
-                       $oldfield = "\"$oldfield\"";
-                       $field    = "\"$field\"";
-                       switch (strtoupper($type)) {
-                               case "INTEGER":
-                                       if (!is_numeric($size)) {
-                                               $fieldtype = "INTEGER";
-                                       } else if ($size <= 4) {
-                                               $fieldtype = "INT2"; // 2 bytes
-                                       } else if ($size <= 10) {
-                                               $fieldtype = "INT4"; // 4 bytes (=INTEGER)
-                                       } else if ($size > 10) {
-                                               $fieldtype = "INT8"; // 8 bytes
-                                       }
-                               break;
-                               case "VARCHAR":
-                                       $fieldtype = "VARCHAR($size)";
-                               break;
-                               default:
-                                       $fieldtype = $type;
-                       }
-                       // start transaction
-                       execute_sql("BEGIN");
-                       // create temporary field
-                       execute_sql("ALTER TABLE $table ADD COLUMN $tmpfield $fieldtype");
-                       // set default
-                       if (isset($default)) {
-                               execute_sql("UPDATE $table SET $tmpfield = $default");
-                               execute_sql("ALTER TABLE $table ALTER COLUMN $tmpfield SET DEFAULT $default");
-                       } else {
-                               execute_sql("ALTER TABLE $table ALTER COLUMN $tmpfield DROP DEFAULT");
-                       }
-                       // set not null
-                       if ($dbversion >= "7.3") {
-                               $notnull = ($notnull ? "SET NOT NULL" : "DROP NOT NULL");
-                               execute_sql("ALTER TABLE $table ALTER COLUMN $tmpfield $notnull");
-                       } else {
-                               execute_sql("
-                                       UPDATE pg_attribute SET attnotnull=".($notnull ? 'TRUE' : 'FALSE')." 
-                                       WHERE attname = $tmpfield
-                                       AND attrelid = (SELECT oid FROM pg_class WHERE relname = '$table')
-                               ");
-                       }
-                       // transfer $oldfield values, if necessary
-                       if ( $oldfield != '""' ) {
-                               execute_sql("UPDATE $table SET $tmpfield = CAST ($oldfield AS $fieldtype)");
-                               execute_sql("ALTER TABLE $table DROP COLUMN $oldfield");
-                       }
-                       // rename $tmpfield to $field
-                       execute_sql("ALTER TABLE $table RENAME COLUMN $tmpfield TO $field");
-                       // do the transaction
-                       execute_sql("COMMIT");
-                       // reclaim disk space (must be done outside transaction)
-                       if ($oldfield != '""' && $dbversion >= "7.3") {
-                               execute_sql("UPDATE $table SET $field = $field");
-                               execute_sql("VACUUM FULL $table");
-                       }
-               break;
-       } // end switch $CGF->dbtype
-       return $ok;
+    $ok = true;
+    global $CFG,$db;
+    // check validity of arguments, and adjust if necessary
+    if ($oldfield && !hotpot_db_field_exists($table, $oldfield)) {
+        $oldfield = '';
+    }
+    if (empty($oldfield) && hotpot_db_field_exists($table, $field)) {
+        $oldfield = $field;
+    } 
+    if (is_string($unsigned)) {
+        $unsigned = (strtoupper($unsigned)=='UNSIGNED');
+    }
+    if (is_string($notnull)) {
+        $notnull = (strtoupper($notnull)=='NOT NULL');
+    }
+    if (isset($default)) {
+        if (!is_numeric($default) && strtoupper($default)!='NULL' && !preg_match("|^'.*'$|", $default)) {
+            $default = "'$default'";
+        }
+    }
+    // set full table name
+    $table = "{$CFG->prefix}$table";
+    // update the field in the database
+    switch (strtolower($CFG->dbtype)) {
+        case 'mysql':
+            // optimize integer types
+            switch (strtoupper($type)) {
+                case 'TEXT':
+                    $size = '';
+                    $unsigned = false;
+                break;
+                case 'INTEGER' :
+                    if (!is_numeric($size)) {
+                        $size = '';
+                    } else if ($size <= 4) {
+                        $type = "TINYINT";   // 1 byte
+                    } else if ($size <= 6) {
+                        $type = "SMALLINT";  // 2 bytes
+                    } else if ($size <= 8) {
+                        $type = "MEDIUMINT"; // 3 bytes
+                    } else if ($size <= 10) {
+                        $type = "INTEGER";   // 4 bytes (=INT)
+                    } else if ($size > 10) {
+                        $type = "BIGINT";    // 8 bytes
+                    }
+                break;
+                case 'VARCHAR':
+                    $unsigned = false;
+                break;
+            }
+            // set action
+            if (empty($oldfield)) {
+                $action = "ADD";
+            } else {
+                $action = "CHANGE `$oldfield`";
+            }
+            // set fieldtype
+            $fieldtype = $type;
+            if ($size) {
+                $fieldtype .= "($size)";
+            }
+            if ($unsigned) {
+                $fieldtype .= ' UNSIGNED';
+            }
+            if ($notnull) {
+                $fieldtype .= ' NOT NULL';
+            }
+            if (isset($default)) {
+                $fieldtype .= " DEFAULT $default";
+            }
+            if (!empty($after)) {
+                $fieldtype .= " AFTER `$after`";
+            }
+            $ok = $ok && execute_sql("ALTER TABLE `$table` $action `$field` $fieldtype");
+        break;
+        case 'postgres7':
+            // get db version
+            $dbinfo = $db->ServerInfo();
+            $dbversion = substr($dbinfo['version'],0,3);
+            // prevent conflicts with reserved words
+            $tmpfield = "\"temporary_{$field}_".time()."\"";
+            $oldfield = "\"$oldfield\"";
+            $field    = "\"$field\"";
+            switch (strtoupper($type)) {
+                case "INTEGER":
+                    if (!is_numeric($size)) {
+                        $fieldtype = "INTEGER";
+                    } else if ($size <= 4) {
+                        $fieldtype = "INT2"; // 2 bytes
+                    } else if ($size <= 10) {
+                        $fieldtype = "INT4"; // 4 bytes (=INTEGER)
+                    } else if ($size > 10) {
+                        $fieldtype = "INT8"; // 8 bytes
+                    }
+                break;
+                case "VARCHAR":
+                    $fieldtype = "VARCHAR($size)";
+                break;
+                default:
+                    $fieldtype = $type;
+            }
+            // start transaction
+            execute_sql("BEGIN");
+            // create temporary field
+            execute_sql("ALTER TABLE $table ADD COLUMN $tmpfield $fieldtype");
+            // set default
+            if (isset($default)) {
+                execute_sql("UPDATE $table SET $tmpfield = $default");
+                execute_sql("ALTER TABLE $table ALTER COLUMN $tmpfield SET DEFAULT $default");
+            } else {
+                execute_sql("ALTER TABLE $table ALTER COLUMN $tmpfield DROP DEFAULT");
+            }
+            // set not null
+            if ($dbversion >= "7.3") {
+                $notnull = ($notnull ? "SET NOT NULL" : "DROP NOT NULL");
+                execute_sql("ALTER TABLE $table ALTER COLUMN $tmpfield $notnull");
+            } else {
+                execute_sql("
+                    UPDATE pg_attribute SET attnotnull=".($notnull ? 'TRUE' : 'FALSE')." 
+                    WHERE attname = $tmpfield
+                    AND attrelid = (SELECT oid FROM pg_class WHERE relname = '$table')
+                ");
+            }
+            // transfer $oldfield values, if necessary
+            if ( $oldfield != '""' ) {
+                execute_sql("UPDATE $table SET $tmpfield = CAST ($oldfield AS $fieldtype)");
+                execute_sql("ALTER TABLE $table DROP COLUMN $oldfield");
+            }
+            // rename $tmpfield to $field
+            execute_sql("ALTER TABLE $table RENAME COLUMN $tmpfield TO $field");
+            // do the transaction
+            execute_sql("COMMIT");
+            // reclaim disk space (must be done outside transaction)
+            if ($oldfield != '""' && $dbversion >= "7.3") {
+                execute_sql("UPDATE $table SET $field = $field");
+                execute_sql("VACUUM FULL $table");
+            }
+        break;
+    } // end switch $CGF->dbtype
+    return $ok;
 }
 function hotpot_db_update_record($table, $record, $forcenull=false) {
-       global $CFG, $db;
-       $ok = true;
-       // set full table name
-       $table = "{$CFG->prefix}$table";
-       // get field names
-       $fields = $db->MetaColumns($table);
-       if (empty($fields)) {
-               $ok = false;
-       } else {
-               // get values
-               $values = array();
-               foreach ($fields as $field) {
-                       $fieldname = $field->name;
-                       if ($fieldname!='id' && ($forcenull || isset($record->$fieldname))) {
-                               $value = isset($record->$fieldname) ? "'".$record->$fieldname."'" : 'NULL';
-                               $values[] = "$fieldname = $value";
-                       }
-               }
-               $values = implode(',', $values);
-               // update values (if there are any)
-               if ($values) {
-                       $sql = "UPDATE $table SET $values WHERE id='$record->id'";
-                       $rs = $db->Execute($sql);
-                       if (empty($rs)) {
-                               $ok = false;
-                               if (isset($CFG->debug) and $CFG->debug > 7) {
-                                       notify($db->ErrorMsg()."<br /><br />$sql");
-                               }
-                       }
-               }
-       }
-       return $ok;
+    global $CFG, $db;
+    $ok = true;
+    // set full table name
+    $table = "{$CFG->prefix}$table";
+    // get field names
+    $fields = $db->MetaColumns($table);
+    if (empty($fields)) {
+        $ok = false;
+    } else {
+        // get values
+        $values = array();
+        foreach ($fields as $field) {
+            $fieldname = $field->name;
+            if ($fieldname!='id' && ($forcenull || isset($record->$fieldname))) {
+                $value = isset($record->$fieldname) ? "'".$record->$fieldname."'" : 'NULL';
+                $values[] = "$fieldname = $value";
+            }
+        }
+        $values = implode(',', $values);
+        // update values (if there are any)
+        if ($values) {
+            $sql = "UPDATE $table SET $values WHERE id='$record->id'";
+            $rs = $db->Execute($sql);
+            if (empty($rs)) {
+                $ok = false;
+                if (isset($CFG->debug) and $CFG->debug > 7) {
+                    notify($db->ErrorMsg()."<br /><br />$sql");
+                }
+            }
+        }
+    }
+    return $ok;
 }
 function hotpot_rm($target, $output=true) {
-       $ok = true;
-       if (!empty($target)) {
-               if (is_file($target)) {
-                       if ($output) {
-                               print "removing file: $target ... ";
-                       }
-                       $ok = @unlink($target);
-               } else if (is_dir($target)) {
-                       $dir = dir($target);
-                       while(false !== ($entry = $dir->read())) {
-                               if ($entry!='.' && $entry!='..') {
-                                       $ok = $ok && hotpot_rm($target.DIRECTORY_SEPARATOR.$entry, $output);
-                               }
-                       }
-                       $dir->close();
-                       if ($output) {
-                               print "removing folder: $target ... ";
-                       }
-                       $ok = $ok && @rmdir($target);
-               } else { // not a file or directory (probably doesn't exist)
-                       $output = false;
-               }
-               if ($output) {
-                       if ($ok) {
-                               print '<font color="green">OK</font><br />';
-                       } else {
-                               print '<font color="red">Failed</font><br />';
-                       }
-               }
-       }
-       return $ok;
+    $ok = true;
+    if (!empty($target)) {
+        if (is_file($target)) {
+            if ($output) {
+                print "removing file: $target ... ";
+            }
+            $ok = @unlink($target);
+        } else if (is_dir($target)) {
+            $dir = dir($target);
+            while(false !== ($entry = $dir->read())) {
+                if ($entry!='.' && $entry!='..') {
+                    $ok = $ok && hotpot_rm($target.DIRECTORY_SEPARATOR.$entry, $output);
+                }
+            }
+            $dir->close();
+            if ($output) {
+                print "removing folder: $target ... ";
+            }
+            $ok = $ok && @rmdir($target);
+        } else { // not a file or directory (probably doesn't exist)
+            $output = false;
+        }
+        if ($output) {
+            if ($ok) {
+                print '<font color="green">OK</font><br />';
+            } else {
+                print '<font color="red">Failed</font><br />';
+            }
+        }
+    }
+    return $ok;
 }
 function hotpot_flush($n=0, $time=false) {
-       if ($time) {
-               $t = strftime("%X",time());
-       } else {
-               $t = "";
-       }
-       echo str_repeat(" ", $n) . $t . "\n";
-       flush();
+    if ($time) {
+        $t = strftime("%X",time());
+    } else {
+        $t = "";
+    }
+    echo str_repeat(" ", $n) . $t . "\n";
+    flush();
 }
 ?>
index 3aceb5e..e7226ac 100644 (file)
 
 // This page lists all the instances of hotpot in a particular course
 
-       require_once("../../config.php");
-       require_once("../../course/lib.php");
-       require_once("lib.php");
-
-       $id = required_param("id");   // course
-
-       if (! $course = get_record("course", "id", $id)) {
-               error("Course ID is incorrect");
-       }
-
-       require_login($course->id);
-
-       add_to_log($course->id, "hotpot", "view all", "index.php?id=$course->id", "");
-
-       // Moodle 1.4+ requires sesskey to be passed in forms
-       if (isset($USER->sesskey)) {
-               $sesskey = '<input type="hidden" name="sesskey" value="'.$USER->sesskey.'" />';
-       } else {
-               $sesskey = '';
-       }
-
-       // get message strings for titles
-       $strmodulenameplural = get_string("modulenameplural", "hotpot");
-       $strmodulename  = get_string("modulename", "hotpot");
-
-       // string translation array for single and double quotes
-       $quotes = array("'"=>"\'", '"'=>'&quot;');
-
-       // Print the header
-
-       $title = "$course->shortname: $strmodulenameplural";
-       $heading = "$course->fullname";
-       $navigation = "$strmodulenameplural";
-       if ($course->category) {
-               $navigation = "<a href=\"../../course/view.php?id=$course->id\">$course->shortname</a> -> $navigation";
-       }
-       print_header($title, $heading, $navigation, "", "", true, "", navmenu($course));
-
-       $next_url = "$CFG->wwwroot/course/view.php?id=$course->id";
-
-       // get display section, if any
-       $section = optional_param('section', 0);
-       if ($section) {
-               $displaysection = course_set_display($course->id, $section);
-       } else {
-               if (isset($USER->display[$course->id])) {
-                       $displaysection = $USER->display[$course->id];
-               } else {
-                       $displaysection = 0;
-               }
-       }
-
-       // Get all instances of this module
-       if (!$hotpots = hotpot_get_all_instances_in_course("hotpot", $course)) {
-               $hotpots = array();
-       }
-
-       // if necessary, remove hotpots that are not in section0 or this $USER's display section
-       if ($displaysection) {
-               foreach ($hotpots as $coursemodule=>$hotpot) {
-                       if ($hotpot->section!=0 && $hotpot->section!=$displaysection) {
-                               unset($hotpots[$coursemodule]);
-                       }
-               }
-       }
-
-       if (empty($hotpots)) {
-               notice("There are no $strmodulenameplural", $next_url);
-               exit;
-       }
-
-       // get list of hotpot ids
-       $hotpotids = array();
-       foreach ($hotpots as $cmid=>$hotpot) {
-               $hotpotids[] = $hotpot->id;
-       }
-       $hotpotids = implode(',', $hotpotids);
-
-       if (isadmin()) {
-
-               // get regrade settings, if any
-               $regrade = optional_param("regrade");
-               $confirm = optional_param("confirm");
-
-               // check regrade is valid
-               unset($regrade_cmid);
-               if (isset($regrade)) {
-                       foreach ($hotpots as $cmid=>$hotpot) {
-                               $found = false;
-                               if ($hotpot->id==$regrade) {
-                                       $regrade_cmid = $cmid;
-                               }
-                       }
-               }
-
-               // regrade, if necessary
-               if (isset($regrade_cmid)) {
-
-                       if (empty($confirm)) {
-
-                               $strregradecheck = get_string('regradecheck', 'hotpot', $hotpots[$regrade_cmid]->name);
-
-                               print_simple_box_start("center", "60%", "#FFAAAA", 20, "noticebox");
-                               print_heading($strregradecheck);
-                               print ''
-                               .       '<table border="0"><tr><td>'
-                               .       '<form target="_parent" method="post" action="'.$ME.'">'
-                               .       '<input type="hidden" name="id" value="'.$course->id.'">'
-                               .       '<input type="hidden" name="regrade" value="'.$regrade.'" />'
-                               .       '<input type="hidden" name="confirm" value="1" />'
-                               .       $sesskey
-                               .       '<input type="submit" value="'.get_string("yes").'" />'
-                               .       '</form>'
-                               .       '</td><td> &nbsp; </td><td>'
-                               .       '<form target="_parent" method="post" action="'.$ME.'">'
-                               .       '<input type="hidden" name="id" value="'.$course->id.'">'
-                               .       $sesskey
-                               .       '<input type="submit" value="'.get_string("no").'" />'
-                               .       '</form>'
-                               .       '</td></tr></table>'
-                               ;
-                               print_simple_box_end();
-                               print_footer($course);
-                               exit;
-
-                       } else { // regrade has been confirmed, so proceed
-
-                               if ($regrade=='all') {
-                                       $select = "hotpot IN ($hotpotids)";
-                               } else {
-                                       $select = "hotpot=$regrade";
-                               }
-
-                               $questionids = array();
-                               if ($questions = get_records_select("hotpot_questions", $select)) {
-                                       $questionids = array_keys($questions);
-                               }
-                               $questionids = implode(',', $questionids);
-
-                               if ($questionids) {
-                                       hotpot_delete_and_notify('hotpot_questions', "id IN ($questionids)", get_string('question', 'quiz'));
-                                       hotpot_delete_and_notify('hotpot_responses', "question IN ($questionids)", get_string('answer', 'quiz'));
-                               }
-
-                               if ($attempts = get_records_select('hotpot_attempts', $select)) {
-
-                                       // start counter and timer
-                                       $start = microtime();
-                                       $count = 0;
-
-                                       // use while loop instead of foreach loop
-                                       // to allow the possibility of splitting a regrade 
-                                       // and so avoid "maximum script time exceeded" errors
-                                       $attemptids = array_keys($attempts);
-                                       $i_max = count($attemptids);
-                                       $i = 0;
-                                       while ($i<$i_max) {
-
-                                               $attemptid = $attemptids[$i];
-                                               $attempt =&$attempts[$attemptid];
-
-                                               $attempt->details = get_field('hotpot_details', 'details', 'attempt', $attemptid);
-                                               if ($attempt->details) {
-
-                                                       hotpot_add_attempt_details($attempt);
-                                                       if (! update_record('hotpot_attempts', $attempt)) {
-                                                               error("Could not update attempt record: ".$db->ErrorMsg(), $next_url);
-                                                       }
-                                               }
-                                               $count++;
-                                               $i++;
-                                       }
-                                       if ($count) {
-                                               notify(get_string('added', 'moodle', "$count x ".get_string('attempts', 'quiz')));
-                                       }
-                                       $msg = get_string('regradecomplete', 'quiz');
-                                       if (!empty($CFG->hotpot_showtimes)) {
-                                               $duration = format_time(sprintf("%0.2f", microtime_diff($start, microtime())));
-                                               $msg .= " ($duration)";
-                                       }
-                                       notify($msg);
-                               }
-                       }
-               } // end regrade
-
-               //print '<center><form action="'.$ME.'" method="post">';
-               //print '<input type="hidden" name="id" value="'.$course->id.'">';
-               //print '<input type="submit" name="regrade" value="'.get_string('regrade', 'quiz').'">';
-               //print '</form></center>'."\n";
-
-
-               // get duplicate hotpot-name questions
-               //      - JMatch LHS is longer than 255 bytes
-               //      - JQuiz question text is longer than 255 bytes
-               //      - other unidentified situations ?!?
-
-               $field = '';
-               $questions = false;
-               $regradehotpots = array();
-
-               switch (strtolower($CFG->dbtype)) {
-                       case 'mysql' : 
-                               $field = "CONCAT(hotpot, '_', name)";
-                               break;
-                       case 'postgres7' :
-                               $field = "hotpot||'_'||name";
-                               break;
-               }
-               if ($field) {
-                       $questions = get_records_sql("
-                               SELECT $field, COUNT(*), hotpot, name
-                               FROM {$CFG->prefix}hotpot_questions 
-                               WHERE hotpot IN ($hotpotids)
-                               GROUP BY hotpot, name 
-                               HAVING COUNT(*) >1
-                       ");
-               }
-               if ($questions) {
-                       foreach ($questions as $question) {
-                               $regradehotpots[] = $question->hotpot;
-                       }
-                       $regradehotpots = array_unique($regradehotpots);
-                       sort($regradehotpots);
-               }
-       }
-
-       // start timer
-       $start = microtime();
-
-       // get total number of attempts, users and details for these hotpots
-       $tables = "{$CFG->prefix}hotpot_attempts AS a";
-       $fields = "
-               a.hotpot AS hotpot,
-               COUNT(DISTINCT a.clickreportid) AS attemptcount,
-               COUNT(DISTINCT a.userid) AS usercount,
-               MAX(a.score) AS maxscore
-       ";
-       $select = "a.hotpot IN ($hotpotids)";
-       if (isteacher($course->id)) {
-               // do nothing (=get all users)
-       } else {
-               // restrict results to this user only
-               $select .= " AND a.userid='$USER->id'";
-       }
-       $usejoin = 1;
-       if (isadmin() && $usejoin) {
-               // join attempts table and details table
-               $tables .= ",{$CFG->prefix}hotpot_details AS d";
-               $fields .= ',COUNT(DISTINCT d.id) AS detailcount';
-               $select .= " AND a.id=d.attempt";
-
-               // this may take about twice as long as getting the gradecounts separately :-(
-               // so this operation could be done after getting the $totals from the attempts table
-       }
-       $totals = get_records_sql("SELECT $fields FROM $tables WHERE $select GROUP BY a.hotpot");
-
-       if (isadmin() && empty($usejoin)) {
-               foreach ($hotpots as $hotpot) {
-                       $totals[$hotpot->id]->detailcount = 0;
-                       if ($ids = get_records('hotpot_attempts', 'hotpot', $hotpot->id)) {
-                               $ids = join(',', array_keys($ids));
-                               $totals[$hotpot->id]->detailcount = count_records_select('hotpot_details', "attempt IN ($ids)");
-                       }
-               }
-       }
-
-       // message strings for main table
-       $strusers  = get_string('users');
-       $strupdate = get_string('update');
-       $strregrade = get_string('regrade', 'hotpot');
-       $strneverclosed = get_string('neverclosed', 'hotpot');
-       $strregraderequired = get_string('regraderequired', 'hotpot');
-
-       // column headings and attributes
-       $table->head = array();
-       $table->align = array();
-
-       if (!empty($CFG->hotpot_showtimes)) {
-               print '<H3>'.sprintf("%0.3f", microtime_diff($start, microtime())).' secs'."</H3>\n";
-       }
-
-       switch ($course->format) {
-               case 'weeks' : 
-                       $title = get_string("week");
-                       break;
-               case 'topics' : 
-                       $title = get_string("topic");
-                       break;
-               default : 
-                       $title = '';
-                       break;
-       }
-       if ($title) {
-               array_push($table->head, $title); 
-               array_push($table->align, "center");
-       }
-       if (isteacheredit($course->id)) {
-               array_push($table->head, $strupdate);
-               array_push($table->align, "center");
-       }
-       array_push($table->head, 
-               get_string("name"), 
-               get_string("quizcloses", "quiz"), 
-               get_string("bestgrade", "quiz"), 
-               get_string("attempts", "quiz")
-       );
-       array_push($table->align, 
-               "left", "left", "center", "left"
-       );
-       if (isadmin()) {
-               array_push($table->head, $strregrade);
-               array_push($table->align, "center");
-       }
-
-       $currentsection = -1;
-       foreach ($hotpots as $hotpot) {
-
-               $printsection = "";
-               if ($hotpot->section != $currentsection) {
-                       if ($hotpot->section) {
-                               $printsection = $hotpot->section;
-                               if ($course->format=='weeks' || $course->format=='topics') {
-                                       // Show the zoom boxes
-                                       if ($displaysection==$hotpot->section) {
-                                               $strshowall = get_string('showall'.$course->format);
-                                               $printsection .= '<br /><a href="index.php?id='.$course->id.'&section=all" title="'.$strshowall.'"><img src="'.$CFG->pixpath.'/i/all.gif" height=25 width=16 border=0></a><br />';
-                                       } else {
-                                               $strshowone = get_string('showonly'.preg_replace('|s$|', '', $course->format, 1), '', $hotpot->section);
-                                               $printsection .=  '<br /><a href="index.php?id='.$course->id.'&section='.$hotpot->section.'" title="'.$strshowone.'"><img src="'.$CFG->pixpath.'/i/one.gif" height=16 width=16 border=0></a><br />';
-                                       }
-                               }
-                       }
-                       if ($currentsection>=0) {
-                               $table->data[] = 'hr';
-                       }
-                       $currentsection = $hotpot->section;
-               }
-
-               $class = ($hotpot->visible) ? '' : 'class="dimmed" ';
-               $quizname = '<a '.$class.'href="view.php?id='.$hotpot->coursemodule.'">'.$hotpot->name.'</A>';
-               $quizclose = empty($hotpot->timeclose) ? $strneverclosed : userdate($hotpot->timeclose);
-
-               // are there any totals for this hotpot?
-               if (empty($totals[$hotpot->id]->attemptcount)) {
-                       $report = "&nbsp;";
-                       $bestscore = "&nbsp;";
-
-               } else {
-                       // report number of attempts and users
-                       $report = get_string("viewallreports","quiz", $totals[$hotpot->id]->attemptcount);
-                       if (isteacher($course->id)) {
-                               $report .= " (".$totals[$hotpot->id]->usercount." $strusers)";
-                       }
-                       $report = '<a href="report.php?hp='.$hotpot->id.'">'.$report.'</a>';
-
-                       // get best score
-                       if (is_numeric($totals[$hotpot->id]->maxscore)) {
-                               $bestscore = $totals[$hotpot->id]->maxscore." / $hotpot->grade";
-                       } else {
-                               $bestscore = "&nbsp;";
-                       }
-               }
-
-               if (isadmin()) {
-                       if (in_array($hotpot->id, $regradehotpots)) {
-                               $report .= ' <font color="red">'.$strregraderequired.'</font>';
-                       }
-               }
-
-               $data = array ();
-
-               if ($course->format=="weeks" || $course->format=="topics") {
-                       array_push($data, $printsection);
-               }
-
-               if (isteacheredit($course->id)) {
-                       $updatebutton = ''
-                       .       '<form target="'.$CFG->framename.'" method="get" action="'.$CFG->wwwroot.'/course/mod.php">'
-                       .       '<input type="hidden" name="update" value="'.$hotpot->coursemodule.'" />'
-                       .       $sesskey
-                       .       '<input type="submit" value="'.$strupdate.'" />'
-                       .       '</form>'
-                       ;
-                       array_push($data, $updatebutton);
-               }
-
-               array_push($data, $quizname, $quizclose, $bestscore, $report);
-
-               if (isadmin()) {
-                       if (empty($totals[$hotpot->id]->detailcount)) {
-                               // no details records for this hotpot, so disable regrade
-                               $regradebutton = '&nbsp;';
-                       } else {
-                               $strregradecheck = get_string('regradecheck', 'hotpot', strtr($hotpot->name, $quotes));
-                               $regradebutton = ''
-                               .       '<form target="_parent" method="post" action="'.$ME.'" onsubmit="var x=window.confirm('."'$strregradecheck'".');this.confirm.value=x;return x;">'
-                               .       '<input type="hidden" name="id" value="'.$course->id.'">'
-                               .       '<input type="hidden" name="regrade" value="'.$hotpot->id.'" />'
-                               .       '<input type="hidden" name="confirm" value="" />'
-                               .       $sesskey
-                               .       '<input type="submit" value="'.$strregrade.'" />'
-                               .       '</form>'
-                               ;
-                       }
-                       array_push($data, $regradebutton);
-               }
-
-               $table->data[] = $data;
-       }
-
-       echo "<br />";
-
-       print_table($table);
-
-       // Finish the page
-       print_footer($course);
+    require_once("../../config.php");
+    require_once("../../course/lib.php");
+    require_once("lib.php");
+
+    $id = required_param("id");   // course
+
+    if (! $course = get_record("course", "id", $id)) {
+        error("Course ID is incorrect");
+    }
+
+    require_login($course->id);
+
+    add_to_log($course->id, "hotpot", "view all", "index.php?id=$course->id", "");
+
+    // Moodle 1.4+ requires sesskey to be passed in forms
+    if (isset($USER->sesskey)) {
+        $sesskey = '<input type="hidden" name="sesskey" value="'.$USER->sesskey.'" />';
+    } else {
+        $sesskey = '';
+    }
+
+    // get message strings for titles
+    $strmodulenameplural = get_string("modulenameplural", "hotpot");
+    $strmodulename  = get_string("modulename", "hotpot");
+
+    // string translation array for single and double quotes
+    $quotes = array("'"=>"\'", '"'=>'&quot;');
+
+    // Print the header
+
+    $title = "$course->shortname: $strmodulenameplural";
+    $heading = "$course->fullname";
+    $navigation = "$strmodulenameplural";
+    if ($course->category) {
+        $navigation = "<a href=\"../../course/view.php?id=$course->id\">$course->shortname</a> -> $navigation";
+    }
+    print_header($title, $heading, $navigation, "", "", true, "", navmenu($course));
+
+    $next_url = "$CFG->wwwroot/course/view.php?id=$course->id";
+
+    // get display section, if any
+    $section = optional_param('section', 0);
+    if ($section) {
+        $displaysection = course_set_display($course->id, $section);
+    } else {
+        if (isset($USER->display[$course->id])) {
+            $displaysection = $USER->display[$course->id];
+        } else {
+            $displaysection = 0;
+        }
+    }
+
+    // Get all instances of this module
+    if (!$hotpots = hotpot_get_all_instances_in_course("hotpot", $course)) {
+        $hotpots = array();
+    }
+
+    // if necessary, remove hotpots that are not in section0 or this $USER's display section
+    if ($displaysection) {
+        foreach ($hotpots as $coursemodule=>$hotpot) {
+            if ($hotpot->section!=0 && $hotpot->section!=$displaysection) {
+                unset($hotpots[$coursemodule]);
+            }
+        }
+    }
+
+    if (empty($hotpots)) {
+        notice("There are no $strmodulenameplural", $next_url);
+        exit;
+    }
+
+    // get list of hotpot ids
+    $hotpotids = array();
+    foreach ($hotpots as $cmid=>$hotpot) {
+        $hotpotids[] = $hotpot->id;
+    }
+    $hotpotids = implode(',', $hotpotids);
+
+    if (isadmin()) {
+
+        // get regrade settings, if any
+        $regrade = optional_param("regrade");
+        $confirm = optional_param("confirm");
+
+        // check regrade is valid
+        unset($regrade_cmid);
+        if (isset($regrade)) {
+            foreach ($hotpots as $cmid=>$hotpot) {
+                $found = false;
+                if ($hotpot->id==$regrade) {
+                    $regrade_cmid = $cmid;
+                }
+            }
+        }
+
+        // regrade, if necessary
+        if (isset($regrade_cmid)) {
+
+            if (empty($confirm)) {
+
+                $strregradecheck = get_string('regradecheck', 'hotpot', $hotpots[$regrade_cmid]->name);
+
+                print_simple_box_start("center", "60%", "#FFAAAA", 20, "noticebox");
+                print_heading($strregradecheck);
+                print ''
+                .   '<table border="0"><tr><td>'
+                .   '<form target="_parent" method="post" action="'.$ME.'">'
+                .   '<input type="hidden" name="id" value="'.$course->id.'">'
+                .   '<input type="hidden" name="regrade" value="'.$regrade.'" />'
+                .   '<input type="hidden" name="confirm" value="1" />'
+                .   $sesskey
+                .   '<input type="submit" value="'.get_string("yes").'" />'
+                .   '</form>'
+                .   '</td><td> &nbsp; </td><td>'
+                .   '<form target="_parent" method="post" action="'.$ME.'">'
+                .   '<input type="hidden" name="id" value="'.$course->id.'">'
+                .   $sesskey
+                .   '<input type="submit" value="'.get_string("no").'" />'
+                .   '</form>'
+                .   '</td></tr></table>'
+                ;
+            &