49d2cb3b60894a26a272cd8794d375dc250b1b9f
[moodle.git] / mod / quiz / renderer.php
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.
13 //
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.
19  *
20  * @package    mod
21  * @subpackage quiz
22  * @copyright  2011 The Open University
23  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  */
27 /**
28  * The renderer for the quiz module.
29  *
30  * @copyright  2011 The Open University
31  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
32  */
33 class mod_quiz_renderer extends plugin_renderer_base {
34     /**
35      * Builds the review page
36      *
37      * @param quiz_attempt $attemptobj an instance of quiz_attempt.
38      * @param array $slots an array of intgers relating to questions.
39      * @param int $page the current page number
40      * @param bool $showall whether to show entire attempt on one page.
41      * @param bool $lastpage if true the current page is the last page.
42      * @param mod_quiz_display_options $displayoptions instance of mod_quiz_display_options.
43      * @param array $summarydata contains all table data
44      * @return $output containing html data.
45      */
46     public function review_page(quiz_attempt $attemptobj, $slots, $page, $showall,
47                                 $lastpage, mod_quiz_display_options $displayoptions,
48                                 $summarydata) {
50         $output = '';
51         $output .= $this->header();
52         $output .= $this->review_summary_table($summarydata, $page);
53         $output .= $this->review_form($page, $showall, $displayoptions,
54                 $this->questions($attemptobj, true, $slots, $page, $showall, $displayoptions),
55                 $attemptobj);
57         $output .= $this->review_next_navigation($attemptobj, $page, $lastpage);
58         $output .= $this->footer();
59         return $output;
60     }
62     /**
63      * Renders the review question pop-up.
64      *
65      * @param quiz_attempt $attemptobj an instance of quiz_attempt.
66      * @param int $slot which question to display.
67      * @param int $seq which step of the question attempt to show. null = latest.
68      * @param mod_quiz_display_options $displayoptions instance of mod_quiz_display_options.
69      * @param array $summarydata contains all table data
70      * @return $output containing html data.
71      */
72     public function review_question_page(quiz_attempt $attemptobj, $slot, $seq,
73             mod_quiz_display_options $displayoptions, $summarydata) {
75         $output = '';
76         $output .= $this->header();
77         $output .= $this->review_summary_table($summarydata, 0);
79         if (!is_null($seq)) {
80             $output .= $attemptobj->render_question_at_step($slot, $seq, true);
81         } else {
82             $output .= $attemptobj->render_question($slot, true);
83         }
85         $output .= $this->close_window_button();
86         $output .= $this->footer();
87         return $output;
88     }
90     /**
91      * Renders the review question pop-up.
92      *
93      * @param string $message Why the review is not allowed.
94      * @return string html to output.
95      */
96     public function review_question_not_allowed($message) {
97         $output = '';
98         $output .= $this->header();
99         $output .= $this->notification($message);
100         $output .= $this->close_window_button();
101         $output .= $this->footer();
102         return $output;
103     }
105     /**
106      * Filters the summarydata array.
107      *
108      * @param array $summarydata contains row data for table
109      * @param int $page the current page number
110      * @return $summarydata containing filtered row data
111      */
112     protected function filter_summary_table($summarydata, $page) {
113         if ($page == 0) {
114             return $summarydata;
115         }
117         // Only show some of summary table on subsequent pages.
118         foreach ($summarydata as $key => $rowdata) {
119             if (!in_array($key, array('user', 'attemptlist'))) {
120                 unset($summarydata[$key]);
121             }
122         }
124         return $summarydata;
125     }
127     /**
128      * Outputs the table containing data from summary data array
129      *
130      * @param array $summarydata contains row data for table
131      * @param int $page contains the current page number
132      */
133     public function review_summary_table($summarydata, $page) {
134         $summarydata = $this->filter_summary_table($summarydata, $page);
135         if (empty($summarydata)) {
136             return '';
137         }
139         $output = '';
140         $output .= html_writer::start_tag('table', array(
141                 'class' => 'generaltable generalbox quizreviewsummary'));
142         $output .= html_writer::start_tag('tbody');
143         foreach ($summarydata as $rowdata) {
144             if ($rowdata['title'] instanceof renderable) {
145                 $title = $this->render($rowdata['title']);
146             } else {
147                 $title = $rowdata['title'];
148             }
150             if ($rowdata['content'] instanceof renderable) {
151                 $content = $this->render($rowdata['content']);
152             } else {
153                 $content = $rowdata['content'];
154             }
156             $output .= html_writer::tag('tr',
157                 html_writer::tag('th', $title, array('class' => 'cell', 'scope' => 'row')) .
158                         html_writer::tag('td', $content, array('class' => 'cell'))
159             );
160         }
162         $output .= html_writer::end_tag('tbody');
163         $output .= html_writer::end_tag('table');
164         return $output;
165     }
167     /**
168      * Renders each question
169      *
170      * @param quiz_attempt $attemptobj instance of quiz_attempt
171      * @param bool $reviewing
172      * @param array $slots array of intgers relating to questions
173      * @param int $page current page number
174      * @param bool $showall if true shows attempt on single page
175      * @param mod_quiz_display_options $displayoptions instance of mod_quiz_display_options
176      */
177     public function questions(quiz_attempt $attemptobj, $reviewing, $slots, $page, $showall,
178                               mod_quiz_display_options $displayoptions) {
179         $output = '';
180         foreach ($slots as $slot) {
181             $output .= $attemptobj->render_question($slot, $reviewing,
182                     $attemptobj->review_url($slot, $page, $showall));
183         }
184         return $output;
185     }
187     /**
188      * Renders the main bit of the review page.
189      *
190      * @param array $summarydata contain row data for table
191      * @param int $page current page number
192      * @param mod_quiz_display_options $displayoptions instance of mod_quiz_display_options
193      * @param $content contains each question
194      * @param quiz_attempt $attemptobj instance of quiz_attempt
195      * @param bool $showall if true display attempt on one page
196      */
197     public function review_form($page, $showall, $displayoptions, $content, $attemptobj) {
198         if ($displayoptions->flags != question_display_options::EDITABLE) {
199             return $content;
200         }
202         $this->page->requires->js_init_call('M.mod_quiz.init_review_form', null, false,
203                 quiz_get_js_module());
205         $output = '';
206         $output .= html_writer::start_tag('form', array('action' => $attemptobj->review_url(0,
207                 $page, $showall), 'method' => 'post', 'class' => 'questionflagsaveform'));
208         $output .= html_writer::start_tag('div');
209         $output .= $content;
210         $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'sesskey',
211                 'value' => sesskey()));
212         $output .= html_writer::start_tag('div', array('class' => 'submitbtns'));
213         $output .= html_writer::empty_tag('input', array('type' => 'submit',
214                 'class' => 'questionflagsavebutton', 'name' => 'savingflags',
215                 'value' => get_string('saveflags', 'question')));
216         $output .= html_writer::end_tag('div');
217         $output .= html_writer::end_tag('div');
218         $output .= html_writer::end_tag('form');
220         return $output;
221     }
223     /**
224      * Returns either a liink or button
225      *
226      * @param $url contains a url for the review link
227      */
228     public function finish_review_link($url) {
229         if ($this->page->pagelayout == 'popup') {
230             // In a 'secure' popup window.
231             $this->page->requires->js_init_call('M.mod_quiz.secure_window.init_close_button',
232                     array($url), quiz_get_js_module());
233             return html_writer::empty_tag('input', array('type' => 'button',
234                     'value' => get_string('finishreview', 'quiz'),
235                     'id' => 'secureclosebutton'));
236         } else {
237             return html_writer::link($url, get_string('finishreview', 'quiz'));
238         }
239     }
241     /**
242      * Creates a next page arrow or the finishing link
243      *
244      * @param quiz_attempt $attemptobj instance of quiz_attempt
245      * @param int $page the current page
246      * @param bool $lastpage if true current page is the last page
247      */
248     public function review_next_navigation(quiz_attempt $attemptobj, $page, $lastpage) {
249         if ($lastpage) {
250             $nav = $this->finish_review_link($attemptobj->view_url());
251         } else {
252             $nav = link_arrow_right(get_string('next'), $attemptobj->review_url(0, $page + 1));
253         }
254         return html_writer::tag('div', $nav, array('class' => 'submitbtns'));
255     }
257     /**
258      * Return the HTML of the quiz timer.
259      * @return string HTML content.
260      */
261     public function countdown_timer() {
262         return html_writer::tag('div', get_string('timeleft', 'quiz') .
263                 html_writer::tag('span', '', array('id' => 'quiz-time-left')),
264                 array('id' => 'quiz-timer'));
265     }
267     /**
268      * Create a preview link
269      *
270      * @param $url contains a url to the given page
271      */
272     public function restart_preview_button($url) {
273         return $this->single_button($url, get_string('startnewpreview', 'quiz'));
274     }
276     /**
277      * Outputs the navigation block panel
278      *
279      * @param quiz_nav_panel_base $panel instance of quiz_nav_panel_base
280      */
281     public function navigation_panel(quiz_nav_panel_base $panel) {
283         $output = '';
284         $userpicture = $panel->user_picture();
285         if ($userpicture) {
286             $output .= html_writer::tag('div', $this->render($userpicture),
287                     array('id' => 'user-picture', 'class' => 'clearfix'));
288         }
289         $output .= $panel->render_before_button_bits($this);
291         $output .= html_writer::start_tag('div', array('class' => 'qn_buttons'));
292         foreach ($panel->get_question_buttons() as $button) {
293             $output .= $this->render($button);
294         }
295         $output .= html_writer::end_tag('div');
297         $output .= html_writer::tag('div', $panel->render_end_bits($this),
298                 array('class' => 'othernav'));
300         $this->page->requires->js_init_call('M.mod_quiz.nav.init', null, false,
301                 quiz_get_js_module());
303         return $output;
304     }
306     /**
307      * Returns the quizzes navigation button
308      *
309      * @param quiz_nav_question_button $button
310      */
311     protected function render_quiz_nav_question_button(quiz_nav_question_button $button) {
312         $classes = array('qnbutton', $button->stateclass);
313         $attributes = array();
315         if ($button->currentpage) {
316             $classes[] = 'thispage';
317             $attributes[] = get_string('onthispage', 'quiz');
318         }
320         $attributes[] = $button->statestring;
322         // Flagged?
323         if ($button->flagged) {
324             $classes[] = 'flagged';
325             $flaglabel = get_string('flagged', 'question');
326         } else {
327             $flaglabel = '';
328         }
329         $attributes[] = html_writer::tag('span', $flaglabel, array('class' => 'flagstate'));
331         if (is_numeric($button->number)) {
332             $qnostring = 'questionnonav';
333         } else {
334             $qnostring = 'questionnonavinfo';
335         }
337         $a = new stdClass();
338         $a->number = $button->number;
339         $a->attributes = implode(' ', $attributes);
341         return html_writer::link($button->url,
342                 html_writer::tag('span', '', array('class' => 'thispageholder')) .
343                 html_writer::tag('span', '', array('class' => 'trafficlight')) .
344                 get_string($qnostring, 'quiz', $a),
345                 array('class' => implode(' ', $classes), 'id' => $button->id,
346                         'title' => $button->statestring));
347     }
349     /**
350      * outputs the link the other attempts.
351      *
352      * @param mod_quiz_links_to_other_attempts $links
353      */
354     protected function render_mod_quiz_links_to_other_attempts(
355             mod_quiz_links_to_other_attempts $links) {
356         $attemptlinks = array();
357         foreach ($links->links as $attempt => $url) {
358             if ($url) {
359                 $attemptlinks[] = html_writer::link($url, $attempt);
360             } else {
361                 $attemptlinks[] = html_writer::tag('strong', $attempt);
362             }
363         }
364         return implode(', ', $attemptlinks);
365     }
367     /**
368      * Attempt Page
369      *
370      * @param quiz_attempt $attemptobj Instance of quiz_attempt
371      * @param int $page Current page number
372      * @param quiz_access_manager $accessmanager Instance of quiz_access_manager
373      * @param array $messages An array of messages
374      * @param array $slots Contains an array of integers that relate to questions
375      * @param int $id The ID of an attempt
376      * @param int $nextpage The number of the next page
377      */
378     public function attempt_page($attemptobj, $page, $accessmanager, $messages, $slots, $id,
379             $nextpage) {
380         $output = '';
381         $output .= $this->quiz_notices($messages);
382         $output .= $this->attempt_form($attemptobj, $page, $slots, $id, $nextpage);
383         return $output;
384     }
386     /**
387      * Returns any notices.
388      *
389      * @param array $messages
390      */
391     public function quiz_notices($messages) {
392         if (!$messages) {
393             return '';
394         }
395         return $this->box($this->heading(get_string('accessnoticesheader', 'quiz'), 3) .
396                 $this->access_messages($messages), 'quizaccessnotices');
397     }
399     /**
400      * Ouputs the form for making an attempt
401      *
402      * @param quiz_attempt $attemptobj
403      * @param int $page Current page number
404      * @param array $slots Array of integers relating to questions
405      * @param int $id ID of the attempt
406      * @param int $nextpage Next page number
407      */
408     public function attempt_form($attemptobj, $page, $slots, $id, $nextpage) {
409         $output = '';
411         //Start Form
412         $output .= html_writer::start_tag('form',
413                 array('action' => $attemptobj->processattempt_url(), 'method' => 'post',
414                 'enctype' => 'multipart/form-data', 'accept-charset' => 'utf-8',
415                 'id' => 'responseform'));
416         $output .= html_writer::start_tag('div');
418         // Print all the questions
419         foreach ($slots as $slot) {
420             $output .= $attemptobj->render_question($slot, false, $attemptobj->attempt_url($id,
421                     $page));
422         }
424         $output .= html_writer::start_tag('div', array('class' => 'submitbtns'));
425         $output .= html_writer::empty_tag('input', array('type' => 'submit', 'name' => 'next',
426                 'value' => get_string('next')));
427         $output .= html_writer::end_tag('div');
429         // Some hidden fields to trach what is going on.
430         $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'attempt',
431                 'value' => $attemptobj->get_attemptid()));
432         $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'thispage',
433                 'value' => $page, 'id' => 'followingpage'));
434         $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'nextpage',
435                 'value' => $nextpage));
436         $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'timeup',
437                 'value' => '0', 'id' => 'timeup'));
438         $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'sesskey',
439                 'value' => sesskey()));
440         $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'scrollpos',
441                 'value' => '', 'id' => 'scrollpos'));
443         // Add a hidden field with questionids. Do this at the end of the form, so
444         // if you navigate before the form has finished loading, it does not wipe all
445         // the student's answers.
446         $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'slots',
447                 'value' => implode(',', $slots)));
449         //Finish form
450         $output .= html_writer::end_tag('div');
451         $output .= html_writer::end_tag('form');
453         return $output;
454     }
456     /**
457      * Print each message in an array, surrounded by &lt;p>, &lt;/p> tags.
458      *
459      * @param array $messages the array of message strings.
460      * @param bool $return if true, return a string, instead of outputting.
461      *
462      * @return mixed, if $return is true, return the string that would have been output, otherwise
463      * return null.
464      */
465     public function access_messages($messages) {
466         $output = '';
467         foreach ($messages as $message) {
468             $output .= html_writer::tag('p', $message) . "\n";
469         }
470         return $output;
471     }
473     /*
474      * Summary Page
475      */
476     /**
477      * Create the summary page
478      *
479      * @param quiz_attempt $attemptobj
480      * @param mod_quiz_display_options $displayoptions
481      */
482     public function summary_page($attemptobj, $displayoptions) {
483         $output = '';
484         $output .= $this->summary_table($attemptobj, $displayoptions);
485         $output .= $this->summary_page_controls($attemptobj);
486         return $output;
487     }
489     /**
490      * Generates the table of summarydata
491      *
492      * @param quiz_attempt $attemptobj
493      * @param mod_quiz_display_options $displayoptions
494      */
495     public function summary_table($attemptobj, $displayoptions) {
496         // Prepare the summary table header
497         $table = new html_table();
498         $table->attributes['class'] = 'generaltable quizsummaryofattempt boxaligncenter';
499         $table->head = array(get_string('question', 'quiz'), get_string('status', 'quiz'));
500         $table->align = array('left', 'left');
501         $table->size = array('', '');
502         $markscolumn = $displayoptions->marks >= question_display_options::MARK_AND_MAX;
503         if ($markscolumn) {
504             $table->head[] = get_string('marks', 'quiz');
505             $table->align[] = 'left';
506             $table->size[] = '';
507         }
508         $table->data = array();
510         // Get the summary info for each question.
511         $slots = $attemptobj->get_slots();
512         foreach ($slots as $slot) {
513             if (!$attemptobj->is_real_question($slot)) {
514                 continue;
515             }
516             $flag = '';
517             if ($attemptobj->is_question_flagged($slot)) {
518                 $flag = html_writer::empty_tag('img', array('src' => $this->pix_url('i/flagged'),
519                         'alt' => get_string('flagged', 'question'), 'class' => 'questionflag'));
520             }
521             $row = array(html_writer::link($attemptobj->attempt_url($slot),
522                     $attemptobj->get_question_number($slot) . $flag),
523                     $attemptobj->get_question_status($slot, $displayoptions->correctness));
524             if ($markscolumn) {
525                 $row[] = $attemptobj->get_question_mark($slot);
526             }
527             $table->data[] = $row;
528             $table->rowclasses[] = $attemptobj->get_question_state_class(
529                     $slot, $displayoptions->correctness);
530         }
532         // Print the summary table.
533         $output = html_writer::table($table);
535         return $output;
536     }
538     /**
539      * Creates any controls a the page should have.
540      *
541      * @param quiz_attempt $attemptobj
542      */
543     public function summary_page_controls($attemptobj) {
544         $output = '';
545         // countdown timer
546         $output .= $this->countdown_timer();
548         // Finish attempt button.
549         $options = array(
550             'attempt' => $attemptobj->get_attemptid(),
551             'finishattempt' => 1,
552             'timeup' => 0,
553             'slots' => '',
554             'sesskey' => sesskey(),
555         );
557         $button = new single_button(
558                 new moodle_url($attemptobj->processattempt_url(), $options),
559                 get_string('submitallandfinish', 'quiz'));
560         $button->id = 'responseform';
561         $button->add_action(new confirm_action(get_string('confirmclose', 'quiz'), null,
562                 get_string('submitallandfinish', 'quiz')));
564         $output .= $this->container($this->container($this->render($button),
565                 'controls'), 'submitbtns mdl-align');
567         return $output;
568     }
570     /*
571      * View Page
572      */
573     /**
574      * Generates the view page
575      *
576      * @param int $course The id of the course
577      * @param array $quiz Array conting quiz data
578      * @param int $cm Course Module ID
579      * @param int $context The page context ID
580      * @param array $infomessages information about this quiz
581      * @param mod_quiz_view_object $viewobj
582      * @param string $buttontext text for the start/continue attempt button, if
583      *      it should be shown.
584      * @param array $infomessages further information about why the student cannot
585      *      attempt this quiz now, if appicable this quiz
586      */
587     public function view_page($course, $quiz, $cm, $context, $infomessages, $viewobj,
588             $buttontext, $preventmessages) {
589         $output = '';
590         $output .= $this->view_information($course, $quiz, $cm, $context, $infomessages);
591         $output .= $this->view_table($quiz, $context, $viewobj);
592         $output .= $this->view_best_score($viewobj);
593         $output .= $this->view_result_info($quiz, $context, $cm, $viewobj);
594         $output .= $this->view_attempt_button($course, $quiz, $cm, $context, $viewobj,
595                 $buttontext, $preventmessages);
596         return $output;
597     }
599     /**
600      * Outputs an error message for any guests accessing the quiz
601      *
602      * @param int $course The course ID
603      * @param array $quiz Array contingin quiz data
604      * @param int $cm Course Module ID
605      * @param int $context The page contect ID
606      * @param array $messages Array containing any messages
607      */
608     public function view_page_guest($course, $quiz, $cm, $context, $messages) {
609         $output = '';
610         $output .= $this->view_information($course, $quiz, $cm, $context, $messages);
611         $guestno = html_writer::tag('p', get_string('guestsno', 'quiz'));
612         $liketologin = html_writer::tag('p', get_string('liketologin'));
613         $output .= $this->confirm($guestno."\n\n".$liketologin."\n", get_login_url(),
614                 get_referer(false));
615         return $output;
616     }
618     /**
619      * Outputs and error message for anyone who is not enrolle don the course
620      *
621      * @param int $course The course ID
622      * @param array $quiz Array contingin quiz data
623      * @param int $cm Course Module ID
624      * @param int $context The page contect ID
625      * @param array $messages Array containing any messages
626      */
627     public function view_page_notenrolled($course, $quiz, $cm, $context, $messages) {
628         global $CFG;
629         $output = '';
630         $output .= $this->view_information($course, $quiz, $cm, $context, $messages);
631         $youneedtoenrol = html_writer::tag('p', get_string('youneedtoenrol', 'quiz'));
632         $button = html_writer::tag('p',
633                 $this->continue_button($CFG->wwwroot . '/course/view.php?id=' . $course->id));
634         $output .= $this->box($youneedtoenrol."\n\n".$button."\n", 'generalbox', 'notice');
635         return $output;
636     }
638     /**
639      * Output the page information
640      *
641      * @param int $course The course ID
642      * @param array $quiz Array contingin quiz data
643      * @param int $cm Course Module ID
644      * @param int $context The page contect ID
645      * @param array $messages Array containing any messages
646      */
647     public function view_information($course, $quiz, $cm, $context, $messages) {
648         global $CFG;
649         $output = '';
650         // Print quiz name and description
651         $output .= $this->heading(format_string($quiz->name));
652         if (trim(strip_tags($quiz->intro))) {
653             $output .= $this->box(format_module_intro('quiz', $quiz, $cm->id), 'generalbox',
654                     'intro');
655         }
657         $output .= $this->box($this->access_messages($messages), 'quizinfo');
659         // Show number of attempts summary to those who can view reports.
660         if (has_capability('mod/quiz:viewreports', $context)) {
661             if ($strattemptnum = $this->quiz_attempt_summary_link_to_reports($quiz, $cm,
662                     $context)) {
663                 $output .= html_writer::tag('div', $strattemptnum,
664                         array('class' => 'quizattemptcounts'));
665             }
666         }
667         return $output;
668     }
670     /**
671      * Generates the table heading.
672      */
673     public function view_table_heading() {
674         return $this->heading(get_string('summaryofattempts', 'quiz'));
675     }
677     /**
678      * Generates the table of data
679      *
680      * @param array $quiz Array contining quiz data
681      * @param int $context The page context ID
682      * @param mod_quiz_view_object $viewobj
683      */
684     public function view_table($quiz, $context, $viewobj) {
685         $output = '';
686         if (!$viewobj->attempts) {
687             return $output;
688         }
689         $output .= $this->view_table_heading();
691         // Prepare table header
692         $table = new html_table();
693         $table->attributes['class'] = 'generaltable quizattemptsummary';
694         $table->head = array();
695         $table->align = array();
696         $table->size = array();
697         if ($viewobj->attemptcolumn) {
698             $table->head[] = get_string('attemptnumber', 'quiz');
699             $table->align[] = 'center';
700             $table->size[] = '';
701         }
702         $table->head[] = get_string('timecompleted', 'quiz');
703         $table->align[] = 'left';
704         $table->size[] = '';
705         if ($viewobj->markcolumn) {
706             $table->head[] = get_string('marks', 'quiz') . ' / ' .
707                     quiz_format_grade($quiz, $quiz->sumgrades);
708             $table->align[] = 'center';
709             $table->size[] = '';
710         }
711         if ($viewobj->gradecolumn) {
712             $table->head[] = get_string('grade') . ' / ' .
713                     quiz_format_grade($quiz, $quiz->grade);
714             $table->align[] = 'center';
715             $table->size[] = '';
716         }
717         if ($viewobj->canreviewmine) {
718             $table->head[] = get_string('review', 'quiz');
719             $table->align[] = 'center';
720             $table->size[] = '';
721         }
722         if ($viewobj->feedbackcolumn) {
723             $table->head[] = get_string('feedback', 'quiz');
724             $table->align[] = 'left';
725             $table->size[] = '';
726         }
727         if (isset($quiz->showtimetaken)) {
728             $table->head[] = get_string('timetaken', 'quiz');
729             $table->align[] = 'left';
730             $table->size[] = '';
731         }
733         // One row for each attempt
734         foreach ($viewobj->attempts as $attempt) {
735             $attemptoptions = quiz_get_review_options($quiz, $attempt, $context);
736             $row = array();
738             // Add the attempt number, making it a link, if appropriate.
739             if ($viewobj->attemptcolumn) {
740                 if ($attempt->preview) {
741                     $row[] = get_string('preview', 'quiz');
742                 } else {
743                     $row[] = $attempt->attempt;
744                 }
745             }
747             // prepare strings for time taken and date completed
748             $timetaken = '';
749             $datecompleted = '';
750             if ($attempt->timefinish > 0) {
751                 // attempt has finished
752                 $timetaken = format_time($attempt->timefinish - $attempt->timestart);
753                 $datecompleted = userdate($attempt->timefinish);
754             } else if (!$quiz->timeclose || $viewobj->timenow < $quiz->timeclose) {
755                 // The attempt is still in progress.
756                 $timetaken = format_time($viewobj->timenow - $attempt->timestart);
757                 $datecompleted = get_string('inprogress', 'quiz');
758             } else {
759                 $timetaken = format_time($quiz->timeclose - $attempt->timestart);
760                 $datecompleted = userdate($quiz->timeclose);
761             }
762             $row[] = $datecompleted;
764             if ($viewobj->markcolumn && $attempt->timefinish > 0) {
765                 if ($attemptoptions->marks >= question_display_options::MARK_AND_MAX) {
766                     $row[] = quiz_format_grade($quiz, $attempt->sumgrades);
767                 } else {
768                     $row[] = '';
769                 }
770             }
772             // Ouside the if because we may be showing feedback but not grades.
773             $attemptgrade = quiz_rescale_grade($attempt->sumgrades, $quiz, false);
775             if ($viewobj->gradecolumn) {
776                 if ($attemptoptions->marks >= question_display_options::MARK_AND_MAX &&
777                         $attempt->timefinish > 0) {
778                     $formattedgrade = quiz_format_grade($quiz, $attemptgrade);
779                     // highlight the highest grade if appropriate
780                     if ($viewobj->overallstats && !$attempt->preview
781                             && $viewobj->numattempts > 1 && !is_null($viewobj->mygrade)
782                             && $attemptgrade == $viewobj->mygrade
783                             && $quiz->grademethod == QUIZ_GRADEHIGHEST) {
784                         $table->rowclasses[$attempt->attempt] = 'bestrow';
785                     }
787                     $row[] = $formattedgrade;
788                 } else {
789                     $row[] = '';
790                 }
791             }
793             if ($viewobj->canreviewmine) {
794                 $row[] = $viewobj->accessmanager->make_review_link($attempt,
795                         $viewobj->canpreview, $attemptoptions);
796             }
798             if ($viewobj->feedbackcolumn && $attempt->timefinish > 0) {
799                 if ($attemptoptions->overallfeedback) {
800                     $row[] = quiz_feedback_for_grade($attemptgrade, $quiz, $context);
801                 } else {
802                     $row[] = '';
803                 }
804             }
806             if (isset($quiz->showtimetaken)) {
807                 $row[] = $timetaken;
808             }
810             if ($attempt->preview) {
811                 $table->data['preview'] = $row;
812             } else {
813                 $table->data[$attempt->attempt] = $row;
814             }
815         } // End of loop over attempts.
816         $output .= html_writer::table($table);
818         return $output;
819     }
821     /**
822      * Prints the students best score
823      *
824      * @param mod_quiz_view_object $viewobj
825      */
826     public function view_best_score($viewobj) {
827         $output = '';
828         // Print information about the student's best score for this quiz if possible.
829         if (!$viewobj->moreattempts) {
830             $output .= $this->heading(get_string('nomoreattempts', 'quiz'));
831         }
832         return $output;
833     }
835     /**
836      * Generates data pertaining to quiz results
837      *
838      * @param array $quiz Array containing quiz data
839      * @param int $context The page context ID
840      * @param int $cm The Course Module Id
841      * @param mod_quiz_view_object $viewobj
842      */
843     public function view_result_info($quiz, $context, $cm, $viewobj) {
844         $output = '';
845         if (!$viewobj->numattempts && !$viewobj->gradecolumn && is_null($viewobj->mygrade)) {
846             return $output;
847         }
848         $resultinfo = '';
850         if ($viewobj->overallstats) {
851             if ($viewobj->moreattempts) {
852                 $a = new stdClass();
853                 $a->method = quiz_get_grading_option_name($quiz->grademethod);
854                 $a->mygrade = quiz_format_grade($quiz, $viewobj->mygrade);
855                 $a->quizgrade = quiz_format_grade($quiz, $quiz->grade);
856                 $resultinfo .= $this->heading(get_string('gradesofar', 'quiz', $a), 2, 'main');
857             } else {
858                 $a = new stdClass();
859                 $a->grade = quiz_format_grade($quiz, $viewobj->mygrade);
860                 $a->maxgrade = quiz_format_grade($quiz, $quiz->grade);
861                 $a = get_string('outofshort', 'quiz', $a);
862                 $resultinfo .= $this->heading(get_string('yourfinalgradeis', 'quiz', $a), 2,
863                         'main');
864             }
865         }
867         if ($viewobj->mygradeoverridden) {
869             $resultinfo .= html_writer::tag('p', get_string('overriddennotice', 'grades'),
870                     array('class' => 'overriddennotice'))."\n";
871         }
872         if ($viewobj->gradebookfeedback) {
873             $resultinfo .= $this->heading(get_string('comment', 'quiz'), 3, 'main');
874             $resultinfo .= '<p class="quizteacherfeedback">'.$viewobj->gradebookfeedback.
875                     "</p>\n";
876         }
877         if ($viewobj->feedbackcolumn) {
878             $resultinfo .= $this->heading(get_string('overallfeedback', 'quiz'), 3, 'main');
879             $resultinfo .= html_writer::tag('p',
880                     quiz_feedback_for_grade($viewobj->mygrade, $quiz, $context),
881                     array('class' => 'quizgradefeedback'))."\n";
882         }
884         if ($resultinfo) {
885             $output .= $this->box($resultinfo, 'generalbox', 'feedback');
886         }
887         return $output;
888     }
890     /**
891      * Generates the view attempt button
892      *
893      * @param int $course The course ID
894      * @param array $quiz Array containging quiz date
895      * @param int $cm The Course Module ID
896      * @param int $context The page Context ID
897      * @param mod_quiz_view_object $viewobj
898      * @param string $buttontext
899      */
900     public function view_attempt_button($course, $quiz, $cm, $context, $viewobj,
901             $buttontext, $preventmessages) {
902         $output = '';
903         // Determine if we should be showing a start/continue attempt button,
904         // or a button to go back to the course page.
905         $output .= $this->box_start('quizattempt');
907         // Now actually print the appropriate button.
908         if (!quiz_clean_layout($quiz->questions, true)) {
909             $output .= quiz_no_questions_message($quiz, $cm, $context);
910         }
912         if ($preventmessages) {
913             $output .= $this->access_messages($preventmessages);
914         }
916         if ($buttontext) {
917             $output .= $viewobj->accessmanager->print_start_attempt_button($viewobj->canpreview,
918                     $buttontext, $viewobj->unfinished);
919         } else if ($buttontext === '') {
920             $output .= $this->single_button(new moodle_url('/course/view.php',
921                     array('id' => $course->id)), get_string('backtocourse', 'quiz'), 'get',
922                     array('class' => 'continuebutton'));
923         }
924         $output .= $this->box_end();
926         return $output;
927     }
929     /**
930      * Returns the same as {@link quiz_num_attempt_summary()} but wrapped in a link
931      * to the quiz reports.
932      *
933      * @param object $quiz the quiz object. Only $quiz->id is used at the moment.
934      * @param object $cm the cm object. Only $cm->course, $cm->groupmode and $cm->groupingid
935      * fields are used at the moment.
936      * @param object $context the quiz context.
937      * @param bool $returnzero if false (default), when no attempts have been made '' is returned
938      * instead of 'Attempts: 0'.
939      * @param int $currentgroup if there is a concept of current group where this method is being
940      * called
941      *         (e.g. a report) pass it in here. Default 0 which means no current group.
942      * @return string HTML fragment for the link.
943      */
944     public function quiz_attempt_summary_link_to_reports($quiz, $cm, $context,
945                                                           $returnzero = false, $currentgroup = 0) {
946         global $CFG;
947         $summary = quiz_num_attempt_summary($quiz, $cm, $returnzero, $currentgroup);
948         if (!$summary) {
949             return '';
950         }
952         require_once($CFG->dirroot . '/mod/quiz/report/reportlib.php');
953         $url = new moodle_url('/mod/quiz/report.php', array(
954                 'id' => $cm->id, 'mode' => quiz_report_default_report($context)));
955         return html_writer::link($url, $summary);
956     }
959 class mod_quiz_links_to_other_attempts implements renderable {
960     /**
961      * @var array string attempt number => url, or null for the current attempt.
962      */
963     public $links = array();
966 class mod_quiz_view_object {
967     /**
968      * @var array $attempt contains all the user's attempts at this quiz.
969      */
970     public $attempts;
971     /**
972      * @var object $accessmanager contains various access rules.
973      */
974     public $accessmanager;
975     /**
976      * @var int $canattempt determins capability for attempting a quiz.
977      */
978     public $canattempt;
979     /**
980      * @var int $canpreview determins capability for previewing a quiz.
981      */
982     public $canpreview;
983     /**
984      * @var int $canreviewmine determins capability for reviwing own quiz.
985      */
986     public $canreviewmine;
987     /**
988      * @var int $attemptcolumn contains the number of attempts done.
989      */
990     public $attemptcolumn;
991     /**
992      * @var int $gradecolumn contains the grades of any attempts.
993      */
994     public $gradecolumn;
995     /**
996      * @var int $markcolumn contains the marks of any attempt.
997      */
998     public $markcolumn;
999     /**
1000      * @var int $overallstats contains all marks for any attempt.
1001      */
1002     public $overallstats;
1003     /**
1004      * @var string $feedbackcolumn contains any feedback for and attempt.
1005      */
1006     public $feedbackcolumn;
1007     /**
1008      * @var string $timenow contains a timestamp in string format.
1009      */
1010     public $timenow;
1011     /**
1012      * @var int $numattempts contains the total number of attempts.
1013      */
1014     public $numattempts;
1015     /**
1016      * @var int $mygrade contains the current users final grade for a quiz.
1017      */
1018     public $mygrade;
1019     /**
1020      * @var int $moreattempts total attempts left.
1021      */
1022     public $moreattempts;
1023     /**
1024      * @var int $mygradeoverridden contains an overriden grade.
1025      */
1026     public $mygradeoverridden;
1027     /**
1028      * @var string $gradebookfeedback contains any feedback for a gradebook.
1029      */
1030     public $gradebookfeedback;
1031     /**
1032      * @var int $unfinished contains 1 if an attempt is unfinished.
1033      */
1034     public $unfinished;
1035     /**
1036      * @var int $lastfinishedattempt contains a pointer to the last attempt in the attempts array.
1037      */
1038     public $lastfinishedattempt;