MDL-49813 quiz: add sections in the right place after page changes
[moodle.git] / mod / quiz / renderer.php
blob01dfa5d80b5005a2d487e3ea8af3f39db02969c5
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);
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 string $message Why the review is not allowed.
96 * @return string html to output.
98 public function review_question_not_allowed($message) {
99 $output = '';
100 $output .= $this->header();
101 $output .= $this->heading(format_string($attemptobj->get_quiz_name(), true,
102 array("context" => $attemptobj->get_quizobj()->get_context())));
103 $output .= $this->notification($message);
104 $output .= $this->close_window_button();
105 $output .= $this->footer();
106 return $output;
110 * Filters the summarydata array.
112 * @param array $summarydata contains row data for table
113 * @param int $page the current page number
114 * @return $summarydata containing filtered row data
116 protected function filter_review_summary_table($summarydata, $page) {
117 if ($page == 0) {
118 return $summarydata;
121 // Only show some of summary table on subsequent pages.
122 foreach ($summarydata as $key => $rowdata) {
123 if (!in_array($key, array('user', 'attemptlist'))) {
124 unset($summarydata[$key]);
128 return $summarydata;
132 * Outputs the table containing data from summary data array
134 * @param array $summarydata contains row data for table
135 * @param int $page contains the current page number
137 public function review_summary_table($summarydata, $page) {
138 $summarydata = $this->filter_review_summary_table($summarydata, $page);
139 if (empty($summarydata)) {
140 return '';
143 $output = '';
144 $output .= html_writer::start_tag('table', array(
145 'class' => 'generaltable generalbox quizreviewsummary'));
146 $output .= html_writer::start_tag('tbody');
147 foreach ($summarydata as $rowdata) {
148 if ($rowdata['title'] instanceof renderable) {
149 $title = $this->render($rowdata['title']);
150 } else {
151 $title = $rowdata['title'];
154 if ($rowdata['content'] instanceof renderable) {
155 $content = $this->render($rowdata['content']);
156 } else {
157 $content = $rowdata['content'];
160 $output .= html_writer::tag('tr',
161 html_writer::tag('th', $title, array('class' => 'cell', 'scope' => 'row')) .
162 html_writer::tag('td', $content, array('class' => 'cell'))
166 $output .= html_writer::end_tag('tbody');
167 $output .= html_writer::end_tag('table');
168 return $output;
172 * Renders each question
174 * @param quiz_attempt $attemptobj instance of quiz_attempt
175 * @param bool $reviewing
176 * @param array $slots array of intgers relating to questions
177 * @param int $page current page number
178 * @param bool $showall if true shows attempt on single page
179 * @param mod_quiz_display_options $displayoptions instance of mod_quiz_display_options
181 public function questions(quiz_attempt $attemptobj, $reviewing, $slots, $page, $showall,
182 mod_quiz_display_options $displayoptions) {
183 $output = '';
184 foreach ($slots as $slot) {
185 $output .= $attemptobj->render_question($slot, $reviewing, $this,
186 $attemptobj->review_url($slot, $page, $showall));
188 return $output;
192 * Renders the main bit of the review page.
194 * @param array $summarydata contain row data for table
195 * @param int $page current page number
196 * @param mod_quiz_display_options $displayoptions instance of mod_quiz_display_options
197 * @param $content contains each question
198 * @param quiz_attempt $attemptobj instance of quiz_attempt
199 * @param bool $showall if true display attempt on one page
201 public function review_form($page, $showall, $displayoptions, $content, $attemptobj) {
202 if ($displayoptions->flags != question_display_options::EDITABLE) {
203 return $content;
206 $this->page->requires->js_init_call('M.mod_quiz.init_review_form', null, false,
207 quiz_get_js_module());
209 $output = '';
210 $output .= html_writer::start_tag('form', array('action' => $attemptobj->review_url(null,
211 $page, $showall), 'method' => 'post', 'class' => 'questionflagsaveform'));
212 $output .= html_writer::start_tag('div');
213 $output .= $content;
214 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'sesskey',
215 'value' => sesskey()));
216 $output .= html_writer::start_tag('div', array('class' => 'submitbtns'));
217 $output .= html_writer::empty_tag('input', array('type' => 'submit',
218 'class' => 'questionflagsavebutton', 'name' => 'savingflags',
219 'value' => get_string('saveflags', 'question')));
220 $output .= html_writer::end_tag('div');
221 $output .= html_writer::end_tag('div');
222 $output .= html_writer::end_tag('form');
224 return $output;
228 * Returns either a liink or button
230 * @param quiz_attempt $attemptobj instance of quiz_attempt
232 public function finish_review_link(quiz_attempt $attemptobj) {
233 $url = $attemptobj->view_url();
235 if ($attemptobj->get_access_manager(time())->attempt_must_be_in_popup()) {
236 $this->page->requires->js_init_call('M.mod_quiz.secure_window.init_close_button',
237 array($url), quiz_get_js_module());
238 return html_writer::empty_tag('input', array('type' => 'button',
239 'value' => get_string('finishreview', 'quiz'),
240 'id' => 'secureclosebutton'));
242 } else {
243 return html_writer::link($url, get_string('finishreview', 'quiz'));
248 * Creates a next page arrow or the finishing link
250 * @param quiz_attempt $attemptobj instance of quiz_attempt
251 * @param int $page the current page
252 * @param bool $lastpage if true current page is the last page
254 public function review_next_navigation(quiz_attempt $attemptobj, $page, $lastpage) {
255 if ($lastpage) {
256 $nav = $this->finish_review_link($attemptobj);
257 } else {
258 $nav = link_arrow_right(get_string('next'), $attemptobj->review_url(null, $page + 1));
260 return html_writer::tag('div', $nav, array('class' => 'submitbtns'));
264 * Return the HTML of the quiz timer.
265 * @return string HTML content.
267 public function countdown_timer(quiz_attempt $attemptobj, $timenow) {
269 $timeleft = $attemptobj->get_time_left_display($timenow);
270 if ($timeleft !== false) {
271 $ispreview = $attemptobj->is_preview();
272 $timerstartvalue = $timeleft;
273 if (!$ispreview) {
274 // Make sure the timer starts just above zero. If $timeleft was <= 0, then
275 // this will just have the effect of causing the quiz to be submitted immediately.
276 $timerstartvalue = max($timerstartvalue, 1);
278 $this->initialise_timer($timerstartvalue, $ispreview);
281 return html_writer::tag('div', get_string('timeleft', 'quiz') . ' ' .
282 html_writer::tag('span', '', array('id' => 'quiz-time-left')),
283 array('id' => 'quiz-timer', 'role' => 'timer',
284 'aria-atomic' => 'true', 'aria-relevant' => 'text'));
288 * Create a preview link
290 * @param $url contains a url to the given page
292 public function restart_preview_button($url) {
293 return $this->single_button($url, get_string('startnewpreview', 'quiz'));
297 * Outputs the navigation block panel
299 * @param quiz_nav_panel_base $panel instance of quiz_nav_panel_base
301 public function navigation_panel(quiz_nav_panel_base $panel) {
303 $output = '';
304 $userpicture = $panel->user_picture();
305 if ($userpicture) {
306 $fullname = fullname($userpicture->user);
307 if ($userpicture->size === true) {
308 $fullname = html_writer::div($fullname);
310 $output .= html_writer::tag('div', $this->render($userpicture) . $fullname,
311 array('id' => 'user-picture', 'class' => 'clearfix'));
313 $output .= $panel->render_before_button_bits($this);
315 $bcc = $panel->get_button_container_class();
316 $output .= html_writer::start_tag('div', array('class' => "qn_buttons clearfix $bcc"));
317 foreach ($panel->get_question_buttons() as $button) {
318 $output .= $this->render($button);
320 $output .= html_writer::end_tag('div');
322 $output .= html_writer::tag('div', $panel->render_end_bits($this),
323 array('class' => 'othernav'));
325 $this->page->requires->js_init_call('M.mod_quiz.nav.init', null, false,
326 quiz_get_js_module());
328 return $output;
332 * Display a quiz navigation button.
334 * @param quiz_nav_question_button $button
335 * @return string HTML fragment.
337 protected function render_quiz_nav_question_button(quiz_nav_question_button $button) {
338 $classes = array('qnbutton', $button->stateclass, $button->navmethod);
339 $extrainfo = array();
341 if ($button->currentpage) {
342 $classes[] = 'thispage';
343 $extrainfo[] = get_string('onthispage', 'quiz');
346 // Flagged?
347 if ($button->flagged) {
348 $classes[] = 'flagged';
349 $flaglabel = get_string('flagged', 'question');
350 } else {
351 $flaglabel = '';
353 $extrainfo[] = html_writer::tag('span', $flaglabel, array('class' => 'flagstate'));
355 if (is_numeric($button->number)) {
356 $qnostring = 'questionnonav';
357 } else {
358 $qnostring = 'questionnonavinfo';
361 $a = new stdClass();
362 $a->number = $button->number;
363 $a->attributes = implode(' ', $extrainfo);
364 $tagcontents = html_writer::tag('span', '', array('class' => 'thispageholder')) .
365 html_writer::tag('span', '', array('class' => 'trafficlight')) .
366 get_string($qnostring, 'quiz', $a);
367 $tagattributes = array('class' => implode(' ', $classes), 'id' => $button->id,
368 'title' => $button->statestring, 'data-quiz-page' => $button->page);
370 if ($button->url) {
371 return html_writer::link($button->url, $tagcontents, $tagattributes);
372 } else {
373 return html_writer::tag('span', $tagcontents, $tagattributes);
378 * Display a quiz navigation heading.
380 * @param quiz_nav_section_heading $heading the heading.
381 * @return string HTML fragment.
383 protected function render_quiz_nav_section_heading(quiz_nav_section_heading $heading) {
384 return $this->heading($heading->heading, 3, 'mod_quiz-section-heading');
388 * outputs the link the other attempts.
390 * @param mod_quiz_links_to_other_attempts $links
392 protected function render_mod_quiz_links_to_other_attempts(
393 mod_quiz_links_to_other_attempts $links) {
394 $attemptlinks = array();
395 foreach ($links->links as $attempt => $url) {
396 if (!$url) {
397 $attemptlinks[] = html_writer::tag('strong', $attempt);
398 } else if ($url instanceof renderable) {
399 $attemptlinks[] = $this->render($url);
400 } else {
401 $attemptlinks[] = html_writer::link($url, $attempt);
404 return implode(', ', $attemptlinks);
407 public function start_attempt_page(quiz $quizobj, mod_quiz_preflight_check_form $mform) {
408 $output = '';
409 $output .= $this->header();
410 $output .= $this->heading(format_string($quizobj->get_quiz_name(), true,
411 array("context" => $quizobj->get_context())));
412 $output .= $this->quiz_intro($quizobj->get_quiz(), $quizobj->get_cm());
413 ob_start();
414 $mform->display();
415 $output .= ob_get_clean();
416 $output .= $this->footer();
417 return $output;
421 * Attempt Page
423 * @param quiz_attempt $attemptobj Instance of quiz_attempt
424 * @param int $page Current page number
425 * @param quiz_access_manager $accessmanager Instance of quiz_access_manager
426 * @param array $messages An array of messages
427 * @param array $slots Contains an array of integers that relate to questions
428 * @param int $id The ID of an attempt
429 * @param int $nextpage The number of the next page
431 public function attempt_page($attemptobj, $page, $accessmanager, $messages, $slots, $id,
432 $nextpage) {
433 $output = '';
434 $output .= $this->header();
435 $output .= $this->quiz_notices($messages);
436 $output .= $this->attempt_form($attemptobj, $page, $slots, $id, $nextpage);
437 $output .= $this->footer();
438 return $output;
442 * Returns any notices.
444 * @param array $messages
446 public function quiz_notices($messages) {
447 if (!$messages) {
448 return '';
450 return $this->box($this->heading(get_string('accessnoticesheader', 'quiz'), 3) .
451 $this->access_messages($messages), 'quizaccessnotices');
455 * Ouputs the form for making an attempt
457 * @param quiz_attempt $attemptobj
458 * @param int $page Current page number
459 * @param array $slots Array of integers relating to questions
460 * @param int $id ID of the attempt
461 * @param int $nextpage Next page number
463 public function attempt_form($attemptobj, $page, $slots, $id, $nextpage) {
464 $output = '';
466 // Start the form.
467 $output .= html_writer::start_tag('form',
468 array('action' => $attemptobj->processattempt_url(), 'method' => 'post',
469 'enctype' => 'multipart/form-data', 'accept-charset' => 'utf-8',
470 'id' => 'responseform'));
471 $output .= html_writer::start_tag('div');
473 // Print all the questions.
474 foreach ($slots as $slot) {
475 $output .= $attemptobj->render_question($slot, false, $this,
476 $attemptobj->attempt_url($slot, $page), $this);
479 $output .= html_writer::start_tag('div', array('class' => 'submitbtns'));
480 $output .= html_writer::empty_tag('input', array('type' => 'submit', 'name' => 'next',
481 'value' => get_string('next')));
482 $output .= html_writer::end_tag('div');
484 // Some hidden fields to trach what is going on.
485 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'attempt',
486 'value' => $attemptobj->get_attemptid()));
487 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'thispage',
488 'value' => $page, 'id' => 'followingpage'));
489 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'nextpage',
490 'value' => $nextpage));
491 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'timeup',
492 'value' => '0', 'id' => 'timeup'));
493 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'sesskey',
494 'value' => sesskey()));
495 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'scrollpos',
496 'value' => '', 'id' => 'scrollpos'));
498 // Add a hidden field with questionids. Do this at the end of the form, so
499 // if you navigate before the form has finished loading, it does not wipe all
500 // the student's answers.
501 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'slots',
502 'value' => implode(',', $attemptobj->get_active_slots($page))));
504 // Finish the form.
505 $output .= html_writer::end_tag('div');
506 $output .= html_writer::end_tag('form');
508 $output .= $this->connection_warning();
510 return $output;
514 * Render a button which allows students to redo a question in the attempt.
516 * @param int $slot the number of the slot to generate the button for.
517 * @param bool $disabled if true, output the button disabled.
518 * @return string HTML fragment.
520 public function redo_question_button($slot, $disabled) {
521 $attributes = array('type' => 'submit', 'name' => 'redoslot' . $slot,
522 'value' => get_string('redoquestion', 'quiz'), 'class' => 'mod_quiz-redo_question_button');
523 if ($disabled) {
524 $attributes['disabled'] = 'disabled';
526 return html_writer::div(html_writer::empty_tag('input', $attributes));
530 * Output the JavaScript required to initialise the countdown timer.
531 * @param int $timerstartvalue time remaining, in seconds.
533 public function initialise_timer($timerstartvalue, $ispreview) {
534 $options = array($timerstartvalue, (bool)$ispreview);
535 $this->page->requires->js_init_call('M.mod_quiz.timer.init', $options, false, quiz_get_js_module());
539 * Output a page with an optional message, and JavaScript code to close the
540 * current window and redirect the parent window to a new URL.
541 * @param moodle_url $url the URL to redirect the parent window to.
542 * @param string $message message to display before closing the window. (optional)
543 * @return string HTML to output.
545 public function close_attempt_popup($url, $message = '') {
546 $output = '';
547 $output .= $this->header();
548 $output .= $this->box_start();
550 if ($message) {
551 $output .= html_writer::tag('p', $message);
552 $output .= html_writer::tag('p', get_string('windowclosing', 'quiz'));
553 $delay = 5;
554 } else {
555 $output .= html_writer::tag('p', get_string('pleaseclose', 'quiz'));
556 $delay = 0;
558 $this->page->requires->js_init_call('M.mod_quiz.secure_window.close',
559 array($url, $delay), false, quiz_get_js_module());
561 $output .= $this->box_end();
562 $output .= $this->footer();
563 return $output;
567 * Print each message in an array, surrounded by &lt;p>, &lt;/p> tags.
569 * @param array $messages the array of message strings.
570 * @param bool $return if true, return a string, instead of outputting.
572 * @return string HTML to output.
574 public function access_messages($messages) {
575 $output = '';
576 foreach ($messages as $message) {
577 $output .= html_writer::tag('p', $message) . "\n";
579 return $output;
583 * Summary Page
586 * Create the summary page
588 * @param quiz_attempt $attemptobj
589 * @param mod_quiz_display_options $displayoptions
591 public function summary_page($attemptobj, $displayoptions) {
592 $output = '';
593 $output .= $this->header();
594 $output .= $this->heading(format_string($attemptobj->get_quiz_name()));
595 $output .= $this->heading(get_string('summaryofattempt', 'quiz'), 3);
596 $output .= $this->summary_table($attemptobj, $displayoptions);
597 $output .= $this->summary_page_controls($attemptobj);
598 $output .= $this->footer();
599 return $output;
603 * Generates the table of summarydata
605 * @param quiz_attempt $attemptobj
606 * @param mod_quiz_display_options $displayoptions
608 public function summary_table($attemptobj, $displayoptions) {
609 // Prepare the summary table header.
610 $table = new html_table();
611 $table->attributes['class'] = 'generaltable quizsummaryofattempt boxaligncenter';
612 $table->head = array(get_string('question', 'quiz'), get_string('status', 'quiz'));
613 $table->align = array('left', 'left');
614 $table->size = array('', '');
615 $markscolumn = $displayoptions->marks >= question_display_options::MARK_AND_MAX;
616 if ($markscolumn) {
617 $table->head[] = get_string('marks', 'quiz');
618 $table->align[] = 'left';
619 $table->size[] = '';
621 $tablewidth = count($table->align);
622 $table->data = array();
624 // Get the summary info for each question.
625 $slots = $attemptobj->get_slots();
626 foreach ($slots as $slot) {
627 // Add a section headings if we need one here.
628 $heading = $attemptobj->get_heading_before_slot($slot);
629 if ($heading) {
630 $cell = new html_table_cell(format_string($heading));
631 $cell->header = true;
632 $cell->colspan = $tablewidth;
633 $table->data[] = array($cell);
636 // Don't display information items.
637 if (!$attemptobj->is_real_question($slot)) {
638 continue;
641 // Real question, show it.
642 $flag = '';
643 if ($attemptobj->is_question_flagged($slot)) {
644 $flag = html_writer::empty_tag('img', array('src' => $this->pix_url('i/flagged'),
645 'alt' => get_string('flagged', 'question'), 'class' => 'questionflag icon-post'));
647 if ($attemptobj->can_navigate_to($slot)) {
648 $row = array(html_writer::link($attemptobj->attempt_url($slot),
649 $attemptobj->get_question_number($slot) . $flag),
650 $attemptobj->get_question_status($slot, $displayoptions->correctness));
651 } else {
652 $row = array($attemptobj->get_question_number($slot) . $flag,
653 $attemptobj->get_question_status($slot, $displayoptions->correctness));
655 if ($markscolumn) {
656 $row[] = $attemptobj->get_question_mark($slot);
658 $table->data[] = $row;
659 $table->rowclasses[] = 'quizsummary' . $slot . ' ' . $attemptobj->get_question_state_class(
660 $slot, $displayoptions->correctness);
663 // Print the summary table.
664 $output = html_writer::table($table);
666 return $output;
670 * Creates any controls a the page should have.
672 * @param quiz_attempt $attemptobj
674 public function summary_page_controls($attemptobj) {
675 $output = '';
677 // Return to place button.
678 if ($attemptobj->get_state() == quiz_attempt::IN_PROGRESS) {
679 $button = new single_button(
680 new moodle_url($attemptobj->attempt_url(null, $attemptobj->get_currentpage())),
681 get_string('returnattempt', 'quiz'));
682 $output .= $this->container($this->container($this->render($button),
683 'controls'), 'submitbtns mdl-align');
686 // Finish attempt button.
687 $options = array(
688 'attempt' => $attemptobj->get_attemptid(),
689 'finishattempt' => 1,
690 'timeup' => 0,
691 'slots' => '',
692 'sesskey' => sesskey(),
695 $button = new single_button(
696 new moodle_url($attemptobj->processattempt_url(), $options),
697 get_string('submitallandfinish', 'quiz'));
698 $button->id = 'responseform';
699 if ($attemptobj->get_state() == quiz_attempt::IN_PROGRESS) {
700 $button->add_action(new confirm_action(get_string('confirmclose', 'quiz'), null,
701 get_string('submitallandfinish', 'quiz')));
704 $duedate = $attemptobj->get_due_date();
705 $message = '';
706 if ($attemptobj->get_state() == quiz_attempt::OVERDUE) {
707 $message = get_string('overduemustbesubmittedby', 'quiz', userdate($duedate));
709 } else if ($duedate) {
710 $message = get_string('mustbesubmittedby', 'quiz', userdate($duedate));
713 $output .= $this->countdown_timer($attemptobj, time());
714 $output .= $this->container($message . $this->container(
715 $this->render($button), 'controls'), 'submitbtns mdl-align');
717 return $output;
721 * View Page
724 * Generates the view page
726 * @param int $course The id of the course
727 * @param array $quiz Array conting quiz data
728 * @param int $cm Course Module ID
729 * @param int $context The page context ID
730 * @param array $infomessages information about this quiz
731 * @param mod_quiz_view_object $viewobj
732 * @param string $buttontext text for the start/continue attempt button, if
733 * it should be shown.
734 * @param array $infomessages further information about why the student cannot
735 * attempt this quiz now, if appicable this quiz
737 public function view_page($course, $quiz, $cm, $context, $viewobj) {
738 $output = '';
739 $output .= $this->view_information($quiz, $cm, $context, $viewobj->infomessages);
740 $output .= $this->view_table($quiz, $context, $viewobj);
741 $output .= $this->view_result_info($quiz, $context, $cm, $viewobj);
742 $output .= $this->box($this->view_page_buttons($viewobj), 'quizattempt');
743 return $output;
747 * Work out, and render, whatever buttons, and surrounding info, should appear
748 * at the end of the review page.
749 * @param mod_quiz_view_object $viewobj the information required to display
750 * the view page.
751 * @return string HTML to output.
753 public function view_page_buttons(mod_quiz_view_object $viewobj) {
754 global $CFG;
755 $output = '';
757 if (!$viewobj->quizhasquestions) {
758 $output .= $this->no_questions_message($viewobj->canedit, $viewobj->editurl);
761 $output .= $this->access_messages($viewobj->preventmessages);
763 if ($viewobj->buttontext) {
764 $output .= $this->start_attempt_button($viewobj->buttontext,
765 $viewobj->startattempturl, $viewobj->startattemptwarning,
766 $viewobj->popuprequired, $viewobj->popupoptions);
770 if ($viewobj->showbacktocourse) {
771 $output .= $this->single_button($viewobj->backtocourseurl,
772 get_string('backtocourse', 'quiz'), 'get',
773 array('class' => 'continuebutton'));
776 return $output;
780 * Generates the view attempt button
782 * @param int $course The course ID
783 * @param array $quiz Array containging quiz date
784 * @param int $cm The Course Module ID
785 * @param int $context The page Context ID
786 * @param mod_quiz_view_object $viewobj
787 * @param string $buttontext
789 public function start_attempt_button($buttontext, moodle_url $url,
790 $startattemptwarning, $popuprequired, $popupoptions) {
792 $button = new single_button($url, $buttontext);
793 $button->class .= ' quizstartbuttondiv';
795 $warning = '';
796 if ($popuprequired) {
797 $this->page->requires->js_module(quiz_get_js_module());
798 $this->page->requires->js('/mod/quiz/module.js');
799 $popupaction = new popup_action('click', $url, 'quizpopup', $popupoptions);
801 $button->class .= ' quizsecuremoderequired';
802 $button->add_action(new component_action('click',
803 'M.mod_quiz.secure_window.start_attempt_action', array(
804 'url' => $url->out(false),
805 'windowname' => 'quizpopup',
806 'options' => $popupaction->get_js_options(),
807 'fullscreen' => true,
808 'startattemptwarning' => $startattemptwarning,
809 )));
811 $warning = html_writer::tag('noscript', $this->heading(get_string('noscript', 'quiz')));
813 } else if ($startattemptwarning) {
814 $button->add_action(new confirm_action($startattemptwarning, null,
815 get_string('startattempt', 'quiz')));
818 return $this->render($button) . $warning;
822 * Generate a message saying that this quiz has no questions, with a button to
823 * go to the edit page, if the user has the right capability.
824 * @param object $quiz the quiz settings.
825 * @param object $cm the course_module object.
826 * @param object $context the quiz context.
827 * @return string HTML to output.
829 public function no_questions_message($canedit, $editurl) {
830 $output = '';
831 $output .= $this->notification(get_string('noquestions', 'quiz'));
832 if ($canedit) {
833 $output .= $this->single_button($editurl, get_string('editquiz', 'quiz'), 'get');
836 return $output;
840 * Outputs an error message for any guests accessing the quiz
842 * @param int $course The course ID
843 * @param array $quiz Array contingin quiz data
844 * @param int $cm Course Module ID
845 * @param int $context The page contect ID
846 * @param array $messages Array containing any messages
848 public function view_page_guest($course, $quiz, $cm, $context, $messages) {
849 $output = '';
850 $output .= $this->view_information($quiz, $cm, $context, $messages);
851 $guestno = html_writer::tag('p', get_string('guestsno', 'quiz'));
852 $liketologin = html_writer::tag('p', get_string('liketologin'));
853 $output .= $this->confirm($guestno."\n\n".$liketologin."\n", get_login_url(),
854 get_referer(false));
855 return $output;
859 * Outputs and error message for anyone who is not enrolle don the course
861 * @param int $course The course ID
862 * @param array $quiz Array contingin quiz data
863 * @param int $cm Course Module ID
864 * @param int $context The page contect ID
865 * @param array $messages Array containing any messages
867 public function view_page_notenrolled($course, $quiz, $cm, $context, $messages) {
868 global $CFG;
869 $output = '';
870 $output .= $this->view_information($quiz, $cm, $context, $messages);
871 $youneedtoenrol = html_writer::tag('p', get_string('youneedtoenrol', 'quiz'));
872 $button = html_writer::tag('p',
873 $this->continue_button($CFG->wwwroot . '/course/view.php?id=' . $course->id));
874 $output .= $this->box($youneedtoenrol."\n\n".$button."\n", 'generalbox', 'notice');
875 return $output;
879 * Output the page information
881 * @param object $quiz the quiz settings.
882 * @param object $cm the course_module object.
883 * @param object $context the quiz context.
884 * @param array $messages any access messages that should be described.
885 * @return string HTML to output.
887 public function view_information($quiz, $cm, $context, $messages) {
888 global $CFG;
890 $output = '';
892 // Print quiz name and description.
893 $output .= $this->heading(format_string($quiz->name));
894 $output .= $this->quiz_intro($quiz, $cm);
896 // Output any access messages.
897 if ($messages) {
898 $output .= $this->box($this->access_messages($messages), 'quizinfo');
901 // Show number of attempts summary to those who can view reports.
902 if (has_capability('mod/quiz:viewreports', $context)) {
903 if ($strattemptnum = $this->quiz_attempt_summary_link_to_reports($quiz, $cm,
904 $context)) {
905 $output .= html_writer::tag('div', $strattemptnum,
906 array('class' => 'quizattemptcounts'));
909 return $output;
913 * Output the quiz intro.
914 * @param object $quiz the quiz settings.
915 * @param object $cm the course_module object.
916 * @return string HTML to output.
918 public function quiz_intro($quiz, $cm) {
919 if (html_is_blank($quiz->intro)) {
920 return '';
923 return $this->box(format_module_intro('quiz', $quiz, $cm->id), 'generalbox', 'intro');
927 * Generates the table heading.
929 public function view_table_heading() {
930 return $this->heading(get_string('summaryofattempts', 'quiz'), 3);
934 * Generates the table of data
936 * @param array $quiz Array contining quiz data
937 * @param int $context The page context ID
938 * @param mod_quiz_view_object $viewobj
940 public function view_table($quiz, $context, $viewobj) {
941 if (!$viewobj->attempts) {
942 return '';
945 // Prepare table header.
946 $table = new html_table();
947 $table->attributes['class'] = 'generaltable quizattemptsummary';
948 $table->head = array();
949 $table->align = array();
950 $table->size = array();
951 if ($viewobj->attemptcolumn) {
952 $table->head[] = get_string('attemptnumber', 'quiz');
953 $table->align[] = 'center';
954 $table->size[] = '';
956 $table->head[] = get_string('attemptstate', 'quiz');
957 $table->align[] = 'left';
958 $table->size[] = '';
959 if ($viewobj->markcolumn) {
960 $table->head[] = get_string('marks', 'quiz') . ' / ' .
961 quiz_format_grade($quiz, $quiz->sumgrades);
962 $table->align[] = 'center';
963 $table->size[] = '';
965 if ($viewobj->gradecolumn) {
966 $table->head[] = get_string('grade') . ' / ' .
967 quiz_format_grade($quiz, $quiz->grade);
968 $table->align[] = 'center';
969 $table->size[] = '';
971 if ($viewobj->canreviewmine) {
972 $table->head[] = get_string('review', 'quiz');
973 $table->align[] = 'center';
974 $table->size[] = '';
976 if ($viewobj->feedbackcolumn) {
977 $table->head[] = get_string('feedback', 'quiz');
978 $table->align[] = 'left';
979 $table->size[] = '';
982 // One row for each attempt.
983 foreach ($viewobj->attemptobjs as $attemptobj) {
984 $attemptoptions = $attemptobj->get_display_options(true);
985 $row = array();
987 // Add the attempt number.
988 if ($viewobj->attemptcolumn) {
989 if ($attemptobj->is_preview()) {
990 $row[] = get_string('preview', 'quiz');
991 } else {
992 $row[] = $attemptobj->get_attempt_number();
996 $row[] = $this->attempt_state($attemptobj);
998 if ($viewobj->markcolumn) {
999 if ($attemptoptions->marks >= question_display_options::MARK_AND_MAX &&
1000 $attemptobj->is_finished()) {
1001 $row[] = quiz_format_grade($quiz, $attemptobj->get_sum_marks());
1002 } else {
1003 $row[] = '';
1007 // Ouside the if because we may be showing feedback but not grades.
1008 $attemptgrade = quiz_rescale_grade($attemptobj->get_sum_marks(), $quiz, false);
1010 if ($viewobj->gradecolumn) {
1011 if ($attemptoptions->marks >= question_display_options::MARK_AND_MAX &&
1012 $attemptobj->is_finished()) {
1014 // Highlight the highest grade if appropriate.
1015 if ($viewobj->overallstats && !$attemptobj->is_preview()
1016 && $viewobj->numattempts > 1 && !is_null($viewobj->mygrade)
1017 && $attemptobj->get_state() == quiz_attempt::FINISHED
1018 && $attemptgrade == $viewobj->mygrade
1019 && $quiz->grademethod == QUIZ_GRADEHIGHEST) {
1020 $table->rowclasses[$attemptobj->get_attempt_number()] = 'bestrow';
1023 $row[] = quiz_format_grade($quiz, $attemptgrade);
1024 } else {
1025 $row[] = '';
1029 if ($viewobj->canreviewmine) {
1030 $row[] = $viewobj->accessmanager->make_review_link($attemptobj->get_attempt(),
1031 $attemptoptions, $this);
1034 if ($viewobj->feedbackcolumn && $attemptobj->is_finished()) {
1035 if ($attemptoptions->overallfeedback) {
1036 $row[] = quiz_feedback_for_grade($attemptgrade, $quiz, $context);
1037 } else {
1038 $row[] = '';
1042 if ($attemptobj->is_preview()) {
1043 $table->data['preview'] = $row;
1044 } else {
1045 $table->data[$attemptobj->get_attempt_number()] = $row;
1047 } // End of loop over attempts.
1049 $output = '';
1050 $output .= $this->view_table_heading();
1051 $output .= html_writer::table($table);
1052 return $output;
1056 * Generate a brief textual desciption of the current state of an attempt.
1057 * @param quiz_attempt $attemptobj the attempt
1058 * @param int $timenow the time to use as 'now'.
1059 * @return string the appropriate lang string to describe the state.
1061 public function attempt_state($attemptobj) {
1062 switch ($attemptobj->get_state()) {
1063 case quiz_attempt::IN_PROGRESS:
1064 return get_string('stateinprogress', 'quiz');
1066 case quiz_attempt::OVERDUE:
1067 return get_string('stateoverdue', 'quiz') . html_writer::tag('span',
1068 get_string('stateoverduedetails', 'quiz',
1069 userdate($attemptobj->get_due_date())),
1070 array('class' => 'statedetails'));
1072 case quiz_attempt::FINISHED:
1073 return get_string('statefinished', 'quiz') . html_writer::tag('span',
1074 get_string('statefinisheddetails', 'quiz',
1075 userdate($attemptobj->get_submitted_date())),
1076 array('class' => 'statedetails'));
1078 case quiz_attempt::ABANDONED:
1079 return get_string('stateabandoned', 'quiz');
1084 * Generates data pertaining to quiz results
1086 * @param array $quiz Array containing quiz data
1087 * @param int $context The page context ID
1088 * @param int $cm The Course Module Id
1089 * @param mod_quiz_view_object $viewobj
1091 public function view_result_info($quiz, $context, $cm, $viewobj) {
1092 $output = '';
1093 if (!$viewobj->numattempts && !$viewobj->gradecolumn && is_null($viewobj->mygrade)) {
1094 return $output;
1096 $resultinfo = '';
1098 if ($viewobj->overallstats) {
1099 if ($viewobj->moreattempts) {
1100 $a = new stdClass();
1101 $a->method = quiz_get_grading_option_name($quiz->grademethod);
1102 $a->mygrade = quiz_format_grade($quiz, $viewobj->mygrade);
1103 $a->quizgrade = quiz_format_grade($quiz, $quiz->grade);
1104 $resultinfo .= $this->heading(get_string('gradesofar', 'quiz', $a), 3);
1105 } else {
1106 $a = new stdClass();
1107 $a->grade = quiz_format_grade($quiz, $viewobj->mygrade);
1108 $a->maxgrade = quiz_format_grade($quiz, $quiz->grade);
1109 $a = get_string('outofshort', 'quiz', $a);
1110 $resultinfo .= $this->heading(get_string('yourfinalgradeis', 'quiz', $a), 3);
1114 if ($viewobj->mygradeoverridden) {
1116 $resultinfo .= html_writer::tag('p', get_string('overriddennotice', 'grades'),
1117 array('class' => 'overriddennotice'))."\n";
1119 if ($viewobj->gradebookfeedback) {
1120 $resultinfo .= $this->heading(get_string('comment', 'quiz'), 3);
1121 $resultinfo .= html_writer::div($viewobj->gradebookfeedback, 'quizteacherfeedback') . "\n";
1123 if ($viewobj->feedbackcolumn) {
1124 $resultinfo .= $this->heading(get_string('overallfeedback', 'quiz'), 3);
1125 $resultinfo .= html_writer::div(
1126 quiz_feedback_for_grade($viewobj->mygrade, $quiz, $context),
1127 'quizgradefeedback') . "\n";
1130 if ($resultinfo) {
1131 $output .= $this->box($resultinfo, 'generalbox', 'feedback');
1133 return $output;
1137 * Output either a link to the review page for an attempt, or a button to
1138 * open the review in a popup window.
1140 * @param moodle_url $url of the target page.
1141 * @param bool $reviewinpopup whether a pop-up is required.
1142 * @param array $popupoptions options to pass to the popup_action constructor.
1143 * @return string HTML to output.
1145 public function review_link($url, $reviewinpopup, $popupoptions) {
1146 if ($reviewinpopup) {
1147 $button = new single_button($url, get_string('review', 'quiz'));
1148 $button->add_action(new popup_action('click', $url, 'quizpopup', $popupoptions));
1149 return $this->render($button);
1151 } else {
1152 return html_writer::link($url, get_string('review', 'quiz'),
1153 array('title' => get_string('reviewthisattempt', 'quiz')));
1158 * Displayed where there might normally be a review link, to explain why the
1159 * review is not available at this time.
1160 * @param string $message optional message explaining why the review is not possible.
1161 * @return string HTML to output.
1163 public function no_review_message($message) {
1164 return html_writer::nonempty_tag('span', $message,
1165 array('class' => 'noreviewmessage'));
1169 * Returns the same as {@link quiz_num_attempt_summary()} but wrapped in a link
1170 * to the quiz reports.
1172 * @param object $quiz the quiz object. Only $quiz->id is used at the moment.
1173 * @param object $cm the cm object. Only $cm->course, $cm->groupmode and $cm->groupingid
1174 * fields are used at the moment.
1175 * @param object $context the quiz context.
1176 * @param bool $returnzero if false (default), when no attempts have been made '' is returned
1177 * instead of 'Attempts: 0'.
1178 * @param int $currentgroup if there is a concept of current group where this method is being
1179 * called
1180 * (e.g. a report) pass it in here. Default 0 which means no current group.
1181 * @return string HTML fragment for the link.
1183 public function quiz_attempt_summary_link_to_reports($quiz, $cm, $context,
1184 $returnzero = false, $currentgroup = 0) {
1185 global $CFG;
1186 $summary = quiz_num_attempt_summary($quiz, $cm, $returnzero, $currentgroup);
1187 if (!$summary) {
1188 return '';
1191 require_once($CFG->dirroot . '/mod/quiz/report/reportlib.php');
1192 $url = new moodle_url('/mod/quiz/report.php', array(
1193 'id' => $cm->id, 'mode' => quiz_report_default_report($context)));
1194 return html_writer::link($url, $summary);
1198 * Output a graph, or a message saying that GD is required.
1199 * @param moodle_url $url the URL of the graph.
1200 * @param string $title the title to display above the graph.
1201 * @return string HTML fragment for the graph.
1203 public function graph(moodle_url $url, $title) {
1204 global $CFG;
1206 $graph = html_writer::empty_tag('img', array('src' => $url, 'alt' => $title));
1208 return $this->heading($title, 3) . html_writer::tag('div', $graph, array('class' => 'graph'));
1212 * Output the connection warning messages, which are initially hidden, and
1213 * only revealed by JavaScript if necessary.
1215 public function connection_warning() {
1216 $options = array('filter' => false, 'newlines' => false);
1217 $warning = format_text(get_string('connectionerror', 'quiz'), FORMAT_MARKDOWN, $options);
1218 $ok = format_text(get_string('connectionok', 'quiz'), FORMAT_MARKDOWN, $options);
1219 return html_writer::tag('div', $warning,
1220 array('id' => 'connection-error', 'style' => 'display: none;', 'role' => 'alert')) .
1221 html_writer::tag('div', $ok, array('id' => 'connection-ok', 'style' => 'display: none;', 'role' => 'alert'));
1226 class mod_quiz_links_to_other_attempts implements renderable {
1228 * @var array string attempt number => url, or null for the current attempt.
1229 * url may be either a moodle_url, or a renderable.
1231 public $links = array();
1235 class mod_quiz_view_object {
1236 /** @var array $infomessages of messages with information to display about the quiz. */
1237 public $infomessages;
1238 /** @var array $attempts contains all the user's attempts at this quiz. */
1239 public $attempts;
1240 /** @var array $attemptobjs quiz_attempt objects corresponding to $attempts. */
1241 public $attemptobjs;
1242 /** @var quiz_access_manager $accessmanager contains various access rules. */
1243 public $accessmanager;
1244 /** @var bool $canreviewmine whether the current user has the capability to
1245 * review their own attempts. */
1246 public $canreviewmine;
1247 /** @var bool $canedit whether the current user has the capability to edit the quiz. */
1248 public $canedit;
1249 /** @var moodle_url $editurl the URL for editing this quiz. */
1250 public $editurl;
1251 /** @var int $attemptcolumn contains the number of attempts done. */
1252 public $attemptcolumn;
1253 /** @var int $gradecolumn contains the grades of any attempts. */
1254 public $gradecolumn;
1255 /** @var int $markcolumn contains the marks of any attempt. */
1256 public $markcolumn;
1257 /** @var int $overallstats contains all marks for any attempt. */
1258 public $overallstats;
1259 /** @var string $feedbackcolumn contains any feedback for and attempt. */
1260 public $feedbackcolumn;
1261 /** @var string $timenow contains a timestamp in string format. */
1262 public $timenow;
1263 /** @var int $numattempts contains the total number of attempts. */
1264 public $numattempts;
1265 /** @var float $mygrade contains the user's final grade for a quiz. */
1266 public $mygrade;
1267 /** @var bool $moreattempts whether this user is allowed more attempts. */
1268 public $moreattempts;
1269 /** @var int $mygradeoverridden contains an overriden grade. */
1270 public $mygradeoverridden;
1271 /** @var string $gradebookfeedback contains any feedback for a gradebook. */
1272 public $gradebookfeedback;
1273 /** @var bool $unfinished contains 1 if an attempt is unfinished. */
1274 public $unfinished;
1275 /** @var object $lastfinishedattempt the last attempt from the attempts array. */
1276 public $lastfinishedattempt;
1277 /** @var array $preventmessages of messages telling the user why they can't
1278 * attempt the quiz now. */
1279 public $preventmessages;
1280 /** @var string $buttontext caption for the start attempt button. If this is null, show no
1281 * button, or if it is '' show a back to the course button. */
1282 public $buttontext;
1283 /** @var string $startattemptwarning alert to show the user before starting an attempt. */
1284 public $startattemptwarning;
1285 /** @var moodle_url $startattempturl URL to start an attempt. */
1286 public $startattempturl;
1287 /** @var moodle_url $startattempturl URL for any Back to the course button. */
1288 public $backtocourseurl;
1289 /** @var bool $showbacktocourse should we show a back to the course button? */
1290 public $showbacktocourse;
1291 /** @var bool whether the attempt must take place in a popup window. */
1292 public $popuprequired;
1293 /** @var array options to use for the popup window, if required. */
1294 public $popupoptions;
1295 /** @var bool $quizhasquestions whether the quiz has any questions. */
1296 public $quizhasquestions;