made a copy
[atutor.git] / tools / take_test_q.php
1 <?php
2 /****************************************************************/
3 /* ATutor                                                                                                               */
4 /****************************************************************/
5 /* Copyright (c) 2002-2008 by Greg Gay & Joel Kronenberg        */
6 /* Adaptive Technology Resource Centre / University of Toronto  */
7 /* http://atutor.ca                                                                                             */
8 /*                                                              */
9 /* This program is free software. You can redistribute it and/or*/
10 /* modify it under the terms of the GNU General Public License  */
11 /* as published by the Free Software Foundation.                                */
12 /****************************************************************/
13 // $Id$
14 define('AT_INCLUDE_PATH', '../include/');
15 require(AT_INCLUDE_PATH.'vitals.inc.php');
16 require(AT_INCLUDE_PATH.'lib/test_result_functions.inc.php');
17 require(AT_INCLUDE_PATH.'classes/testQuestions.class.php');
18
19 $tid = intval($_REQUEST['tid']);
20
21 if (isset($_REQUEST['gid']))
22         $mid = $addslashes($_REQUEST['gid']);
23 else
24         $mid = $_SESSION['member_id'];
25
26 //make sure max attempts not reached, and still on going
27 $sql            = "SELECT *, UNIX_TIMESTAMP(start_date) AS start_date, UNIX_TIMESTAMP(end_date) AS end_date FROM ".TABLE_PREFIX."tests WHERE test_id=".$tid." AND course_id=".$_SESSION['course_id'];
28 $result= mysql_query($sql, $db);
29 $test_row = mysql_fetch_assoc($result);
30 /* check to make sure we can access this test: */
31 if (!$test_row['guests'] && ($_SESSION['enroll'] == AT_ENROLL_NO || $_SESSION['enroll'] == AT_ENROLL_ALUMNUS)) {
32         require(AT_INCLUDE_PATH.'header.inc.php');
33         $msg->printInfos('NOT_ENROLLED');
34
35         require(AT_INCLUDE_PATH.'footer.inc.php');
36         exit;
37 }
38
39 if (!$test_row['guests'] && !authenticate_test($tid)) {
40         header('Location: '.url_rewrite('tools/my_tests.php', AT_PRETTY_URL_IS_HEADER));
41         exit;
42 }
43
44 // checks one/all questions per page, and forward user to the correct one
45 if (!$test_row['display']) {
46         header('Location: '.url_rewrite('tools/take_test.php?tid='.$tid, AT_PRETTY_URL_IS_HEADER));
47 }
48
49 $out_of = $test_row['out_of'];
50
51 $sql    = "SELECT COUNT(*) AS num_questions FROM ".TABLE_PREFIX."tests_questions_assoc WHERE test_id=$tid";
52 $result = mysql_query($sql, $db);
53 $row = mysql_fetch_assoc($result);
54 if (!$test_row['random'] || $test_row['num_questions'] > $row['num_questions']) {
55         $test_row['num_questions'] = $row['num_questions'];
56 }
57
58 $sql            = "SELECT COUNT(*) AS cnt FROM ".TABLE_PREFIX."tests_results WHERE status=1 AND test_id=".$tid." AND member_id='".$mid."'";
59 $takes_result= mysql_query($sql, $db) or die(mysql_error());
60 $takes = mysql_fetch_assoc($takes_result);      
61
62 if ( (($test_row['start_date'] > time()) || ($test_row['end_date'] < time())) || 
63    ( ($test_row['num_takes'] != AT_TESTS_TAKE_UNLIMITED) && ($takes['cnt'] >= $test_row['num_takes']) )  ) {
64         require(AT_INCLUDE_PATH.'header.inc.php');
65         $msg->printErrors('MAX_ATTEMPTS');
66         require(AT_INCLUDE_PATH.'footer.inc.php');
67         exit;
68 }
69
70 if (!isset($_GET['pos'])) {
71         $pos = 0; // first question
72 } else {
73         $pos = abs($_GET['pos']);
74 }
75
76 $max_pos = 0;
77
78 // get and check for a valid result_id. if there is none then get all the questions and insert them as in progress.
79 // note: for guests without guest information, the result_id is stored in session, but no need to really know that here;
80 //       for guests with guest information, always start a new test.
81 if (isset($_REQUEST['gid']))
82         $result_id = 0;
83 else
84         $result_id = get_test_result_id($tid, $max_pos);
85         
86 // set position to allow users to return to a test they have partially completed, and continue from where they left of.
87 if (!isset($_GET['pos']) && $result_id > 0)
88 {
89         $sql = "SELECT COUNT(*) total_questions FROM ".TABLE_PREFIX."tests_answers WHERE result_id = ". $result_id;
90         $total_result = mysql_query($sql, $db) or die(mysql_error());
91         $total = mysql_fetch_assoc($total_result);
92         
93         $sql = "SELECT COUNT(*) pos FROM ".TABLE_PREFIX."tests_answers WHERE result_id = ". $result_id ." AND answer <> ''";
94         $answer_result = mysql_query($sql, $db) or die(mysql_error());
95         $answer = mysql_fetch_assoc($answer_result);
96
97         // if user answered all the questions without cliking last "next" button, resume test at the last question
98         $pos = ($total['total_questions'] == $answer['pos']) ? (--$answer['pos']) : $answer['pos'];
99 }
100
101 if ($result_id == 0) {
102         // there is no test in progress, yet.
103         // init this test.
104
105         // simple safety op to make sure nothing is being posted (as it shouldn't!)
106         // $_POST = array(); // don't need this because of the else-if
107         // basically, shouldn't be able to post to this page if there isn't a valid result_id first (how can someone post an answer
108         // to a question they haven't viewed? [unless they're trying to 'hack' something])
109
110         $result_id = init_test_result_questions($tid, (bool) $test_row['random'], $test_row['num_questions'], $mid);
111
112         if (!$_SESSION['member_id']) {
113                 // this is a guest, so we store the result_id in SESSION
114                 $_SESSION['test_result_id'] = $result_id;
115         }
116
117         $pos = 0; // force to always start at the first question
118                 
119 } else if (isset($_POST['next']) || isset($_POST['previous'])) {
120         // if the test isn't time limited, then what happens when only a few questions are answered? the test result
121         // will be inconsistant.
122         // need to keep track of the max(pos) answered, so that we know if a question is being re-answered.
123         // store 'max_pos' in session or db or form?
124
125         // assuming only one question is displayed      
126         $question_id = intval(key($_POST['answers']));
127
128         // get the old score (incase this question is being re-answered)
129         $sql = "SELECT score FROM ".TABLE_PREFIX."tests_answers WHERE result_id=$result_id AND question_id=$question_id";
130         $result = mysql_query($sql, $db);
131         $row = mysql_fetch_assoc($result);
132         $old_score = $row['score'];
133
134         $score = 0;
135
136         $sql = "SELECT TQA.weight, TQA.question_id, TQ.type, TQ.answer_0, TQ.answer_1, TQ.answer_2, TQ.answer_3, TQ.answer_4, TQ.answer_5, TQ.answer_6, TQ.answer_7, TQ.answer_8, TQ.answer_9 FROM ".TABLE_PREFIX."tests_questions_assoc TQA INNER JOIN ".TABLE_PREFIX."tests_questions TQ USING (question_id) WHERE TQA.test_id=$tid AND TQA.question_id=$question_id";
137         $result = mysql_query($sql, $db);
138
139         if ($row = mysql_fetch_assoc($result)) {
140                 if (isset($_POST['answers'][$row['question_id']])) {
141                         $obj = TestQuestions::getQuestion($row['type']);
142                         $score = $obj->mark($row);
143
144                         $sql    = "UPDATE ".TABLE_PREFIX."tests_answers SET answer='{$_POST[answers][$row[question_id]]}', score='$score' WHERE result_id=$result_id AND question_id=$row[question_id]";
145                         mysql_query($sql, $db);
146                         
147                         if (is_null($score) && $test_row['result_release']==AT_RELEASE_MARKED)
148                                 $_REQUEST['efs'] = 1; // set final score to empty if there's any unmarked question and release option is "once quiz submitted and all questions are marked"
149                 }
150         }
151
152         $pos++;
153
154         if ($_REQUEST['efs']) // set final score to empty if there's any unmarked question and release option is "once quiz submitted and all questions are marked"
155         {
156                 $sql    = "UPDATE ".TABLE_PREFIX."tests_results SET final_score=null, date_taken=date_taken, end_time=NOW(), max_pos=$pos WHERE result_id=$result_id";
157                 $result = mysql_query($sql, $db);
158         }
159         // update the final score
160         // update status to complate to fix refresh test issue.
161         else if ($pos > $max_pos) {
162                 $sql    = "UPDATE ".TABLE_PREFIX."tests_results SET final_score=final_score + $score, date_taken=date_taken, end_time=NOW(), max_pos=$pos WHERE result_id=$result_id";
163                 $result = mysql_query($sql, $db);
164         } else {
165                 // this question has already been answered, so we have to re-mark it, which means finding the OLD score for this question and adjusting
166                 // $score with the positive or negative difference.
167                 // no need to update max_pos b/c we're only updating a previously answered question.
168
169                 $score = $old_score - $score;
170
171                 $sql    = "UPDATE ".TABLE_PREFIX."tests_results SET final_score=final_score - $score, date_taken=date_taken, end_time=NOW() WHERE result_id=$result_id";
172                 $result = mysql_query($sql, $db);
173         }
174
175         if (isset($_POST['previous'])) {
176                 $pos-=2;
177                 if ($pos < 0) {
178                         $pos = 0;
179                 }
180         }
181
182         if ($pos >= $test_row['num_questions']) {
183                 // end of the test.
184                 $sql    = "UPDATE ".TABLE_PREFIX."tests_results SET status=1, date_taken=date_taken, end_time=NOW() WHERE result_id=$result_id";
185                 $result = mysql_query($sql, $db);
186
187                 $msg->addFeedback('ACTION_COMPLETED_SUCCESSFULLY');
188                 if (!$_SESSION['enroll'] || $test_row['result_release']==AT_RELEASE_IMMEDIATE) {
189                         header('Location: '.url_rewrite('tools/view_results.php?tid='.$tid.SEP.'rid='.$result_id, AT_PRETTY_URL_IS_HEADER));
190                         exit;
191                 }
192                 header('Location: '.url_rewrite('tools/my_tests.php', AT_PRETTY_URL_IS_HEADER));
193                 exit;
194         } // else:
195         
196         header('Location: '.url_rewrite('tools/take_test_q.php?tid='.$tid.SEP.'pos='.$pos.SEP.'efs='.$_REQUEST['efs'], AT_PRETTY_URL_IS_HEADER));
197         exit;
198 }
199
200 if (defined('AT_FORCE_GET_FILE') && AT_FORCE_GET_FILE) {
201         $content_base_href = 'get.php/';
202 } else {
203         $course_base_href = 'content/' . $_SESSION['course_id'] . '/';
204 }
205
206 require(AT_INCLUDE_PATH.'header.inc.php');
207
208 /* Retrieve the content_id of this test */
209 $num_questions = $test_row['num_questions'];
210 $content_id = $test_row['content_id'];
211 $anonymous = $test_row['anonymous'];
212 $instructions = $test_row['instructions'];
213 $title = $test_row['title'];
214
215 $_letters = array(_AT('A'), _AT('B'), _AT('C'), _AT('D'), _AT('E'), _AT('F'), _AT('G'), _AT('H'), _AT('I'), _AT('J'));
216
217 // this is a kludge to get the question number incremented.
218 // a diff approach could be to pass the position to the display() method.
219 for ($i = 0; $i < $pos; $i++) {
220         TestQuestionCounter(true);
221 }
222
223 // retrieve the test questions that were saved to `tests_answers`
224 if ($test_row['random']) {
225         $sql    = "SELECT R.*, A.*, Q.* FROM ".TABLE_PREFIX."tests_answers R INNER JOIN ".TABLE_PREFIX."tests_questions_assoc A USING (question_id) INNER JOIN ".TABLE_PREFIX."tests_questions Q USING (question_id) WHERE R.result_id=$result_id AND A.test_id=$tid ORDER BY Q.question_id LIMIT $pos, 1";
226 } else {
227         $sql    = "SELECT R.*, A.*, Q.* FROM ".TABLE_PREFIX."tests_answers R INNER JOIN ".TABLE_PREFIX."tests_questions_assoc A USING (question_id) INNER JOIN ".TABLE_PREFIX."tests_questions Q USING (question_id) WHERE R.result_id=$result_id AND A.test_id=$tid ORDER BY A.ordering, Q.question_id LIMIT $pos, 1";
228 }
229 $result = mysql_query($sql, $db);
230 $question_row = mysql_fetch_assoc($result);
231
232 if (!$result || !$question_row) {
233         echo '<p>'._AT('no_questions').'</p>';
234         require(AT_INCLUDE_PATH.'footer.inc.php');
235         exit;
236 }
237
238 ?>
239 <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>?pos=<?php echo $pos; ?>">
240 <input type="hidden" name="tid" value="<?php echo $tid; ?>" />
241 <div class="input-form" style="width:80%">
242
243         <fieldset class="group_form"><legend class="group_form"><?php echo $title ?> (<?php echo _AT('question').' '. ($pos+1).'/'.$test_row['num_questions']; ?>)</legend>
244         <?php if ($_REQUEST['efs']){?>
245         <input type="hidden" name="efs" value=<?php echo $_REQUEST['efs']; ?> />
246         <?php }?>
247         
248         <?php
249         // retrieve the answer to re-populate the form (so we can edit our answer)
250         $sql = "SELECT answer FROM ".TABLE_PREFIX."tests_answers WHERE result_id=$result_id AND question_id=$question_row[question_id]";
251         $result = mysql_query($sql, $db);
252         $row = mysql_fetch_assoc($result);
253         
254         $obj = TestQuestions::getQuestion($question_row['type']);
255         $obj->display($question_row, $row['answer']);
256
257         ?>
258         <div class="row buttons">
259                  <div style="display:none"><input type="submit" value="<?php echo _AT('next'); ?>" name="next"/></div>
260                 <?php if ($pos > 0): ?>
261                         <input type="submit" name="previous" value="<?php echo _AT('previous'); ?>" />
262                 <?php endif; ?>
263                 <input type="submit" name="next" value="<?php echo _AT('next'); ?>" accesskey="s" />
264         </div>
265 </div>
266 </form>
267 <script type="text/javascript">
268 //<!--
269 function iframeSetHeight(id, height) {
270         document.getElementById("qframe" + id).style.height = (height + 20) + "px";
271 }
272 //-->
273 </script>
274 <?php require(AT_INCLUDE_PATH.'footer.inc.php'); ?>