Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.

Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 39 and 401] [Versions 400 and 401] [Versions 401 and 402] [Versions 401 and 403]

   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/>.
  16  
  17  /**
  18   * Defines the renderer for the quiz module.
  19   *
  20   * @package   mod_quiz
  21   * @copyright 2011 The Open University
  22   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23   */
  24  
  25  
  26  defined('MOODLE_INTERNAL') || die();
  27  
  28  
  29  /**
  30   * The renderer for the quiz module.
  31   *
  32   * @copyright  2011 The Open University
  33   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  34   */
  35  class mod_quiz_renderer extends plugin_renderer_base {
  36      /**
  37       * Builds the review page
  38       *
  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.
  47       */
  48      public function review_page(quiz_attempt $attemptobj, $slots, $page, $showall,
  49                                  $lastpage, mod_quiz_display_options $displayoptions,
  50                                  $summarydata) {
  51  
  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);
  58  
  59          $output .= $this->review_next_navigation($attemptobj, $page, $lastpage, $showall);
  60          $output .= $this->footer();
  61          return $output;
  62      }
  63  
  64      /**
  65       * Renders the review question pop-up.
  66       *
  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.
  73       */
  74      public function review_question_page(quiz_attempt $attemptobj, $slot, $seq,
  75              mod_quiz_display_options $displayoptions, $summarydata) {
  76  
  77          $output = '';
  78          $output .= $this->header();
  79          $output .= $this->review_summary_table($summarydata, 0);
  80  
  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);
  85          }
  86  
  87          $output .= $this->close_window_button();
  88          $output .= $this->footer();
  89          return $output;
  90      }
  91  
  92      /**
  93       * Renders the review question pop-up.
  94       *
  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.
  98       */
  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;
 108      }
 109  
 110      /**
 111       * Filters the summarydata array.
 112       *
 113       * @param array $summarydata contains row data for table
 114       * @param int $page the current page number
 115       * @return $summarydata containing filtered row data
 116       */
 117      protected function filter_review_summary_table($summarydata, $page) {
 118          if ($page == 0) {
 119              return $summarydata;
 120          }
 121  
 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]);
 126              }
 127          }
 128  
 129          return $summarydata;
 130      }
 131  
 132      /**
 133       * Outputs the table containing data from summary data array
 134       *
 135       * @param array $summarydata contains row data for table
 136       * @param int $page contains the current page number
 137       */
 138      public function review_summary_table($summarydata, $page) {
 139          $summarydata = $this->filter_review_summary_table($summarydata, $page);
 140          if (empty($summarydata)) {
 141              return '';
 142          }
 143  
 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'];
 153              }
 154  
 155              if ($rowdata['content'] instanceof renderable) {
 156                  $content = $this->render($rowdata['content']);
 157              } else {
 158                  $content = $rowdata['content'];
 159              }
 160  
 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'))
 164              );
 165          }
 166  
 167          $output .= html_writer::end_tag('tbody');
 168          $output .= html_writer::end_tag('table');
 169          return $output;
 170      }
 171  
 172      /**
 173       * Renders each question
 174       *
 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
 181       */
 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));
 188          }
 189          return $output;
 190      }
 191  
 192      /**
 193       * Renders the main bit of the review page.
 194       *
 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
 201       */
 202      public function review_form($page, $showall, $displayoptions, $content, $attemptobj) {
 203          if ($displayoptions->flags != question_display_options::EDITABLE) {
 204              return $content;
 205          }
 206  
 207          $this->page->requires->js_init_call('M.mod_quiz.init_review_form', null, false,
 208                  quiz_get_js_module());
 209  
 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');
 224  
 225          return $output;
 226      }
 227  
 228      /**
 229       * Returns either a liink or button
 230       *
 231       * @param quiz_attempt $attemptobj instance of quiz_attempt
 232       */
 233      public function finish_review_link(quiz_attempt $attemptobj) {
 234          $url = $attemptobj->view_url();
 235  
 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'));
 243  
 244          } else {
 245              return html_writer::link($url, get_string('finishreview', 'quiz'),
 246                      array('class' => 'mod_quiz-next-nav'));
 247          }
 248      }
 249  
 250      /**
 251       * Creates the navigation links/buttons at the bottom of the reivew attempt page.
 252       *
 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.
 255       *
 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.
 261       *
 262       * @return string HTML fragment.
 263       */
 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');
 269          }
 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');
 275          }
 276          return html_writer::tag('div', $nav, array('class' => 'submitbtns'));
 277      }
 278  
 279      /**
 280       * Return the HTML of the quiz timer.
 281       * @return string HTML content.
 282       */
 283      public function countdown_timer(quiz_attempt $attemptobj, $timenow) {
 284  
 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);
 293              }
 294              $this->initialise_timer($timerstartvalue, $ispreview);
 295          }
 296  
 297  
 298          return $this->output->render_from_template('mod_quiz/timer', (object)[]);
 299      }
 300  
 301      /**
 302       * Create a preview link
 303       *
 304       * @param moodle_url $url contains a url to the given page
 305       */
 306      public function restart_preview_button($url) {
 307          return $this->single_button($url, get_string('startnewpreview', 'quiz'));
 308      }
 309  
 310      /**
 311       * Outputs the navigation block panel
 312       *
 313       * @param quiz_nav_panel_base $panel instance of quiz_nav_panel_base
 314       */
 315      public function navigation_panel(quiz_nav_panel_base $panel) {
 316  
 317          $output = '';
 318          $userpicture = $panel->user_picture();
 319          if ($userpicture) {
 320              $fullname = fullname($userpicture->user);
 321              if ($userpicture->size === true) {
 322                  $fullname = html_writer::div($fullname);
 323              }
 324              $output .= html_writer::tag('div', $this->render($userpicture) . $fullname,
 325                      array('id' => 'user-picture', 'class' => 'clearfix'));
 326          }
 327          $output .= $panel->render_before_button_bits($this);
 328  
 329          $bcc = $panel->get_button_container_class();
 330          $output .= html_writer::start_tag('div', array('class' => "qn_buttons clearfix $bcc"));
 331          foreach ($panel->get_question_buttons() as $button) {
 332              $output .= $this->render($button);
 333          }
 334          $output .= html_writer::end_tag('div');
 335  
 336          $output .= html_writer::tag('div', $panel->render_end_bits($this),
 337                  array('class' => 'othernav'));
 338  
 339          $this->page->requires->js_init_call('M.mod_quiz.nav.init', null, false,
 340                  quiz_get_js_module());
 341  
 342          return $output;
 343      }
 344  
 345      /**
 346       * Display a quiz navigation button.
 347       *
 348       * @param quiz_nav_question_button $button
 349       * @return string HTML fragment.
 350       */
 351      protected function render_quiz_nav_question_button(quiz_nav_question_button $button) {
 352          $classes = array('qnbutton', $button->stateclass, $button->navmethod, 'btn');
 353          $extrainfo = array();
 354  
 355          if ($button->currentpage) {
 356              $classes[] = 'thispage';
 357              $extrainfo[] = get_string('onthispage', 'quiz');
 358          }
 359  
 360          // Flagged?
 361          if ($button->flagged) {
 362              $classes[] = 'flagged';
 363              $flaglabel = get_string('flagged', 'question');
 364          } else {
 365              $flaglabel = '';
 366          }
 367          $extrainfo[] = html_writer::tag('span', $flaglabel, array('class' => 'flagstate'));
 368  
 369          if (is_numeric($button->number)) {
 370              $qnostring = 'questionnonav';
 371          } else {
 372              $qnostring = 'questionnonavinfo';
 373          }
 374  
 375          $a = new stdClass();
 376          $a->number = $button->number;
 377          $a->attributes = implode(' ', $extrainfo);
 378          $tagcontents = html_writer::tag('span', '', array('class' => 'thispageholder')) .
 379                          html_writer::tag('span', '', array('class' => 'trafficlight')) .
 380                          get_string($qnostring, 'quiz', $a);
 381          $tagattributes = array('class' => implode(' ', $classes), 'id' => $button->id,
 382                                    'title' => $button->statestring, 'data-quiz-page' => $button->page);
 383  
 384          if ($button->url) {
 385              return html_writer::link($button->url, $tagcontents, $tagattributes);
 386          } else {
 387              return html_writer::tag('span', $tagcontents, $tagattributes);
 388          }
 389      }
 390  
 391      /**
 392       * Display a quiz navigation heading.
 393       *
 394       * @param quiz_nav_section_heading $heading the heading.
 395       * @return string HTML fragment.
 396       */
 397      protected function render_quiz_nav_section_heading(quiz_nav_section_heading $heading) {
 398          if (empty($heading->heading)) {
 399              $headingtext = get_string('sectionnoname', 'quiz');
 400              $class = ' dimmed_text';
 401          } else {
 402              $headingtext = $heading->heading;
 403              $class = '';
 404          }
 405          return $this->heading($headingtext, 3, 'mod_quiz-section-heading' . $class);
 406      }
 407  
 408      /**
 409       * outputs the link the other attempts.
 410       *
 411       * @param mod_quiz_links_to_other_attempts $links
 412       */
 413      protected function render_mod_quiz_links_to_other_attempts(
 414              mod_quiz_links_to_other_attempts $links) {
 415          $attemptlinks = array();
 416          foreach ($links->links as $attempt => $url) {
 417              if (!$url) {
 418                  $attemptlinks[] = html_writer::tag('strong', $attempt);
 419              } else if ($url instanceof renderable) {
 420                  $attemptlinks[] = $this->render($url);
 421              } else {
 422                  $attemptlinks[] = html_writer::link($url, $attempt);
 423              }
 424          }
 425          return implode(', ', $attemptlinks);
 426      }
 427  
 428      public function start_attempt_page(quiz $quizobj, mod_quiz_preflight_check_form $mform) {
 429          $output = '';
 430          $output .= $this->header();
 431          $output .= $this->during_attempt_tertiary_nav($quizobj->view_url());
 432          $output .= $this->heading(format_string($quizobj->get_quiz_name(), true,
 433                                    array("context" => $quizobj->get_context())));
 434          $output .= $this->quiz_intro($quizobj->get_quiz(), $quizobj->get_cm());
 435          $output .= $mform->render();
 436          $output .= $this->footer();
 437          return $output;
 438      }
 439  
 440      /**
 441       * Attempt Page
 442       *
 443       * @param quiz_attempt $attemptobj Instance of quiz_attempt
 444       * @param int $page Current page number
 445       * @param quiz_access_manager $accessmanager Instance of quiz_access_manager
 446       * @param array $messages An array of messages
 447       * @param array $slots Contains an array of integers that relate to questions
 448       * @param int $id The ID of an attempt
 449       * @param int $nextpage The number of the next page
 450       * @return string HTML to output.
 451       */
 452      public function attempt_page($attemptobj, $page, $accessmanager, $messages, $slots, $id,
 453              $nextpage) {
 454          $output = '';
 455          $output .= $this->header();
 456          $output .= $this->during_attempt_tertiary_nav($attemptobj->view_url());
 457          $output .= $this->quiz_notices($messages);
 458          $output .= $this->countdown_timer($attemptobj, time());
 459          $output .= $this->attempt_form($attemptobj, $page, $slots, $id, $nextpage);
 460          $output .= $this->footer();
 461          return $output;
 462      }
 463  
 464      /**
 465       * Render the tertiary navigation for pages during the attempt.
 466       *
 467       * @param string|moodle_url $quizviewurl url of the view.php page for this quiz.
 468       * @return string HTML to output.
 469       */
 470      public function during_attempt_tertiary_nav($quizviewurl): string {
 471          $output = '';
 472          $output .= html_writer::start_div('container-fluid tertiary-navigation');
 473          $output .= html_writer::start_div('row');
 474          $output .= html_writer::start_div('navitem');
 475          $output .= html_writer::link($quizviewurl, get_string('back'),
 476                  ['class' => 'btn btn-secondary']);
 477          $output .= html_writer::end_div();
 478          $output .= html_writer::end_div();
 479          $output .= html_writer::end_div();
 480          return $output;
 481      }
 482  
 483      /**
 484       * Returns any notices.
 485       *
 486       * @param array $messages
 487       */
 488      public function quiz_notices($messages) {
 489          if (!$messages) {
 490              return '';
 491          }
 492          return $this->notification(
 493              html_writer::tag('p', get_string('accessnoticesheader', 'quiz')) . $this->access_messages($messages),
 494              'warning',
 495              false
 496          );
 497      }
 498  
 499      /**
 500       * Ouputs the form for making an attempt
 501       *
 502       * @param quiz_attempt $attemptobj
 503       * @param int $page Current page number
 504       * @param array $slots Array of integers relating to questions
 505       * @param int $id ID of the attempt
 506       * @param int $nextpage Next page number
 507       */
 508      public function attempt_form($attemptobj, $page, $slots, $id, $nextpage) {
 509          $output = '';
 510  
 511          // Start the form.
 512          $output .= html_writer::start_tag('form',
 513                  array('action' => new moodle_url($attemptobj->processattempt_url(),
 514                  array('cmid' => $attemptobj->get_cmid())), 'method' => 'post',
 515                  'enctype' => 'multipart/form-data', 'accept-charset' => 'utf-8',
 516                  'id' => 'responseform'));
 517          $output .= html_writer::start_tag('div');
 518  
 519          // Print all the questions.
 520          foreach ($slots as $slot) {
 521              $output .= $attemptobj->render_question($slot, false, $this,
 522                      $attemptobj->attempt_url($slot, $page), $this);
 523          }
 524  
 525          $navmethod = $attemptobj->get_quiz()->navmethod;
 526          $output .= $this->attempt_navigation_buttons($page, $attemptobj->is_last_page($page), $navmethod);
 527  
 528          // Some hidden fields to trach what is going on.
 529          $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'attempt',
 530                  'value' => $attemptobj->get_attemptid()));
 531          $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'thispage',
 532                  'value' => $page, 'id' => 'followingpage'));
 533          $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'nextpage',
 534                  'value' => $nextpage));
 535          $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'timeup',
 536                  'value' => '0', 'id' => 'timeup'));
 537          $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'sesskey',
 538                  'value' => sesskey()));
 539          $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'scrollpos',
 540                  'value' => '', 'id' => 'scrollpos'));
 541  
 542          // Add a hidden field with questionids. Do this at the end of the form, so
 543          // if you navigate before the form has finished loading, it does not wipe all
 544          // the student's answers.
 545          $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'slots',
 546                  'value' => implode(',', $attemptobj->get_active_slots($page))));
 547  
 548          // Finish the form.
 549          $output .= html_writer::end_tag('div');
 550          $output .= html_writer::end_tag('form');
 551  
 552          $output .= $this->connection_warning();
 553  
 554          return $output;
 555      }
 556  
 557      /**
 558       * Display the prev/next buttons that go at the bottom of each page of the attempt.
 559       *
 560       * @param int $page the page number. Starts at 0 for the first page.
 561       * @param bool $lastpage is this the last page in the quiz?
 562       * @param string $navmethod Optional quiz attribute, 'free' (default) or 'sequential'
 563       * @return string HTML fragment.
 564       */
 565      protected function attempt_navigation_buttons($page, $lastpage, $navmethod = 'free') {
 566          $output = '';
 567  
 568          $output .= html_writer::start_tag('div', array('class' => 'submitbtns'));
 569          if ($page > 0 && $navmethod == 'free') {
 570              $output .= html_writer::empty_tag('input', array('type' => 'submit', 'name' => 'previous',
 571                      'value' => get_string('navigateprevious', 'quiz'), 'class' => 'mod_quiz-prev-nav btn btn-secondary',
 572                      'id' => 'mod_quiz-prev-nav'));
 573              $this->page->requires->js_call_amd('core_form/submit', 'init', ['mod_quiz-prev-nav']);
 574          }
 575          if ($lastpage) {
 576              $nextlabel = get_string('endtest', 'quiz');
 577          } else {
 578              $nextlabel = get_string('navigatenext', 'quiz');
 579          }
 580          $output .= html_writer::empty_tag('input', array('type' => 'submit', 'name' => 'next',
 581                  'value' => $nextlabel, 'class' => 'mod_quiz-next-nav btn btn-primary', 'id' => 'mod_quiz-next-nav'));
 582          $output .= html_writer::end_tag('div');
 583          $this->page->requires->js_call_amd('core_form/submit', 'init', ['mod_quiz-next-nav']);
 584  
 585          return $output;
 586      }
 587  
 588      /**
 589       * Render a button which allows students to redo a question in the attempt.
 590       *
 591       * @param int $slot the number of the slot to generate the button for.
 592       * @param bool $disabled if true, output the button disabled.
 593       * @return string HTML fragment.
 594       */
 595      public function redo_question_button($slot, $disabled) {
 596          $attributes = array('type' => 'submit',  'name' => 'redoslot' . $slot,
 597              'value' => get_string('redoquestion', 'quiz'),
 598              'class' => 'mod_quiz-redo_question_button btn btn-secondary');
 599          if ($disabled) {
 600              $attributes['disabled'] = 'disabled';
 601          }
 602          return html_writer::div(html_writer::empty_tag('input', $attributes));
 603      }
 604  
 605      /**
 606       * Output the JavaScript required to initialise the countdown timer.
 607       * @param int $timerstartvalue time remaining, in seconds.
 608       */
 609      public function initialise_timer($timerstartvalue, $ispreview) {
 610          $options = array($timerstartvalue, (bool)$ispreview);
 611          $this->page->requires->js_init_call('M.mod_quiz.timer.init', $options, false, quiz_get_js_module());
 612      }
 613  
 614      /**
 615       * Output a page with an optional message, and JavaScript code to close the
 616       * current window and redirect the parent window to a new URL.
 617       * @param moodle_url $url the URL to redirect the parent window to.
 618       * @param string $message message to display before closing the window. (optional)
 619       * @return string HTML to output.
 620       */
 621      public function close_attempt_popup($url, $message = '') {
 622          $output = '';
 623          $output .= $this->header();
 624          $output .= $this->box_start();
 625  
 626          if ($message) {
 627              $output .= html_writer::tag('p', $message);
 628              $output .= html_writer::tag('p', get_string('windowclosing', 'quiz'));
 629              $delay = 5;
 630          } else {
 631              $output .= html_writer::tag('p', get_string('pleaseclose', 'quiz'));
 632              $delay = 0;
 633          }
 634          $this->page->requires->js_init_call('M.mod_quiz.secure_window.close',
 635                  array($url, $delay), false, quiz_get_js_module());
 636  
 637          $output .= $this->box_end();
 638          $output .= $this->footer();
 639          return $output;
 640      }
 641  
 642      /**
 643       * Print each message in an array, surrounded by &lt;p>, &lt;/p> tags.
 644       *
 645       * @param array $messages the array of message strings.
 646       * @param bool $return if true, return a string, instead of outputting.
 647       *
 648       * @return string HTML to output.
 649       */
 650      public function access_messages($messages) {
 651          $output = '';
 652          foreach ($messages as $message) {
 653              $output .= html_writer::tag('p', $message, ['class' => 'text-left']);
 654          }
 655          return $output;
 656      }
 657  
 658      /*
 659       * Summary Page
 660       */
 661      /**
 662       * Create the summary page
 663       *
 664       * @param quiz_attempt $attemptobj
 665       * @param mod_quiz_display_options $displayoptions
 666       */
 667      public function summary_page($attemptobj, $displayoptions) {
 668          $output = '';
 669          $output .= $this->header();
 670          $output .= $this->during_attempt_tertiary_nav($attemptobj->view_url());
 671          $output .= $this->heading(format_string($attemptobj->get_quiz_name()));
 672          $output .= $this->heading(get_string('summaryofattempt', 'quiz'), 3);
 673          $output .= $this->summary_table($attemptobj, $displayoptions);
 674          $output .= $this->summary_page_controls($attemptobj);
 675          $output .= $this->footer();
 676          return $output;
 677      }
 678  
 679      /**
 680       * Generates the table of summarydata
 681       *
 682       * @param quiz_attempt $attemptobj
 683       * @param mod_quiz_display_options $displayoptions
 684       */
 685      public function summary_table($attemptobj, $displayoptions) {
 686          // Prepare the summary table header.
 687          $table = new html_table();
 688          $table->attributes['class'] = 'generaltable quizsummaryofattempt boxaligncenter';
 689          $table->head = array(get_string('question', 'quiz'), get_string('status', 'quiz'));
 690          $table->align = array('left', 'left');
 691          $table->size = array('', '');
 692          $markscolumn = $displayoptions->marks >= question_display_options::MARK_AND_MAX;
 693          if ($markscolumn) {
 694              $table->head[] = get_string('marks', 'quiz');
 695              $table->align[] = 'left';
 696              $table->size[] = '';
 697          }
 698          $tablewidth = count($table->align);
 699          $table->data = array();
 700  
 701          // Get the summary info for each question.
 702          $slots = $attemptobj->get_slots();
 703          foreach ($slots as $slot) {
 704              // Add a section headings if we need one here.
 705              $heading = $attemptobj->get_heading_before_slot($slot);
 706              if ($heading !== null) {
 707                  // There is a heading here.
 708                  $rowclasses = 'quizsummaryheading';
 709                  if ($heading) {
 710                      $heading = format_string($heading);
 711                  } else if (count($attemptobj->get_quizobj()->get_sections()) > 1) {
 712                      // If this is the start of an unnamed section, and the quiz has more
 713                      // than one section, then add a default heading.
 714                      $heading = get_string('sectionnoname', 'quiz');
 715                      $rowclasses .= ' dimmed_text';
 716                  }
 717                  $cell = new html_table_cell(format_string($heading));
 718                  $cell->header = true;
 719                  $cell->colspan = $tablewidth;
 720                  $table->data[] = array($cell);
 721                  $table->rowclasses[] = $rowclasses;
 722              }
 723  
 724              // Don't display information items.
 725              if (!$attemptobj->is_real_question($slot)) {
 726                  continue;
 727              }
 728  
 729              // Real question, show it.
 730              $flag = '';
 731              if ($attemptobj->is_question_flagged($slot)) {
 732                  // Quiz has custom JS manipulating these image tags - so we can't use the pix_icon method here.
 733                  $flag = html_writer::empty_tag('img', array('src' => $this->image_url('i/flagged'),
 734                          'alt' => get_string('flagged', 'question'), 'class' => 'questionflag icon-post'));
 735              }
 736              if ($attemptobj->can_navigate_to($slot)) {
 737                  $row = array(html_writer::link($attemptobj->attempt_url($slot),
 738                          $attemptobj->get_question_number($slot) . $flag),
 739                          $attemptobj->get_question_status($slot, $displayoptions->correctness));
 740              } else {
 741                  $row = array($attemptobj->get_question_number($slot) . $flag,
 742                                  $attemptobj->get_question_status($slot, $displayoptions->correctness));
 743              }
 744              if ($markscolumn) {
 745                  $row[] = $attemptobj->get_question_mark($slot);
 746              }
 747              $table->data[] = $row;
 748              $table->rowclasses[] = 'quizsummary' . $slot . ' ' . $attemptobj->get_question_state_class(
 749                      $slot, $displayoptions->correctness);
 750          }
 751  
 752          // Print the summary table.
 753          $output = html_writer::table($table);
 754  
 755          return $output;
 756      }
 757  
 758      /**
 759       * Creates any controls a the page should have.
 760       *
 761       * @param quiz_attempt $attemptobj
 762       */
 763      public function summary_page_controls($attemptobj) {
 764          $output = '';
 765  
 766          // Return to place button.
 767          if ($attemptobj->get_state() == quiz_attempt::IN_PROGRESS) {
 768              $button = new single_button(
 769                      new moodle_url($attemptobj->attempt_url(null, $attemptobj->get_currentpage())),
 770                      get_string('returnattempt', 'quiz'));
 771              $output .= $this->container($this->container($this->render($button),
 772                      'controls'), 'submitbtns mdl-align');
 773          }
 774  
 775          // Finish attempt button.
 776          $options = array(
 777              'attempt' => $attemptobj->get_attemptid(),
 778              'finishattempt' => 1,
 779              'timeup' => 0,
 780              'slots' => '',
 781              'cmid' => $attemptobj->get_cmid(),
 782              'sesskey' => sesskey(),
 783          );
 784  
 785          $button = new single_button(
 786                  new moodle_url($attemptobj->processattempt_url(), $options),
 787                  get_string('submitallandfinish', 'quiz'));
 788          $button->id = 'responseform';
 789          $button->class = 'btn-finishattempt';
 790          $button->formid = 'frm-finishattempt';
 791          if ($attemptobj->get_state() == quiz_attempt::IN_PROGRESS) {
 792              $totalunanswered = 0;
 793              if ($attemptobj->get_quiz()->navmethod == 'free') {
 794                  // Only count the unanswered question if the navigation method is set to free.
 795                  $totalunanswered = $attemptobj->get_number_of_unanswered_questions();
 796              }
 797              $this->page->requires->js_call_amd('mod_quiz/submission_confirmation', 'init', [$totalunanswered]);
 798          }
 799          $button->primary = true;
 800  
 801          $duedate = $attemptobj->get_due_date();
 802          $message = '';
 803          if ($attemptobj->get_state() == quiz_attempt::OVERDUE) {
 804              $message = get_string('overduemustbesubmittedby', 'quiz', userdate($duedate));
 805  
 806          } else if ($duedate) {
 807              $message = get_string('mustbesubmittedby', 'quiz', userdate($duedate));
 808          }
 809  
 810          $output .= $this->countdown_timer($attemptobj, time());
 811          $output .= $this->container($message . $this->container(
 812                  $this->render($button), 'controls'), 'submitbtns mdl-align');
 813  
 814          return $output;
 815      }
 816  
 817      /*
 818       * View Page
 819       */
 820      /**
 821       * Generates the view page
 822       *
 823       * @param stdClass $course the course settings row from the database.
 824       * @param stdClass $quiz the quiz settings row from the database.
 825       * @param stdClass $cm the course_module settings row from the database.
 826       * @param context_module $context the quiz context.
 827       * @param mod_quiz_view_object $viewobj
 828       * @return string HTML to display
 829       */
 830      public function view_page($course, $quiz, $cm, $context, $viewobj) {
 831          $output = '';
 832  
 833          $output .= $this->view_page_tertiary_nav($viewobj);
 834          $output .= $this->view_information($quiz, $cm, $context, $viewobj->infomessages);
 835          $output .= $this->view_table($quiz, $context, $viewobj);
 836          $output .= $this->view_result_info($quiz, $context, $cm, $viewobj);
 837          $output .= $this->box($this->view_page_buttons($viewobj), 'quizattempt');
 838          return $output;
 839      }
 840  
 841      /**
 842       * Render the tertiary navigation for the view page.
 843       *
 844       * @param mod_quiz_view_object $viewobj the information required to display the view page.
 845       * @return string HTML to output.
 846       */
 847      public function view_page_tertiary_nav(mod_quiz_view_object $viewobj): string {
 848          $content = '';
 849  
 850          if ($viewobj->buttontext) {
 851              $attemptbtn = $this->start_attempt_button($viewobj->buttontext,
 852                      $viewobj->startattempturl, $viewobj->preflightcheckform,
 853                      $viewobj->popuprequired, $viewobj->popupoptions);
 854              $content .= $attemptbtn;
 855          }
 856  
 857          if ($viewobj->canedit && !$viewobj->quizhasquestions) {
 858              $content .= html_writer::link($viewobj->editurl, get_string('addquestion', 'quiz'),
 859                      ['class' => 'btn btn-secondary']);
 860          }
 861  
 862          if ($content) {
 863              return html_writer::div(html_writer::div($content, 'row'), 'container-fluid tertiary-navigation');
 864          } else {
 865              return '';
 866          }
 867      }
 868  
 869      /**
 870       * Work out, and render, whatever buttons, and surrounding info, should appear
 871       * at the end of the review page.
 872       *
 873       * @param mod_quiz_view_object $viewobj the information required to display the view page.
 874       * @return string HTML to output.
 875       */
 876      public function view_page_buttons(mod_quiz_view_object $viewobj) {
 877          $output = '';
 878  
 879          if (!$viewobj->quizhasquestions) {
 880              $output .= html_writer::div(
 881                      $this->notification(get_string('noquestions', 'quiz'), 'warning', false),
 882                      'text-left mb-3');
 883          }
 884          $output .= $this->access_messages($viewobj->preventmessages);
 885  
 886          if ($viewobj->showbacktocourse) {
 887              $output .= $this->single_button($viewobj->backtocourseurl,
 888                      get_string('backtocourse', 'quiz'), 'get',
 889                      array('class' => 'continuebutton'));
 890          }
 891  
 892          return $output;
 893      }
 894  
 895      /**
 896       * Generates the view attempt button
 897       *
 898       * @param string $buttontext the label to display on the button.
 899       * @param moodle_url $url The URL to POST to in order to start the attempt.
 900       * @param mod_quiz_preflight_check_form $preflightcheckform deprecated.
 901       * @param bool $popuprequired whether the attempt needs to be opened in a pop-up.
 902       * @param array $popupoptions the options to use if we are opening a popup.
 903       * @return string HTML fragment.
 904       */
 905      public function start_attempt_button($buttontext, moodle_url $url,
 906              mod_quiz_preflight_check_form $preflightcheckform = null,
 907              $popuprequired = false, $popupoptions = null) {
 908  
 909          if (is_string($preflightcheckform)) {
 910              // Calling code was not updated since the API change.
 911              debugging('The third argument to start_attempt_button should now be the ' .
 912                      'mod_quiz_preflight_check_form from ' .
 913                      'quiz_access_manager::get_preflight_check_form, not a warning message string.');
 914          }
 915  
 916          $button = new single_button($url, $buttontext, 'post', true);
 917          $button->class .= ' quizstartbuttondiv';
 918          if ($popuprequired) {
 919              $button->class .= ' quizsecuremoderequired';
 920          }
 921  
 922          $popupjsoptions = null;
 923          if ($popuprequired && $popupoptions) {
 924              $action = new popup_action('click', $url, 'popup', $popupoptions);
 925              $popupjsoptions = $action->get_js_options();
 926          }
 927  
 928          if ($preflightcheckform) {
 929              $checkform = $preflightcheckform->render();
 930          } else {
 931              $checkform = null;
 932          }
 933  
 934          $this->page->requires->js_call_amd('mod_quiz/preflightcheck', 'init',
 935                  array('.quizstartbuttondiv [type=submit]', get_string('startattempt', 'quiz'),
 936                         '#mod_quiz_preflight_form', $popupjsoptions));
 937  
 938          return $this->render($button) . $checkform;
 939      }
 940  
 941      /**
 942       * Generate a message saying that this quiz has no questions, with a button to
 943       * go to the edit page, if the user has the right capability.
 944       *
 945       * @param bool $canedit can the current user edit the quiz?
 946       * @param moodle_url $editurl URL of the edit quiz page.
 947       * @return string HTML to output.
 948       *
 949       * @deprecated since Moodle 4.0 MDL-71915 - please do not use this function any more.
 950       */
 951      public function no_questions_message($canedit, $editurl) {
 952          debugging('no_questions_message() is deprecated, please use generate_no_questions_message() instead.', DEBUG_DEVELOPER);
 953  
 954          $output = html_writer::start_tag('div', array('class' => 'card text-center mb-3'));
 955          $output .= html_writer::start_tag('div', array('class' => 'card-body'));
 956  
 957          $output .= $this->notification(get_string('noquestions', 'quiz'), 'warning', false);
 958          if ($canedit) {
 959              $output .= $this->single_button($editurl, get_string('editquiz', 'quiz'), 'get');
 960          }
 961          $output .= html_writer::end_tag('div');
 962          $output .= html_writer::end_tag('div');
 963  
 964          return $output;
 965      }
 966  
 967      /**
 968       * Outputs an error message for any guests accessing the quiz
 969       *
 970       * @param stdClass $course the course settings row from the database.
 971       * @param stdClass $quiz the quiz settings row from the database.
 972       * @param stdClass $cm the course_module settings row from the database.
 973       * @param context_module $context the quiz context.
 974       * @param array $messages Array containing any messages
 975       * @param mod_quiz_view_object $viewobj
 976       */
 977      public function view_page_guest($course, $quiz, $cm, $context, $messages, $viewobj) {
 978          $output = '';
 979          $output .= $this->view_page_tertiary_nav($viewobj);
 980          $output .= $this->view_information($quiz, $cm, $context, $messages);
 981          $guestno = html_writer::tag('p', get_string('guestsno', 'quiz'));
 982          $liketologin = html_writer::tag('p', get_string('liketologin'));
 983          $referer = get_local_referer(false);
 984          $output .= $this->confirm($guestno."\n\n".$liketologin."\n", get_login_url(), $referer);
 985          return $output;
 986      }
 987  
 988      /**
 989       * Outputs and error message for anyone who is not enrolle don the course
 990       *
 991       * @param stdClass $course the course settings row from the database.
 992       * @param stdClass $quiz the quiz settings row from the database.
 993       * @param stdClass $cm the course_module settings row from the database.
 994       * @param context_module $context the quiz context.
 995       * @param array $messages Array containing any messages
 996       * @param mod_quiz_view_object $viewobj
 997       */
 998      public function view_page_notenrolled($course, $quiz, $cm, $context, $messages, $viewobj) {
 999          global $CFG;
1000          $output = '';
1001          $output .= $this->view_page_tertiary_nav($viewobj);
1002          $output .= $this->view_information($quiz, $cm, $context, $messages);
1003          $youneedtoenrol = html_writer::tag('p', get_string('youneedtoenrol', 'quiz'));
1004          $button = html_writer::tag('p',
1005                  $this->continue_button($CFG->wwwroot . '/course/view.php?id=' . $course->id));
1006          $output .= $this->box($youneedtoenrol."\n\n".$button."\n", 'generalbox', 'notice');
1007          return $output;
1008      }
1009  
1010      /**
1011       * Output the page information
1012       *
1013       * @param object $quiz the quiz settings.
1014       * @param object $cm the course_module object.
1015       * @param context $context the quiz context.
1016       * @param array $messages any access messages that should be described.
1017       * @param bool $quizhasquestions does quiz has questions added.
1018       * @return string HTML to output.
1019       */
1020      public function view_information($quiz, $cm, $context, $messages, bool $quizhasquestions = false) {
1021          $output = '';
1022  
1023          // Output any access messages.
1024          if ($messages) {
1025              $output .= $this->box($this->access_messages($messages), 'quizinfo');
1026          }
1027  
1028          // Show number of attempts summary to those who can view reports.
1029          if (has_capability('mod/quiz:viewreports', $context)) {
1030              if ($strattemptnum = $this->quiz_attempt_summary_link_to_reports($quiz, $cm,
1031                      $context)) {
1032                  $output .= html_writer::tag('div', $strattemptnum,
1033                          array('class' => 'quizattemptcounts'));
1034              }
1035          }
1036  
1037          if (has_any_capability(['mod/quiz:manageoverrides', 'mod/quiz:viewoverrides'], $context)) {
1038              if ($overrideinfo = $this->quiz_override_summary_links($quiz, $cm)) {
1039                  $output .= html_writer::tag('div', $overrideinfo, ['class' => 'quizattemptcounts']);
1040              }
1041          }
1042  
1043          return $output;
1044      }
1045  
1046      /**
1047       * Output the quiz intro.
1048       * @param object $quiz the quiz settings.
1049       * @param object $cm the course_module object.
1050       * @return string HTML to output.
1051       */
1052      public function quiz_intro($quiz, $cm) {
1053          if (html_is_blank($quiz->intro)) {
1054              return '';
1055          }
1056  
1057          return $this->box(format_module_intro('quiz', $quiz, $cm->id), 'generalbox', 'intro');
1058      }
1059  
1060      /**
1061       * Generates the table heading.
1062       */
1063      public function view_table_heading() {
1064          return $this->heading(get_string('summaryofattempts', 'quiz'), 3);
1065      }
1066  
1067      /**
1068       * Generates the table of data
1069       *
1070       * @param array $quiz Array contining quiz data
1071       * @param int $context The page context ID
1072       * @param mod_quiz_view_object $viewobj
1073       */
1074      public function view_table($quiz, $context, $viewobj) {
1075          if (!$viewobj->attempts) {
1076              return '';
1077          }
1078  
1079          // Prepare table header.
1080          $table = new html_table();
1081          $table->attributes['class'] = 'generaltable quizattemptsummary';
1082          $table->head = array();
1083          $table->align = array();
1084          $table->size = array();
1085          $table->caption = get_string('summaryofattempts', 'quiz');
1086          $table->captionhide = true;
1087          if ($viewobj->attemptcolumn) {
1088              $table->head[] = get_string('attemptnumber', 'quiz');
1089              $table->align[] = 'center';
1090              $table->size[] = '';
1091          }
1092          $table->head[] = get_string('attemptstate', 'quiz');
1093          $table->align[] = 'left';
1094          $table->size[] = '';
1095          if ($viewobj->markcolumn) {
1096              $table->head[] = get_string('marks', 'quiz') . ' / ' .
1097                      quiz_format_grade($quiz, $quiz->sumgrades);
1098              $table->align[] = 'center';
1099              $table->size[] = '';
1100          }
1101          if ($viewobj->gradecolumn) {
1102              $table->head[] = get_string('gradenoun') . ' / ' .
1103                      quiz_format_grade($quiz, $quiz->grade);
1104              $table->align[] = 'center';
1105              $table->size[] = '';
1106          }
1107          if ($viewobj->canreviewmine) {
1108              $table->head[] = get_string('review', 'quiz');
1109              $table->align[] = 'center';
1110              $table->size[] = '';
1111          }
1112          if ($viewobj->feedbackcolumn) {
1113              $table->head[] = get_string('feedback', 'quiz');
1114              $table->align[] = 'left';
1115              $table->size[] = '';
1116          }
1117  
1118          // One row for each attempt.
1119          foreach ($viewobj->attemptobjs as $attemptobj) {
1120              $attemptoptions = $attemptobj->get_display_options(true);
1121              $row = array();
1122  
1123              // Add the attempt number.
1124              if ($viewobj->attemptcolumn) {
1125                  if ($attemptobj->is_preview()) {
1126                      $row[] = get_string('preview', 'quiz');
1127                  } else {
1128                      $row[] = $attemptobj->get_attempt_number();
1129                  }
1130              }
1131  
1132              $row[] = $this->attempt_state($attemptobj);
1133  
1134              if ($viewobj->markcolumn) {
1135                  if ($attemptoptions->marks >= question_display_options::MARK_AND_MAX &&
1136                          $attemptobj->is_finished()) {
1137                      $row[] = quiz_format_grade($quiz, $attemptobj->get_sum_marks());
1138                  } else {
1139                      $row[] = '';
1140                  }
1141              }
1142  
1143              // Ouside the if because we may be showing feedback but not grades.
1144              $attemptgrade = quiz_rescale_grade($attemptobj->get_sum_marks(), $quiz, false);
1145  
1146              if ($viewobj->gradecolumn) {
1147                  if ($attemptoptions->marks >= question_display_options::MARK_AND_MAX &&
1148                          $attemptobj->is_finished()) {
1149  
1150                      // Highlight the highest grade if appropriate.
1151                      if ($viewobj->overallstats && !$attemptobj->is_preview()
1152                              && $viewobj->numattempts > 1 && !is_null($viewobj->mygrade)
1153                              && $attemptobj->get_state() == quiz_attempt::FINISHED
1154                              && $attemptgrade == $viewobj->mygrade
1155                              && $quiz->grademethod == QUIZ_GRADEHIGHEST) {
1156                          $table->rowclasses[$attemptobj->get_attempt_number()] = 'bestrow';
1157                      }
1158  
1159                      $row[] = quiz_format_grade($quiz, $attemptgrade);
1160                  } else {
1161                      $row[] = '';
1162                  }
1163              }
1164  
1165              if ($viewobj->canreviewmine) {
1166                  $row[] = $viewobj->accessmanager->make_review_link($attemptobj->get_attempt(),
1167                          $attemptoptions, $this);
1168              }
1169  
1170              if ($viewobj->feedbackcolumn && $attemptobj->is_finished()) {
1171                  if ($attemptoptions->overallfeedback) {
1172                      $row[] = quiz_feedback_for_grade($attemptgrade, $quiz, $context);
1173                  } else {
1174                      $row[] = '';
1175                  }
1176              }
1177  
1178              if ($attemptobj->is_preview()) {
1179                  $table->data['preview'] = $row;
1180              } else {
1181                  $table->data[$attemptobj->get_attempt_number()] = $row;
1182              }
1183          } // End of loop over attempts.
1184  
1185          $output = '';
1186          $output .= $this->view_table_heading();
1187          $output .= html_writer::table($table);
1188          return $output;
1189      }
1190  
1191      /**
1192       * Generate a brief textual desciption of the current state of an attempt.
1193       * @param quiz_attempt $attemptobj the attempt
1194       * @param int $timenow the time to use as 'now'.
1195       * @return string the appropriate lang string to describe the state.
1196       */
1197      public function attempt_state($attemptobj) {
1198          switch ($attemptobj->get_state()) {
1199              case quiz_attempt::IN_PROGRESS:
1200                  return get_string('stateinprogress', 'quiz');
1201  
1202              case quiz_attempt::OVERDUE:
1203                  return get_string('stateoverdue', 'quiz') . html_writer::tag('span',
1204                          get_string('stateoverduedetails', 'quiz',
1205                                  userdate($attemptobj->get_due_date())),
1206                          array('class' => 'statedetails'));
1207  
1208              case quiz_attempt::FINISHED:
1209                  return get_string('statefinished', 'quiz') . html_writer::tag('span',
1210                          get_string('statefinisheddetails', 'quiz',
1211                                  userdate($attemptobj->get_submitted_date())),
1212                          array('class' => 'statedetails'));
1213  
1214              case quiz_attempt::ABANDONED:
1215                  return get_string('stateabandoned', 'quiz');
1216          }
1217      }
1218  
1219      /**
1220       * Generates data pertaining to quiz results
1221       *
1222       * @param array $quiz Array containing quiz data
1223       * @param int $context The page context ID
1224       * @param int $cm The Course Module Id
1225       * @param mod_quiz_view_object $viewobj
1226       */
1227      public function view_result_info($quiz, $context, $cm, $viewobj) {
1228          $output = '';
1229          if (!$viewobj->numattempts && !$viewobj->gradecolumn && is_null($viewobj->mygrade)) {
1230              return $output;
1231          }
1232          $resultinfo = '';
1233  
1234          if ($viewobj->overallstats) {
1235              if ($viewobj->moreattempts) {
1236                  $a = new stdClass();
1237                  $a->method = quiz_get_grading_option_name($quiz->grademethod);
1238                  $a->mygrade = quiz_format_grade($quiz, $viewobj->mygrade);
1239                  $a->quizgrade = quiz_format_grade($quiz, $quiz->grade);
1240                  $resultinfo .= $this->heading(get_string('gradesofar', 'quiz', $a), 3);
1241              } else {
1242                  $a = new stdClass();
1243                  $a->grade = quiz_format_grade($quiz, $viewobj->mygrade);
1244                  $a->maxgrade = quiz_format_grade($quiz, $quiz->grade);
1245                  $a = get_string('outofshort', 'quiz', $a);
1246                  $resultinfo .= $this->heading(get_string('yourfinalgradeis', 'quiz', $a), 3);
1247              }
1248          }
1249  
1250          if ($viewobj->mygradeoverridden) {
1251  
1252              $resultinfo .= html_writer::tag('p', get_string('overriddennotice', 'grades'),
1253                      array('class' => 'overriddennotice'))."\n";
1254          }
1255          if ($viewobj->gradebookfeedback) {
1256              $resultinfo .= $this->heading(get_string('comment', 'quiz'), 3);
1257              $resultinfo .= html_writer::div($viewobj->gradebookfeedback, 'quizteacherfeedback') . "\n";
1258          }
1259          if ($viewobj->feedbackcolumn) {
1260              $resultinfo .= $this->heading(get_string('overallfeedback', 'quiz'), 3);
1261              $resultinfo .= html_writer::div(
1262                      quiz_feedback_for_grade($viewobj->mygrade, $quiz, $context),
1263                      'quizgradefeedback') . "\n";
1264          }
1265  
1266          if ($resultinfo) {
1267              $output .= $this->box($resultinfo, 'generalbox', 'feedback');
1268          }
1269          return $output;
1270      }
1271  
1272      /**
1273       * Output either a link to the review page for an attempt, or a button to
1274       * open the review in a popup window.
1275       *
1276       * @param moodle_url $url of the target page.
1277       * @param bool $reviewinpopup whether a pop-up is required.
1278       * @param array $popupoptions options to pass to the popup_action constructor.
1279       * @return string HTML to output.
1280       */
1281      public function review_link($url, $reviewinpopup, $popupoptions) {
1282          if ($reviewinpopup) {
1283              $button = new single_button($url, get_string('review', 'quiz'));
1284              $button->add_action(new popup_action('click', $url, 'quizpopup', $popupoptions));
1285              return $this->render($button);
1286  
1287          } else {
1288              return html_writer::link($url, get_string('review', 'quiz'),
1289                      array('title' => get_string('reviewthisattempt', 'quiz')));
1290          }
1291      }
1292  
1293      /**
1294       * Displayed where there might normally be a review link, to explain why the
1295       * review is not available at this time.
1296       * @param string $message optional message explaining why the review is not possible.
1297       * @return string HTML to output.
1298       */
1299      public function no_review_message($message) {
1300          return html_writer::nonempty_tag('span', $message,
1301                  array('class' => 'noreviewmessage'));
1302      }
1303  
1304      /**
1305       * Returns the same as {@link quiz_num_attempt_summary()} but wrapped in a link
1306       * to the quiz reports.
1307       *
1308       * @param stdClass $quiz the quiz object. Only $quiz->id is used at the moment.
1309       * @param stdClass $cm the cm object. Only $cm->course, $cm->groupmode and $cm->groupingid
1310       * fields are used at the moment.
1311       * @param context $context the quiz context.
1312       * @param bool $returnzero if false (default), when no attempts have been made '' is returned
1313       *      instead of 'Attempts: 0'.
1314       * @param int $currentgroup if there is a concept of current group where this method is being
1315       *      called (e.g. a report) pass it in here. Default 0 which means no current group.
1316       * @return string HTML fragment for the link.
1317       */
1318      public function quiz_attempt_summary_link_to_reports($quiz, $cm, $context,
1319                                                            $returnzero = false, $currentgroup = 0) {
1320          global $CFG;
1321          $summary = quiz_num_attempt_summary($quiz, $cm, $returnzero, $currentgroup);
1322          if (!$summary) {
1323              return '';
1324          }
1325  
1326          require_once($CFG->dirroot . '/mod/quiz/report/reportlib.php');
1327          $url = new moodle_url('/mod/quiz/report.php', array(
1328                  'id' => $cm->id, 'mode' => quiz_report_default_report($context)));
1329          return html_writer::link($url, $summary);
1330      }
1331  
1332      /**
1333       * Render a summary of the number of group and user overrides, with corresponding links.
1334       *
1335       * @param stdClass $quiz the quiz settings.
1336       * @param stdClass|cm_info $cm the cm object.
1337       * @param int $currentgroup currently selected group, if there is one.
1338       * @return string HTML fragment for the link.
1339       */
1340      public function quiz_override_summary_links(stdClass $quiz, stdClass $cm, $currentgroup = 0): string {
1341  
1342          $baseurl = new moodle_url('/mod/quiz/overrides.php', ['cmid' => $cm->id]);
1343          $counts = quiz_override_summary($quiz, $cm, $currentgroup);
1344  
1345          $links = [];
1346          if ($counts['group']) {
1347              $links[] = html_writer::link(new moodle_url($baseurl, ['mode' => 'group']),
1348                      get_string('overridessummarygroup', 'quiz', $counts['group']));
1349          }
1350          if ($counts['user']) {
1351              $links[] = html_writer::link(new moodle_url($baseurl, ['mode' => 'user']),
1352                      get_string('overridessummaryuser', 'quiz', $counts['user']));
1353          }
1354  
1355          if (!$links) {
1356              return '';
1357          }
1358  
1359          $links = implode(', ', $links);
1360          switch ($counts['mode']) {
1361              case 'onegroup':
1362                  return get_string('overridessummarythisgroup', 'quiz', $links);
1363  
1364              case 'somegroups':
1365                  return get_string('overridessummaryyourgroups', 'quiz', $links);
1366  
1367              case 'allgroups':
1368                  return get_string('overridessummary', 'quiz', $links);
1369  
1370              default:
1371                  throw new coding_exception('Unexpected mode ' . $counts['mode']);
1372          }
1373      }
1374  
1375      /**
1376       * Outputs a chart.
1377       *
1378       * @param \core\chart_base $chart The chart.
1379       * @param string $title The title to display above the graph.
1380       * @param array $attrs extra container html attributes.
1381       * @return string HTML fragment for the graph.
1382       */
1383      public function chart(\core\chart_base $chart, $title, $attrs = []) {
1384          return $this->heading($title, 3) . html_writer::tag('div',
1385              $this->render($chart), array_merge(['class' => 'graph'], $attrs));
1386      }
1387  
1388      /**
1389       * Output a graph, or a message saying that GD is required.
1390       * @param moodle_url $url the URL of the graph.
1391       * @param string $title the title to display above the graph.
1392       * @return string HTML fragment for the graph.
1393       */
1394      public function graph(moodle_url $url, $title) {
1395          global $CFG;
1396  
1397          $graph = html_writer::empty_tag('img', array('src' => $url, 'alt' => $title));
1398  
1399          return $this->heading($title, 3) . html_writer::tag('div', $graph, array('class' => 'graph'));
1400      }
1401  
1402      /**
1403       * Output the connection warning messages, which are initially hidden, and
1404       * only revealed by JavaScript if necessary.
1405       */
1406      public function connection_warning() {
1407          $options = array('filter' => false, 'newlines' => false);
1408          $warning = format_text(get_string('connectionerror', 'quiz'), FORMAT_MARKDOWN, $options);
1409          $ok = format_text(get_string('connectionok', 'quiz'), FORMAT_MARKDOWN, $options);
1410          return html_writer::tag('div', $warning,
1411                      array('id' => 'connection-error', 'style' => 'display: none;', 'role' => 'alert')) .
1412                      html_writer::tag('div', $ok, array('id' => 'connection-ok', 'style' => 'display: none;', 'role' => 'alert'));
1413      }
1414  }
1415  
1416  
1417  class mod_quiz_links_to_other_attempts implements renderable {
1418      /**
1419       * @var array string attempt number => url, or null for the current attempt.
1420       * url may be either a moodle_url, or a renderable.
1421       */
1422      public $links = array();
1423  }
1424  
1425  
1426  class mod_quiz_view_object {
1427      /** @var array $infomessages of messages with information to display about the quiz. */
1428      public $infomessages;
1429      /** @var array $attempts contains all the user's attempts at this quiz. */
1430      public $attempts;
1431      /** @var array $attemptobjs quiz_attempt objects corresponding to $attempts. */
1432      public $attemptobjs;
1433      /** @var quiz_access_manager $accessmanager contains various access rules. */
1434      public $accessmanager;
1435      /** @var bool $canreviewmine whether the current user has the capability to
1436       *       review their own attempts. */
1437      public $canreviewmine;
1438      /** @var bool $canedit whether the current user has the capability to edit the quiz. */
1439      public $canedit;
1440      /** @var moodle_url $editurl the URL for editing this quiz. */
1441      public $editurl;
1442      /** @var int $attemptcolumn contains the number of attempts done. */
1443      public $attemptcolumn;
1444      /** @var int $gradecolumn contains the grades of any attempts. */
1445      public $gradecolumn;
1446      /** @var int $markcolumn contains the marks of any attempt. */
1447      public $markcolumn;
1448      /** @var int $overallstats contains all marks for any attempt. */
1449      public $overallstats;
1450      /** @var string $feedbackcolumn contains any feedback for and attempt. */
1451      public $feedbackcolumn;
1452      /** @var string $timenow contains a timestamp in string format. */
1453      public $timenow;
1454      /** @var int $numattempts contains the total number of attempts. */
1455      public $numattempts;
1456      /** @var float $mygrade contains the user's final grade for a quiz. */
1457      public $mygrade;
1458      /** @var bool $moreattempts whether this user is allowed more attempts. */
1459      public $moreattempts;
1460      /** @var int $mygradeoverridden contains an overriden grade. */
1461      public $mygradeoverridden;
1462      /** @var string $gradebookfeedback contains any feedback for a gradebook. */
1463      public $gradebookfeedback;
1464      /** @var bool $unfinished contains 1 if an attempt is unfinished. */
1465      public $unfinished;
1466      /** @var object $lastfinishedattempt the last attempt from the attempts array. */
1467      public $lastfinishedattempt;
1468      /** @var array $preventmessages of messages telling the user why they can't
1469       *       attempt the quiz now. */
1470      public $preventmessages;
1471      /** @var string $buttontext caption for the start attempt button. If this is null, show no
1472       *      button, or if it is '' show a back to the course button. */
1473      public $buttontext;
1474      /** @var moodle_url $startattempturl URL to start an attempt. */
1475      public $startattempturl;
1476      /** @var mod_quiz_preflight_check_form|null $preflightcheckform confirmation form that must be
1477       *       submitted before an attempt is started, if required. */
1478      public $preflightcheckform;
1479      /** @var moodle_url $startattempturl URL for any Back to the course button. */
1480      public $backtocourseurl;
1481      /** @var bool $showbacktocourse should we show a back to the course button? */
1482      public $showbacktocourse;
1483      /** @var bool whether the attempt must take place in a popup window. */
1484      public $popuprequired;
1485      /** @var array options to use for the popup window, if required. */
1486      public $popupoptions;
1487      /** @var bool $quizhasquestions whether the quiz has any questions. */
1488      public $quizhasquestions;
1489  
1490      public function __get($field) {
1491          switch ($field) {
1492              case 'startattemptwarning':
1493                  debugging('startattemptwarning has been deprecated. It is now always blank.');
1494                  return '';
1495  
1496              default:
1497                  debugging('Unknown property ' . $field);
1498                  return null;
1499          }
1500      }
1501  }