Search moodle.org's
Developer Documentation

See Release Notes

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