Merge branch 'MDL-65026-37' of git://github.com/jleyva/moodle into MOODLE_37_STABLE
[moodle.git] / mod / quiz / renderer.php
blobe9fc84c6f1dde2a616d4033b08f6237b5c0cb95a
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Defines the renderer for the quiz module.
20 * @package mod_quiz
21 * @copyright 2011 The Open University
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
29 /**
30 * The renderer for the quiz module.
32 * @copyright 2011 The Open University
33 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35 class mod_quiz_renderer extends plugin_renderer_base {
36 /**
37 * Builds the review page
39 * @param quiz_attempt $attemptobj an instance of quiz_attempt.
40 * @param array $slots an array of intgers relating to questions.
41 * @param int $page the current page number
42 * @param bool $showall whether to show entire attempt on one page.
43 * @param bool $lastpage if true the current page is the last page.
44 * @param mod_quiz_display_options $displayoptions instance of mod_quiz_display_options.
45 * @param array $summarydata contains all table data
46 * @return $output containing html data.
48 public function review_page(quiz_attempt $attemptobj, $slots, $page, $showall,
49 $lastpage, mod_quiz_display_options $displayoptions,
50 $summarydata) {
52 $output = '';
53 $output .= $this->header();
54 $output .= $this->review_summary_table($summarydata, $page);
55 $output .= $this->review_form($page, $showall, $displayoptions,
56 $this->questions($attemptobj, true, $slots, $page, $showall, $displayoptions),
57 $attemptobj);
59 $output .= $this->review_next_navigation($attemptobj, $page, $lastpage, $showall);
60 $output .= $this->footer();
61 return $output;
64 /**
65 * Renders the review question pop-up.
67 * @param quiz_attempt $attemptobj an instance of quiz_attempt.
68 * @param int $slot which question to display.
69 * @param int $seq which step of the question attempt to show. null = latest.
70 * @param mod_quiz_display_options $displayoptions instance of mod_quiz_display_options.
71 * @param array $summarydata contains all table data
72 * @return $output containing html data.
74 public function review_question_page(quiz_attempt $attemptobj, $slot, $seq,
75 mod_quiz_display_options $displayoptions, $summarydata) {
77 $output = '';
78 $output .= $this->header();
79 $output .= $this->review_summary_table($summarydata, 0);
81 if (!is_null($seq)) {
82 $output .= $attemptobj->render_question_at_step($slot, $seq, true, $this);
83 } else {
84 $output .= $attemptobj->render_question($slot, true, $this);
87 $output .= $this->close_window_button();
88 $output .= $this->footer();
89 return $output;
92 /**
93 * Renders the review question pop-up.
95 * @param quiz_attempt $attemptobj an instance of quiz_attempt.
96 * @param string $message Why the review is not allowed.
97 * @return string html to output.
99 public function review_question_not_allowed(quiz_attempt $attemptobj, $message) {
100 $output = '';
101 $output .= $this->header();
102 $output .= $this->heading(format_string($attemptobj->get_quiz_name(), true,
103 array("context" => $attemptobj->get_quizobj()->get_context())));
104 $output .= $this->notification($message);
105 $output .= $this->close_window_button();
106 $output .= $this->footer();
107 return $output;
111 * Filters the summarydata array.
113 * @param array $summarydata contains row data for table
114 * @param int $page the current page number
115 * @return $summarydata containing filtered row data
117 protected function filter_review_summary_table($summarydata, $page) {
118 if ($page == 0) {
119 return $summarydata;
122 // Only show some of summary table on subsequent pages.
123 foreach ($summarydata as $key => $rowdata) {
124 if (!in_array($key, array('user', 'attemptlist'))) {
125 unset($summarydata[$key]);
129 return $summarydata;
133 * Outputs the table containing data from summary data array
135 * @param array $summarydata contains row data for table
136 * @param int $page contains the current page number
138 public function review_summary_table($summarydata, $page) {
139 $summarydata = $this->filter_review_summary_table($summarydata, $page);
140 if (empty($summarydata)) {
141 return '';
144 $output = '';
145 $output .= html_writer::start_tag('table', array(
146 'class' => 'generaltable generalbox quizreviewsummary'));
147 $output .= html_writer::start_tag('tbody');
148 foreach ($summarydata as $rowdata) {
149 if ($rowdata['title'] instanceof renderable) {
150 $title = $this->render($rowdata['title']);
151 } else {
152 $title = $rowdata['title'];
155 if ($rowdata['content'] instanceof renderable) {
156 $content = $this->render($rowdata['content']);
157 } else {
158 $content = $rowdata['content'];
161 $output .= html_writer::tag('tr',
162 html_writer::tag('th', $title, array('class' => 'cell', 'scope' => 'row')) .
163 html_writer::tag('td', $content, array('class' => 'cell'))
167 $output .= html_writer::end_tag('tbody');
168 $output .= html_writer::end_tag('table');
169 return $output;
173 * Renders each question
175 * @param quiz_attempt $attemptobj instance of quiz_attempt
176 * @param bool $reviewing
177 * @param array $slots array of intgers relating to questions
178 * @param int $page current page number
179 * @param bool $showall if true shows attempt on single page
180 * @param mod_quiz_display_options $displayoptions instance of mod_quiz_display_options
182 public function questions(quiz_attempt $attemptobj, $reviewing, $slots, $page, $showall,
183 mod_quiz_display_options $displayoptions) {
184 $output = '';
185 foreach ($slots as $slot) {
186 $output .= $attemptobj->render_question($slot, $reviewing, $this,
187 $attemptobj->review_url($slot, $page, $showall));
189 return $output;
193 * Renders the main bit of the review page.
195 * @param array $summarydata contain row data for table
196 * @param int $page current page number
197 * @param mod_quiz_display_options $displayoptions instance of mod_quiz_display_options
198 * @param $content contains each question
199 * @param quiz_attempt $attemptobj instance of quiz_attempt
200 * @param bool $showall if true display attempt on one page
202 public function review_form($page, $showall, $displayoptions, $content, $attemptobj) {
203 if ($displayoptions->flags != question_display_options::EDITABLE) {
204 return $content;
207 $this->page->requires->js_init_call('M.mod_quiz.init_review_form', null, false,
208 quiz_get_js_module());
210 $output = '';
211 $output .= html_writer::start_tag('form', array('action' => $attemptobj->review_url(null,
212 $page, $showall), 'method' => 'post', 'class' => 'questionflagsaveform'));
213 $output .= html_writer::start_tag('div');
214 $output .= $content;
215 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'sesskey',
216 'value' => sesskey()));
217 $output .= html_writer::start_tag('div', array('class' => 'submitbtns'));
218 $output .= html_writer::empty_tag('input', array('type' => 'submit',
219 'class' => 'questionflagsavebutton btn btn-secondary', 'name' => 'savingflags',
220 'value' => get_string('saveflags', 'question')));
221 $output .= html_writer::end_tag('div');
222 $output .= html_writer::end_tag('div');
223 $output .= html_writer::end_tag('form');
225 return $output;
229 * Returns either a liink or button
231 * @param quiz_attempt $attemptobj instance of quiz_attempt
233 public function finish_review_link(quiz_attempt $attemptobj) {
234 $url = $attemptobj->view_url();
236 if ($attemptobj->get_access_manager(time())->attempt_must_be_in_popup()) {
237 $this->page->requires->js_init_call('M.mod_quiz.secure_window.init_close_button',
238 array($url), false, quiz_get_js_module());
239 return html_writer::empty_tag('input', array('type' => 'button',
240 'value' => get_string('finishreview', 'quiz'),
241 'id' => 'secureclosebutton',
242 'class' => 'mod_quiz-next-nav btn btn-primary'));
244 } else {
245 return html_writer::link($url, get_string('finishreview', 'quiz'),
246 array('class' => 'mod_quiz-next-nav'));
251 * Creates the navigation links/buttons at the bottom of the reivew attempt page.
253 * Note, the name of this function is no longer accurate, but when the design
254 * changed, it was decided to keep the old name for backwards compatibility.
256 * @param quiz_attempt $attemptobj instance of quiz_attempt
257 * @param int $page the current page
258 * @param bool $lastpage if true current page is the last page
259 * @param bool|null $showall if true, the URL will be to review the entire attempt on one page,
260 * and $page will be ignored. If null, a sensible default will be chosen.
262 * @return string HTML fragment.
264 public function review_next_navigation(quiz_attempt $attemptobj, $page, $lastpage, $showall = null) {
265 $nav = '';
266 if ($page > 0) {
267 $nav .= link_arrow_left(get_string('navigateprevious', 'quiz'),
268 $attemptobj->review_url(null, $page - 1, $showall), false, 'mod_quiz-prev-nav');
270 if ($lastpage) {
271 $nav .= $this->finish_review_link($attemptobj);
272 } else {
273 $nav .= link_arrow_right(get_string('navigatenext', 'quiz'),
274 $attemptobj->review_url(null, $page + 1, $showall), false, 'mod_quiz-next-nav');
276 return html_writer::tag('div', $nav, array('class' => 'submitbtns'));
280 * Return the HTML of the quiz timer.
281 * @return string HTML content.
283 public function countdown_timer(quiz_attempt $attemptobj, $timenow) {
285 $timeleft = $attemptobj->get_time_left_display($timenow);
286 if ($timeleft !== false) {
287 $ispreview = $attemptobj->is_preview();
288 $timerstartvalue = $timeleft;
289 if (!$ispreview) {
290 // Make sure the timer starts just above zero. If $timeleft was <= 0, then
291 // this will just have the effect of causing the quiz to be submitted immediately.
292 $timerstartvalue = max($timerstartvalue, 1);
294 $this->initialise_timer($timerstartvalue, $ispreview);
297 return html_writer::tag('div', get_string('timeleft', 'quiz') . ' ' .
298 html_writer::tag('span', '', array('id' => 'quiz-time-left')),
299 array('id' => 'quiz-timer', 'role' => 'timer',
300 'aria-atomic' => 'true', 'aria-relevant' => 'text'));
304 * Create a preview link
306 * @param $url contains a url to the given page
308 public function restart_preview_button($url) {
309 return $this->single_button($url, get_string('startnewpreview', 'quiz'));
313 * Outputs the navigation block panel
315 * @param quiz_nav_panel_base $panel instance of quiz_nav_panel_base
317 public function navigation_panel(quiz_nav_panel_base $panel) {
319 $output = '';
320 $userpicture = $panel->user_picture();
321 if ($userpicture) {
322 $fullname = fullname($userpicture->user);
323 if ($userpicture->size === true) {
324 $fullname = html_writer::div($fullname);
326 $output .= html_writer::tag('div', $this->render($userpicture) . $fullname,
327 array('id' => 'user-picture', 'class' => 'clearfix'));
329 $output .= $panel->render_before_button_bits($this);
331 $bcc = $panel->get_button_container_class();
332 $output .= html_writer::start_tag('div', array('class' => "qn_buttons clearfix $bcc"));
333 foreach ($panel->get_question_buttons() as $button) {
334 $output .= $this->render($button);
336 $output .= html_writer::end_tag('div');
338 $output .= html_writer::tag('div', $panel->render_end_bits($this),
339 array('class' => 'othernav'));
341 $this->page->requires->js_init_call('M.mod_quiz.nav.init', null, false,
342 quiz_get_js_module());
344 return $output;
348 * Display a quiz navigation button.
350 * @param quiz_nav_question_button $button
351 * @return string HTML fragment.
353 protected function render_quiz_nav_question_button(quiz_nav_question_button $button) {
354 $classes = array('qnbutton', $button->stateclass, $button->navmethod, 'btn', 'btn-secondary');
355 $extrainfo = array();
357 if ($button->currentpage) {
358 $classes[] = 'thispage';
359 $extrainfo[] = get_string('onthispage', 'quiz');
362 // Flagged?
363 if ($button->flagged) {
364 $classes[] = 'flagged';
365 $flaglabel = get_string('flagged', 'question');
366 } else {
367 $flaglabel = '';
369 $extrainfo[] = html_writer::tag('span', $flaglabel, array('class' => 'flagstate'));
371 if (is_numeric($button->number)) {
372 $qnostring = 'questionnonav';
373 } else {
374 $qnostring = 'questionnonavinfo';
377 $a = new stdClass();
378 $a->number = $button->number;
379 $a->attributes = implode(' ', $extrainfo);
380 $tagcontents = html_writer::tag('span', '', array('class' => 'thispageholder')) .
381 html_writer::tag('span', '', array('class' => 'trafficlight')) .
382 get_string($qnostring, 'quiz', $a);
383 $tagattributes = array('class' => implode(' ', $classes), 'id' => $button->id,
384 'title' => $button->statestring, 'data-quiz-page' => $button->page);
386 if ($button->url) {
387 return html_writer::link($button->url, $tagcontents, $tagattributes);
388 } else {
389 return html_writer::tag('span', $tagcontents, $tagattributes);
394 * Display a quiz navigation heading.
396 * @param quiz_nav_section_heading $heading the heading.
397 * @return string HTML fragment.
399 protected function render_quiz_nav_section_heading(quiz_nav_section_heading $heading) {
400 return $this->heading($heading->heading, 3, 'mod_quiz-section-heading');
404 * outputs the link the other attempts.
406 * @param mod_quiz_links_to_other_attempts $links
408 protected function render_mod_quiz_links_to_other_attempts(
409 mod_quiz_links_to_other_attempts $links) {
410 $attemptlinks = array();
411 foreach ($links->links as $attempt => $url) {
412 if (!$url) {
413 $attemptlinks[] = html_writer::tag('strong', $attempt);
414 } else if ($url instanceof renderable) {
415 $attemptlinks[] = $this->render($url);
416 } else {
417 $attemptlinks[] = html_writer::link($url, $attempt);
420 return implode(', ', $attemptlinks);
423 public function start_attempt_page(quiz $quizobj, mod_quiz_preflight_check_form $mform) {
424 $output = '';
425 $output .= $this->header();
426 $output .= $this->heading(format_string($quizobj->get_quiz_name(), true,
427 array("context" => $quizobj->get_context())));
428 $output .= $this->quiz_intro($quizobj->get_quiz(), $quizobj->get_cm());
429 $output .= $mform->render();
430 $output .= $this->footer();
431 return $output;
435 * Attempt Page
437 * @param quiz_attempt $attemptobj Instance of quiz_attempt
438 * @param int $page Current page number
439 * @param quiz_access_manager $accessmanager Instance of quiz_access_manager
440 * @param array $messages An array of messages
441 * @param array $slots Contains an array of integers that relate to questions
442 * @param int $id The ID of an attempt
443 * @param int $nextpage The number of the next page
445 public function attempt_page($attemptobj, $page, $accessmanager, $messages, $slots, $id,
446 $nextpage) {
447 $output = '';
448 $output .= $this->header();
449 $output .= $this->quiz_notices($messages);
450 $output .= $this->attempt_form($attemptobj, $page, $slots, $id, $nextpage);
451 $output .= $this->footer();
452 return $output;
456 * Returns any notices.
458 * @param array $messages
460 public function quiz_notices($messages) {
461 if (!$messages) {
462 return '';
464 return $this->box($this->heading(get_string('accessnoticesheader', 'quiz'), 3) .
465 $this->access_messages($messages), 'quizaccessnotices');
469 * Ouputs the form for making an attempt
471 * @param quiz_attempt $attemptobj
472 * @param int $page Current page number
473 * @param array $slots Array of integers relating to questions
474 * @param int $id ID of the attempt
475 * @param int $nextpage Next page number
477 public function attempt_form($attemptobj, $page, $slots, $id, $nextpage) {
478 $output = '';
480 // Start the form.
481 $output .= html_writer::start_tag('form',
482 array('action' => new moodle_url($attemptobj->processattempt_url(),
483 array('cmid' => $attemptobj->get_cmid())), 'method' => 'post',
484 'enctype' => 'multipart/form-data', 'accept-charset' => 'utf-8',
485 'id' => 'responseform'));
486 $output .= html_writer::start_tag('div');
488 // Print all the questions.
489 foreach ($slots as $slot) {
490 $output .= $attemptobj->render_question($slot, false, $this,
491 $attemptobj->attempt_url($slot, $page), $this);
494 $navmethod = $attemptobj->get_quiz()->navmethod;
495 $output .= $this->attempt_navigation_buttons($page, $attemptobj->is_last_page($page), $navmethod);
497 // Some hidden fields to trach what is going on.
498 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'attempt',
499 'value' => $attemptobj->get_attemptid()));
500 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'thispage',
501 'value' => $page, 'id' => 'followingpage'));
502 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'nextpage',
503 'value' => $nextpage));
504 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'timeup',
505 'value' => '0', 'id' => 'timeup'));
506 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'sesskey',
507 'value' => sesskey()));
508 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'scrollpos',
509 'value' => '', 'id' => 'scrollpos'));
511 // Add a hidden field with questionids. Do this at the end of the form, so
512 // if you navigate before the form has finished loading, it does not wipe all
513 // the student's answers.
514 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'slots',
515 'value' => implode(',', $attemptobj->get_active_slots($page))));
517 // Finish the form.
518 $output .= html_writer::end_tag('div');
519 $output .= html_writer::end_tag('form');
521 $output .= $this->connection_warning();
523 return $output;
527 * Display the prev/next buttons that go at the bottom of each page of the attempt.
529 * @param int $page the page number. Starts at 0 for the first page.
530 * @param bool $lastpage is this the last page in the quiz?
531 * @param string $navmethod Optional quiz attribute, 'free' (default) or 'sequential'
532 * @return string HTML fragment.
534 protected function attempt_navigation_buttons($page, $lastpage, $navmethod = 'free') {
535 $output = '';
537 $output .= html_writer::start_tag('div', array('class' => 'submitbtns'));
538 if ($page > 0 && $navmethod == 'free') {
539 $output .= html_writer::empty_tag('input', array('type' => 'submit', 'name' => 'previous',
540 'value' => get_string('navigateprevious', 'quiz'), 'class' => 'mod_quiz-prev-nav btn btn-secondary'));
542 if ($lastpage) {
543 $nextlabel = get_string('endtest', 'quiz');
544 } else {
545 $nextlabel = get_string('navigatenext', 'quiz');
547 $output .= html_writer::empty_tag('input', array('type' => 'submit', 'name' => 'next',
548 'value' => $nextlabel, 'class' => 'mod_quiz-next-nav btn btn-primary'));
549 $output .= html_writer::end_tag('div');
551 return $output;
555 * Render a button which allows students to redo a question in the attempt.
557 * @param int $slot the number of the slot to generate the button for.
558 * @param bool $disabled if true, output the button disabled.
559 * @return string HTML fragment.
561 public function redo_question_button($slot, $disabled) {
562 $attributes = array('type' => 'submit', 'name' => 'redoslot' . $slot,
563 'value' => get_string('redoquestion', 'quiz'), 'class' => 'mod_quiz-redo_question_button');
564 if ($disabled) {
565 $attributes['disabled'] = 'disabled';
567 return html_writer::div(html_writer::empty_tag('input', $attributes));
571 * Output the JavaScript required to initialise the countdown timer.
572 * @param int $timerstartvalue time remaining, in seconds.
574 public function initialise_timer($timerstartvalue, $ispreview) {
575 $options = array($timerstartvalue, (bool)$ispreview);
576 $this->page->requires->js_init_call('M.mod_quiz.timer.init', $options, false, quiz_get_js_module());
580 * Output a page with an optional message, and JavaScript code to close the
581 * current window and redirect the parent window to a new URL.
582 * @param moodle_url $url the URL to redirect the parent window to.
583 * @param string $message message to display before closing the window. (optional)
584 * @return string HTML to output.
586 public function close_attempt_popup($url, $message = '') {
587 $output = '';
588 $output .= $this->header();
589 $output .= $this->box_start();
591 if ($message) {
592 $output .= html_writer::tag('p', $message);
593 $output .= html_writer::tag('p', get_string('windowclosing', 'quiz'));
594 $delay = 5;
595 } else {
596 $output .= html_writer::tag('p', get_string('pleaseclose', 'quiz'));
597 $delay = 0;
599 $this->page->requires->js_init_call('M.mod_quiz.secure_window.close',
600 array($url, $delay), false, quiz_get_js_module());
602 $output .= $this->box_end();
603 $output .= $this->footer();
604 return $output;
608 * Print each message in an array, surrounded by &lt;p>, &lt;/p> tags.
610 * @param array $messages the array of message strings.
611 * @param bool $return if true, return a string, instead of outputting.
613 * @return string HTML to output.
615 public function access_messages($messages) {
616 $output = '';
617 foreach ($messages as $message) {
618 $output .= html_writer::tag('p', $message) . "\n";
620 return $output;
624 * Summary Page
627 * Create the summary page
629 * @param quiz_attempt $attemptobj
630 * @param mod_quiz_display_options $displayoptions
632 public function summary_page($attemptobj, $displayoptions) {
633 $output = '';
634 $output .= $this->header();
635 $output .= $this->heading(format_string($attemptobj->get_quiz_name()));
636 $output .= $this->heading(get_string('summaryofattempt', 'quiz'), 3);
637 $output .= $this->summary_table($attemptobj, $displayoptions);
638 $output .= $this->summary_page_controls($attemptobj);
639 $output .= $this->footer();
640 return $output;
644 * Generates the table of summarydata
646 * @param quiz_attempt $attemptobj
647 * @param mod_quiz_display_options $displayoptions
649 public function summary_table($attemptobj, $displayoptions) {
650 // Prepare the summary table header.
651 $table = new html_table();
652 $table->attributes['class'] = 'generaltable quizsummaryofattempt boxaligncenter';
653 $table->head = array(get_string('question', 'quiz'), get_string('status', 'quiz'));
654 $table->align = array('left', 'left');
655 $table->size = array('', '');
656 $markscolumn = $displayoptions->marks >= question_display_options::MARK_AND_MAX;
657 if ($markscolumn) {
658 $table->head[] = get_string('marks', 'quiz');
659 $table->align[] = 'left';
660 $table->size[] = '';
662 $tablewidth = count($table->align);
663 $table->data = array();
665 // Get the summary info for each question.
666 $slots = $attemptobj->get_slots();
667 foreach ($slots as $slot) {
668 // Add a section headings if we need one here.
669 $heading = $attemptobj->get_heading_before_slot($slot);
670 if ($heading) {
671 $cell = new html_table_cell(format_string($heading));
672 $cell->header = true;
673 $cell->colspan = $tablewidth;
674 $table->data[] = array($cell);
675 $table->rowclasses[] = 'quizsummaryheading';
678 // Don't display information items.
679 if (!$attemptobj->is_real_question($slot)) {
680 continue;
683 // Real question, show it.
684 $flag = '';
685 if ($attemptobj->is_question_flagged($slot)) {
686 // Quiz has custom JS manipulating these image tags - so we can't use the pix_icon method here.
687 $flag = html_writer::empty_tag('img', array('src' => $this->image_url('i/flagged'),
688 'alt' => get_string('flagged', 'question'), 'class' => 'questionflag icon-post'));
690 if ($attemptobj->can_navigate_to($slot)) {
691 $row = array(html_writer::link($attemptobj->attempt_url($slot),
692 $attemptobj->get_question_number($slot) . $flag),
693 $attemptobj->get_question_status($slot, $displayoptions->correctness));
694 } else {
695 $row = array($attemptobj->get_question_number($slot) . $flag,
696 $attemptobj->get_question_status($slot, $displayoptions->correctness));
698 if ($markscolumn) {
699 $row[] = $attemptobj->get_question_mark($slot);
701 $table->data[] = $row;
702 $table->rowclasses[] = 'quizsummary' . $slot . ' ' . $attemptobj->get_question_state_class(
703 $slot, $displayoptions->correctness);
706 // Print the summary table.
707 $output = html_writer::table($table);
709 return $output;
713 * Creates any controls a the page should have.
715 * @param quiz_attempt $attemptobj
717 public function summary_page_controls($attemptobj) {
718 $output = '';
720 // Return to place button.
721 if ($attemptobj->get_state() == quiz_attempt::IN_PROGRESS) {
722 $button = new single_button(
723 new moodle_url($attemptobj->attempt_url(null, $attemptobj->get_currentpage())),
724 get_string('returnattempt', 'quiz'));
725 $output .= $this->container($this->container($this->render($button),
726 'controls'), 'submitbtns mdl-align');
729 // Finish attempt button.
730 $options = array(
731 'attempt' => $attemptobj->get_attemptid(),
732 'finishattempt' => 1,
733 'timeup' => 0,
734 'slots' => '',
735 'cmid' => $attemptobj->get_cmid(),
736 'sesskey' => sesskey(),
739 $button = new single_button(
740 new moodle_url($attemptobj->processattempt_url(), $options),
741 get_string('submitallandfinish', 'quiz'));
742 $button->id = 'responseform';
743 if ($attemptobj->get_state() == quiz_attempt::IN_PROGRESS) {
744 $button->add_action(new confirm_action(get_string('confirmclose', 'quiz'), null,
745 get_string('submitallandfinish', 'quiz')));
748 $duedate = $attemptobj->get_due_date();
749 $message = '';
750 if ($attemptobj->get_state() == quiz_attempt::OVERDUE) {
751 $message = get_string('overduemustbesubmittedby', 'quiz', userdate($duedate));
753 } else if ($duedate) {
754 $message = get_string('mustbesubmittedby', 'quiz', userdate($duedate));
757 $output .= $this->countdown_timer($attemptobj, time());
758 $output .= $this->container($message . $this->container(
759 $this->render($button), 'controls'), 'submitbtns mdl-align');
761 return $output;
765 * View Page
768 * Generates the view page
770 * @param int $course The id of the course
771 * @param array $quiz Array conting quiz data
772 * @param int $cm Course Module ID
773 * @param int $context The page context ID
774 * @param array $infomessages information about this quiz
775 * @param mod_quiz_view_object $viewobj
776 * @param string $buttontext text for the start/continue attempt button, if
777 * it should be shown.
778 * @param array $infomessages further information about why the student cannot
779 * attempt this quiz now, if appicable this quiz
781 public function view_page($course, $quiz, $cm, $context, $viewobj) {
782 $output = '';
783 $output .= $this->view_information($quiz, $cm, $context, $viewobj->infomessages);
784 $output .= $this->view_table($quiz, $context, $viewobj);
785 $output .= $this->view_result_info($quiz, $context, $cm, $viewobj);
786 $output .= $this->box($this->view_page_buttons($viewobj), 'quizattempt');
787 return $output;
791 * Work out, and render, whatever buttons, and surrounding info, should appear
792 * at the end of the review page.
793 * @param mod_quiz_view_object $viewobj the information required to display
794 * the view page.
795 * @return string HTML to output.
797 public function view_page_buttons(mod_quiz_view_object $viewobj) {
798 global $CFG;
799 $output = '';
801 if (!$viewobj->quizhasquestions) {
802 $output .= $this->no_questions_message($viewobj->canedit, $viewobj->editurl);
805 $output .= $this->access_messages($viewobj->preventmessages);
807 if ($viewobj->buttontext) {
808 $output .= $this->start_attempt_button($viewobj->buttontext,
809 $viewobj->startattempturl, $viewobj->preflightcheckform,
810 $viewobj->popuprequired, $viewobj->popupoptions);
813 if ($viewobj->showbacktocourse) {
814 $output .= $this->single_button($viewobj->backtocourseurl,
815 get_string('backtocourse', 'quiz'), 'get',
816 array('class' => 'continuebutton'));
819 return $output;
823 * Generates the view attempt button
825 * @param string $buttontext the label to display on the button.
826 * @param moodle_url $url The URL to POST to in order to start the attempt.
827 * @param mod_quiz_preflight_check_form $preflightcheckform deprecated.
828 * @param bool $popuprequired whether the attempt needs to be opened in a pop-up.
829 * @param array $popupoptions the options to use if we are opening a popup.
830 * @return string HTML fragment.
832 public function start_attempt_button($buttontext, moodle_url $url,
833 mod_quiz_preflight_check_form $preflightcheckform = null,
834 $popuprequired = false, $popupoptions = null) {
836 if (is_string($preflightcheckform)) {
837 // Calling code was not updated since the API change.
838 debugging('The third argument to start_attempt_button should now be the ' .
839 'mod_quiz_preflight_check_form from ' .
840 'quiz_access_manager::get_preflight_check_form, not a warning message string.');
843 $button = new single_button($url, $buttontext);
844 $button->class .= ' quizstartbuttondiv';
845 if ($popuprequired) {
846 $button->class .= ' quizsecuremoderequired';
849 $popupjsoptions = null;
850 if ($popuprequired && $popupoptions) {
851 $action = new popup_action('click', $url, 'popup', $popupoptions);
852 $popupjsoptions = $action->get_js_options();
855 if ($preflightcheckform) {
856 $checkform = $preflightcheckform->render();
857 } else {
858 $checkform = null;
861 $this->page->requires->js_call_amd('mod_quiz/preflightcheck', 'init',
862 array('.quizstartbuttondiv [type=submit]', get_string('startattempt', 'quiz'),
863 '#mod_quiz_preflight_form', $popupjsoptions));
865 return $this->render($button) . $checkform;
869 * Generate a message saying that this quiz has no questions, with a button to
870 * go to the edit page, if the user has the right capability.
871 * @param object $quiz the quiz settings.
872 * @param object $cm the course_module object.
873 * @param object $context the quiz context.
874 * @return string HTML to output.
876 public function no_questions_message($canedit, $editurl) {
877 $output = '';
878 $output .= $this->notification(get_string('noquestions', 'quiz'));
879 if ($canedit) {
880 $output .= $this->single_button($editurl, get_string('editquiz', 'quiz'), 'get');
883 return $output;
887 * Outputs an error message for any guests accessing the quiz
889 * @param int $course The course ID
890 * @param array $quiz Array contingin quiz data
891 * @param int $cm Course Module ID
892 * @param int $context The page contect ID
893 * @param array $messages Array containing any messages
895 public function view_page_guest($course, $quiz, $cm, $context, $messages) {
896 $output = '';
897 $output .= $this->view_information($quiz, $cm, $context, $messages);
898 $guestno = html_writer::tag('p', get_string('guestsno', 'quiz'));
899 $liketologin = html_writer::tag('p', get_string('liketologin'));
900 $referer = get_local_referer(false);
901 $output .= $this->confirm($guestno."\n\n".$liketologin."\n", get_login_url(), $referer);
902 return $output;
906 * Outputs and error message for anyone who is not enrolle don the course
908 * @param int $course The course ID
909 * @param array $quiz Array contingin quiz data
910 * @param int $cm Course Module ID
911 * @param int $context The page contect ID
912 * @param array $messages Array containing any messages
914 public function view_page_notenrolled($course, $quiz, $cm, $context, $messages) {
915 global $CFG;
916 $output = '';
917 $output .= $this->view_information($quiz, $cm, $context, $messages);
918 $youneedtoenrol = html_writer::tag('p', get_string('youneedtoenrol', 'quiz'));
919 $button = html_writer::tag('p',
920 $this->continue_button($CFG->wwwroot . '/course/view.php?id=' . $course->id));
921 $output .= $this->box($youneedtoenrol."\n\n".$button."\n", 'generalbox', 'notice');
922 return $output;
926 * Output the page information
928 * @param object $quiz the quiz settings.
929 * @param object $cm the course_module object.
930 * @param object $context the quiz context.
931 * @param array $messages any access messages that should be described.
932 * @return string HTML to output.
934 public function view_information($quiz, $cm, $context, $messages) {
935 global $CFG;
937 $output = '';
939 // Print quiz name and description.
940 $output .= $this->heading(format_string($quiz->name));
941 $output .= $this->quiz_intro($quiz, $cm);
943 // Output any access messages.
944 if ($messages) {
945 $output .= $this->box($this->access_messages($messages), 'quizinfo');
948 // Show number of attempts summary to those who can view reports.
949 if (has_capability('mod/quiz:viewreports', $context)) {
950 if ($strattemptnum = $this->quiz_attempt_summary_link_to_reports($quiz, $cm,
951 $context)) {
952 $output .= html_writer::tag('div', $strattemptnum,
953 array('class' => 'quizattemptcounts'));
956 return $output;
960 * Output the quiz intro.
961 * @param object $quiz the quiz settings.
962 * @param object $cm the course_module object.
963 * @return string HTML to output.
965 public function quiz_intro($quiz, $cm) {
966 if (html_is_blank($quiz->intro)) {
967 return '';
970 return $this->box(format_module_intro('quiz', $quiz, $cm->id), 'generalbox', 'intro');
974 * Generates the table heading.
976 public function view_table_heading() {
977 return $this->heading(get_string('summaryofattempts', 'quiz'), 3);
981 * Generates the table of data
983 * @param array $quiz Array contining quiz data
984 * @param int $context The page context ID
985 * @param mod_quiz_view_object $viewobj
987 public function view_table($quiz, $context, $viewobj) {
988 if (!$viewobj->attempts) {
989 return '';
992 // Prepare table header.
993 $table = new html_table();
994 $table->attributes['class'] = 'generaltable quizattemptsummary';
995 $table->head = array();
996 $table->align = array();
997 $table->size = array();
998 if ($viewobj->attemptcolumn) {
999 $table->head[] = get_string('attemptnumber', 'quiz');
1000 $table->align[] = 'center';
1001 $table->size[] = '';
1003 $table->head[] = get_string('attemptstate', 'quiz');
1004 $table->align[] = 'left';
1005 $table->size[] = '';
1006 if ($viewobj->markcolumn) {
1007 $table->head[] = get_string('marks', 'quiz') . ' / ' .
1008 quiz_format_grade($quiz, $quiz->sumgrades);
1009 $table->align[] = 'center';
1010 $table->size[] = '';
1012 if ($viewobj->gradecolumn) {
1013 $table->head[] = get_string('grade') . ' / ' .
1014 quiz_format_grade($quiz, $quiz->grade);
1015 $table->align[] = 'center';
1016 $table->size[] = '';
1018 if ($viewobj->canreviewmine) {
1019 $table->head[] = get_string('review', 'quiz');
1020 $table->align[] = 'center';
1021 $table->size[] = '';
1023 if ($viewobj->feedbackcolumn) {
1024 $table->head[] = get_string('feedback', 'quiz');
1025 $table->align[] = 'left';
1026 $table->size[] = '';
1029 // One row for each attempt.
1030 foreach ($viewobj->attemptobjs as $attemptobj) {
1031 $attemptoptions = $attemptobj->get_display_options(true);
1032 $row = array();
1034 // Add the attempt number.
1035 if ($viewobj->attemptcolumn) {
1036 if ($attemptobj->is_preview()) {
1037 $row[] = get_string('preview', 'quiz');
1038 } else {
1039 $row[] = $attemptobj->get_attempt_number();
1043 $row[] = $this->attempt_state($attemptobj);
1045 if ($viewobj->markcolumn) {
1046 if ($attemptoptions->marks >= question_display_options::MARK_AND_MAX &&
1047 $attemptobj->is_finished()) {
1048 $row[] = quiz_format_grade($quiz, $attemptobj->get_sum_marks());
1049 } else {
1050 $row[] = '';
1054 // Ouside the if because we may be showing feedback but not grades.
1055 $attemptgrade = quiz_rescale_grade($attemptobj->get_sum_marks(), $quiz, false);
1057 if ($viewobj->gradecolumn) {
1058 if ($attemptoptions->marks >= question_display_options::MARK_AND_MAX &&
1059 $attemptobj->is_finished()) {
1061 // Highlight the highest grade if appropriate.
1062 if ($viewobj->overallstats && !$attemptobj->is_preview()
1063 && $viewobj->numattempts > 1 && !is_null($viewobj->mygrade)
1064 && $attemptobj->get_state() == quiz_attempt::FINISHED
1065 && $attemptgrade == $viewobj->mygrade
1066 && $quiz->grademethod == QUIZ_GRADEHIGHEST) {
1067 $table->rowclasses[$attemptobj->get_attempt_number()] = 'bestrow';
1070 $row[] = quiz_format_grade($quiz, $attemptgrade);
1071 } else {
1072 $row[] = '';
1076 if ($viewobj->canreviewmine) {
1077 $row[] = $viewobj->accessmanager->make_review_link($attemptobj->get_attempt(),
1078 $attemptoptions, $this);
1081 if ($viewobj->feedbackcolumn && $attemptobj->is_finished()) {
1082 if ($attemptoptions->overallfeedback) {
1083 $row[] = quiz_feedback_for_grade($attemptgrade, $quiz, $context);
1084 } else {
1085 $row[] = '';
1089 if ($attemptobj->is_preview()) {
1090 $table->data['preview'] = $row;
1091 } else {
1092 $table->data[$attemptobj->get_attempt_number()] = $row;
1094 } // End of loop over attempts.
1096 $output = '';
1097 $output .= $this->view_table_heading();
1098 $output .= html_writer::table($table);
1099 return $output;
1103 * Generate a brief textual desciption of the current state of an attempt.
1104 * @param quiz_attempt $attemptobj the attempt
1105 * @param int $timenow the time to use as 'now'.
1106 * @return string the appropriate lang string to describe the state.
1108 public function attempt_state($attemptobj) {
1109 switch ($attemptobj->get_state()) {
1110 case quiz_attempt::IN_PROGRESS:
1111 return get_string('stateinprogress', 'quiz');
1113 case quiz_attempt::OVERDUE:
1114 return get_string('stateoverdue', 'quiz') . html_writer::tag('span',
1115 get_string('stateoverduedetails', 'quiz',
1116 userdate($attemptobj->get_due_date())),
1117 array('class' => 'statedetails'));
1119 case quiz_attempt::FINISHED:
1120 return get_string('statefinished', 'quiz') . html_writer::tag('span',
1121 get_string('statefinisheddetails', 'quiz',
1122 userdate($attemptobj->get_submitted_date())),
1123 array('class' => 'statedetails'));
1125 case quiz_attempt::ABANDONED:
1126 return get_string('stateabandoned', 'quiz');
1131 * Generates data pertaining to quiz results
1133 * @param array $quiz Array containing quiz data
1134 * @param int $context The page context ID
1135 * @param int $cm The Course Module Id
1136 * @param mod_quiz_view_object $viewobj
1138 public function view_result_info($quiz, $context, $cm, $viewobj) {
1139 $output = '';
1140 if (!$viewobj->numattempts && !$viewobj->gradecolumn && is_null($viewobj->mygrade)) {
1141 return $output;
1143 $resultinfo = '';
1145 if ($viewobj->overallstats) {
1146 if ($viewobj->moreattempts) {
1147 $a = new stdClass();
1148 $a->method = quiz_get_grading_option_name($quiz->grademethod);
1149 $a->mygrade = quiz_format_grade($quiz, $viewobj->mygrade);
1150 $a->quizgrade = quiz_format_grade($quiz, $quiz->grade);
1151 $resultinfo .= $this->heading(get_string('gradesofar', 'quiz', $a), 3);
1152 } else {
1153 $a = new stdClass();
1154 $a->grade = quiz_format_grade($quiz, $viewobj->mygrade);
1155 $a->maxgrade = quiz_format_grade($quiz, $quiz->grade);
1156 $a = get_string('outofshort', 'quiz', $a);
1157 $resultinfo .= $this->heading(get_string('yourfinalgradeis', 'quiz', $a), 3);
1161 if ($viewobj->mygradeoverridden) {
1163 $resultinfo .= html_writer::tag('p', get_string('overriddennotice', 'grades'),
1164 array('class' => 'overriddennotice'))."\n";
1166 if ($viewobj->gradebookfeedback) {
1167 $resultinfo .= $this->heading(get_string('comment', 'quiz'), 3);
1168 $resultinfo .= html_writer::div($viewobj->gradebookfeedback, 'quizteacherfeedback') . "\n";
1170 if ($viewobj->feedbackcolumn) {
1171 $resultinfo .= $this->heading(get_string('overallfeedback', 'quiz'), 3);
1172 $resultinfo .= html_writer::div(
1173 quiz_feedback_for_grade($viewobj->mygrade, $quiz, $context),
1174 'quizgradefeedback') . "\n";
1177 if ($resultinfo) {
1178 $output .= $this->box($resultinfo, 'generalbox', 'feedback');
1180 return $output;
1184 * Output either a link to the review page for an attempt, or a button to
1185 * open the review in a popup window.
1187 * @param moodle_url $url of the target page.
1188 * @param bool $reviewinpopup whether a pop-up is required.
1189 * @param array $popupoptions options to pass to the popup_action constructor.
1190 * @return string HTML to output.
1192 public function review_link($url, $reviewinpopup, $popupoptions) {
1193 if ($reviewinpopup) {
1194 $button = new single_button($url, get_string('review', 'quiz'));
1195 $button->add_action(new popup_action('click', $url, 'quizpopup', $popupoptions));
1196 return $this->render($button);
1198 } else {
1199 return html_writer::link($url, get_string('review', 'quiz'),
1200 array('title' => get_string('reviewthisattempt', 'quiz')));
1205 * Displayed where there might normally be a review link, to explain why the
1206 * review is not available at this time.
1207 * @param string $message optional message explaining why the review is not possible.
1208 * @return string HTML to output.
1210 public function no_review_message($message) {
1211 return html_writer::nonempty_tag('span', $message,
1212 array('class' => 'noreviewmessage'));
1216 * Returns the same as {@link quiz_num_attempt_summary()} but wrapped in a link
1217 * to the quiz reports.
1219 * @param object $quiz the quiz object. Only $quiz->id is used at the moment.
1220 * @param object $cm the cm object. Only $cm->course, $cm->groupmode and $cm->groupingid
1221 * fields are used at the moment.
1222 * @param object $context the quiz context.
1223 * @param bool $returnzero if false (default), when no attempts have been made '' is returned
1224 * instead of 'Attempts: 0'.
1225 * @param int $currentgroup if there is a concept of current group where this method is being
1226 * called
1227 * (e.g. a report) pass it in here. Default 0 which means no current group.
1228 * @return string HTML fragment for the link.
1230 public function quiz_attempt_summary_link_to_reports($quiz, $cm, $context,
1231 $returnzero = false, $currentgroup = 0) {
1232 global $CFG;
1233 $summary = quiz_num_attempt_summary($quiz, $cm, $returnzero, $currentgroup);
1234 if (!$summary) {
1235 return '';
1238 require_once($CFG->dirroot . '/mod/quiz/report/reportlib.php');
1239 $url = new moodle_url('/mod/quiz/report.php', array(
1240 'id' => $cm->id, 'mode' => quiz_report_default_report($context)));
1241 return html_writer::link($url, $summary);
1245 * Outputs a chart.
1247 * @param \core\chart_base $chart The chart.
1248 * @param string $title The title to display above the graph.
1249 * @return string HTML fragment for the graph.
1251 public function chart(\core\chart_base $chart, $title) {
1252 return $this->heading($title, 3) . html_writer::tag('div', $this->render($chart), array('class' => 'graph'));
1256 * Output a graph, or a message saying that GD is required.
1257 * @param moodle_url $url the URL of the graph.
1258 * @param string $title the title to display above the graph.
1259 * @return string HTML fragment for the graph.
1261 public function graph(moodle_url $url, $title) {
1262 global $CFG;
1264 $graph = html_writer::empty_tag('img', array('src' => $url, 'alt' => $title));
1266 return $this->heading($title, 3) . html_writer::tag('div', $graph, array('class' => 'graph'));
1270 * Output the connection warning messages, which are initially hidden, and
1271 * only revealed by JavaScript if necessary.
1273 public function connection_warning() {
1274 $options = array('filter' => false, 'newlines' => false);
1275 $warning = format_text(get_string('connectionerror', 'quiz'), FORMAT_MARKDOWN, $options);
1276 $ok = format_text(get_string('connectionok', 'quiz'), FORMAT_MARKDOWN, $options);
1277 return html_writer::tag('div', $warning,
1278 array('id' => 'connection-error', 'style' => 'display: none;', 'role' => 'alert')) .
1279 html_writer::tag('div', $ok, array('id' => 'connection-ok', 'style' => 'display: none;', 'role' => 'alert'));
1284 class mod_quiz_links_to_other_attempts implements renderable {
1286 * @var array string attempt number => url, or null for the current attempt.
1287 * url may be either a moodle_url, or a renderable.
1289 public $links = array();
1293 class mod_quiz_view_object {
1294 /** @var array $infomessages of messages with information to display about the quiz. */
1295 public $infomessages;
1296 /** @var array $attempts contains all the user's attempts at this quiz. */
1297 public $attempts;
1298 /** @var array $attemptobjs quiz_attempt objects corresponding to $attempts. */
1299 public $attemptobjs;
1300 /** @var quiz_access_manager $accessmanager contains various access rules. */
1301 public $accessmanager;
1302 /** @var bool $canreviewmine whether the current user has the capability to
1303 * review their own attempts. */
1304 public $canreviewmine;
1305 /** @var bool $canedit whether the current user has the capability to edit the quiz. */
1306 public $canedit;
1307 /** @var moodle_url $editurl the URL for editing this quiz. */
1308 public $editurl;
1309 /** @var int $attemptcolumn contains the number of attempts done. */
1310 public $attemptcolumn;
1311 /** @var int $gradecolumn contains the grades of any attempts. */
1312 public $gradecolumn;
1313 /** @var int $markcolumn contains the marks of any attempt. */
1314 public $markcolumn;
1315 /** @var int $overallstats contains all marks for any attempt. */
1316 public $overallstats;
1317 /** @var string $feedbackcolumn contains any feedback for and attempt. */
1318 public $feedbackcolumn;
1319 /** @var string $timenow contains a timestamp in string format. */
1320 public $timenow;
1321 /** @var int $numattempts contains the total number of attempts. */
1322 public $numattempts;
1323 /** @var float $mygrade contains the user's final grade for a quiz. */
1324 public $mygrade;
1325 /** @var bool $moreattempts whether this user is allowed more attempts. */
1326 public $moreattempts;
1327 /** @var int $mygradeoverridden contains an overriden grade. */
1328 public $mygradeoverridden;
1329 /** @var string $gradebookfeedback contains any feedback for a gradebook. */
1330 public $gradebookfeedback;
1331 /** @var bool $unfinished contains 1 if an attempt is unfinished. */
1332 public $unfinished;
1333 /** @var object $lastfinishedattempt the last attempt from the attempts array. */
1334 public $lastfinishedattempt;
1335 /** @var array $preventmessages of messages telling the user why they can't
1336 * attempt the quiz now. */
1337 public $preventmessages;
1338 /** @var string $buttontext caption for the start attempt button. If this is null, show no
1339 * button, or if it is '' show a back to the course button. */
1340 public $buttontext;
1341 /** @var moodle_url $startattempturl URL to start an attempt. */
1342 public $startattempturl;
1343 /** @var moodleform|null $preflightcheckform confirmation form that must be
1344 * submitted before an attempt is started, if required. */
1345 public $preflightcheckform;
1346 /** @var moodle_url $startattempturl URL for any Back to the course button. */
1347 public $backtocourseurl;
1348 /** @var bool $showbacktocourse should we show a back to the course button? */
1349 public $showbacktocourse;
1350 /** @var bool whether the attempt must take place in a popup window. */
1351 public $popuprequired;
1352 /** @var array options to use for the popup window, if required. */
1353 public $popupoptions;
1354 /** @var bool $quizhasquestions whether the quiz has any questions. */
1355 public $quizhasquestions;
1357 public function __get($field) {
1358 switch ($field) {
1359 case 'startattemptwarning':
1360 debugging('startattemptwarning has been deprecated. It is now always blank.');
1361 return '';
1363 default:
1364 debugging('Unknown property ' . $field);
1365 return null;