Merge branch 'MDL-53349-31' of https://github.com/xow/moodle into MOODLE_31_STABLE
[moodle.git] / availability / classes / info.php
blob05d82fa7a5d64b736587b1271fec9f568dcf9c86
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 * Base class for conditional availability information (for module or section).
20 * @package core_availability
21 * @copyright 2014 The Open University
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 namespace core_availability;
27 defined('MOODLE_INTERNAL') || die();
29 /**
30 * Base class for conditional availability information (for module or section).
32 * @package core_availability
33 * @copyright 2014 The Open University
34 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36 abstract class info {
37 /** @var \stdClass Course */
38 protected $course;
40 /** @var \course_modinfo Modinfo (available only during some functions) */
41 protected $modinfo = null;
43 /** @var bool Visibility flag (eye icon) */
44 protected $visible;
46 /** @var string Availability data as JSON string */
47 protected $availability;
49 /** @var tree Availability configuration, decoded from JSON; null if unset */
50 protected $availabilitytree;
52 /** @var array|null Array of information about current restore if any */
53 protected static $restoreinfo = null;
55 /**
56 * Constructs with item details.
58 * @param \stdClass $course Course object
59 * @param int $visible Value of visible flag (eye icon)
60 * @param string $availability Availability definition (JSON format) or null
61 * @throws \coding_exception If data is not valid JSON format
63 public function __construct($course, $visible, $availability) {
64 // Set basic values.
65 $this->course = $course;
66 $this->visible = (bool)$visible;
67 $this->availability = $availability;
70 /**
71 * Obtains the course associated with this availability information.
73 * @return \stdClass Moodle course object
75 public function get_course() {
76 return $this->course;
79 /**
80 * Gets context used for checking capabilities for this item.
82 * @return \context Context for this item
84 public abstract function get_context();
86 /**
87 * Obtains the modinfo associated with this availability information.
89 * Note: This field is available ONLY for use by conditions when calculating
90 * availability or information.
92 * @return \course_modinfo Modinfo
93 * @throws \coding_exception If called at incorrect times
95 public function get_modinfo() {
96 if (!$this->modinfo) {
97 throw new \coding_exception(
98 'info::get_modinfo available only during condition checking');
100 return $this->modinfo;
104 * Gets the availability tree, decoding it if not already done.
106 * @return tree Availability tree
108 public function get_availability_tree() {
109 if (is_null($this->availabilitytree)) {
110 if (is_null($this->availability)) {
111 throw new \coding_exception(
112 'Cannot call get_availability_tree with null availability');
114 $this->availabilitytree = $this->decode_availability($this->availability, true);
116 return $this->availabilitytree;
120 * Decodes availability data from JSON format.
122 * This function also validates the retrieved data as follows:
123 * 1. Data that does not meet the API-defined structure causes a
124 * coding_exception (this should be impossible unless there is
125 * a system bug or somebody manually hacks the database).
126 * 2. Data that meets the structure but cannot be implemented (e.g.
127 * reference to missing plugin or to module that doesn't exist) is
128 * either silently discarded (if $lax is true) or causes a
129 * coding_exception (if $lax is false).
131 * @param string $availability Availability string in JSON format
132 * @param boolean $lax If true, throw exceptions only for invalid structure
133 * @return tree Availability tree
134 * @throws \coding_exception If data is not valid JSON format
136 protected function decode_availability($availability, $lax) {
137 // Decode JSON data.
138 $structure = json_decode($availability);
139 if (is_null($structure)) {
140 throw new \coding_exception('Invalid availability text', $availability);
143 // Recursively decode tree.
144 return new tree($structure, $lax);
148 * Determines whether this particular item is currently available
149 * according to the availability criteria.
151 * - This does not include the 'visible' setting (i.e. this might return
152 * true even if visible is false); visible is handled independently.
153 * - This does not take account of the viewhiddenactivities capability.
154 * That should apply later.
156 * Depending on options selected, a description of the restrictions which
157 * mean the student can't view it (in HTML format) may be stored in
158 * $information. If there is nothing in $information and this function
159 * returns false, then the activity should not be displayed at all.
161 * This function displays debugging() messages if the availability
162 * information is invalid.
164 * @param string $information String describing restrictions in HTML format
165 * @param bool $grabthelot Performance hint: if true, caches information
166 * required for all course-modules, to make the front page and similar
167 * pages work more quickly (works only for current user)
168 * @param int $userid If set, specifies a different user ID to check availability for
169 * @param \course_modinfo $modinfo Usually leave as null for default. Specify when
170 * calling recursively from inside get_fast_modinfo()
171 * @return bool True if this item is available to the user, false otherwise
173 public function is_available(&$information, $grabthelot = false, $userid = 0,
174 \course_modinfo $modinfo = null) {
175 global $USER;
177 // Default to no information.
178 $information = '';
180 // Do nothing if there are no availability restrictions.
181 if (is_null($this->availability)) {
182 return true;
185 // Resolve optional parameters.
186 if (!$userid) {
187 $userid = $USER->id;
189 if (!$modinfo) {
190 $modinfo = get_fast_modinfo($this->course, $userid);
192 $this->modinfo = $modinfo;
194 // Get availability from tree.
195 try {
196 $tree = $this->get_availability_tree();
197 $result = $tree->check_available(false, $this, $grabthelot, $userid);
198 } catch (\coding_exception $e) {
199 $this->warn_about_invalid_availability($e);
200 $this->modinfo = null;
201 return false;
204 // See if there are any messages.
205 if ($result->is_available()) {
206 $this->modinfo = null;
207 return true;
208 } else {
209 // If the item is marked as 'not visible' then we don't change the available
210 // flag (visible/available are treated distinctly), but we remove any
211 // availability info. If the item is hidden with the eye icon, it doesn't
212 // make sense to show 'Available from <date>' or similar, because even
213 // when that date arrives it will still not be available unless somebody
214 // toggles the eye icon.
215 if ($this->visible) {
216 $information = $tree->get_result_information($this, $result);
219 $this->modinfo = null;
220 return false;
225 * Checks whether this activity is going to be available for all users.
227 * Normally, if there are any conditions, then it may be hidden depending
228 * on the user. However in the case of date conditions there are some
229 * conditions which will definitely not result in it being hidden for
230 * anyone.
232 * @return bool True if activity is available for all
234 public function is_available_for_all() {
235 if (is_null($this->availability)) {
236 return true;
237 } else {
238 try {
239 return $this->get_availability_tree()->is_available_for_all();
240 } catch (\coding_exception $e) {
241 $this->warn_about_invalid_availability($e);
242 return false;
248 * Obtains a string describing all availability restrictions (even if
249 * they do not apply any more). Used to display information for staff
250 * editing the website.
252 * The modinfo parameter must be specified when it is called from inside
253 * get_fast_modinfo, to avoid infinite recursion.
255 * This function displays debugging() messages if the availability
256 * information is invalid.
258 * @param \course_modinfo $modinfo Usually leave as null for default
259 * @return string Information string (for admin) about all restrictions on
260 * this item
262 public function get_full_information(\course_modinfo $modinfo = null) {
263 // Do nothing if there are no availability restrictions.
264 if (is_null($this->availability)) {
265 return '';
268 // Resolve optional parameter.
269 if (!$modinfo) {
270 $modinfo = get_fast_modinfo($this->course);
272 $this->modinfo = $modinfo;
274 try {
275 $result = $this->get_availability_tree()->get_full_information($this);
276 $this->modinfo = null;
277 return $result;
278 } catch (\coding_exception $e) {
279 $this->warn_about_invalid_availability($e);
280 return false;
285 * In some places we catch coding_exception because if a bug happens, it
286 * would be fatal for the course page GUI; instead we just show a developer
287 * debug message.
289 * @param \coding_exception $e Exception that occurred
291 protected function warn_about_invalid_availability(\coding_exception $e) {
292 $name = $this->get_thing_name();
293 // If it occurs while building modinfo based on somebody calling $cm->name,
294 // we can't get $cm->name, and this line will cause a warning.
295 $htmlname = @$this->format_info($name, $this->course);
296 if ($htmlname === '') {
297 // So instead use the numbers (cmid) from the tag.
298 $htmlname = preg_replace('~[^0-9]~', '', $name);
300 $info = 'Error processing availability data for &lsquo;' . $htmlname
301 . '&rsquo;: ' . s($e->a);
302 debugging($info, DEBUG_DEVELOPER);
306 * Called during restore (near end of restore). Updates any necessary ids
307 * and writes the updated tree to the database. May output warnings if
308 * necessary (e.g. if a course-module cannot be found after restore).
310 * @param string $restoreid Restore identifier
311 * @param int $courseid Target course id
312 * @param \base_logger $logger Logger for any warnings
313 * @param int $dateoffset Date offset to be added to any dates (0 = none)
314 * @param \base_task $task Restore task
316 public function update_after_restore($restoreid, $courseid, \base_logger $logger,
317 $dateoffset, \base_task $task) {
318 $tree = $this->get_availability_tree();
319 // Set static data for use by get_restore_date_offset function.
320 self::$restoreinfo = array('restoreid' => $restoreid, 'dateoffset' => $dateoffset,
321 'task' => $task);
322 $changed = $tree->update_after_restore($restoreid, $courseid, $logger,
323 $this->get_thing_name());
324 if ($changed) {
325 // Save modified data.
326 if ($tree->is_empty()) {
327 // If the tree is empty, but the tree has changed, remove this condition.
328 $this->set_in_database(null);
329 } else {
330 $structure = $tree->save();
331 $this->set_in_database(json_encode($structure));
337 * Gets the date offset (amount by which any date values should be
338 * adjusted) for the current restore.
340 * @param string $restoreid Restore identifier
341 * @return int Date offset (0 if none)
342 * @throws coding_exception If not in a restore (or not in that restore)
344 public static function get_restore_date_offset($restoreid) {
345 if (!self::$restoreinfo) {
346 throw new coding_exception('Only valid during restore');
348 if (self::$restoreinfo['restoreid'] !== $restoreid) {
349 throw new coding_exception('Data not available for that restore id');
351 return self::$restoreinfo['dateoffset'];
355 * Gets the restore task (specifically, the task that calls the
356 * update_after_restore method) for the current restore.
358 * @param string $restoreid Restore identifier
359 * @return \base_task Restore task
360 * @throws coding_exception If not in a restore (or not in that restore)
362 public static function get_restore_task($restoreid) {
363 if (!self::$restoreinfo) {
364 throw new coding_exception('Only valid during restore');
366 if (self::$restoreinfo['restoreid'] !== $restoreid) {
367 throw new coding_exception('Data not available for that restore id');
369 return self::$restoreinfo['task'];
373 * Obtains the name of the item (cm_info or section_info, at present) that
374 * this is controlling availability of. Name should be formatted ready
375 * for on-screen display.
377 * @return string Name of item
379 protected abstract function get_thing_name();
382 * Stores an updated availability tree JSON structure into the relevant
383 * database table.
385 * @param string $availabilty New JSON value
387 protected abstract function set_in_database($availabilty);
390 * In rare cases the system may want to change all references to one ID
391 * (e.g. one course-module ID) to another one, within a course. This
392 * function does that for the conditional availability data for all
393 * modules and sections on the course.
395 * @param int|\stdClass $courseorid Course id or object
396 * @param string $table Table name e.g. 'course_modules'
397 * @param int $oldid Previous ID
398 * @param int $newid New ID
399 * @return bool True if anything changed, otherwise false
401 public static function update_dependency_id_across_course(
402 $courseorid, $table, $oldid, $newid) {
403 global $DB;
404 $transaction = $DB->start_delegated_transaction();
405 $modinfo = get_fast_modinfo($courseorid);
406 $anychanged = false;
407 foreach ($modinfo->get_cms() as $cm) {
408 $info = new info_module($cm);
409 $changed = $info->update_dependency_id($table, $oldid, $newid);
410 $anychanged = $anychanged || $changed;
412 foreach ($modinfo->get_section_info_all() as $section) {
413 $info = new info_section($section);
414 $changed = $info->update_dependency_id($table, $oldid, $newid);
415 $anychanged = $anychanged || $changed;
417 $transaction->allow_commit();
418 if ($anychanged) {
419 get_fast_modinfo($courseorid, 0, true);
421 return $anychanged;
425 * Called on a single item. If necessary, updates availability data where
426 * it has a dependency on an item with a particular id.
428 * @param string $table Table name e.g. 'course_modules'
429 * @param int $oldid Previous ID
430 * @param int $newid New ID
431 * @return bool True if it changed, otherwise false
433 protected function update_dependency_id($table, $oldid, $newid) {
434 // Do nothing if there are no availability restrictions.
435 if (is_null($this->availability)) {
436 return false;
438 // Pass requirement on to tree object.
439 $tree = $this->get_availability_tree();
440 $changed = $tree->update_dependency_id($table, $oldid, $newid);
441 if ($changed) {
442 // Save modified data.
443 $structure = $tree->save();
444 $this->set_in_database(json_encode($structure));
446 return $changed;
450 * Converts legacy data from fields (if provided) into the new availability
451 * syntax.
453 * Supported fields: availablefrom, availableuntil, showavailability
454 * (and groupingid for sections).
456 * It also supports the groupmembersonly field for modules. This part was
457 * optional in 2.7 but now always runs (because groupmembersonly has been
458 * removed).
460 * @param \stdClass $rec Object possibly containing legacy fields
461 * @param bool $section True if this is a section
462 * @param bool $modgroupmembersonlyignored Ignored option, previously used
463 * @return string|null New availability value or null if none
465 public static function convert_legacy_fields($rec, $section, $modgroupmembersonlyignored = false) {
466 // Do nothing if the fields are not set.
467 if (empty($rec->availablefrom) && empty($rec->availableuntil) &&
468 (empty($rec->groupmembersonly)) &&
469 (!$section || empty($rec->groupingid))) {
470 return null;
473 // Handle legacy availability data.
474 $conditions = array();
475 $shows = array();
477 // Groupmembersonly condition (if enabled) for modules, groupingid for
478 // sections.
479 if (!empty($rec->groupmembersonly) ||
480 (!empty($rec->groupingid) && $section)) {
481 if (!empty($rec->groupingid)) {
482 $conditions[] = '{"type":"grouping"' .
483 ($rec->groupingid ? ',"id":' . $rec->groupingid : '') . '}';
484 } else {
485 // No grouping specified, so allow any group.
486 $conditions[] = '{"type":"group"}';
488 // Group members only condition was not displayed to students.
489 $shows[] = 'false';
492 // Date conditions.
493 if (!empty($rec->availablefrom)) {
494 $conditions[] = '{"type":"date","d":">=","t":' . $rec->availablefrom . '}';
495 $shows[] = !empty($rec->showavailability) ? 'true' : 'false';
497 if (!empty($rec->availableuntil)) {
498 $conditions[] = '{"type":"date","d":"<","t":' . $rec->availableuntil . '}';
499 // Until dates never showed to students.
500 $shows[] = 'false';
503 // If there are some conditions, return them.
504 if ($conditions) {
505 return '{"op":"&","showc":[' . implode(',', $shows) . '],' .
506 '"c":[' . implode(',', $conditions) . ']}';
507 } else {
508 return null;
513 * Adds a condition from the legacy availability condition.
515 * (For use during restore only.)
517 * This function assumes that the activity either has no conditions, or
518 * that it has an AND tree with one or more conditions.
520 * @param string|null $availability Current availability conditions
521 * @param \stdClass $rec Object containing information from old table
522 * @param bool $show True if 'show' option should be enabled
523 * @return string New availability conditions
525 public static function add_legacy_availability_condition($availability, $rec, $show) {
526 if (!empty($rec->sourcecmid)) {
527 // Completion condition.
528 $condition = '{"type":"completion","cm":' . $rec->sourcecmid .
529 ',"e":' . $rec->requiredcompletion . '}';
530 } else {
531 // Grade condition.
532 $minmax = '';
533 if (!empty($rec->grademin)) {
534 $minmax .= ',"min":' . sprintf('%.5f', $rec->grademin);
536 if (!empty($rec->grademax)) {
537 $minmax .= ',"max":' . sprintf('%.5f', $rec->grademax);
539 $condition = '{"type":"grade","id":' . $rec->gradeitemid . $minmax . '}';
542 return self::add_legacy_condition($availability, $condition, $show);
546 * Adds a condition from the legacy availability field condition.
548 * (For use during restore only.)
550 * This function assumes that the activity either has no conditions, or
551 * that it has an AND tree with one or more conditions.
553 * @param string|null $availability Current availability conditions
554 * @param \stdClass $rec Object containing information from old table
555 * @param bool $show True if 'show' option should be enabled
556 * @return string New availability conditions
558 public static function add_legacy_availability_field_condition($availability, $rec, $show) {
559 if (isset($rec->userfield)) {
560 // Standard field.
561 $fieldbit = ',"sf":' . json_encode($rec->userfield);
562 } else {
563 // Custom field.
564 $fieldbit = ',"cf":' . json_encode($rec->shortname);
566 // Value is not included for certain operators.
567 switch($rec->operator) {
568 case 'isempty':
569 case 'isnotempty':
570 $valuebit = '';
571 break;
573 default:
574 $valuebit = ',"v":' . json_encode($rec->value);
575 break;
577 $condition = '{"type":"profile","op":"' . $rec->operator . '"' .
578 $fieldbit . $valuebit . '}';
580 return self::add_legacy_condition($availability, $condition, $show);
584 * Adds a condition to an AND group.
586 * (For use during restore only.)
588 * This function assumes that the activity either has no conditions, or
589 * that it has only conditions added by this function.
591 * @param string|null $availability Current availability conditions
592 * @param string $condition Condition text '{...}'
593 * @param bool $show True if 'show' option should be enabled
594 * @return string New availability conditions
596 protected static function add_legacy_condition($availability, $condition, $show) {
597 $showtext = ($show ? 'true' : 'false');
598 if (is_null($availability)) {
599 $availability = '{"op":"&","showc":[' . $showtext .
600 '],"c":[' . $condition . ']}';
601 } else {
602 $matches = array();
603 if (!preg_match('~^({"op":"&","showc":\[(?:true|false)(?:,(?:true|false))*)' .
604 '(\],"c":\[.*)(\]})$~', $availability, $matches)) {
605 throw new \coding_exception('Unexpected availability value');
607 $availability = $matches[1] . ',' . $showtext . $matches[2] .
608 ',' . $condition . $matches[3];
610 return $availability;
614 * Tests against a user list. Users who cannot access the activity due to
615 * availability restrictions will be removed from the list.
617 * Note this only includes availability restrictions (those handled within
618 * this API) and not other ways of restricting access.
620 * This test ONLY includes conditions which are marked as being applied to
621 * user lists. For example, group conditions are included but date
622 * conditions are not included.
624 * The function operates reasonably efficiently i.e. should not do per-user
625 * database queries. It is however likely to be fairly slow.
627 * @param array $users Array of userid => object
628 * @return array Filtered version of input array
630 public function filter_user_list(array $users) {
631 global $CFG;
632 if (is_null($this->availability) || !$CFG->enableavailability) {
633 return $users;
635 $tree = $this->get_availability_tree();
636 $checker = new capability_checker($this->get_context());
638 // Filter using availability tree.
639 $this->modinfo = get_fast_modinfo($this->get_course());
640 $filtered = $tree->filter_user_list($users, false, $this, $checker);
641 $this->modinfo = null;
643 // Include users in the result if they're either in the filtered list,
644 // or they have viewhidden. This logic preserves ordering of the
645 // passed users array.
646 $result = array();
647 $canviewhidden = $checker->get_users_by_capability($this->get_view_hidden_capability());
648 foreach ($users as $userid => $data) {
649 if (array_key_exists($userid, $filtered) || array_key_exists($userid, $canviewhidden)) {
650 $result[$userid] = $users[$userid];
654 return $result;
658 * Gets the capability used to view hidden activities/sections (as
659 * appropriate).
661 * @return string Name of capability used to view hidden items of this type
663 protected abstract function get_view_hidden_capability();
666 * Obtains SQL that returns a list of enrolled users that has been filtered
667 * by the conditions applied in the availability API, similar to calling
668 * get_enrolled_users and then filter_user_list. As for filter_user_list,
669 * this ONLY filters out users with conditions that are marked as applying
670 * to user lists. For example, group conditions are included but date
671 * conditions are not included.
673 * The returned SQL is a query that returns a list of user IDs. It does not
674 * include brackets, so you neeed to add these to make it into a subquery.
675 * You would normally use it in an SQL phrase like "WHERE u.id IN ($sql)".
677 * The function returns an array with '' and an empty array, if there are
678 * no restrictions on users from these conditions.
680 * The SQL will be complex and may be slow. It uses named parameters (sorry,
681 * I know they are annoying, but it was unavoidable here).
683 * @param bool $onlyactive True if including only active enrolments
684 * @return array Array of SQL code (may be empty) and params
686 public function get_user_list_sql($onlyactive) {
687 global $CFG;
688 if (is_null($this->availability) || !$CFG->enableavailability) {
689 return array('', array());
692 // Get SQL for the availability filter.
693 $tree = $this->get_availability_tree();
694 list ($filtersql, $filterparams) = $tree->get_user_list_sql(false, $this, $onlyactive);
695 if ($filtersql === '') {
696 // No restrictions, so return empty query.
697 return array('', array());
700 // Get SQL for the view hidden list.
701 list ($viewhiddensql, $viewhiddenparams) = get_enrolled_sql(
702 $this->get_context(), $this->get_view_hidden_capability(), 0, $onlyactive);
704 // Result is a union of the two.
705 return array('(' . $filtersql . ') UNION (' . $viewhiddensql . ')',
706 array_merge($filterparams, $viewhiddenparams));
710 * Formats the $cm->availableinfo string for display. This includes
711 * filling in the names of any course-modules that might be mentioned.
712 * Should be called immediately prior to display, or at least somewhere
713 * that we can guarantee does not happen from within building the modinfo
714 * object.
716 * @param \renderable|string $inforenderable Info string or renderable
717 * @param int|\stdClass $courseorid
718 * @return string Correctly formatted info string
720 public static function format_info($inforenderable, $courseorid) {
721 global $PAGE;
723 // Use renderer if required.
724 if (is_string($inforenderable)) {
725 $info = $inforenderable;
726 } else {
727 $renderer = $PAGE->get_renderer('core', 'availability');
728 $info = $renderer->render($inforenderable);
731 // Don't waste time if there are no special tags.
732 if (strpos($info, '<AVAILABILITY_') === false) {
733 return $info;
736 // Handle CMNAME tags.
737 $modinfo = get_fast_modinfo($courseorid);
738 $context = \context_course::instance($modinfo->courseid);
739 $info = preg_replace_callback('~<AVAILABILITY_CMNAME_([0-9]+)/>~',
740 function($matches) use($modinfo, $context) {
741 $cm = $modinfo->get_cm($matches[1]);
742 if ($cm->has_view() and $cm->uservisible) {
743 // Help student by providing a link to the module which is preventing availability.
744 return \html_writer::link($cm->url, format_string($cm->name, true, array('context' => $context)));
745 } else {
746 return format_string($cm->name, true, array('context' => $context));
748 }, $info);
750 return $info;
754 * Used in course/lib.php because we need to disable the completion tickbox
755 * JS (using the non-JS version instead, which causes a page reload) if a
756 * completion tickbox value may affect a conditional activity.
758 * @param \stdClass $course Moodle course object
759 * @param int $cmid Course-module id
760 * @return bool True if this is used in a condition, false otherwise
762 public static function completion_value_used($course, $cmid) {
763 // Access all plugins. Normally only the completion plugin is going
764 // to affect this value, but it's potentially possible that some other
765 // plugin could also rely on the completion plugin.
766 $pluginmanager = \core_plugin_manager::instance();
767 $enabled = $pluginmanager->get_enabled_plugins('availability');
768 $componentparams = new \stdClass();
769 foreach ($enabled as $plugin => $info) {
770 // Use the static method.
771 $class = '\availability_' . $plugin . '\condition';
772 if ($class::completion_value_used($course, $cmid)) {
773 return true;
776 return false;