Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.0.x will end 8 May 2023 (12 months).
  • Bug fixes for security issues in 4.0.x will end 13 November 2023 (18 months).
  • PHP version: minimum PHP 7.3.0 Note: the minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is also supported.

Differences Between: [Versions 310 and 400] [Versions 311 and 400] [Versions 39 and 400] [Versions 400 and 401] [Versions 400 and 402] [Versions 400 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   * Quiz statistics report class.
  19   *
  20   * @package   quiz_statistics
  21   * @copyright 2014 Open University
  22   * @author    James Pratt <me@jamiep.org>
  23   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  24   */
  25  
  26  defined('MOODLE_INTERNAL') || die();
  27  
  28  use core_question\statistics\responses\analyser;
  29  use core_question\statistics\questions\all_calculated_for_qubaid_condition;
  30  
  31  require_once($CFG->dirroot . '/mod/quiz/report/default.php');
  32  require_once($CFG->dirroot . '/mod/quiz/report/reportlib.php');
  33  require_once($CFG->dirroot . '/mod/quiz/report/statistics/statistics_form.php');
  34  require_once($CFG->dirroot . '/mod/quiz/report/statistics/statistics_table.php');
  35  require_once($CFG->dirroot . '/mod/quiz/report/statistics/statistics_question_table.php');
  36  require_once($CFG->dirroot . '/mod/quiz/report/statistics/statisticslib.php');
  37  
  38  /**
  39   * The quiz statistics report provides summary information about each question in
  40   * a quiz, compared to the whole quiz. It also provides a drill-down to more
  41   * detailed information about each question.
  42   *
  43   * @copyright 2008 Jamie Pratt
  44   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  45   */
  46  class quiz_statistics_report extends quiz_default_report {
  47  
  48      /** @var context_module context of this quiz.*/
  49      protected $context;
  50  
  51      /** @var quiz_statistics_table instance of table class used for main questions stats table. */
  52      protected $table;
  53  
  54      /** @var \core\progress\base|null $progress Handles progress reporting or not. */
  55      protected $progress = null;
  56  
  57      /**
  58       * Display the report.
  59       */
  60      public function display($quiz, $cm, $course) {
  61          global $OUTPUT, $DB;
  62  
  63          raise_memory_limit(MEMORY_HUGE);
  64  
  65          $this->context = context_module::instance($cm->id);
  66  
  67          if (!quiz_has_questions($quiz->id)) {
  68              $this->print_header_and_tabs($cm, $course, $quiz, 'statistics');
  69              echo quiz_no_questions_message($quiz, $cm, $this->context);
  70              return true;
  71          }
  72  
  73          // Work out the display options.
  74          $download = optional_param('download', '', PARAM_ALPHA);
  75          $everything = optional_param('everything', 0, PARAM_BOOL);
  76          $recalculate = optional_param('recalculate', 0, PARAM_BOOL);
  77          // A qid paramter indicates we should display the detailed analysis of a sub question.
  78          $qid = optional_param('qid', 0, PARAM_INT);
  79          $slot = optional_param('slot', 0, PARAM_INT);
  80          $variantno = optional_param('variant', null, PARAM_INT);
  81          $whichattempts = optional_param('whichattempts', $quiz->grademethod, PARAM_INT);
  82          $whichtries = optional_param('whichtries', question_attempt::LAST_TRY, PARAM_ALPHA);
  83  
  84          $pageoptions = array();
  85          $pageoptions['id'] = $cm->id;
  86          $pageoptions['mode'] = 'statistics';
  87  
  88          $reporturl = new moodle_url('/mod/quiz/report.php', $pageoptions);
  89  
  90          $mform = new quiz_statistics_settings_form($reporturl, compact('quiz'));
  91  
  92          $mform->set_data(array('whichattempts' => $whichattempts, 'whichtries' => $whichtries));
  93  
  94          if ($whichattempts != $quiz->grademethod) {
  95              $reporturl->param('whichattempts', $whichattempts);
  96          }
  97  
  98          if ($whichtries != question_attempt::LAST_TRY) {
  99              $reporturl->param('whichtries', $whichtries);
 100          }
 101  
 102          // Find out current groups mode.
 103          $currentgroup = $this->get_current_group($cm, $course, $this->context);
 104          $nostudentsingroup = false; // True if a group is selected and there is no one in it.
 105          if (empty($currentgroup)) {
 106              $currentgroup = 0;
 107              $groupstudentsjoins = new \core\dml\sql_join();
 108  
 109          } else if ($currentgroup == self::NO_GROUPS_ALLOWED) {
 110              $groupstudentsjoins = new \core\dml\sql_join();
 111              $nostudentsingroup = true;
 112  
 113          } else {
 114              // All users who can attempt quizzes and who are in the currently selected group.
 115              $groupstudentsjoins = get_enrolled_with_capabilities_join($this->context, '',
 116                      array('mod/quiz:reviewmyattempts', 'mod/quiz:attempt'), $currentgroup);
 117              if (!empty($groupstudentsjoins->joins)) {
 118                  $sql = "SELECT DISTINCT u.id
 119                      FROM {user} u
 120                      {$groupstudentsjoins->joins}
 121                      WHERE {$groupstudentsjoins->wheres}";
 122                  if (!$DB->record_exists_sql($sql, $groupstudentsjoins->params)) {
 123                      $nostudentsingroup = true;
 124                  }
 125              }
 126          }
 127  
 128          $qubaids = quiz_statistics_qubaids_condition($quiz->id, $groupstudentsjoins, $whichattempts);
 129  
 130          // If recalculate was requested, handle that.
 131          if ($recalculate && confirm_sesskey()) {
 132              $this->clear_cached_data($qubaids);
 133              redirect($reporturl);
 134          }
 135  
 136          // Set up the main table.
 137          $this->table = new quiz_statistics_table();
 138          if ($everything) {
 139              $report = get_string('completestatsfilename', 'quiz_statistics');
 140          } else {
 141              $report = get_string('questionstatsfilename', 'quiz_statistics');
 142          }
 143          $courseshortname = format_string($course->shortname, true,
 144                  array('context' => context_course::instance($course->id)));
 145          $filename = quiz_report_download_filename($report, $courseshortname, $quiz->name);
 146          $this->table->is_downloading($download, $filename,
 147                  get_string('quizstructureanalysis', 'quiz_statistics'));
 148          $questions = $this->load_and_initialise_questions_for_calculations($quiz);
 149  
 150          // Print the page header stuff (if not downloading.
 151          if (!$this->table->is_downloading()) {
 152              $this->print_header_and_tabs($cm, $course, $quiz, 'statistics');
 153          }
 154  
 155          if (!$nostudentsingroup) {
 156              // Get the data to be displayed.
 157              $progress = $this->get_progress_trace_instance();
 158              list($quizstats, $questionstats) =
 159                  $this->get_all_stats_and_analysis($quiz, $whichattempts, $whichtries, $groupstudentsjoins, $questions, $progress);
 160          } else {
 161              // Or create empty stats containers.
 162              $quizstats = new \quiz_statistics\calculated($whichattempts);
 163              $questionstats = new \core_question\statistics\questions\all_calculated_for_qubaid_condition();
 164          }
 165  
 166          // Set up the table.
 167          $this->table->statistics_setup($quiz, $cm->id, $reporturl, $quizstats->s());
 168  
 169          // Print the rest of the page header stuff (if not downloading.
 170          if (!$this->table->is_downloading()) {
 171  
 172              if (groups_get_activity_groupmode($cm)) {
 173                  groups_print_activity_menu($cm, $reporturl->out());
 174                  if ($currentgroup && $nostudentsingroup) {
 175                      $OUTPUT->notification(get_string('nostudentsingroup', 'quiz_statistics'));
 176                  }
 177              }
 178  
 179              if (!$this->table->is_downloading() && $quizstats->s() == 0) {
 180                  echo $OUTPUT->notification(get_string('nogradedattempts', 'quiz_statistics'));
 181              }
 182  
 183              foreach ($questionstats->any_error_messages() as $errormessage) {
 184                  echo $OUTPUT->notification($errormessage);
 185              }
 186  
 187              // Print display options form.
 188              $mform->display();
 189          }
 190  
 191          if ($everything) { // Implies is downloading.
 192              // Overall report, then the analysis of each question.
 193              $quizinfo = $quizstats->get_formatted_quiz_info_data($course, $cm, $quiz);
 194              $this->download_quiz_info_table($quizinfo);
 195  
 196              if ($quizstats->s()) {
 197                  $this->output_quiz_structure_analysis_table($questionstats);
 198  
 199                  if ($this->table->is_downloading() == 'html' && $quizstats->s() != 0) {
 200                      $this->output_statistics_graph($quiz->id, $qubaids);
 201                  }
 202  
 203                  $this->output_all_question_response_analysis($qubaids, $questions, $questionstats, $reporturl, $whichtries);
 204              }
 205  
 206              $this->table->export_class_instance()->finish_document();
 207  
 208          } else if ($qid) {
 209              // Report on an individual sub-question indexed questionid.
 210              if (!$questionstats->has_subq($qid, $variantno)) {
 211                  print_error('questiondoesnotexist', 'question');
 212              }
 213  
 214              $this->output_individual_question_data($quiz, $questionstats->for_subq($qid, $variantno));
 215              $this->output_individual_question_response_analysis($questionstats->for_subq($qid, $variantno)->question,
 216                                                                  $variantno,
 217                                                                  $questionstats->for_subq($qid, $variantno)->s,
 218                                                                  $reporturl,
 219                                                                  $qubaids,
 220                                                                  $whichtries);
 221              // Back to overview link.
 222              echo $OUTPUT->box('<a href="' . $reporturl->out() . '">' .
 223                                get_string('backtoquizreport', 'quiz_statistics') . '</a>',
 224                                'boxaligncenter generalbox boxwidthnormal mdl-align');
 225          } else if ($slot) {
 226              // Report on an individual question indexed by position.
 227              if (!isset($questions[$slot])) {
 228                  print_error('questiondoesnotexist', 'question');
 229              }
 230  
 231              if ($variantno === null &&
 232                                  ($questionstats->for_slot($slot)->get_sub_question_ids()
 233                                  || $questionstats->for_slot($slot)->get_variants())) {
 234                  if (!$this->table->is_downloading()) {
 235                      $number = $questionstats->for_slot($slot)->question->number;
 236                      echo $OUTPUT->heading(get_string('slotstructureanalysis', 'quiz_statistics', $number), 3);
 237                  }
 238                  $this->table->define_baseurl(new moodle_url($reporturl, array('slot' => $slot)));
 239                  $this->table->format_and_add_array_of_rows($questionstats->structure_analysis_for_one_slot($slot));
 240              } else {
 241                  $this->output_individual_question_data($quiz, $questionstats->for_slot($slot, $variantno));
 242                  $this->output_individual_question_response_analysis($questions[$slot],
 243                                                                      $variantno,
 244                                                                      $questionstats->for_slot($slot, $variantno)->s,
 245                                                                      $reporturl,
 246                                                                      $qubaids,
 247                                                                      $whichtries);
 248              }
 249              if (!$this->table->is_downloading()) {
 250                  // Back to overview link.
 251                  echo $OUTPUT->box('<a href="' . $reporturl->out() . '">' .
 252                          get_string('backtoquizreport', 'quiz_statistics') . '</a>',
 253                          'backtomainstats boxaligncenter generalbox boxwidthnormal mdl-align');
 254              } else {
 255                  $this->table->finish_output();
 256              }
 257  
 258          } else if ($this->table->is_downloading()) {
 259              // Downloading overview report.
 260              $quizinfo = $quizstats->get_formatted_quiz_info_data($course, $cm, $quiz);
 261              $this->download_quiz_info_table($quizinfo);
 262              if ($quizstats->s()) {
 263                  $this->output_quiz_structure_analysis_table($questionstats);
 264              }
 265              $this->table->export_class_instance()->finish_document();
 266  
 267          } else {
 268              // On-screen display of overview report.
 269              echo $OUTPUT->heading(get_string('quizinformation', 'quiz_statistics'), 3);
 270              echo $this->output_caching_info($quizstats->timemodified, $quiz->id, $groupstudentsjoins, $whichattempts, $reporturl);
 271              echo $this->everything_download_options($reporturl);
 272              $quizinfo = $quizstats->get_formatted_quiz_info_data($course, $cm, $quiz);
 273              echo $this->output_quiz_info_table($quizinfo);
 274              if ($quizstats->s()) {
 275                  echo $OUTPUT->heading(get_string('quizstructureanalysis', 'quiz_statistics'), 3);
 276                  $this->output_quiz_structure_analysis_table($questionstats);
 277                  $this->output_statistics_graph($quiz, $qubaids);
 278              }
 279          }
 280  
 281          return true;
 282      }
 283  
 284      /**
 285       * Display the statistical and introductory information about a question.
 286       * Only called when not downloading.
 287       *
 288       * @param object                                         $quiz         the quiz settings.
 289       * @param \core_question\statistics\questions\calculated $questionstat the question to report on.
 290       */
 291      protected function output_individual_question_data($quiz, $questionstat) {
 292          global $OUTPUT;
 293  
 294          // On-screen display. Show a summary of the question's place in the quiz,
 295          // and the question statistics.
 296          $datumfromtable = $this->table->format_row($questionstat);
 297  
 298          // Set up the question info table.
 299          $questioninfotable = new html_table();
 300          $questioninfotable->align = array('center', 'center');
 301          $questioninfotable->width = '60%';
 302          $questioninfotable->attributes['class'] = 'generaltable titlesleft';
 303  
 304          $questioninfotable->data = array();
 305          $questioninfotable->data[] = array(get_string('modulename', 'quiz'), $quiz->name);
 306          $questioninfotable->data[] = array(get_string('questionname', 'quiz_statistics'),
 307                  $questionstat->question->name.'&nbsp;'.$datumfromtable['actions']);
 308  
 309          if ($questionstat->variant !== null) {
 310              $questioninfotable->data[] = array(get_string('variant', 'quiz_statistics'), $questionstat->variant);
 311  
 312          }
 313          $questioninfotable->data[] = array(get_string('questiontype', 'quiz_statistics'),
 314                  $datumfromtable['icon'] . '&nbsp;' .
 315                  question_bank::get_qtype($questionstat->question->qtype, false)->menu_name() . '&nbsp;' .
 316                  $datumfromtable['icon']);
 317          $questioninfotable->data[] = array(get_string('positions', 'quiz_statistics'),
 318                  $questionstat->positions);
 319  
 320          // Set up the question statistics table.
 321          $questionstatstable = new html_table();
 322          $questionstatstable->align = array('center', 'center');
 323          $questionstatstable->width = '60%';
 324          $questionstatstable->attributes['class'] = 'generaltable titlesleft';
 325  
 326          unset($datumfromtable['number']);
 327          unset($datumfromtable['icon']);
 328          $actions = $datumfromtable['actions'];
 329          unset($datumfromtable['actions']);
 330          unset($datumfromtable['name']);
 331          $labels = array(
 332              's' => get_string('attempts', 'quiz_statistics'),
 333              'facility' => get_string('facility', 'quiz_statistics'),
 334              'sd' => get_string('standarddeviationq', 'quiz_statistics'),
 335              'random_guess_score' => get_string('random_guess_score', 'quiz_statistics'),
 336              'intended_weight' => get_string('intended_weight', 'quiz_statistics'),
 337              'effective_weight' => get_string('effective_weight', 'quiz_statistics'),
 338              'discrimination_index' => get_string('discrimination_index', 'quiz_statistics'),
 339              'discriminative_efficiency' =>
 340                                  get_string('discriminative_efficiency', 'quiz_statistics')
 341          );
 342          foreach ($datumfromtable as $item => $value) {
 343              $questionstatstable->data[] = array($labels[$item], $value);
 344          }
 345  
 346          // Display the various bits.
 347          echo $OUTPUT->heading(get_string('questioninformation', 'quiz_statistics'), 3);
 348          echo html_writer::table($questioninfotable);
 349          echo $this->render_question_text($questionstat->question);
 350          echo $OUTPUT->heading(get_string('questionstatistics', 'quiz_statistics'), 3);
 351          echo html_writer::table($questionstatstable);
 352      }
 353  
 354      /**
 355       * Output question text in a box with urls appropriate for a preview of the question.
 356       *
 357       * @param object $question question data.
 358       * @return string HTML of question text, ready for display.
 359       */
 360      protected function render_question_text($question) {
 361          global $OUTPUT;
 362  
 363          $text = question_rewrite_question_preview_urls($question->questiontext, $question->id,
 364                  $question->contextid, 'question', 'questiontext', $question->id,
 365                  $this->context->id, 'quiz_statistics');
 366  
 367          return $OUTPUT->box(format_text($text, $question->questiontextformat,
 368                  array('noclean' => true, 'para' => false, 'overflowdiv' => true)),
 369                  'questiontext boxaligncenter generalbox boxwidthnormal mdl-align');
 370      }
 371  
 372      /**
 373       * Display the response analysis for a question.
 374       *
 375       * @param object           $question  the question to report on.
 376       * @param int|null         $variantno the variant
 377       * @param int              $s
 378       * @param moodle_url       $reporturl the URL to redisplay this report.
 379       * @param qubaid_condition $qubaids
 380       * @param string           $whichtries
 381       */
 382      protected function output_individual_question_response_analysis($question, $variantno, $s, $reporturl, $qubaids,
 383                                                                      $whichtries = question_attempt::LAST_TRY) {
 384          global $OUTPUT;
 385  
 386          if (!question_bank::get_qtype($question->qtype, false)->can_analyse_responses()) {
 387              return;
 388          }
 389  
 390          $qtable = new quiz_statistics_question_table($question->id);
 391          $exportclass = $this->table->export_class_instance();
 392          $qtable->export_class_instance($exportclass);
 393          if (!$this->table->is_downloading()) {
 394              // Output an appropriate title.
 395              echo $OUTPUT->heading(get_string('analysisofresponses', 'quiz_statistics'), 3);
 396  
 397          } else {
 398              // Work out an appropriate title.
 399              $a = clone($question);
 400              $a->variant = $variantno;
 401  
 402              if (!empty($question->number) && !is_null($variantno)) {
 403                  $questiontabletitle = get_string('analysisnovariant', 'quiz_statistics', $a);
 404              } else if (!empty($question->number)) {
 405                  $questiontabletitle = get_string('analysisno', 'quiz_statistics', $a);
 406              } else if (!is_null($variantno)) {
 407                  $questiontabletitle = get_string('analysisvariant', 'quiz_statistics', $a);
 408              } else {
 409                  $questiontabletitle = get_string('analysisnameonly', 'quiz_statistics', $a);
 410              }
 411  
 412              if ($this->table->is_downloading() == 'html') {
 413                  $questiontabletitle = get_string('analysisofresponsesfor', 'quiz_statistics', $questiontabletitle);
 414              }
 415  
 416              // Set up the table.
 417              $exportclass->start_table($questiontabletitle);
 418  
 419              if ($this->table->is_downloading() == 'html') {
 420                  echo $this->render_question_text($question);
 421              }
 422          }
 423  
 424          $responesanalyser = new analyser($question, $whichtries);
 425          $responseanalysis = $responesanalyser->load_cached($qubaids, $whichtries);
 426  
 427          $qtable->question_setup($reporturl, $question, $s, $responseanalysis);
 428          if ($this->table->is_downloading()) {
 429              $exportclass->output_headers($qtable->headers);
 430          }
 431  
 432          // Where no variant no is specified the variant no is actually one.
 433          if ($variantno === null) {
 434              $variantno = 1;
 435          }
 436          foreach ($responseanalysis->get_subpart_ids($variantno) as $partid) {
 437              $subpart = $responseanalysis->get_analysis_for_subpart($variantno, $partid);
 438              foreach ($subpart->get_response_class_ids() as $responseclassid) {
 439                  $responseclass = $subpart->get_response_class($responseclassid);
 440                  $tabledata = $responseclass->data_for_question_response_table($subpart->has_multiple_response_classes(), $partid);
 441                  foreach ($tabledata as $row) {
 442                      $qtable->add_data_keyed($qtable->format_row($row));
 443                  }
 444              }
 445          }
 446  
 447          $qtable->finish_output(!$this->table->is_downloading());
 448      }
 449  
 450      /**
 451       * Output the table that lists all the questions in the quiz with their statistics.
 452       *
 453       * @param \core_question\statistics\questions\all_calculated_for_qubaid_condition $questionstats the stats for all questions in
 454       *                                                                                               the quiz including subqs and
 455       *                                                                                               variants.
 456       */
 457      protected function output_quiz_structure_analysis_table($questionstats) {
 458          $limitvariants = !$this->table->is_downloading();
 459          foreach ($questionstats->get_all_slots() as $slot) {
 460              // Output the data for these question statistics.
 461              $structureanalysis = $questionstats->structure_analysis_for_one_slot($slot, $limitvariants);
 462              if (is_null($structureanalysis)) {
 463                  $this->table->add_separator();
 464              } else {
 465                  foreach ($structureanalysis as $row) {
 466                      $bgcssclass = '';
 467                      // The only way to identify in this point of the report if a row is a summary row
 468                      // is checking if it's a instance of calculated_question_summary class.
 469                      if ($row instanceof \core_question\statistics\questions\calculated_question_summary) {
 470                          // Apply a custom css class to summary row to remove border and reduce paddings.
 471                          $bgcssclass = 'quiz_statistics-summaryrow';
 472  
 473                          // For question that contain a summary row, we add a "hidden" row in between so the report
 474                          // display both rows with same background color.
 475                          $this->table->add_data_keyed([], 'd-none hidden');
 476                      }
 477  
 478                      $this->table->add_data_keyed($this->table->format_row($row), $bgcssclass);
 479                  }
 480              }
 481          }
 482  
 483          $this->table->finish_output(!$this->table->is_downloading());
 484      }
 485  
 486      /**
 487       * Return HTML for table of overall quiz statistics.
 488       *
 489       * @param array $quizinfo as returned by {@link get_formatted_quiz_info_data()}.
 490       * @return string the HTML.
 491       */
 492      protected function output_quiz_info_table($quizinfo) {
 493  
 494          $quizinfotable = new html_table();
 495          $quizinfotable->align = array('center', 'center');
 496          $quizinfotable->width = '60%';
 497          $quizinfotable->attributes['class'] = 'generaltable titlesleft';
 498          $quizinfotable->data = array();
 499  
 500          foreach ($quizinfo as $heading => $value) {
 501               $quizinfotable->data[] = array($heading, $value);
 502          }
 503  
 504          return html_writer::table($quizinfotable);
 505      }
 506  
 507      /**
 508       * Download the table of overall quiz statistics.
 509       *
 510       * @param array $quizinfo as returned by {@link get_formatted_quiz_info_data()}.
 511       */
 512      protected function download_quiz_info_table($quizinfo) {
 513          global $OUTPUT;
 514  
 515          // HTML download is a special case.
 516          if ($this->table->is_downloading() == 'html') {
 517              echo $OUTPUT->heading(get_string('quizinformation', 'quiz_statistics'), 3);
 518              echo $this->output_quiz_info_table($quizinfo);
 519              return;
 520          }
 521  
 522          // Reformat the data ready for output.
 523          $headers = array();
 524          $row = array();
 525          foreach ($quizinfo as $heading => $value) {
 526              $headers[] = $heading;
 527              $row[] = $value;
 528          }
 529  
 530          // Do the output.
 531          $exportclass = $this->table->export_class_instance();
 532          $exportclass->start_table(get_string('quizinformation', 'quiz_statistics'));
 533          $exportclass->output_headers($headers);
 534          $exportclass->add_data($row);
 535          $exportclass->finish_table();
 536      }
 537  
 538      /**
 539       * Output the HTML needed to show the statistics graph.
 540       *
 541       * @param int|object $quizorid The quiz, or its ID.
 542       * @param qubaid_condition $qubaids the question usages whose responses to analyse.
 543       * @param string $whichattempts Which attempts constant.
 544       */
 545      protected function output_statistics_graph($quizorid, $qubaids) {
 546          global $DB, $PAGE;
 547  
 548          $quiz = $quizorid;
 549          if (!is_object($quiz)) {
 550              $quiz = $DB->get_record('quiz', array('id' => $quizorid), '*', MUST_EXIST);
 551          }
 552  
 553          // Load the rest of the required data.
 554          $questions = quiz_report_get_significant_questions($quiz);
 555  
 556          // Only load main question not sub questions.
 557          $questionstatistics = $DB->get_records_select('question_statistics',
 558                  'hashcode = ? AND slot IS NOT NULL AND variant IS NULL',
 559              [$qubaids->get_hash_code()]);
 560  
 561          // Configure what to display.
 562          $fieldstoplot = [
 563              'facility' => get_string('facility', 'quiz_statistics'),
 564              'discriminativeefficiency' => get_string('discriminative_efficiency', 'quiz_statistics')
 565          ];
 566          $fieldstoplotfactor = ['facility' => 100, 'discriminativeefficiency' => 1];
 567  
 568          // Prepare the arrays to hold the data.
 569          $xdata = [];
 570          foreach (array_keys($fieldstoplot) as $fieldtoplot) {
 571              $ydata[$fieldtoplot] = [];
 572          }
 573  
 574          // Fill in the data for each question.
 575          foreach ($questionstatistics as $questionstatistic) {
 576              $number = $questions[$questionstatistic->slot]->number;
 577              $xdata[$number] = $number;
 578  
 579              foreach ($fieldstoplot as $fieldtoplot => $notused) {
 580                  $value = $questionstatistic->$fieldtoplot;
 581                  if (is_null($value)) {
 582                      $value = 0;
 583                  }
 584                  $value *= $fieldstoplotfactor[$fieldtoplot];
 585                  $ydata[$fieldtoplot][$number] = number_format($value, 2);
 586              }
 587          }
 588  
 589          // Create the chart.
 590          sort($xdata);
 591          $chart = new \core\chart_bar();
 592          $chart->get_xaxis(0, true)->set_label(get_string('position', 'quiz_statistics'));
 593          $chart->set_labels(array_values($xdata));
 594  
 595          foreach ($fieldstoplot as $fieldtoplot => $notused) {
 596              ksort($ydata[$fieldtoplot]);
 597              $series = new \core\chart_series($fieldstoplot[$fieldtoplot], array_values($ydata[$fieldtoplot]));
 598              $chart->add_series($series);
 599          }
 600  
 601          // Find max.
 602          $max = 0;
 603          foreach ($fieldstoplot as $fieldtoplot => $notused) {
 604              $max = max($max, max($ydata[$fieldtoplot]));
 605          }
 606  
 607          // Set Y properties.
 608          $yaxis = $chart->get_yaxis(0, true);
 609          $yaxis->set_stepsize(10);
 610          $yaxis->set_label('%');
 611  
 612          $output = $PAGE->get_renderer('mod_quiz');
 613          $graphname = get_string('statisticsreportgraph', 'quiz_statistics');
 614          echo $output->chart($chart, $graphname);
 615      }
 616  
 617      /**
 618       * Get the quiz and question statistics, either by loading the cached results,
 619       * or by recomputing them.
 620       *
 621       * @param object $quiz               the quiz settings.
 622       * @param string $whichattempts      which attempts to use, represented internally as one of the constants as used in
 623       *                                   $quiz->grademethod ie.
 624       *                                   QUIZ_GRADEAVERAGE, QUIZ_GRADEHIGHEST, QUIZ_ATTEMPTLAST or QUIZ_ATTEMPTFIRST
 625       *                                   we calculate stats based on which attempts would affect the grade for each student.
 626       * @param string $whichtries         which tries to analyse for response analysis. Will be one of
 627       *                                   question_attempt::FIRST_TRY, LAST_TRY or ALL_TRIES.
 628       * @param \core\dml\sql_join $groupstudentsjoins Contains joins, wheres, params for students in this group.
 629       * @param array  $questions          full question data.
 630       * @param \core\progress\base|null   $progress
 631       * @param bool $calculateifrequired  if true (the default) the stats will be calculated if not already stored.
 632       *                                   If false, [null, null] will be returned if the stats are not already available.
 633       * @return array with 2 elements:    - $quizstats The statistics for overall attempt scores.
 634       *                                   - $questionstats \core_question\statistics\questions\all_calculated_for_qubaid_condition
 635       *                                   Both may be null, if $calculateifrequired is false.
 636       */
 637      public function get_all_stats_and_analysis(
 638              $quiz, $whichattempts, $whichtries, \core\dml\sql_join $groupstudentsjoins,
 639              $questions, $progress = null, bool $calculateifrequired = true) {
 640  
 641          if ($progress === null) {
 642              $progress = new \core\progress\none();
 643          }
 644  
 645          $qubaids = quiz_statistics_qubaids_condition($quiz->id, $groupstudentsjoins, $whichattempts);
 646  
 647          $qcalc = new \core_question\statistics\questions\calculator($questions, $progress);
 648  
 649          $quizcalc = new \quiz_statistics\calculator($progress);
 650  
 651          $progress->start_progress('', 3);
 652          if ($quizcalc->get_last_calculated_time($qubaids) === false) {
 653              if (!$calculateifrequired) {
 654                  $progress->progress(3);
 655                  $progress->end_progress();
 656                  return [null, null];
 657              }
 658  
 659              // Recalculate now.
 660              $questionstats = $qcalc->calculate($qubaids);
 661              $progress->progress(1);
 662  
 663              $quizstats = $quizcalc->calculate($quiz->id, $whichattempts, $groupstudentsjoins, count($questions),
 664                                                $qcalc->get_sum_of_mark_variance());
 665              $progress->progress(2);
 666          } else {
 667              $quizstats = $quizcalc->get_cached($qubaids);
 668              $progress->progress(1);
 669              $questionstats = $qcalc->get_cached($qubaids);
 670              $progress->progress(2);
 671          }
 672  
 673          if ($quizstats->s()) {
 674              $subquestions = $questionstats->get_sub_questions();
 675              $this->analyse_responses_for_all_questions_and_subquestions($questions,
 676                                                                          $subquestions,
 677                                                                          $qubaids,
 678                                                                          $whichtries,
 679                                                                          $progress);
 680          }
 681          $progress->progress(3);
 682          $progress->end_progress();
 683  
 684          return array($quizstats, $questionstats);
 685      }
 686  
 687      /**
 688       * Appropriate instance depending if we want html output for the user or not.
 689       *
 690       * @return \core\progress\base child of \core\progress\base to handle the display (or not) of task progress.
 691       */
 692      protected function get_progress_trace_instance() {
 693          if ($this->progress === null) {
 694              if (!$this->table->is_downloading()) {
 695                  $this->progress = new \core\progress\display_if_slow(get_string('calculatingallstats', 'quiz_statistics'));
 696                  $this->progress->set_display_names();
 697              } else {
 698                  $this->progress = new \core\progress\none();
 699              }
 700          }
 701          return $this->progress;
 702      }
 703  
 704      /**
 705       * Analyse responses for all questions and sub questions in this quiz.
 706       *
 707       * @param object[] $questions as returned by self::load_and_initialise_questions_for_calculations
 708       * @param object[] $subquestions full question objects.
 709       * @param qubaid_condition $qubaids the question usages whose responses to analyse.
 710       * @param string $whichtries which tries to analyse \question_attempt::FIRST_TRY, LAST_TRY or ALL_TRIES.
 711       * @param null|\core\progress\base $progress Used to indicate progress of task.
 712       */
 713      protected function analyse_responses_for_all_questions_and_subquestions($questions, $subquestions, $qubaids,
 714                                                                              $whichtries, $progress = null) {
 715          if ($progress === null) {
 716              $progress = new \core\progress\none();
 717          }
 718  
 719          // Starting response analysis tasks.
 720          $progress->start_progress('', count($questions) + count($subquestions));
 721  
 722          $done = $this->analyse_responses_for_questions($questions, $qubaids, $whichtries, $progress);
 723  
 724          $this->analyse_responses_for_questions($subquestions, $qubaids, $whichtries, $progress, $done);
 725  
 726          // Finished all response analysis tasks.
 727          $progress->end_progress();
 728      }
 729  
 730      /**
 731       * Analyse responses for an array of questions or sub questions.
 732       *
 733       * @param object[] $questions  as returned by self::load_and_initialise_questions_for_calculations.
 734       * @param qubaid_condition $qubaids the question usages whose responses to analyse.
 735       * @param string $whichtries which tries to analyse \question_attempt::FIRST_TRY, LAST_TRY or ALL_TRIES.
 736       * @param null|\core\progress\base $progress Used to indicate progress of task.
 737       * @param int[] $done array keys are ids of questions that have been analysed before calling method.
 738       * @return array array keys are ids of questions that were analysed after this method call.
 739       */
 740      protected function analyse_responses_for_questions($questions, $qubaids, $whichtries, $progress = null, $done = array()) {
 741          $countquestions = count($questions);
 742          if (!$countquestions) {
 743              return array();
 744          }
 745          if ($progress === null) {
 746              $progress = new \core\progress\none();
 747          }
 748          $progress->start_progress('', $countquestions, $countquestions);
 749          foreach ($questions as $question) {
 750              $progress->increment_progress();
 751              if (question_bank::get_qtype($question->qtype, false)->can_analyse_responses()  && !isset($done[$question->id])) {
 752                  $responesstats = new analyser($question, $whichtries);
 753                  $responesstats->calculate($qubaids, $whichtries);
 754              }
 755              $done[$question->id] = 1;
 756          }
 757          $progress->end_progress();
 758          return $done;
 759      }
 760  
 761      /**
 762       * Return a little form for the user to request to download the full report, including quiz stats and response analysis for
 763       * all questions and sub-questions.
 764       *
 765       * @param moodle_url $reporturl the base URL of the report.
 766       * @return string HTML.
 767       */
 768      protected function everything_download_options(moodle_url $reporturl) {
 769          global $OUTPUT;
 770          return $OUTPUT->download_dataformat_selector(get_string('downloadeverything', 'quiz_statistics'),
 771              $reporturl->out_omit_querystring(), 'download', $reporturl->params() + array('everything' => 1));
 772      }
 773  
 774      /**
 775       * Return HTML for a message that says when the stats were last calculated and a 'recalculate now' button.
 776       *
 777       * @param int    $lastcachetime  the time the stats were last cached.
 778       * @param int    $quizid         the quiz id.
 779       * @param array  $groupstudentsjoins (joins, wheres, params) for students in the group or empty array if groups not used.
 780       * @param string $whichattempts which attempts to use, represented internally as one of the constants as used in
 781       *                                   $quiz->grademethod ie.
 782       *                                   QUIZ_GRADEAVERAGE, QUIZ_GRADEHIGHEST, QUIZ_ATTEMPTLAST or QUIZ_ATTEMPTFIRST
 783       *                                   we calculate stats based on which attempts would affect the grade for each student.
 784       * @param moodle_url $reporturl url for this report
 785       * @return string HTML.
 786       */
 787      protected function output_caching_info($lastcachetime, $quizid, $groupstudentsjoins, $whichattempts, $reporturl) {
 788          global $DB, $OUTPUT;
 789  
 790          if (empty($lastcachetime)) {
 791              return '';
 792          }
 793  
 794          // Find the number of attempts since the cached statistics were computed.
 795          list($fromqa, $whereqa, $qaparams) = quiz_statistics_attempts_sql($quizid, $groupstudentsjoins, $whichattempts, true);
 796          $count = $DB->count_records_sql("
 797                  SELECT COUNT(1)
 798                  FROM $fromqa
 799                  WHERE $whereqa
 800                  AND quiza.timefinish > {$lastcachetime}", $qaparams);
 801  
 802          if (!$count) {
 803              $count = 0;
 804          }
 805  
 806          // Generate the output.
 807          $a = new stdClass();
 808          $a->lastcalculated = format_time(time() - $lastcachetime);
 809          $a->count = $count;
 810  
 811          $recalcualteurl = new moodle_url($reporturl,
 812                  array('recalculate' => 1, 'sesskey' => sesskey()));
 813          $output = '';
 814          $output .= $OUTPUT->box_start(
 815                  'boxaligncenter generalbox boxwidthnormal mdl-align', 'cachingnotice');
 816          $output .= get_string('lastcalculated', 'quiz_statistics', $a);
 817          $output .= $OUTPUT->single_button($recalcualteurl,
 818                  get_string('recalculatenow', 'quiz_statistics'));
 819          $output .= $OUTPUT->box_end(true);
 820  
 821          return $output;
 822      }
 823  
 824      /**
 825       * Clear the cached data for a particular report configuration. This will trigger a re-computation the next time the report
 826       * is displayed.
 827       *
 828       * @param $qubaids qubaid_condition
 829       */
 830      public function clear_cached_data($qubaids) {
 831          global $DB;
 832          $DB->delete_records('quiz_statistics', array('hashcode' => $qubaids->get_hash_code()));
 833          $DB->delete_records('question_statistics', array('hashcode' => $qubaids->get_hash_code()));
 834          $DB->delete_records('question_response_analysis', array('hashcode' => $qubaids->get_hash_code()));
 835      }
 836  
 837      /**
 838       * Load the questions in this quiz and add some properties to the objects needed in the reports.
 839       *
 840       * @param object $quiz the quiz.
 841       * @return array of questions for this quiz.
 842       */
 843      public function load_and_initialise_questions_for_calculations($quiz) {
 844          // Load the questions.
 845          $questions = quiz_report_get_significant_questions($quiz);
 846          $questiondata = [];
 847          foreach ($questions as $qs => $question) {
 848              if ($question->qtype === 'random') {
 849                  $question->id = 0;
 850                  $question->name = get_string('random', 'quiz');
 851                  $question->questiontext = get_string('random', 'quiz');
 852                  $question->parenttype = 'random';
 853                  $questiondata[$question->slot] = $question;
 854              } else if ($question->qtype === 'missingtype') {
 855                  $question->id = is_numeric($question->id) ? (int) $question->id : 0;
 856                  $questiondata[$question->slot] = $question;
 857                  $question->name = get_string('deletedquestion', 'qtype_missingtype');
 858                  $question->questiontext = get_string('deletedquestiontext', 'qtype_missingtype');
 859              } else {
 860                  $q = question_bank::load_question_data($question->id);
 861                  $q->maxmark = $question->maxmark;
 862                  $q->slot = $question->slot;
 863                  $q->number = $question->number;
 864                  $q->parenttype = null;
 865                  $questiondata[$question->slot] = $q;
 866              }
 867          }
 868  
 869          return $questiondata;
 870      }
 871  
 872      /**
 873       * Output all response analysis for all questions, sub-questions and variants. For download in a number of formats.
 874       *
 875       * @param $qubaids
 876       * @param $questions
 877       * @param $questionstats
 878       * @param $reporturl
 879       * @param $whichtries string
 880       */
 881      protected function output_all_question_response_analysis($qubaids,
 882                                                               $questions,
 883                                                               $questionstats,
 884                                                               $reporturl,
 885                                                               $whichtries = question_attempt::LAST_TRY) {
 886          foreach ($questions as $slot => $question) {
 887              if (question_bank::get_qtype(
 888                  $question->qtype, false)->can_analyse_responses()
 889              ) {
 890                  if ($questionstats->for_slot($slot)->get_variants()) {
 891                      foreach ($questionstats->for_slot($slot)->get_variants() as $variantno) {
 892                          $this->output_individual_question_response_analysis($question,
 893                                                                              $variantno,
 894                                                                              $questionstats->for_slot($slot, $variantno)->s,
 895                                                                              $reporturl,
 896                                                                              $qubaids,
 897                                                                              $whichtries);
 898                      }
 899                  } else {
 900                      $this->output_individual_question_response_analysis($question,
 901                                                                          null,
 902                                                                          $questionstats->for_slot($slot)->s,
 903                                                                          $reporturl,
 904                                                                          $qubaids,
 905                                                                          $whichtries);
 906                  }
 907              } else if ($subqids = $questionstats->for_slot($slot)->get_sub_question_ids()) {
 908                  foreach ($subqids as $subqid) {
 909                      if ($variants = $questionstats->for_subq($subqid)->get_variants()) {
 910                          foreach ($variants as $variantno) {
 911                              $this->output_individual_question_response_analysis(
 912                                  $questionstats->for_subq($subqid, $variantno)->question,
 913                                  $variantno,
 914                                  $questionstats->for_subq($subqid, $variantno)->s,
 915                                  $reporturl,
 916                                  $qubaids,
 917                                  $whichtries);
 918                          }
 919                      } else {
 920                          $this->output_individual_question_response_analysis(
 921                              $questionstats->for_subq($subqid)->question,
 922                              null,
 923                              $questionstats->for_subq($subqid)->s,
 924                              $reporturl,
 925                              $qubaids,
 926                              $whichtries);
 927  
 928                      }
 929                  }
 930              }
 931          }
 932      }
 933  
 934      /**
 935       * Load question stats for a quiz
 936       *
 937       * @param int $quizid question usage
 938       * @param bool $calculateifrequired if true (the default) the stats will be calculated if not already stored.
 939       *     If false, null will be returned if the stats are not already available.
 940       * @return ?all_calculated_for_qubaid_condition question stats
 941       */
 942      public function calculate_questions_stats_for_question_bank(
 943              int $quizid,
 944              bool $calculateifrequired = true
 945          ): ?all_calculated_for_qubaid_condition {
 946          global $DB;
 947          $quiz = $DB->get_record('quiz', ['id' => $quizid], '*', MUST_EXIST);
 948          $questions = $this->load_and_initialise_questions_for_calculations($quiz);
 949  
 950          [, $questionstats] = $this->get_all_stats_and_analysis($quiz,
 951              $quiz->grademethod, question_attempt::ALL_TRIES, new \core\dml\sql_join(),
 952              $questions, null, $calculateifrequired);
 953  
 954          return $questionstats;
 955      }
 956  }