MDL-29254 Fixed whitespace
[moodle.git] / mod / quiz / accessmanager.php
blob39c5e80b2ddbf92b664cd1f87368eca6fecbffa2
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.
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/>.
17 /**
18 * Classes to enforce the various access rules that can apply to a quiz.
20 * @package mod
21 * @subpackage quiz
22 * @copyright 2009 Tim Hunt
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') || die();
30 /**
31 * This class keeps track of the various access rules that apply to a particular
32 * quiz, with convinient methods for seeing whether access is allowed.
34 * @copyright 2009 Tim Hunt
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
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();
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', ...)).
53 public function __construct($quizobj, $timenow, $canignoretimelimits) {
54 $this->quizobj = $quizobj;
55 $this->timenow = $timenow;
56 $this->rules = $this->make_rules($quizobj, $timenow, $canignoretimelimits);
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.
67 protected function make_rules($quizobj, $timenow, $canignoretimelimits) {
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;
77 $superceededrules = array();
78 foreach ($rules as $rule) {
79 $superceededrules += $rule->get_superceded_rules();
82 foreach ($superceededrules as $superceededrule) {
83 unset($rules['quizaccess_' . $superceededrule]);
86 return $rules;
89 /**
90 * @return array of all the installed rule class names.
92 protected static function get_rule_classes() {
93 return get_plugin_list_with_class('quizaccess', '', 'rule.php');
96 /**
97 * Add any form fields that the access rules require to the settings form.
99 * Note that the standard plugins do not use this mechanism, becuase all their
100 * settings are stored in the quiz table.
102 * @param mod_quiz_mod_form $quizform the quiz settings form that is being built.
103 * @param MoodleQuickForm $mform the wrapped MoodleQuickForm.
105 public static function add_settings_form_fields(
106 mod_quiz_mod_form $quizform, MoodleQuickForm $mform) {
108 foreach (self::get_rule_classes() as $rule) {
109 $rule::add_settings_form_fields($quizform, $mform);
114 * The the options for the Browser security settings menu.
116 * @return array key => lang string.
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();
123 return $options;
127 * Save any submitted settings when the quiz settings form is submitted.
129 * Note that the standard plugins do not use this mechanism, becuase all their
130 * settings are stored in the quiz table.
132 * @param object $quiz the data from the quiz form, including $quiz->id
133 * which is the is of the quiz being saved.
135 public static function save_settings($quiz) {
137 foreach (self::get_rule_classes() as $rule) {
138 $rule::save_settings($quiz);
143 * Build the SQL for loading all the access settings in one go.
144 * @param int $quizid the quiz id.
145 * @param string $basefields initial part of the select list.
146 * @return array with two elements, the sql and the placeholder values.
147 * If $basefields is '' then you must allow for the possibility that
148 * there is no data to load, in which case this method returns $sql = ''.
150 protected static function get_load_sql($quizid, $rules, $basefields) {
151 $allfields = $basefields;
152 $alljoins = '{quiz} quiz';
153 $allparams = array('quizid' => $quizid);
155 foreach ($rules as $rule) {
156 list($fields, $joins, $params) = $rule::get_settings_sql($quizid);
157 if ($fields) {
158 if ($allfields) {
159 $allfields .= ', ';
161 $allfields .= $fields;
163 if ($joins) {
164 $alljoins .= ' ' . $joins;
166 if ($params) {
167 $allparams += $params;
171 if ($allfields === '') {
172 return array('', array());
175 return array("SELECT $allfields FROM $alljoins WHERE quiz.id = :quizid", $allparams);
179 * Load any settings required by the access rules. We try to do this with
180 * a single DB query.
182 * Note that the standard plugins do not use this mechanism, becuase all their
183 * settings are stored in the quiz table.
185 * @param int $quizid the quiz id.
186 * @return array setting value name => value. The value names should all
187 * start with the name of the corresponding plugin to avoid collisions.
189 public static function load_settings($quizid) {
190 global $DB;
192 $rules = self::get_rule_classes();
193 list($sql, $params) = self::get_load_sql($quizid, $rules, '');
195 if ($sql) {
196 $data = (array) $DB->get_record_sql($sql, $params);
197 } else {
198 $data = array();
201 foreach ($rules as $rule) {
202 $data += $rule::get_extra_settings($quizid);
205 return $data;
209 * Load the quiz settings and any settings required by the access rules.
210 * We try to do this with a single DB query.
212 * Note that the standard plugins do not use this mechanism, becuase all their
213 * settings are stored in the quiz table.
215 * @param int $quizid the quiz id.
216 * @return object mdl_quiz row with extra fields.
218 public static function load_quiz_and_settings($quizid) {
219 global $DB;
221 $rules = self::get_rule_classes();
222 list($sql, $params) = self::get_load_sql($quizid, $rules, 'quiz.*');
223 $quiz = $DB->get_record_sql($sql, $params, MUST_EXIST);
225 foreach ($rules as $rule) {
226 foreach ($rule::get_extra_settings($quizid) as $name => $value) {
227 $quiz->$name = $value;
231 return $quiz;
235 * @return array the class names of all the active rules. Mainly useful for
236 * debugging.
238 public function get_active_rule_names() {
239 $classnames = array();
240 foreach ($this->rules as $rule) {
241 $classnames[] = get_class($rule);
243 return $classnames;
247 * Accumulates an array of messages.
248 * @param array $messages the current list of messages.
249 * @param string|array $new the new messages or messages.
250 * @return array the updated array of messages.
252 protected function accumulate_messages($messages, $new) {
253 if (is_array($new)) {
254 $messages = array_merge($messages, $new);
255 } else if (is_string($new) && $new) {
256 $messages[] = $new;
258 return $messages;
262 * Provide a description of the rules that apply to this quiz, such
263 * as is shown at the top of the quiz view page. Note that not all
264 * rules consider themselves important enough to output a description.
266 * @return array an array of description messages which may be empty. It
267 * would be sensible to output each one surrounded by &lt;p> tags.
269 public function describe_rules() {
270 $result = array();
271 foreach ($this->rules as $rule) {
272 $result = $this->accumulate_messages($result, $rule->description());
274 return $result;
278 * Whether or not a user should be allowed to start a new attempt at this quiz now.
279 * If there are any restrictions in force now, return an array of reasons why access
280 * should be blocked. If access is OK, return false.
282 * @param int $numattempts the number of previous attempts this user has made.
283 * @param object|false $lastattempt information about the user's last completed attempt.
284 * if there is not a previous attempt, the false is passed.
285 * @return mixed An array of reason why access is not allowed, or an empty array
286 * (== false) if access should be allowed.
288 public function prevent_new_attempt($numprevattempts, $lastattempt) {
289 $reasons = array();
290 foreach ($this->rules as $rule) {
291 $reasons = $this->accumulate_messages($reasons,
292 $rule->prevent_new_attempt($numprevattempts, $lastattempt));
294 return $reasons;
298 * Whether the user should be blocked from starting a new attempt or continuing
299 * an attempt now. If there are any restrictions in force now, return an array
300 * of reasons why access should be blocked. If access is OK, return false.
302 * @return mixed An array of reason why access is not allowed, or an empty array
303 * (== false) if access should be allowed.
305 public function prevent_access() {
306 $reasons = array();
307 foreach ($this->rules as $rule) {
308 $reasons = $this->accumulate_messages($reasons, $rule->prevent_access());
310 return $reasons;
314 * @param int|null $attemptid the id of the current attempt, if there is one,
315 * otherwise null.
316 * @return bool whether a check is required before the user starts/continues
317 * their attempt.
319 public function is_preflight_check_required($attemptid) {
320 foreach ($this->rules as $rule) {
321 if ($rule->is_preflight_check_required($attemptid)) {
322 return true;
325 return false;
329 * Build the form required to do the pre-flight checks.
330 * @param moodle_url $url the form action URL.
331 * @param int|null $attemptid the id of the current attempt, if there is one,
332 * otherwise null.
333 * @return mod_quiz_preflight_check_form the form.
335 public function get_preflight_check_form(moodle_url $url, $attemptid) {
336 return new mod_quiz_preflight_check_form($url->out_omit_querystring(),
337 array('rules' => $this->rules, 'quizobj' => $this->quizobj,
338 'attemptid' => $attemptid, 'hidden' => $url->params()));
342 * The pre-flight check has passed. This is a chance to record that fact in
343 * some way.
344 * @param int|null $attemptid the id of the current attempt, if there is one,
345 * otherwise null.
347 public function notify_preflight_check_passed($attemptid) {
348 foreach ($this->rules as $rule) {
349 $rule->notify_preflight_check_passed($attemptid);
354 * Inform the rules that the current attempt is finished. This is use, for example
355 * by the password rule, to clear the flag in the session.
357 public function current_attempt_finished() {
358 foreach ($this->rules as $rule) {
359 $rule->current_attempt_finished();
364 * Do any of the rules mean that this student will no be allowed any further attempts at this
365 * quiz. Used, for example, to change the label by the grade displayed on the view page from
366 * 'your current grade is' to 'your final grade is'.
368 * @param int $numattempts the number of previous attempts this user has made.
369 * @param object $lastattempt information about the user's last completed attempt.
370 * @return bool true if there is no way the user will ever be allowed to attempt
371 * this quiz again.
373 public function is_finished($numprevattempts, $lastattempt) {
374 foreach ($this->rules as $rule) {
375 if ($rule->is_finished($numprevattempts, $lastattempt)) {
376 return true;
379 return false;
383 * Sets up the attempt (review or summary) page with any properties required
384 * by the access rules.
386 * @param moodle_page $page the page object to initialise.
388 public function setup_attempt_page($page) {
389 foreach ($this->rules as $rule) {
390 $rule->setup_attempt_page($page);
395 * Will cause the attempt time to start counting down after the page has loaded,
396 * if that is necessary.
398 * @param object $attempt the data from the relevant quiz_attempts row.
399 * @param int $timenow the time to consider as 'now'.
400 * @param mod_quiz_renderer $output the quiz renderer.
402 public function show_attempt_timer_if_needed($attempt, $timenow, $output) {
404 $timeleft = false;
405 foreach ($this->rules as $rule) {
406 $ruletimeleft = $rule->time_left($attempt, $timenow);
407 if ($ruletimeleft !== false && ($timeleft === false || $ruletimeleft < $timeleft)) {
408 $timeleft = $ruletimeleft;
412 if ($timeleft !== false) {
413 // Make sure the timer starts just above zero. If $timeleft was <= 0, then
414 // this will just have the effect of causing the quiz to be submitted immediately.
415 $timerstartvalue = max($timeleft, 1);
416 $output->initialise_timer($timerstartvalue);
421 * @return bolean if this quiz should only be shown to students in a popup window.
423 public function attempt_must_be_in_popup() {
424 foreach ($this->rules as $rule) {
425 if ($rule->attempt_must_be_in_popup()) {
426 return true;
429 return false;
433 * @return array any options that are required for showing the attempt page
434 * in a popup window.
436 public function get_popup_options() {
437 $options = array();
438 foreach ($this->rules as $rule) {
439 $options += $rule->get_popup_options();
441 return $options;
445 * Send the user back to the quiz view page. Normally this is just a redirect, but
446 * If we were in a secure window, we close this window, and reload the view window we came from.
448 * This method does not return;
450 * @param mod_quiz_renderer $output the quiz renderer.
451 * @param string $message optional message to output while redirecting.
453 public function back_to_view_page($output, $message = '') {
454 if ($this->attempt_must_be_in_popup()) {
455 echo $output->close_attempt_popup($message, $this->quizobj->view_url());
456 die();
457 } else {
458 redirect($this->quizobj->view_url(), $message);
463 * Make some text into a link to review the quiz, if that is appropriate.
465 * @param string $linktext some text.
466 * @param object $attempt the attempt object
467 * @return string some HTML, the $linktext either unmodified or wrapped in a
468 * link to the review page.
470 public function make_review_link($attempt, $reviewoptions, $output) {
472 // If review of responses is not allowed, or the attempt is still open, don't link.
473 if (!$attempt->timefinish) {
474 return $output->no_review_message('');
477 $when = quiz_attempt_state($this->quizobj->get_quiz(), $attempt);
478 $reviewoptions = mod_quiz_display_options::make_from_quiz(
479 $this->quizobj->get_quiz(), $when);
481 if (!$reviewoptions->attempt) {
482 return $output->no_review_message($this->quizobj->cannot_review_message($when, true));
484 } else {
485 return $output->review_link($this->quizobj->review_url($attempt->id),
486 $this->attempt_must_be_in_popup(), $this->get_popup_options());