Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.10.x will end 8 November 2021 (12 months).
  • Bug fixes for security issues in 3.10.x will end 9 May 2022 (18 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.

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

   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   * This file defines the quiz manual grading report class.
  19   *
  20   * @package   quiz_grading
  21   * @copyright 2006 Gustav Delius
  22   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23   */
  24  
  25  
  26  defined('MOODLE_INTERNAL') || die();
  27  
  28  require_once($CFG->dirroot . '/mod/quiz/report/grading/gradingsettings_form.php');
  29  
  30  
  31  /**
  32   * Quiz report to help teachers manually grade questions that need it.
  33   *
  34   * This report basically provides two screens:
  35   * - List question that might need manual grading (or optionally all questions).
  36   * - Provide an efficient UI to grade all attempts at a particular question.
  37   *
  38   * @copyright 2006 Gustav Delius
  39   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  40   */
  41  class quiz_grading_report extends quiz_default_report {
  42      const DEFAULT_PAGE_SIZE = 5;
  43      const DEFAULT_ORDER = 'random';
  44  
  45      /** @var string Positive integer regular expression. */
  46      const REGEX_POSITIVE_INT = '/^[1-9]\d*$/';
  47  
  48      /** @var array URL parameters for what is being displayed when grading. */
  49      protected $viewoptions = [];
  50  
  51      /** @var int the current group, 0 if none, or NO_GROUPS_ALLOWED. */
  52      protected $currentgroup;
  53  
  54      /** @var array from quiz_report_get_significant_questions. */
  55      protected $questions;
  56  
  57      /** @var stdClass the course settings. */
  58      protected $course;
  59  
  60      /** @var stdClass the course_module settings. */
  61      protected $cm;
  62  
  63      /** @var stdClass the quiz settings. */
  64      protected $quiz;
  65  
  66      /** @var context the quiz context. */
  67      protected $context;
  68  
  69      /** @var quiz_grading_renderer Renderer of Quiz Grading. */
  70      protected $renderer;
  71  
  72      /** @var string fragment of SQL code to restrict to the relevant users. */
  73      protected $userssql;
  74  
  75      public function display($quiz, $cm, $course) {
  76  
  77          $this->quiz = $quiz;
  78          $this->cm = $cm;
  79          $this->course = $course;
  80  
  81          // Get the URL options.
  82          $slot = optional_param('slot', null, PARAM_INT);
  83          $questionid = optional_param('qid', null, PARAM_INT);
  84          $grade = optional_param('grade', null, PARAM_ALPHA);
  85  
  86          $includeauto = optional_param('includeauto', false, PARAM_BOOL);
  87          if (!in_array($grade, array('all', 'needsgrading', 'autograded', 'manuallygraded'))) {
  88              $grade = null;
  89          }
  90          $pagesize = optional_param('pagesize',
  91                  get_user_preferences('quiz_grading_pagesize', self::DEFAULT_PAGE_SIZE),
  92                  PARAM_INT);
  93          $page = optional_param('page', 0, PARAM_INT);
  94          $order = optional_param('order',
  95                  get_user_preferences('quiz_grading_order', self::DEFAULT_ORDER),
  96                  PARAM_ALPHA);
  97  
  98          // Assemble the options required to reload this page.
  99          $optparams = array('includeauto', 'page');
 100          foreach ($optparams as $param) {
 101              if ($$param) {
 102                  $this->viewoptions[$param] = $$param;
 103              }
 104          }
 105          if (!data_submitted() && !preg_match(self::REGEX_POSITIVE_INT, $pagesize)) {
 106              // We only validate if the user accesses the page via a cleaned-up GET URL here.
 107              throw new moodle_exception('invalidpagesize');
 108          }
 109          if ($pagesize != self::DEFAULT_PAGE_SIZE) {
 110              $this->viewoptions['pagesize'] = $pagesize;
 111          }
 112          if ($order != self::DEFAULT_ORDER) {
 113              $this->viewoptions['order'] = $order;
 114          }
 115  
 116          // Check permissions.
 117          $this->context = context_module::instance($this->cm->id);
 118          require_capability('mod/quiz:grade', $this->context);
 119          $shownames = has_capability('quiz/grading:viewstudentnames', $this->context);
 120          $showidnumbers = has_capability('quiz/grading:viewidnumber', $this->context);
 121  
 122          // Validate order.
 123          if (!in_array($order, array('random', 'date', 'studentfirstname', 'studentlastname', 'idnumber'))) {
 124              $order = self::DEFAULT_ORDER;
 125          } else if (!$shownames && ($order == 'studentfirstname' || $order == 'studentlastname')) {
 126              $order = self::DEFAULT_ORDER;
 127          } else if (!$showidnumbers && $order == 'idnumber') {
 128              $order = self::DEFAULT_ORDER;
 129          }
 130          if ($order == 'random') {
 131              $page = 0;
 132          }
 133  
 134          // Get the list of questions in this quiz.
 135          $this->questions = quiz_report_get_significant_questions($quiz);
 136          if ($slot && !array_key_exists($slot, $this->questions)) {
 137              throw new moodle_exception('unknownquestion', 'quiz_grading');
 138          }
 139  
 140          // Process any submitted data.
 141          if ($data = data_submitted() && confirm_sesskey() && $this->validate_submitted_marks()) {
 142              $this->process_submitted_data();
 143  
 144              redirect($this->grade_question_url($slot, $questionid, $grade, $page + 1));
 145          }
 146  
 147          // Get the group, and the list of significant users.
 148          $this->currentgroup = $this->get_current_group($cm, $course, $this->context);
 149          if ($this->currentgroup == self::NO_GROUPS_ALLOWED) {
 150              $this->userssql = array();
 151          } else {
 152              $this->userssql = get_enrolled_sql($this->context,
 153                      array('mod/quiz:reviewmyattempts', 'mod/quiz:attempt'), $this->currentgroup);
 154          }
 155  
 156          $hasquestions = quiz_has_questions($this->quiz->id);
 157          if (!$hasquestions) {
 158              $this->print_header_and_tabs($cm, $course, $quiz, 'grading');
 159              echo $this->renderer->render_quiz_no_question_notification($quiz, $cm, $this->context);
 160              return true;
 161          }
 162  
 163          if (!$slot) {
 164              $this->display_index($includeauto);
 165              return true;
 166          }
 167  
 168          // Display the grading UI for one question.
 169  
 170          // Make sure there is something to do.
 171          $counts = null;
 172          $statecounts = $this->get_question_state_summary([$slot]);
 173          foreach ($statecounts as $record) {
 174              if ($record->questionid == $questionid) {
 175                  $counts = $record;
 176                  break;
 177              }
 178          }
 179  
 180          // If not, redirect back to the list.
 181          if (!$counts || $counts->$grade == 0) {
 182              redirect($this->list_questions_url(), get_string('alldoneredirecting', 'quiz_grading'));
 183          }
 184  
 185          $this->display_grading_interface($slot, $questionid, $grade,
 186                  $pagesize, $page, $shownames, $showidnumbers, $order, $counts);
 187          return true;
 188      }
 189  
 190      /**
 191       * Get the JOIN conditions needed so we only show attempts by relevant users.
 192       *
 193       * @return qubaid_join
 194       */
 195      protected function get_qubaids_condition() {
 196  
 197          $where = "quiza.quiz = :mangrquizid AND
 198                  quiza.preview = 0 AND
 199                  quiza.state = :statefinished";
 200          $params = array('mangrquizid' => $this->cm->instance, 'statefinished' => quiz_attempt::FINISHED);
 201  
 202          $usersjoin = '';
 203          $currentgroup = groups_get_activity_group($this->cm, true);
 204          $enrolleduserscount = count_enrolled_users($this->context,
 205                  array('mod/quiz:reviewmyattempts', 'mod/quiz:attempt'), $currentgroup);
 206          if ($currentgroup) {
 207              $userssql = get_enrolled_sql($this->context,
 208                      array('mod/quiz:reviewmyattempts', 'mod/quiz:attempt'), $currentgroup);
 209              if ($enrolleduserscount < 1) {
 210                  $where .= ' AND quiza.userid = 0';
 211              } else {
 212                  $usersjoin = "JOIN ({$userssql[0]}) AS enr ON quiza.userid = enr.id";
 213                  $params += $userssql[1];
 214              }
 215          }
 216  
 217          return new qubaid_join("{quiz_attempts} quiza $usersjoin ", 'quiza.uniqueid', $where, $params);
 218      }
 219  
 220      /**
 221       * Load the quiz_attempts rows corresponding to a list of question_usage ids.
 222       *
 223       * @param int[] $qubaids the question_usage ids of the quiz_attempts to load.
 224       * @return array quiz attempts, with added user name fields.
 225       */
 226      protected function load_attempts_by_usage_ids($qubaids) {
 227          global $DB;
 228  
 229          list($asql, $params) = $DB->get_in_or_equal($qubaids);
 230          $params[] = quiz_attempt::FINISHED;
 231          $params[] = $this->quiz->id;
 232  
 233          $fields = 'quiza.*, u.idnumber, ';
 234          $fields .= get_all_user_name_fields(true, 'u');
 235          $attemptsbyid = $DB->get_records_sql("
 236                  SELECT $fields
 237                  FROM {quiz_attempts} quiza
 238                  JOIN {user} u ON u.id = quiza.userid
 239                  WHERE quiza.uniqueid $asql AND quiza.state = ? AND quiza.quiz = ?",
 240                  $params);
 241  
 242          $attempts = array();
 243          foreach ($attemptsbyid as $attempt) {
 244              $attempts[$attempt->uniqueid] = $attempt;
 245          }
 246          return $attempts;
 247      }
 248  
 249      /**
 250       * Get the URL of the front page of the report that lists all the questions.
 251       *
 252       * @return moodle_url the URL.
 253       */
 254      protected function base_url() {
 255          return new moodle_url('/mod/quiz/report.php',
 256                  ['id' => $this->cm->id, 'mode' => 'grading']);
 257      }
 258  
 259      /**
 260       * Get the URL of the front page of the report that lists all the questions.
 261       *
 262       * @param bool $includeauto if not given, use the current setting, otherwise,
 263       *      force a particular value of includeauto in the URL.
 264       * @return moodle_url the URL.
 265       */
 266      protected function list_questions_url($includeauto = null) {
 267          $url = $this->base_url();
 268  
 269          $url->params($this->viewoptions);
 270  
 271          if (!is_null($includeauto)) {
 272              $url->param('includeauto', $includeauto);
 273          }
 274  
 275          return $url;
 276      }
 277  
 278      /**
 279       * Get the URL to grade a batch of question attempts.
 280       *
 281       * @param int $slot
 282       * @param int $questionid
 283       * @param string $grade
 284       * @param int|bool $page = true, link to current page. false = omit page.
 285       *      number = link to specific page.
 286       * @return moodle_url
 287       */
 288      protected function grade_question_url($slot, $questionid, $grade, $page = true) {
 289          $url = $this->base_url();
 290          $url->params(['slot' => $slot, 'qid' => $questionid, 'grade' => $grade]);
 291          $url->params($this->viewoptions);
 292  
 293          if (!$page) {
 294              $url->remove_params('page');
 295          } else if (is_integer($page)) {
 296              $url->param('page', $page);
 297          }
 298  
 299          return $url;
 300      }
 301  
 302      /**
 303       * Renders the contents of one cell of the table on the index view.
 304       *
 305       * @param stdClass $counts counts of different types of attempt for this slot.
 306       * @param string $type the type of count to format.
 307       * @param string $gradestring get_string identifier for the grading link text, if required.
 308       * @return string HTML.
 309       */
 310      protected function format_count_for_table($counts, $type, $gradestring) {
 311          $result = $counts->$type;
 312          if ($counts->$type > 0) {
 313              $gradeurl = $this->grade_question_url($counts->slot, $counts->questionid, $type);
 314              $result .= $this->renderer->render_grade_link($counts, $type, $gradestring, $gradeurl);
 315          }
 316          return $result;
 317      }
 318  
 319      /**
 320       * Display the report front page which summarises the number of attempts to grade.
 321       *
 322       * @param bool $includeauto whether to show automatically-graded questions.
 323       */
 324      protected function display_index($includeauto) {
 325          global $PAGE;
 326  
 327          $this->print_header_and_tabs($this->cm, $this->course, $this->quiz, 'grading');
 328  
 329          if ($groupmode = groups_get_activity_groupmode($this->cm)) {
 330              // Groups is being used.
 331              groups_print_activity_menu($this->cm, $this->list_questions_url());
 332          }
 333          $statecounts = $this->get_question_state_summary(array_keys($this->questions));
 334          if ($includeauto) {
 335              $linktext = get_string('hideautomaticallygraded', 'quiz_grading');
 336          } else {
 337              $linktext = get_string('alsoshowautomaticallygraded', 'quiz_grading');
 338          }
 339          echo $this->renderer->render_display_index_heading($linktext, $this->list_questions_url(!$includeauto));
 340          $data = [];
 341          $header = [];
 342  
 343          $header[] = get_string('qno', 'quiz_grading');
 344          $header[] = get_string('qtypeveryshort', 'question');
 345          $header[] = get_string('questionname', 'quiz_grading');
 346          $header[] = get_string('tograde', 'quiz_grading');
 347          $header[] = get_string('alreadygraded', 'quiz_grading');
 348          if ($includeauto) {
 349              $header[] = get_string('automaticallygraded', 'quiz_grading');
 350          }
 351          $header[] = get_string('total', 'quiz_grading');
 352  
 353          foreach ($statecounts as $counts) {
 354              if ($counts->all == 0) {
 355                  continue;
 356              }
 357              if (!$includeauto && $counts->needsgrading == 0 && $counts->manuallygraded == 0) {
 358                  continue;
 359              }
 360  
 361              $row = [];
 362  
 363              $row[] = $this->questions[$counts->slot]->number;
 364  
 365              $row[] = $PAGE->get_renderer('question', 'bank')->qtype_icon($this->questions[$counts->slot]->type);
 366  
 367              $row[] = format_string($counts->name);
 368  
 369              $row[] = $this->format_count_for_table($counts, 'needsgrading', 'grade');
 370  
 371              $row[] = $this->format_count_for_table($counts, 'manuallygraded', 'updategrade');
 372  
 373              if ($includeauto) {
 374                  $row[] = $this->format_count_for_table($counts, 'autograded', 'updategrade');
 375              }
 376  
 377              $row[] = $this->format_count_for_table($counts, 'all', 'gradeall');
 378  
 379              $data[] = $row;
 380          }
 381          echo $this->renderer->render_questions_table($includeauto, $data, $header);
 382      }
 383  
 384      /**
 385       * Display the UI for grading attempts at one question.
 386       *
 387       * @param int $slot identifies which question to grade.
 388       * @param int $questionid identifies which question to grade.
 389       * @param string $grade type of attempts to grade.
 390       * @param int $pagesize number of questions to show per page.
 391       * @param int $page current page number.
 392       * @param bool $shownames whether student names should be shown.
 393       * @param bool $showidnumbers wither student idnumbers should be shown.
 394       * @param string $order preferred order of attempts.
 395       * @param stdClass $counts object that stores the number of each type of attempt.
 396       */
 397      protected function display_grading_interface($slot, $questionid, $grade,
 398              $pagesize, $page, $shownames, $showidnumbers, $order, $counts) {
 399  
 400          if ($pagesize * $page >= $counts->$grade) {
 401              $page = 0;
 402          }
 403  
 404          // Prepare the options form.
 405          $hidden = [
 406              'id' => $this->cm->id,
 407              'mode' => 'grading',
 408              'slot' => $slot,
 409              'qid' => $questionid,
 410              'page' => $page,
 411          ];
 412          if (array_key_exists('includeauto', $this->viewoptions)) {
 413              $hidden['includeauto'] = $this->viewoptions['includeauto'];
 414          }
 415          $mform = new quiz_grading_settings_form($hidden, $counts, $shownames, $showidnumbers);
 416  
 417          // Tell the form the current settings.
 418          $settings = new stdClass();
 419          $settings->grade = $grade;
 420          $settings->pagesize = $pagesize;
 421          $settings->order = $order;
 422          $mform->set_data($settings);
 423  
 424          if ($mform->is_submitted()) {
 425              if ($mform->is_validated()) {
 426                  // If the form was submitted and validated, save the user preferences, and
 427                  // redirect to a cleaned-up GET URL.
 428                  set_user_preference('quiz_grading_pagesize', $pagesize);
 429                  set_user_preference('quiz_grading_order', $order);
 430                  redirect($this->grade_question_url($slot, $questionid, $grade, $page));
 431              } else {
 432                  // Set the pagesize back to the previous value, so the report page can continue the render
 433                  // and the form can show the validation.
 434                  $pagesize = get_user_preferences('quiz_grading_pagesize', self::DEFAULT_PAGE_SIZE);
 435              }
 436          }
 437  
 438          list($qubaids, $count) = $this->get_usage_ids_where_question_in_state(
 439                  $grade, $slot, $questionid, $order, $page, $pagesize);
 440          $attempts = $this->load_attempts_by_usage_ids($qubaids);
 441  
 442          // Question info.
 443          $questioninfo = new stdClass();
 444          $questioninfo->number = $this->questions[$slot]->number;
 445          $questioninfo->questionname = format_string($counts->name);
 446  
 447          // Paging info.
 448          $paginginfo = new stdClass();
 449          $paginginfo->from = $page * $pagesize + 1;
 450          $paginginfo->to = min(($page + 1) * $pagesize, $count);
 451          $paginginfo->of = $count;
 452          $qubaidlist = implode(',', $qubaids);
 453  
 454          $this->print_header_and_tabs($this->cm, $this->course, $this->quiz, 'grading');
 455  
 456          $gradequestioncontent = '';
 457          foreach ($qubaids as $qubaid) {
 458              $attempt = $attempts[$qubaid];
 459              $quba = question_engine::load_questions_usage_by_activity($qubaid);
 460              $displayoptions = quiz_get_review_options($this->quiz, $attempt, $this->context);
 461              $displayoptions->hide_all_feedback();
 462              $displayoptions->rightanswer = question_display_options::VISIBLE;
 463              $displayoptions->history = question_display_options::HIDDEN;
 464              $displayoptions->manualcomment = question_display_options::EDITABLE;
 465  
 466              $gradequestioncontent .= $this->renderer->render_grade_question(
 467                      $quba,
 468                      $slot,
 469                      $displayoptions,
 470                      $this->questions[$slot]->number,
 471                      $this->get_question_heading($attempt, $shownames, $showidnumbers)
 472              );
 473          }
 474  
 475          $pagingbar = new stdClass();
 476          $pagingbar->count = $count;
 477          $pagingbar->page = $page;
 478          $pagingbar->pagesize = $pagesize;
 479          $pagingbar->pagesize = $pagesize;
 480          $pagingbar->order = $order;
 481          $pagingbar->pagingurl = $this->grade_question_url($slot, $questionid, $grade, false);
 482  
 483          $hiddeninputs = [
 484                  'qubaids' => $qubaidlist,
 485                  'slots' => $slot,
 486                  'sesskey' => sesskey()
 487          ];
 488  
 489          echo $this->renderer->render_grading_interface(
 490                  $questioninfo,
 491                  $this->list_questions_url(),
 492                  $mform,
 493                  $paginginfo,
 494                  $pagingbar,
 495                  $this->grade_question_url($slot, $questionid, $grade, $page),
 496                  $hiddeninputs,
 497                  $gradequestioncontent
 498          );
 499      }
 500  
 501      /**
 502       * When saving a grading page, are all the submitted marks valid?
 503       *
 504       * @return bool true if all valid, else false.
 505       */
 506      protected function validate_submitted_marks() {
 507  
 508          $qubaids = optional_param('qubaids', null, PARAM_SEQUENCE);
 509          if (!$qubaids) {
 510              return false;
 511          }
 512          $qubaids = clean_param_array(explode(',', $qubaids), PARAM_INT);
 513  
 514          $slots = optional_param('slots', '', PARAM_SEQUENCE);
 515          if (!$slots) {
 516              $slots = [];
 517          } else {
 518              $slots = explode(',', $slots);
 519          }
 520  
 521          foreach ($qubaids as $qubaid) {
 522              foreach ($slots as $slot) {
 523                  if (!question_engine::is_manual_grade_in_range($qubaid, $slot)) {
 524                      return false;
 525                  }
 526              }
 527          }
 528  
 529          return true;
 530      }
 531  
 532      /**
 533       * Save all submitted marks to the database.
 534       */
 535      protected function process_submitted_data() {
 536          global $DB;
 537  
 538          $qubaids = optional_param('qubaids', null, PARAM_SEQUENCE);
 539          $assumedslotforevents = optional_param('slot', null, PARAM_INT);
 540  
 541          if (!$qubaids) {
 542              return;
 543          }
 544  
 545          $qubaids = clean_param_array(explode(',', $qubaids), PARAM_INT);
 546          $attempts = $this->load_attempts_by_usage_ids($qubaids);
 547          $events = [];
 548  
 549          $transaction = $DB->start_delegated_transaction();
 550          foreach ($qubaids as $qubaid) {
 551              $attempt = $attempts[$qubaid];
 552              $attemptobj = new quiz_attempt($attempt, $this->quiz, $this->cm, $this->course);
 553              $attemptobj->process_submitted_actions(time());
 554  
 555              // Add the event we will trigger later.
 556              $params = [
 557                  'objectid' => $attemptobj->get_question_attempt($assumedslotforevents)->get_question_id(),
 558                  'courseid' => $attemptobj->get_courseid(),
 559                  'context' => context_module::instance($attemptobj->get_cmid()),
 560                  'other' => [
 561                      'quizid' => $attemptobj->get_quizid(),
 562                      'attemptid' => $attemptobj->get_attemptid(),
 563                      'slot' => $assumedslotforevents,
 564                  ],
 565              ];
 566              $events[] = \mod_quiz\event\question_manually_graded::create($params);
 567          }
 568          $transaction->allow_commit();
 569  
 570          // Trigger events for all the questions we manually marked.
 571          foreach ($events as $event) {
 572              $event->trigger();
 573          }
 574      }
 575  
 576      /**
 577       * Load information about the number of attempts at various questions in each
 578       * summarystate.
 579       *
 580       * The results are returned as an two dimensional array $qubaid => $slot => $dataobject
 581       *
 582       * @param array $slots A list of slots for the questions you want to konw about.
 583       * @return array The array keys are slot,qestionid. The values are objects with
 584       * fields $slot, $questionid, $inprogress, $name, $needsgrading, $autograded,
 585       * $manuallygraded and $all.
 586       */
 587      protected function get_question_state_summary($slots) {
 588          $dm = new question_engine_data_mapper();
 589          return $dm->load_questions_usages_question_state_summary(
 590                  $this->get_qubaids_condition(), $slots);
 591      }
 592  
 593      /**
 594       * Get a list of usage ids where the question with slot $slot, and optionally
 595       * also with question id $questionid, is in summary state $summarystate. Also
 596       * return the total count of such states.
 597       *
 598       * Only a subset of the ids can be returned by using $orderby, $limitfrom and
 599       * $limitnum. A special value 'random' can be passed as $orderby, in which case
 600       * $limitfrom is ignored.
 601       *
 602       * @param int $slot The slot for the questions you want to konw about.
 603       * @param int $questionid (optional) Only return attempts that were of this specific question.
 604       * @param string $summarystate 'all', 'needsgrading', 'autograded' or 'manuallygraded'.
 605       * @param string $orderby 'random', 'date', 'student' or 'idnumber'.
 606       * @param int $page implements paging of the results.
 607       *      Ignored if $orderby = random or $pagesize is null.
 608       * @param int $pagesize implements paging of the results. null = all.
 609       * @return array with two elements, an array of usage ids, and a count of the total number.
 610       */
 611      protected function get_usage_ids_where_question_in_state($summarystate, $slot,
 612              $questionid = null, $orderby = 'random', $page = 0, $pagesize = null) {
 613          $dm = new question_engine_data_mapper();
 614  
 615          if ($pagesize && $orderby != 'random') {
 616              $limitfrom = $page * $pagesize;
 617          } else {
 618              $limitfrom = 0;
 619          }
 620  
 621          $qubaids = $this->get_qubaids_condition();
 622  
 623          $params = [];
 624          if ($orderby == 'date') {
 625              list($statetest, $params) = $dm->in_summary_state_test(
 626                      'manuallygraded', false, 'mangrstate');
 627              $orderby = "(
 628                      SELECT MAX(sortqas.timecreated)
 629                      FROM {question_attempt_steps} sortqas
 630                      WHERE sortqas.questionattemptid = qa.id
 631                          AND sortqas.state $statetest
 632                      )";
 633          } else if ($orderby == 'studentfirstname' || $orderby == 'studentlastname' || $orderby == 'idnumber') {
 634              $qubaids->from .= " JOIN {user} u ON quiza.userid = u.id ";
 635              // For name sorting, map orderby form value to
 636              // actual column names; 'idnumber' maps naturally.
 637              switch ($orderby) {
 638                  case "studentlastname":
 639                      $orderby = "u.lastname, u.firstname";
 640                      break;
 641                  case "studentfirstname":
 642                      $orderby = "u.firstname, u.lastname";
 643                      break;
 644                  case "idnumber":
 645                      $orderby = "u.idnumber";
 646                      break;
 647              }
 648          }
 649  
 650          return $dm->load_questions_usages_where_question_in_state($qubaids, $summarystate,
 651                  $slot, $questionid, $orderby, $params, $limitfrom, $pagesize);
 652      }
 653  
 654      /**
 655       * Initialise some parts of $PAGE and start output.
 656       *
 657       * @param object $cm the course_module information.
 658       * @param object $course the course settings.
 659       * @param object $quiz the quiz settings.
 660       * @param string $reportmode the report name.
 661       */
 662      public function print_header_and_tabs($cm, $course, $quiz, $reportmode = 'overview') {
 663          global $PAGE;
 664          $this->renderer = $PAGE->get_renderer('quiz_grading');
 665          parent::print_header_and_tabs($cm, $course, $quiz, $reportmode);
 666      }
 667  
 668      /**
 669       * Get question heading.
 670       *
 671       * @param object $attempt an instance of quiz_attempt.
 672       * @param bool $shownames True to show the question name.
 673       * @param bool $showidnumbers True to show the question id number.
 674       * @return string The string text for the question heading.
 675       * @throws coding_exception
 676       */
 677      protected function get_question_heading($attempt, $shownames, $showidnumbers) {
 678          $a = new stdClass();
 679          $a->attempt = $attempt->attempt;
 680          $a->fullname = fullname($attempt);
 681          $a->idnumber = s($attempt->idnumber);
 682  
 683          $showidnumbers = $showidnumbers && !empty($attempt->idnumber);
 684  
 685          if ($shownames && $showidnumbers) {
 686              return get_string('gradingattemptwithidnumber', 'quiz_grading', $a);
 687          } else if ($shownames) {
 688              return get_string('gradingattempt', 'quiz_grading', $a);
 689          } else if ($showidnumbers) {
 690              $a->fullname = $attempt->idnumber;
 691              return get_string('gradingattempt', 'quiz_grading', $a);
 692          } else {
 693              return '';
 694          }
 695      }
 696  }