Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.

Differences Between: [Versions 311 and 402] [Versions 311 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   * Classes to enforce the various access rules that can apply to a quiz.
  19   *
  20   * @package   mod_quiz
  21   * @copyright 2009 Tim Hunt
  22   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23   */
  24  
  25  
  26  defined('MOODLE_INTERNAL') || die();
  27  
  28  
  29  /**
  30   * This class keeps track of the various access rules that apply to a particular
  31   * quiz, with convinient methods for seeing whether access is allowed.
  32   *
  33   * @copyright 2009 Tim Hunt
  34   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  35   * @since     Moodle 2.2
  36   */
  37  class quiz_access_manager {
  38      /** @var quiz the quiz settings object. */
  39      protected $quizobj;
  40      /** @var int the time to be considered as 'now'. */
  41      protected $timenow;
  42      /** @var array of quiz_access_rule_base. */
  43      protected $rules = array();
  44  
  45      /**
  46       * Create an instance for a particular quiz.
  47       * @param object $quizobj An instance of the class quiz from attemptlib.php.
  48       *      The quiz we will be controlling access to.
  49       * @param int $timenow The time to use as 'now'.
  50       * @param bool $canignoretimelimits Whether this user is exempt from time
  51       *      limits (has_capability('mod/quiz:ignoretimelimits', ...)).
  52       */
  53      public function __construct($quizobj, $timenow, $canignoretimelimits) {
  54          $this->quizobj = $quizobj;
  55          $this->timenow = $timenow;
  56          $this->rules = $this->make_rules($quizobj, $timenow, $canignoretimelimits);
  57      }
  58  
  59      /**
  60       * Make all the rules relevant to a particular quiz.
  61       * @param quiz $quizobj information about the quiz in question.
  62       * @param int $timenow the time that should be considered as 'now'.
  63       * @param bool $canignoretimelimits whether the current user is exempt from
  64       *      time limits by the mod/quiz:ignoretimelimits capability.
  65       * @return array of {@link quiz_access_rule_base}s.
  66       */
  67      protected function make_rules($quizobj, $timenow, $canignoretimelimits) {
  68  
  69          $rules = array();
  70          foreach (self::get_rule_classes() as $ruleclass) {
  71              $rule = $ruleclass::make($quizobj, $timenow, $canignoretimelimits);
  72              if ($rule) {
  73                  $rules[$ruleclass] = $rule;
  74              }
  75          }
  76  
  77          $superceededrules = array();
  78          foreach ($rules as $rule) {
  79              $superceededrules += $rule->get_superceded_rules();
  80          }
  81  
  82          foreach ($superceededrules as $superceededrule) {
  83              unset($rules['quizaccess_' . $superceededrule]);
  84          }
  85  
  86          return $rules;
  87      }
  88  
  89      /**
  90       * @return array of all the installed rule class names.
  91       */
  92      protected static function get_rule_classes() {
  93          return core_component::get_plugin_list_with_class('quizaccess', '', 'rule.php');
  94      }
  95  
  96      /**
  97       * Add any form fields that the access rules require to the settings form.
  98       *
  99       * Note that the standard plugins do not use this mechanism, becuase all their
 100       * settings are stored in the quiz table.
 101       *
 102       * @param mod_quiz_mod_form $quizform the quiz settings form that is being built.
 103       * @param MoodleQuickForm $mform the wrapped MoodleQuickForm.
 104       */
 105      public static function add_settings_form_fields(
 106              mod_quiz_mod_form $quizform, MoodleQuickForm $mform) {
 107  
 108          foreach (self::get_rule_classes() as $rule) {
 109              $rule::add_settings_form_fields($quizform, $mform);
 110          }
 111      }
 112  
 113      /**
 114       * The the options for the Browser security settings menu.
 115       *
 116       * @return array key => lang string.
 117       */
 118      public static function get_browser_security_choices() {
 119          $options = array('-' => get_string('none', 'quiz'));
 120          foreach (self::get_rule_classes() as $rule) {
 121              $options += $rule::get_browser_security_choices();
 122          }
 123          return $options;
 124      }
 125  
 126      /**
 127       * Validate the data from any form fields added using {@link add_settings_form_fields()}.
 128       * @param array $errors the errors found so far.
 129       * @param array $data the submitted form data.
 130       * @param array $files information about any uploaded files.
 131       * @param mod_quiz_mod_form $quizform the quiz form object.
 132       * @return array $errors the updated $errors array.
 133       */
 134      public static function validate_settings_form_fields(array $errors,
 135              array $data, $files, mod_quiz_mod_form $quizform) {
 136  
 137          foreach (self::get_rule_classes() as $rule) {
 138              $errors = $rule::validate_settings_form_fields($errors, $data, $files, $quizform);
 139          }
 140  
 141          return $errors;
 142      }
 143  
 144      /**
 145       * Save any submitted settings when the quiz settings form is submitted.
 146       *
 147       * Note that the standard plugins do not use this mechanism because their
 148       * settings are stored in the quiz table.
 149       *
 150       * @param object $quiz the data from the quiz form, including $quiz->id
 151       *      which is the id of the quiz being saved.
 152       */
 153      public static function save_settings($quiz) {
 154  
 155          foreach (self::get_rule_classes() as $rule) {
 156              $rule::save_settings($quiz);
 157          }
 158      }
 159  
 160      /**
 161       * Delete any rule-specific settings when the quiz is deleted.
 162       *
 163       * Note that the standard plugins do not use this mechanism because their
 164       * settings are stored in the quiz table.
 165       *
 166       * @param object $quiz the data from the database, including $quiz->id
 167       *      which is the id of the quiz being deleted.
 168       * @since Moodle 2.7.1, 2.6.4, 2.5.7
 169       */
 170      public static function delete_settings($quiz) {
 171  
 172          foreach (self::get_rule_classes() as $rule) {
 173              $rule::delete_settings($quiz);
 174          }
 175      }
 176  
 177      /**
 178       * Build the SQL for loading all the access settings in one go.
 179       * @param int $quizid the quiz id.
 180       * @param string $basefields initial part of the select list.
 181       * @return array with two elements, the sql and the placeholder values.
 182       *      If $basefields is '' then you must allow for the possibility that
 183       *      there is no data to load, in which case this method returns $sql = ''.
 184       */
 185      protected static function get_load_sql($quizid, $rules, $basefields) {
 186          $allfields = $basefields;
 187          $alljoins = '{quiz} quiz';
 188          $allparams = array('quizid' => $quizid);
 189  
 190          foreach ($rules as $rule) {
 191              list($fields, $joins, $params) = $rule::get_settings_sql($quizid);
 192              if ($fields) {
 193                  if ($allfields) {
 194                      $allfields .= ', ';
 195                  }
 196                  $allfields .= $fields;
 197              }
 198              if ($joins) {
 199                  $alljoins .= ' ' . $joins;
 200              }
 201              if ($params) {
 202                  $allparams += $params;
 203              }
 204          }
 205  
 206          if ($allfields === '') {
 207              return array('', array());
 208          }
 209  
 210          return array("SELECT $allfields FROM $alljoins WHERE quiz.id = :quizid", $allparams);
 211      }
 212  
 213      /**
 214       * Load any settings required by the access rules. We try to do this with
 215       * a single DB query.
 216       *
 217       * Note that the standard plugins do not use this mechanism, becuase all their
 218       * settings are stored in the quiz table.
 219       *
 220       * @param int $quizid the quiz id.
 221       * @return array setting value name => value. The value names should all
 222       *      start with the name of the corresponding plugin to avoid collisions.
 223       */
 224      public static function load_settings($quizid) {
 225          global $DB;
 226  
 227          $rules = self::get_rule_classes();
 228          list($sql, $params) = self::get_load_sql($quizid, $rules, '');
 229  
 230          if ($sql) {
 231              $data = (array) $DB->get_record_sql($sql, $params);
 232          } else {
 233              $data = array();
 234          }
 235  
 236          foreach ($rules as $rule) {
 237              $data += $rule::get_extra_settings($quizid);
 238          }
 239  
 240          return $data;
 241      }
 242  
 243      /**
 244       * Load the quiz settings and any settings required by the access rules.
 245       * We try to do this with a single DB query.
 246       *
 247       * Note that the standard plugins do not use this mechanism, becuase all their
 248       * settings are stored in the quiz table.
 249       *
 250       * @param int $quizid the quiz id.
 251       * @return object mdl_quiz row with extra fields.
 252       */
 253      public static function load_quiz_and_settings($quizid) {
 254          global $DB;
 255  
 256          $rules = self::get_rule_classes();
 257          list($sql, $params) = self::get_load_sql($quizid, $rules, 'quiz.*');
 258          $quiz = $DB->get_record_sql($sql, $params, MUST_EXIST);
 259  
 260          foreach ($rules as $rule) {
 261              foreach ($rule::get_extra_settings($quizid) as $name => $value) {
 262                  $quiz->$name = $value;
 263              }
 264          }
 265  
 266          return $quiz;
 267      }
 268  
 269      /**
 270       * @return array the class names of all the active rules. Mainly useful for
 271       * debugging.
 272       */
 273      public function get_active_rule_names() {
 274          $classnames = array();
 275          foreach ($this->rules as $rule) {
 276              $classnames[] = get_class($rule);
 277          }
 278          return $classnames;
 279      }
 280  
 281      /**
 282       * Accumulates an array of messages.
 283       * @param array $messages the current list of messages.
 284       * @param string|array $new the new messages or messages.
 285       * @return array the updated array of messages.
 286       */
 287      protected function accumulate_messages($messages, $new) {
 288          if (is_array($new)) {
 289              $messages = array_merge($messages, $new);
 290          } else if (is_string($new) && $new) {
 291              $messages[] = $new;
 292          }
 293          return $messages;
 294      }
 295  
 296      /**
 297       * Provide a description of the rules that apply to this quiz, such
 298       * as is shown at the top of the quiz view page. Note that not all
 299       * rules consider themselves important enough to output a description.
 300       *
 301       * @return array an array of description messages which may be empty. It
 302       *         would be sensible to output each one surrounded by &lt;p> tags.
 303       */
 304      public function describe_rules() {
 305          $result = array();
 306          foreach ($this->rules as $rule) {
 307              $result = $this->accumulate_messages($result, $rule->description());
 308          }
 309          return $result;
 310      }
 311  
 312      /**
 313       * Whether or not a user should be allowed to start a new attempt at this quiz now.
 314       * If there are any restrictions in force now, return an array of reasons why access
 315       * should be blocked. If access is OK, return false.
 316       *
 317       * @param int $numattempts the number of previous attempts this user has made.
 318       * @param object|false $lastattempt information about the user's last completed attempt.
 319       *      if there is not a previous attempt, the false is passed.
 320       * @return mixed An array of reason why access is not allowed, or an empty array
 321       *         (== false) if access should be allowed.
 322       */
 323      public function prevent_new_attempt($numprevattempts, $lastattempt) {
 324          $reasons = array();
 325          foreach ($this->rules as $rule) {
 326              $reasons = $this->accumulate_messages($reasons,
 327                      $rule->prevent_new_attempt($numprevattempts, $lastattempt));
 328          }
 329          return $reasons;
 330      }
 331  
 332      /**
 333       * Whether the user should be blocked from starting a new attempt or continuing
 334       * an attempt now. If there are any restrictions in force now, return an array
 335       * of reasons why access should be blocked. If access is OK, return false.
 336       *
 337       * @return mixed An array of reason why access is not allowed, or an empty array
 338       *         (== false) if access should be allowed.
 339       */
 340      public function prevent_access() {
 341          $reasons = array();
 342          foreach ($this->rules as $rule) {
 343              $reasons = $this->accumulate_messages($reasons, $rule->prevent_access());
 344          }
 345          return $reasons;
 346      }
 347  
 348      /**
 349       * @param int|null $attemptid the id of the current attempt, if there is one,
 350       *      otherwise null.
 351       * @return bool whether a check is required before the user starts/continues
 352       *      their attempt.
 353       */
 354      public function is_preflight_check_required($attemptid) {
 355          foreach ($this->rules as $rule) {
 356              if ($rule->is_preflight_check_required($attemptid)) {
 357                  return true;
 358              }
 359          }
 360          return false;
 361      }
 362  
 363      /**
 364       * Build the form required to do the pre-flight checks.
 365       * @param moodle_url $url the form action URL.
 366       * @param int|null $attemptid the id of the current attempt, if there is one,
 367       *      otherwise null.
 368       * @return mod_quiz_preflight_check_form the form.
 369       */
 370      public function get_preflight_check_form(moodle_url $url, $attemptid) {
 371          // This form normally wants POST submissins. However, it also needs to
 372          // accept GET submissions. Since formslib is strict, we have to detect
 373          // which case we are in, and set the form property appropriately.
 374          $method = 'post';
 375          if (!empty($_GET['_qf__mod_quiz_preflight_check_form'])) {
 376              $method = 'get';
 377          }
 378          return new mod_quiz_preflight_check_form($url->out_omit_querystring(),
 379                  array('rules' => $this->rules, 'quizobj' => $this->quizobj,
 380                        'attemptid' => $attemptid, 'hidden' => $url->params()), $method);
 381      }
 382  
 383      /**
 384       * The pre-flight check has passed. This is a chance to record that fact in
 385       * some way.
 386       * @param int|null $attemptid the id of the current attempt, if there is one,
 387       *      otherwise null.
 388       */
 389      public function notify_preflight_check_passed($attemptid) {
 390          foreach ($this->rules as $rule) {
 391              $rule->notify_preflight_check_passed($attemptid);
 392          }
 393      }
 394  
 395      /**
 396       * Inform the rules that the current attempt is finished. This is use, for example
 397       * by the password rule, to clear the flag in the session.
 398       */
 399      public function current_attempt_finished() {
 400          foreach ($this->rules as $rule) {
 401              $rule->current_attempt_finished();
 402          }
 403      }
 404  
 405      /**
 406       * Do any of the rules mean that this student will no be allowed any further attempts at this
 407       * quiz. Used, for example, to change the label by the grade displayed on the view page from
 408       * 'your current grade is' to 'your final grade is'.
 409       *
 410       * @param int $numattempts the number of previous attempts this user has made.
 411       * @param object $lastattempt information about the user's last completed attempt.
 412       * @return bool true if there is no way the user will ever be allowed to attempt
 413       *      this quiz again.
 414       */
 415      public function is_finished($numprevattempts, $lastattempt) {
 416          foreach ($this->rules as $rule) {
 417              if ($rule->is_finished($numprevattempts, $lastattempt)) {
 418                  return true;
 419              }
 420          }
 421          return false;
 422      }
 423  
 424      /**
 425       * Sets up the attempt (review or summary) page with any properties required
 426       * by the access rules.
 427       *
 428       * @param moodle_page $page the page object to initialise.
 429       */
 430      public function setup_attempt_page($page) {
 431          foreach ($this->rules as $rule) {
 432              $rule->setup_attempt_page($page);
 433          }
 434      }
 435  
 436      /**
 437       * Compute when the attempt must be submitted.
 438       *
 439       * @param object $attempt the data from the relevant quiz_attempts row.
 440       * @return int|false the attempt close time.
 441       *      False if there is no limit.
 442       */
 443      public function get_end_time($attempt) {
 444          $timeclose = false;
 445          foreach ($this->rules as $rule) {
 446              $ruletimeclose = $rule->end_time($attempt);
 447              if ($ruletimeclose !== false && ($timeclose === false || $ruletimeclose < $timeclose)) {
 448                  $timeclose = $ruletimeclose;
 449              }
 450          }
 451          return $timeclose;
 452      }
 453  
 454      /**
 455       * Compute what should be displayed to the user for time remaining in this attempt.
 456       *
 457       * @param object $attempt the data from the relevant quiz_attempts row.
 458       * @param int $timenow the time to consider as 'now'.
 459       * @return int|false the number of seconds remaining for this attempt.
 460       *      False if no limit should be displayed.
 461       */
 462      public function get_time_left_display($attempt, $timenow) {
 463          $timeleft = false;
 464          foreach ($this->rules as $rule) {
 465              $ruletimeleft = $rule->time_left_display($attempt, $timenow);
 466              if ($ruletimeleft !== false && ($timeleft === false || $ruletimeleft < $timeleft)) {
 467                  $timeleft = $ruletimeleft;
 468              }
 469          }
 470          return $timeleft;
 471      }
 472  
 473      /**
 474       * @return bolean if this quiz should only be shown to students in a popup window.
 475       */
 476      public function attempt_must_be_in_popup() {
 477          foreach ($this->rules as $rule) {
 478              if ($rule->attempt_must_be_in_popup()) {
 479                  return true;
 480              }
 481          }
 482          return false;
 483      }
 484  
 485      /**
 486       * @return array any options that are required for showing the attempt page
 487       *      in a popup window.
 488       */
 489      public function get_popup_options() {
 490          $options = array();
 491          foreach ($this->rules as $rule) {
 492              $options += $rule->get_popup_options();
 493          }
 494          return $options;
 495      }
 496  
 497      /**
 498       * Send the user back to the quiz view page. Normally this is just a redirect, but
 499       * If we were in a secure window, we close this window, and reload the view window we came from.
 500       *
 501       * This method does not return;
 502       *
 503       * @param mod_quiz_renderer $output the quiz renderer.
 504       * @param string $message optional message to output while redirecting.
 505       */
 506      public function back_to_view_page($output, $message = '') {
 507          if ($this->attempt_must_be_in_popup()) {
 508              echo $output->close_attempt_popup($this->quizobj->view_url(), $message);
 509              die();
 510          } else {
 511              redirect($this->quizobj->view_url(), $message);
 512          }
 513      }
 514  
 515      /**
 516       * Make some text into a link to review the quiz, if that is appropriate.
 517       *
 518       * @param string $linktext some text.
 519       * @param object $attempt the attempt object
 520       * @return string some HTML, the $linktext either unmodified or wrapped in a
 521       *      link to the review page.
 522       */
 523      public function make_review_link($attempt, $reviewoptions, $output) {
 524  
 525          // If the attempt is still open, don't link.
 526          if (in_array($attempt->state, array(quiz_attempt::IN_PROGRESS, quiz_attempt::OVERDUE))) {
 527              return $output->no_review_message('');
 528          }
 529  
 530          $when = quiz_attempt_state($this->quizobj->get_quiz(), $attempt);
 531          $reviewoptions = mod_quiz_display_options::make_from_quiz(
 532                  $this->quizobj->get_quiz(), $when);
 533  
 534          if (!$reviewoptions->attempt) {
 535              return $output->no_review_message($this->quizobj->cannot_review_message($when, true));
 536  
 537          } else {
 538              return $output->review_link($this->quizobj->review_url($attempt->id),
 539                      $this->attempt_must_be_in_popup(), $this->get_popup_options());
 540          }
 541      }
 542  
 543      /**
 544       * Run the preflight checks using the given data in all the rules supporting them.
 545       *
 546       * @param array $data passed data for validation
 547       * @param array $files un-used, Moodle seems to not support it anymore
 548       * @param int|null $attemptid the id of the current attempt, if there is one,
 549       *      otherwise null.
 550       * @return array of errors, empty array means no erros
 551       * @since  Moodle 3.1
 552       */
 553      public function validate_preflight_check($data, $files, $attemptid) {
 554          $errors = array();
 555          foreach ($this->rules as $rule) {
 556              if ($rule->is_preflight_check_required($attemptid)) {
 557                  $errors = $rule->validate_preflight_check($data, $files, $errors, $attemptid);
 558              }
 559          }
 560          return $errors;
 561      }
 562  }