Moodle release 1.9.16
[moodle.git] / mod / quiz / view.php
blobefd44c0fee5ebf9d21451ccf299af9a7f539eeb8
1 <?php // $Id$
3 // This page prints a particular instance of quiz
5 require_once("../../config.php");
6 require_once($CFG->libdir.'/blocklib.php');
7 require_once($CFG->libdir.'/gradelib.php');
8 require_once($CFG->dirroot.'/mod/quiz/locallib.php');
9 require_once($CFG->dirroot.'/mod/quiz/pagelib.php');
11 $id = optional_param('id', 0, PARAM_INT); // Course Module ID, or
12 $q = optional_param('q', 0, PARAM_INT); // quiz ID
13 $edit = optional_param('edit', -1, PARAM_BOOL);
15 if ($id) {
16 if (! $cm = get_coursemodule_from_id('quiz', $id)) {
17 error("There is no coursemodule with id $id");
19 if (! $course = get_record("course", "id", $cm->course)) {
20 error("Course is misconfigured");
22 if (! $quiz = get_record("quiz", "id", $cm->instance)) {
23 error("The quiz with id $cm->instance corresponding to this coursemodule $id is missing");
25 } else {
26 if (! $quiz = get_record("quiz", "id", $q)) {
27 error("There is no quiz with id $q");
29 if (! $course = get_record("course", "id", $quiz->course)) {
30 error("The course with id $quiz->course that the quiz with id $q belongs to is missing");
32 if (! $cm = get_coursemodule_from_instance("quiz", $quiz->id, $course->id)) {
33 error("The course module for the quiz with id $q is missing");
37 // Check login and get context.
38 require_login($course->id, false, $cm);
39 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
41 // if no questions have been set up yet redirect to edit.php
42 if (!$quiz->questions and has_capability('mod/quiz:manage', $context)) {
43 redirect($CFG->wwwroot . '/mod/quiz/edit.php?cmid=' . $cm->id);
46 add_to_log($course->id, "quiz", "view", "view.php?id=$cm->id", $quiz->id, $cm->id);
48 // Initialize $PAGE, compute blocks
49 $PAGE = page_create_instance($quiz->id);
50 $pageblocks = blocks_setup($PAGE);
51 $blocks_preferred_width = bounded_number(180, blocks_preferred_width($pageblocks[BLOCK_POS_LEFT]), 210);
53 // Print the page header
54 if ($edit != -1 and $PAGE->user_allowed_editing()) {
55 $USER->editing = $edit;
58 //only check pop ups if the user is not a teacher, and popup is set
60 $bodytags = (has_capability('mod/quiz:attempt', $context) && $quiz->popup == 1)?'onload="popupchecker(\'' . get_string('popupblockerwarning', 'quiz') . '\');"':'';
61 $PAGE->print_header($course->shortname.': %fullname%','',$bodytags);
63 echo '<table id="layout-table"><tr>';
65 if(!empty($CFG->showblocksonmodpages) && (blocks_have_content($pageblocks, BLOCK_POS_LEFT) || $PAGE->user_is_editing())) {
66 echo '<td style="width: '.$blocks_preferred_width.'px;" id="left-column">';
67 print_container_start();
68 blocks_print_group($PAGE, $pageblocks, BLOCK_POS_LEFT);
69 print_container_end();
70 echo '</td>';
73 echo '<td id="middle-column">';
74 print_container_start();
76 // Print the main part of the page
78 // Print heading and tabs (if there is more than one).
79 $currenttab = 'info';
80 include('tabs.php');
82 // Print quiz name
84 print_heading(format_string($quiz->name));
86 if (has_capability('mod/quiz:view', $context)) {
88 // Print quiz description
89 if (trim(strip_tags($quiz->intro))) {
90 $formatoptions->noclean = true;
91 $formatoptions->para = false;
92 print_box(format_text($quiz->intro, FORMAT_MOODLE, $formatoptions), 'generalbox', 'intro');
95 echo '<div class="quizinfo">';
97 // Print information about number of attempts and grading method.
98 if ($quiz->attempts > 1) {
99 echo "<p>".get_string("attemptsallowed", "quiz").": $quiz->attempts</p>";
101 if ($quiz->attempts != 1) {
102 echo "<p>".get_string("grademethod", "quiz").": ".quiz_get_grading_option_name($quiz->grademethod)."</p>";
105 // Print information about timings.
106 $timenow = time();
107 $available = $quiz->timeopen < $timenow && ($timenow < $quiz->timeclose || !$quiz->timeclose);
108 if ($available) {
109 if ($quiz->timelimit) {
110 echo "<p>".get_string("quiztimelimit","quiz", format_time($quiz->timelimit * 60))."</p>";
112 if ($quiz->timeopen) {
113 echo '<p>', get_string('quizopens', 'quiz'), ': ', userdate($quiz->timeopen), '</p>';
115 if ($quiz->timeclose) {
116 echo '<p>', get_string('quizcloses', 'quiz'), ': ', userdate($quiz->timeclose), '</p>';
118 } else if ($timenow < $quiz->timeopen) {
119 echo "<p>".get_string("quiznotavailable", "quiz", userdate($quiz->timeopen))."</p>";
120 } else {
121 echo "<p>".get_string("quizclosed", "quiz", userdate($quiz->timeclose))."</p>";
123 echo '</div>';
124 $available = $available && has_any_capability(array('mod/quiz:attempt', 'mod/quiz:preview'), $context);
125 } else {
126 $available = false;
129 // Show number of attempts summary to those who can view reports.
130 if (has_capability('mod/quiz:viewreports', $context)) {
131 if ($strattemptnum = quiz_num_attempt_summary($quiz, $cm)) {
132 echo '<div class="quizattemptcounts"><a href="report.php?mode=overview&amp;id=' .
133 $cm->id . '">' . $strattemptnum . '</a></div>';
137 // Guests can't do a quiz, so offer them a choice of logging in or going back.
138 if (isguestuser()) {
139 $loginurl = $CFG->wwwroot.'/login/index.php';
140 if (!empty($CFG->loginhttps)) {
141 $loginurl = str_replace('http:','https:', $loginurl);
144 notice_yesno('<p>' . get_string('guestsno', 'quiz') . "</p>\n\n</p>" .
145 get_string('liketologin') . '</p>', $loginurl, get_referer(false));
146 finish_page($course);
149 if (!has_any_capability(array('mod/quiz:reviewmyattempts', 'mod/quiz:attempt', 'mod/quiz:preview'), $context)) {
150 print_box('<p>' . get_string('youneedtoenrol', 'quiz') . '</p><p>' .
151 print_continue($CFG->wwwroot . '/course/view.php?id=' . $course->id, true) .
152 '</p>', 'generalbox', 'notice');
153 finish_page($course);
156 // Get this user's attempts.
157 $attempts = quiz_get_user_attempts($quiz->id, $USER->id);
158 $unfinished = false;
159 if ($unfinishedattempt = quiz_get_user_attempt_unfinished($quiz->id, $USER->id)) {
160 $attempts[] = $unfinishedattempt;
161 $unfinished = true;
163 $numattempts = count($attempts);
165 // Work out the final grade, checking whether it was overridden in the gradebook.
166 $mygrade = quiz_get_best_grade($quiz, $USER->id);
167 $mygradeoverridden = false;
168 $gradebookfeedback = '';
170 $grading_info = grade_get_grades($course->id, 'mod', 'quiz', $quiz->id, $USER->id);
171 if (!empty($grading_info->items)) {
172 $item = $grading_info->items[0];
173 if (isset($item->grades[$USER->id])) {
174 $grade = $item->grades[$USER->id];
176 if ($grade->overridden) {
177 $mygrade = $grade->grade + 0; // Convert to number.
178 $mygradeoverridden = true;
180 if (!empty($grade->str_feedback)) {
181 $gradebookfeedback = $grade->str_feedback;
186 // Print table with existing attempts
187 if ($attempts) {
189 print_heading(get_string('summaryofattempts', 'quiz'));
191 // Work out which columns we need, taking account what data is available in each attempt.
192 list($someoptions, $alloptions) = quiz_get_combined_reviewoptions($quiz, $attempts, $context);
194 $gradecolumn = $someoptions->scores && $quiz->grade && $quiz->sumgrades;
195 $markcolumn = $gradecolumn && ($quiz->grade != $quiz->sumgrades);
196 $overallstats = $alloptions->scores;
198 $feedbackcolumn = quiz_has_feedback($quiz->id);
199 $overallfeedback = $feedbackcolumn && $alloptions->overallfeedback;
201 // Prepare table header
202 $table->class = 'generaltable quizattemptsummary';
203 $table->head = array(get_string('attempt', 'quiz'), get_string('timecompleted', 'quiz'));
204 $table->align = array('center', 'left');
205 $table->size = array('', '');
206 if ($markcolumn) {
207 $table->head[] = get_string('marks', 'quiz') . " / $quiz->sumgrades";
208 $table->align[] = 'center';
209 $table->size[] = '';
211 if ($gradecolumn) {
212 $table->head[] = get_string('grade') . " / $quiz->grade";
213 $table->align[] = 'center';
214 $table->size[] = '';
216 if ($feedbackcolumn) {
217 $table->head[] = get_string('feedback', 'quiz');
218 $table->align[] = 'left';
219 $table->size[] = '';
221 if (isset($quiz->showtimetaken)) {
222 $table->head[] = get_string('timetaken', 'quiz');
223 $table->align[] = 'left';
224 $table->size[] = '';
227 // One row for each attempt
228 foreach ($attempts as $attempt) {
229 $attemptoptions = quiz_get_reviewoptions($quiz, $attempt, $context);
230 $row = array();
232 // Add the attempt number, making it a link, if appropriate.
233 if ($attempt->preview) {
234 $row[] = make_review_link(get_string('preview', 'quiz'), $quiz, $attempt, $context);
235 } else {
236 $row[] = make_review_link($attempt->attempt, $quiz, $attempt, $context);
239 // prepare strings for time taken and date completed
240 $timetaken = '';
241 $datecompleted = '';
242 if ($attempt->timefinish > 0) {
243 // attempt has finished
244 $timetaken = format_time($attempt->timefinish - $attempt->timestart);
245 $datecompleted = userdate($attempt->timefinish);
246 } else if ($available) {
247 // The attempt is still in progress.
248 $timetaken = format_time(time() - $attempt->timestart);
249 $datecompleted = '';
250 } else if ($quiz->timeclose) {
251 // The attempt was not completed but is also not available any more becuase the quiz is closed.
252 $timetaken = format_time($quiz->timeclose - $attempt->timestart);
253 $datecompleted = userdate($quiz->timeclose);
254 } else {
255 // Something weird happened.
256 $timetaken = '';
257 $datecompleted = '';
259 $row[] = $datecompleted;
261 if ($markcolumn && $attempt->timefinish > 0) {
262 if ($attemptoptions->scores) {
263 $row[] = make_review_link(round($attempt->sumgrades, $quiz->decimalpoints), $quiz, $attempt, $context);
264 } else {
265 $row[] = '';
269 // Ouside the if because we may be showing feedback but not grades.
270 $attemptgrade = quiz_rescale_grade($attempt->sumgrades, $quiz, false);
272 if ($gradecolumn) {
273 if ($attemptoptions->scores && $attempt->timefinish > 0) {
274 $formattedgrade = round($attemptgrade, $quiz->decimalpoints);
275 // highlight the highest grade if appropriate
276 if ($overallstats && $numattempts > 1 && !is_null($mygrade) && $attemptgrade == $mygrade && $quiz->grademethod == QUIZ_GRADEHIGHEST) {
277 $table->rowclass[$attempt->attempt] = 'bestrow';
280 $row[] = make_review_link($formattedgrade, $quiz, $attempt, $context);
281 } else {
282 $row[] = '';
286 if ($feedbackcolumn && $attempt->timefinish > 0) {
287 if ($attemptoptions->overallfeedback) {
288 $row[] = quiz_feedback_for_grade($attemptgrade, $quiz->id);
289 } else {
290 $row[] = '';
294 if (isset($quiz->showtimetaken)) {
295 $row[] = $timetaken;
298 $table->data[$attempt->attempt] = $row;
299 } // End of loop over attempts.
300 print_table($table);
303 // Print information about the student's best score for this quiz if possible.
304 $moreattempts = $unfinished || $numattempts < $quiz->attempts || $quiz->attempts == 0;
305 if (!$moreattempts) {
306 print_heading(get_string("nomoreattempts", "quiz"));
309 if ($numattempts && $quiz->sumgrades && !is_null($mygrade)) {
310 $resultinfo = '';
312 if ($overallstats) {
313 if ($available && $moreattempts) {
314 $a = new stdClass;
315 $a->method = quiz_get_grading_option_name($quiz->grademethod);
316 $a->mygrade = round($mygrade, $quiz->decimalpoints);
317 $a->quizgrade = $quiz->grade;
318 $resultinfo .= print_heading(get_string('gradesofar', 'quiz', $a), '', 2, 'main', true);
319 } else {
320 $resultinfo .= print_heading(get_string('yourfinalgradeis', 'quiz', "$mygrade / $quiz->grade"), '', 2, 'main', true);
324 if ($mygradeoverridden) {
325 $resultinfo .= '<p class="overriddennotice">'.get_string('overriddennotice', 'grades').'</p>';
327 if ($gradebookfeedback) {
328 $resultinfo .= print_heading(get_string('comment', 'quiz'), '', 3, 'main', true);
329 $resultinfo .= '<p class="quizteacherfeedback">'.$gradebookfeedback.'</p>';
331 if ($overallfeedback) {
332 $resultinfo .= print_heading(get_string('overallfeedback', 'quiz'), '', 3, 'main', true);
333 $resultinfo .= '<p class="quizgradefeedback">'.quiz_feedback_for_grade($mygrade, $quiz->id).'</p>';
336 if ($resultinfo) {
337 print_box($resultinfo, 'generalbox', 'feedback');
341 // Print a button to start/continue an attempt, if appropriate.
342 if (!$quiz->questions) {
343 print_heading(get_string("noquestions", "quiz"));
345 } else if ($available && $moreattempts) {
346 echo "<br />";
347 echo "<div class=\"quizattempt\">";
349 if ($unfinished) {
350 if (has_capability('mod/quiz:preview', $context)) {
351 $buttontext = get_string('continuepreview', 'quiz');
352 } else {
353 $buttontext = get_string('continueattemptquiz', 'quiz');
355 } else {
357 // Work out the appropriate button caption.
358 if (has_capability('mod/quiz:preview', $context)) {
359 $buttontext = get_string('previewquiznow', 'quiz');
360 } else if ($numattempts == 0) {
361 $buttontext = get_string('attemptquiznow', 'quiz');
362 } else {
363 $buttontext = get_string('reattemptquiz', 'quiz');
366 // Work out if the quiz is temporarily unavailable because of the delay option.
367 if (!empty($attempts)) {
368 $tempunavailable = '';
369 $lastattempt = end($attempts);
370 $lastattempttime = $lastattempt->timefinish;
371 if ($quiz->timelimit > 0) {
372 $lastattempttime = min($lastattempttime, $lastattempt->timestart + $quiz->timelimit*60);
374 if ($numattempts == 1 && $quiz->delay1 && $timenow <= $lastattempttime + $quiz->delay1) {
375 $tempunavailable = get_string('temporaryblocked', 'quiz') .
376 ' <strong>'. userdate($lastattempttime + $quiz->delay1). '</strong>';
377 } else if ($numattempts > 1 && $quiz->delay2 && $timenow <= $lastattempttime + $quiz->delay2) {
378 $tempunavailable = get_string('temporaryblocked', 'quiz') .
379 ' <strong>'. userdate($lastattempttime + $quiz->delay2). '</strong>';
382 // If so, display a message and prevent the start button from appearing.
383 if ($tempunavailable) {
384 print_simple_box($tempunavailable, "center");
385 print_continue($CFG->wwwroot . '/course/view.php?id=' . $course->id);
386 $buttontext = '';
391 // Actually print the start button.
392 if ($buttontext) {
393 $buttontext = htmlspecialchars($buttontext, ENT_QUOTES);
395 // Do we need a confirm javascript alert?
396 if ($unfinished) {
397 $strconfirmstartattempt = '';
398 } else if ($quiz->timelimit && $quiz->attempts) {
399 $strconfirmstartattempt = get_string('confirmstartattempttimelimit','quiz', $quiz->attempts);
400 } else if ($quiz->timelimit) {
401 $strconfirmstartattempt = get_string('confirmstarttimelimit','quiz');
402 } else if ($quiz->attempts) {
403 $strconfirmstartattempt = get_string('confirmstartattemptlimit','quiz', $quiz->attempts);
404 } else {
405 $strconfirmstartattempt = '';
407 // Determine the URL to use.
408 $attempturl = "attempt.php?id=$cm->id";
410 // Prepare options depending on whether the quiz should be a popup.
411 if ($quiz->popup == 1) {
412 $window = 'quizpopup';
413 $windowoptions = "left=0, top=0, height='+window.screen.height+', " .
414 "width='+window.screen.width+', channelmode=yes, fullscreen=yes, " .
415 "scrollbars=yes, resizeable=no, directories=no, toolbar=no, " .
416 "titlebar=no, location=no, status=no, menubar=no";
417 if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()])) {
418 $attempturl = sid_process_url($attempturl);
421 echo '<input type="button" value="'.$buttontext.'" onclick="javascript:';
422 if ($strconfirmstartattempt) {
423 $strconfirmstartattempt = addslashes($strconfirmstartattempt);
424 echo "if (confirm('".addslashes_js($strconfirmstartattempt)."')) ";
426 echo "window.open('$attempturl','$window','$windowoptions');", '" />';
427 } else if ($quiz->popup == 2 && !quiz_check_safe_browser()) {
428 notify(get_string('safebrowsererror', 'quiz'));
429 }else {
430 print_single_button("attempt.php", array('id'=>$cm->id), $buttontext, 'get', '', false, '', false, $strconfirmstartattempt);
435 <noscript>
436 <div>
437 <?php print_heading(get_string('noscript', 'quiz')); ?>
438 </div>
439 </noscript>
440 <?php
443 echo "</div>\n";
444 } else {
445 print_continue($CFG->wwwroot . '/course/view.php?id=' . $course->id);
448 // Should we not be seeing if we need to print right-hand-side blocks?
450 finish_page($course);
452 // Utility functions =================================================================
454 function finish_page($course) {
455 global $THEME;
456 print_container_end();
457 echo '</td></tr></table>';
458 print_footer($course);
459 exit;
462 /** Make some text into a link to review the quiz, if that is appropriate. */
463 function make_review_link($linktext, $quiz, $attempt, $context) {
464 static $canreview = null;
465 if (is_null($canreview)) {
466 $canreview = has_capability('mod/quiz:reviewmyattempts', $context);
468 // If not even responses are to be shown in review then we don't allow any review, or does not have review capability.
469 if (!$canreview || !($quiz->review & QUIZ_REVIEW_RESPONSES)) {
470 return $linktext;
473 // If the quiz is still open, are reviews allowed?
474 if ((!$quiz->timeclose or time() < $quiz->timeclose) and !($quiz->review & QUIZ_REVIEW_OPEN & QUIZ_REVIEW_RESPONSES)) {
475 // If not, don't link.
476 return $linktext;
479 // If the quiz is closed, are reviews allowed?
480 if (($quiz->timeclose and time() > $quiz->timeclose) and !($quiz->review & QUIZ_REVIEW_CLOSED & QUIZ_REVIEW_RESPONSES)) {
481 // If not, don't link.
482 return $linktext;
485 // If the attempt is still open, don't link.
486 if (!$attempt->timefinish) {
487 return $linktext;
490 $url = "review.php?q=$quiz->id&amp;attempt=$attempt->id";
491 if ($quiz->popup == 1) {
492 $windowoptions = "left=0, top=0, channelmode=yes, fullscreen=yes, scrollbars=yes, resizeable=no, directories=no, toolbar=no, titlebar=no, location=no, status=no, menubar=no";
493 return link_to_popup_window('/mod/quiz/' . $url, 'quizpopup', $linktext, '+window.screen.height+', '+window.screen.width+', '', $windowoptions, true);
494 } else {
495 return "<a href='$url'>$linktext</a>";