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 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   * The file defines a base class that can be used to build a report like the
  19   * overview or responses report, that has one row per attempt.
  20   *
  21   * @package   mod_quiz
  22   * @copyright 2010 The Open University
  23   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  24   */
  25  
  26  
  27  defined('MOODLE_INTERNAL') || die();
  28  
  29  require_once($CFG->libdir.'/tablelib.php');
  30  
  31  
  32  /**
  33   * Base class for quiz reports that are basically a table with one row for each attempt.
  34   *
  35   * @copyright 2010 The Open University
  36   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  37   */
  38  abstract class quiz_attempts_report extends quiz_default_report {
  39      /** @var int default page size for reports. */
  40      const DEFAULT_PAGE_SIZE = 30;
  41  
  42      /** @var string constant used for the options, means all users with attempts. */
  43      const ALL_WITH = 'all_with';
  44      /** @var string constant used for the options, means only enrolled users with attempts. */
  45      const ENROLLED_WITH = 'enrolled_with';
  46      /** @var string constant used for the options, means only enrolled users without attempts. */
  47      const ENROLLED_WITHOUT = 'enrolled_without';
  48      /** @var string constant used for the options, means all enrolled users. */
  49      const ENROLLED_ALL = 'enrolled_any';
  50  
  51      /** @var string the mode this report is. */
  52      protected $mode;
  53  
  54      /** @var context_module the quiz context. */
  55      protected $context;
  56  
  57      /** @var mod_quiz_attempts_report_form The settings form to use. */
  58      protected $form;
  59  
  60      /** @var string SQL fragment for selecting the attempt that gave the final grade,
  61       * if applicable. */
  62      protected $qmsubselect;
  63  
  64      /** @var boolean caches the results of {@link should_show_grades()}. */
  65      protected $showgrades = null;
  66  
  67      /**
  68       *  Initialise various aspects of this report.
  69       *
  70       * @param string $mode
  71       * @param string $formclass
  72       * @param object $quiz
  73       * @param object $cm
  74       * @param object $course
  75       * @return array with four elements:
  76       *      0 => integer the current group id (0 for none).
  77       *      1 => \core\dml\sql_join Contains joins, wheres, params for all the students in this course.
  78       *      2 => \core\dml\sql_join Contains joins, wheres, params for all the students in the current group.
  79       *      3 => \core\dml\sql_join Contains joins, wheres, params for all the students to show in the report.
  80       *              Will be the same as either element 1 or 2.
  81       */
  82      public function init($mode, $formclass, $quiz, $cm, $course) {
  83          $this->mode = $mode;
  84  
  85          $this->context = context_module::instance($cm->id);
  86  
  87          list($currentgroup, $studentsjoins, $groupstudentsjoins, $allowedjoins) = $this->get_students_joins(
  88                  $cm, $course);
  89  
  90          $this->qmsubselect = quiz_report_qm_filter_select($quiz);
  91  
  92          $this->form = new $formclass($this->get_base_url(),
  93                  array('quiz' => $quiz, 'currentgroup' => $currentgroup, 'context' => $this->context));
  94  
  95          return array($currentgroup, $studentsjoins, $groupstudentsjoins, $allowedjoins);
  96      }
  97  
  98      /**
  99       * Get the base URL for this report.
 100       * @return moodle_url the URL.
 101       */
 102      protected function get_base_url() {
 103          return new moodle_url('/mod/quiz/report.php',
 104                  array('id' => $this->context->instanceid, 'mode' => $this->mode));
 105      }
 106  
 107      /**
 108       * Get sql fragments (joins) which can be used to build queries that
 109       * will select an appropriate set of students to show in the reports.
 110       *
 111       * @param object $cm the course module.
 112       * @param object $course the course settings.
 113       * @return array with four elements:
 114       *      0 => integer the current group id (0 for none).
 115       *      1 => \core\dml\sql_join Contains joins, wheres, params for all the students in this course.
 116       *      2 => \core\dml\sql_join Contains joins, wheres, params for all the students in the current group.
 117       *      3 => \core\dml\sql_join Contains joins, wheres, params for all the students to show in the report.
 118       *              Will be the same as either element 1 or 2.
 119       */
 120      protected function get_students_joins($cm, $course = null) {
 121          $currentgroup = $this->get_current_group($cm, $course, $this->context);
 122  
 123          $empty = new \core\dml\sql_join();
 124          if ($currentgroup == self::NO_GROUPS_ALLOWED) {
 125              return array($currentgroup, $empty, $empty, $empty);
 126          }
 127  
 128          $studentsjoins = get_enrolled_with_capabilities_join($this->context, '',
 129                  array('mod/quiz:attempt', 'mod/quiz:reviewmyattempts'));
 130  
 131          if (empty($currentgroup)) {
 132              return array($currentgroup, $studentsjoins, $empty, $studentsjoins);
 133          }
 134  
 135          // We have a currently selected group.
 136          $groupstudentsjoins = get_enrolled_with_capabilities_join($this->context, '',
 137                  array('mod/quiz:attempt', 'mod/quiz:reviewmyattempts'), $currentgroup);
 138  
 139          return array($currentgroup, $studentsjoins, $groupstudentsjoins, $groupstudentsjoins);
 140      }
 141  
 142      /**
 143       * Outputs the things you commonly want at the top of a quiz report.
 144       *
 145       * Calls through to {@link print_header_and_tabs()} and then
 146       * outputs the standard group selector, number of attempts summary,
 147       * and messages to cover common cases when the report can't be shown.
 148       *
 149       * @param stdClass $cm the course_module information.
 150       * @param stdClass $course the course settings.
 151       * @param stdClass $quiz the quiz settings.
 152       * @param mod_quiz_attempts_report_options $options the current report settings.
 153       * @param int $currentgroup the current group.
 154       * @param bool $hasquestions whether there are any questions in the quiz.
 155       * @param bool $hasstudents whether there are any relevant students.
 156       */
 157      protected function print_standard_header_and_messages($cm, $course, $quiz,
 158              $options, $currentgroup, $hasquestions, $hasstudents) {
 159          global $OUTPUT;
 160  
 161          $this->print_header_and_tabs($cm, $course, $quiz, $this->mode);
 162  
 163          if (groups_get_activity_groupmode($cm)) {
 164              // Groups are being used, so output the group selector if we are not downloading.
 165              groups_print_activity_menu($cm, $options->get_url());
 166          }
 167  
 168          // Print information on the number of existing attempts.
 169          if ($strattemptnum = quiz_num_attempt_summary($quiz, $cm, true, $currentgroup)) {
 170              echo '<div class="quizattemptcounts">' . $strattemptnum . '</div>';
 171          }
 172  
 173          if (!$hasquestions) {
 174              echo quiz_no_questions_message($quiz, $cm, $this->context);
 175          } else if ($currentgroup == self::NO_GROUPS_ALLOWED) {
 176              echo $OUTPUT->notification(get_string('notingroup'));
 177          } else if (!$hasstudents) {
 178              echo $OUTPUT->notification(get_string('nostudentsyet'));
 179          } else if ($currentgroup && !$this->hasgroupstudents) {
 180              echo $OUTPUT->notification(get_string('nostudentsingroup'));
 181          }
 182      }
 183  
 184      /**
 185       * Add all the user-related columns to the $columns and $headers arrays.
 186       * @param table_sql $table the table being constructed.
 187       * @param array $columns the list of columns. Added to.
 188       * @param array $headers the columns headings. Added to.
 189       */
 190      protected function add_user_columns($table, &$columns, &$headers) {
 191          global $CFG;
 192          if (!$table->is_downloading() && $CFG->grade_report_showuserimage) {
 193              $columns[] = 'picture';
 194              $headers[] = '';
 195          }
 196          if (!$table->is_downloading()) {
 197              $columns[] = 'fullname';
 198              $headers[] = get_string('name');
 199          } else {
 200              $columns[] = 'lastname';
 201              $headers[] = get_string('lastname');
 202              $columns[] = 'firstname';
 203              $headers[] = get_string('firstname');
 204          }
 205  
 206          $extrafields = \core_user\fields::get_identity_fields($this->context);
 207          foreach ($extrafields as $field) {
 208              $columns[] = $field;
 209              $headers[] = \core_user\fields::get_display_name($field);
 210          }
 211      }
 212  
 213      /**
 214       * Set the display options for the user-related columns in the table.
 215       * @param table_sql $table the table being constructed.
 216       */
 217      protected function configure_user_columns($table) {
 218          $table->column_suppress('picture');
 219          $table->column_suppress('fullname');
 220  
 221          $extrafields = \core_user\fields::get_identity_fields($this->context);
 222          foreach ($extrafields as $field) {
 223              $table->column_suppress($field);
 224          }
 225  
 226          $table->column_class('picture', 'picture');
 227          $table->column_class('lastname', 'bold');
 228          $table->column_class('firstname', 'bold');
 229          $table->column_class('fullname', 'bold');
 230      }
 231  
 232      /**
 233       * Add the state column to the $columns and $headers arrays.
 234       * @param array $columns the list of columns. Added to.
 235       * @param array $headers the columns headings. Added to.
 236       */
 237      protected function add_state_column(&$columns, &$headers) {
 238          $columns[] = 'state';
 239          $headers[] = get_string('attemptstate', 'quiz');
 240      }
 241  
 242      /**
 243       * Add all the time-related columns to the $columns and $headers arrays.
 244       * @param array $columns the list of columns. Added to.
 245       * @param array $headers the columns headings. Added to.
 246       */
 247      protected function add_time_columns(&$columns, &$headers) {
 248          $columns[] = 'timestart';
 249          $headers[] = get_string('startedon', 'quiz');
 250  
 251          $columns[] = 'timefinish';
 252          $headers[] = get_string('timecompleted', 'quiz');
 253  
 254          $columns[] = 'duration';
 255          $headers[] = get_string('attemptduration', 'quiz');
 256      }
 257  
 258      /**
 259       * Add all the grade and feedback columns, if applicable, to the $columns
 260       * and $headers arrays.
 261       * @param object $quiz the quiz settings.
 262       * @param bool $usercanseegrades whether the user is allowed to see grades for this quiz.
 263       * @param array $columns the list of columns. Added to.
 264       * @param array $headers the columns headings. Added to.
 265       * @param bool $includefeedback whether to include the feedbacktext columns
 266       */
 267      protected function add_grade_columns($quiz, $usercanseegrades, &$columns, &$headers, $includefeedback = true) {
 268          if ($usercanseegrades) {
 269              $columns[] = 'sumgrades';
 270              $headers[] = get_string('grade', 'quiz') . '/' .
 271                      quiz_format_grade($quiz, $quiz->grade);
 272          }
 273  
 274          if ($includefeedback && quiz_has_feedback($quiz)) {
 275              $columns[] = 'feedbacktext';
 276              $headers[] = get_string('feedback', 'quiz');
 277          }
 278      }
 279  
 280      /**
 281       * Set up the table.
 282       * @param table_sql $table the table being constructed.
 283       * @param array $columns the list of columns.
 284       * @param array $headers the columns headings.
 285       * @param moodle_url $reporturl the URL of this report.
 286       * @param mod_quiz_attempts_report_options $options the display options.
 287       * @param bool $collapsible whether to allow columns in the report to be collapsed.
 288       */
 289      protected function set_up_table_columns($table, $columns, $headers, $reporturl,
 290              mod_quiz_attempts_report_options $options, $collapsible) {
 291          $table->define_columns($columns);
 292          $table->define_headers($headers);
 293          $table->sortable(true, 'uniqueid');
 294  
 295          $table->define_baseurl($options->get_url());
 296  
 297          $this->configure_user_columns($table);
 298  
 299          $table->no_sorting('feedbacktext');
 300          $table->column_class('sumgrades', 'bold');
 301  
 302          $table->set_attribute('id', 'attempts');
 303  
 304          $table->collapsible($collapsible);
 305      }
 306  
 307      /**
 308       * Process any submitted actions.
 309       * @param object $quiz the quiz settings.
 310       * @param object $cm the cm object for the quiz.
 311       * @param int $currentgroup the currently selected group.
 312       * @param \core\dml\sql_join $groupstudentsjoins (joins, wheres, params) the students in the current group.
 313       * @param \core\dml\sql_join $allowedjoins (joins, wheres, params) the users whose attempt this user is allowed to modify.
 314       * @param moodle_url $redirecturl where to redircet to after a successful action.
 315       */
 316      protected function process_actions($quiz, $cm, $currentgroup, \core\dml\sql_join $groupstudentsjoins,
 317              \core\dml\sql_join $allowedjoins, $redirecturl) {
 318          if (empty($currentgroup) || $this->hasgroupstudents) {
 319              if (optional_param('delete', 0, PARAM_BOOL) && confirm_sesskey()) {
 320                  if ($attemptids = optional_param_array('attemptid', array(), PARAM_INT)) {
 321                      require_capability('mod/quiz:deleteattempts', $this->context);
 322                      $this->delete_selected_attempts($quiz, $cm, $attemptids, $allowedjoins);
 323                      redirect($redirecturl);
 324                  }
 325              }
 326          }
 327      }
 328  
 329      /**
 330       * Delete the quiz attempts
 331       * @param object $quiz the quiz settings. Attempts that don't belong to
 332       * this quiz are not deleted.
 333       * @param object $cm the course_module object.
 334       * @param array $attemptids the list of attempt ids to delete.
 335       * @param \core\dml\sql_join $allowedjoins (joins, wheres, params) This list of userids that are visible in the report.
 336       *      Users can only delete attempts that they are allowed to see in the report.
 337       *      Empty means all users.
 338       */
 339      protected function delete_selected_attempts($quiz, $cm, $attemptids, \core\dml\sql_join $allowedjoins) {
 340          global $DB;
 341  
 342          foreach ($attemptids as $attemptid) {
 343              if (empty($allowedjoins->joins)) {
 344                  $sql = "SELECT quiza.*
 345                            FROM {quiz_attempts} quiza
 346                            JOIN {user} u ON u.id = quiza.userid
 347                           WHERE quiza.id = :attemptid";
 348              } else {
 349                  $sql = "SELECT quiza.*
 350                            FROM {quiz_attempts} quiza
 351                            JOIN {user} u ON u.id = quiza.userid
 352                          {$allowedjoins->joins}
 353                           WHERE {$allowedjoins->wheres} AND quiza.id = :attemptid";
 354              }
 355              $params = $allowedjoins->params + array('attemptid' => $attemptid);
 356              $attempt = $DB->get_record_sql($sql, $params, IGNORE_MULTIPLE);
 357              if (!$attempt || $attempt->quiz != $quiz->id || $attempt->preview != 0) {
 358                  // Ensure the attempt exists, belongs to this quiz and belongs to
 359                  // a student included in the report. If not skip.
 360                  continue;
 361              }
 362  
 363              // Set the course module id before calling quiz_delete_attempt().
 364              $quiz->cmid = $cm->id;
 365              quiz_delete_attempt($attempt, $quiz);
 366          }
 367      }
 368  
 369      /**
 370       * Get information about which students to show in the report.
 371       * @param object $cm the coures module.
 372       * @param object $course the course settings.
 373       * @return array with four elements:
 374       *      0 => integer the current group id (0 for none).
 375       *      1 => array ids of all the students in this course.
 376       *      2 => array ids of all the students in the current group.
 377       *      3 => array ids of all the students to show in the report. Will be the
 378       *              same as either element 1 or 2.
 379       * @deprecated since Moodle 3.2 Please use get_students_joins() instead.
 380       */
 381      protected function load_relevant_students($cm, $course = null) {
 382          $msg = 'The function load_relevant_students() is deprecated. Please use get_students_joins() instead.';
 383          throw new coding_exception($msg);
 384      }
 385  }