Merge branch 'MDL-81073' of https://github.com/paulholden/moodle
[moodle.git] / availability / classes / info.php
bloba5cdac3078b2d34d41f390189f71065bb1b43338
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 abstract public 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 global $CFG;
236 if (is_null($this->availability) || empty($CFG->enableavailability)) {
237 return true;
238 } else {
239 try {
240 return $this->get_availability_tree()->is_available_for_all();
241 } catch (\coding_exception $e) {
242 $this->warn_about_invalid_availability($e);
243 return false;
249 * Obtains a string describing all availability restrictions (even if
250 * they do not apply any more). Used to display information for staff
251 * editing the website.
253 * The modinfo parameter must be specified when it is called from inside
254 * get_fast_modinfo, to avoid infinite recursion.
256 * This function displays debugging() messages if the availability
257 * information is invalid.
259 * @param \course_modinfo $modinfo Usually leave as null for default
260 * @return string Information string (for admin) about all restrictions on
261 * this item
263 public function get_full_information(\course_modinfo $modinfo = null) {
264 // Do nothing if there are no availability restrictions.
265 if (is_null($this->availability)) {
266 return '';
269 // Resolve optional parameter.
270 if (!$modinfo) {
271 $modinfo = get_fast_modinfo($this->course);
273 $this->modinfo = $modinfo;
275 try {
276 $result = $this->get_availability_tree()->get_full_information($this);
277 $this->modinfo = null;
278 return $result;
279 } catch (\coding_exception $e) {
280 $this->warn_about_invalid_availability($e);
281 return false;
286 * In some places we catch coding_exception because if a bug happens, it
287 * would be fatal for the course page GUI; instead we just show a developer
288 * debug message.
290 * @param \coding_exception $e Exception that occurred
292 protected function warn_about_invalid_availability(\coding_exception $e) {
293 $name = $this->get_thing_name();
294 $htmlname = $this->format_info($name, $this->course);
295 // Because we call format_info here, likely in the middle of building dynamic data for the
296 // activity, there could be a chance that the name might not be available.
297 if ($htmlname === '') {
298 // So instead use the numbers (cmid) from the tag.
299 $htmlname = preg_replace('~[^0-9]~', '', $name);
301 $htmlname = html_to_text($htmlname, 75, false);
302 $info = 'Error processing availability data for &lsquo;' . $htmlname
303 . '&rsquo;: ' . s($e->a);
304 debugging($info, DEBUG_DEVELOPER);
308 * Called during restore (near end of restore). Updates any necessary ids
309 * and writes the updated tree to the database. May output warnings if
310 * necessary (e.g. if a course-module cannot be found after restore).
312 * @param string $restoreid Restore identifier
313 * @param int $courseid Target course id
314 * @param \base_logger $logger Logger for any warnings
315 * @param int $dateoffset Date offset to be added to any dates (0 = none)
316 * @param \base_task $task Restore task
318 public function update_after_restore($restoreid, $courseid, \base_logger $logger,
319 $dateoffset, \base_task $task) {
320 $tree = $this->get_availability_tree();
321 // Set static data for use by get_restore_date_offset function.
322 self::$restoreinfo = array('restoreid' => $restoreid, 'dateoffset' => $dateoffset,
323 'task' => $task);
324 $changed = $tree->update_after_restore($restoreid, $courseid, $logger,
325 $this->get_thing_name());
326 if ($changed) {
327 // Save modified data.
328 if ($tree->is_empty()) {
329 // If the tree is empty, but the tree has changed, remove this condition.
330 $this->set_in_database(null);
331 } else {
332 $structure = $tree->save();
333 $this->set_in_database(json_encode($structure));
339 * Gets the date offset (amount by which any date values should be
340 * adjusted) for the current restore.
342 * @param string $restoreid Restore identifier
343 * @return int Date offset (0 if none)
344 * @throws coding_exception If not in a restore (or not in that restore)
346 public static function get_restore_date_offset($restoreid) {
347 if (!self::$restoreinfo) {
348 throw new coding_exception('Only valid during restore');
350 if (self::$restoreinfo['restoreid'] !== $restoreid) {
351 throw new coding_exception('Data not available for that restore id');
353 return self::$restoreinfo['dateoffset'];
357 * Gets the restore task (specifically, the task that calls the
358 * update_after_restore method) for the current restore.
360 * @param string $restoreid Restore identifier
361 * @return \base_task Restore task
362 * @throws coding_exception If not in a restore (or not in that restore)
364 public static function get_restore_task($restoreid) {
365 if (!self::$restoreinfo) {
366 throw new coding_exception('Only valid during restore');
368 if (self::$restoreinfo['restoreid'] !== $restoreid) {
369 throw new coding_exception('Data not available for that restore id');
371 return self::$restoreinfo['task'];
375 * Obtains the name of the item (cm_info or section_info, at present) that
376 * this is controlling availability of. Name should be formatted ready
377 * for on-screen display.
379 * @return string Name of item
381 abstract protected function get_thing_name();
384 * Stores an updated availability tree JSON structure into the relevant
385 * database table.
387 * @param string $availabilty New JSON value
389 abstract protected function set_in_database($availabilty);
392 * In rare cases the system may want to change all references to one ID
393 * (e.g. one course-module ID) to another one, within a course. This
394 * function does that for the conditional availability data for all
395 * modules and sections on the course.
397 * @param int|\stdClass $courseorid Course id or object
398 * @param string $table Table name e.g. 'course_modules'
399 * @param int $oldid Previous ID
400 * @param int $newid New ID
401 * @return bool True if anything changed, otherwise false
403 public static function update_dependency_id_across_course(
404 $courseorid, $table, $oldid, $newid) {
405 global $DB;
406 $transaction = $DB->start_delegated_transaction();
407 $modinfo = get_fast_modinfo($courseorid);
408 $anychanged = false;
409 foreach ($modinfo->get_cms() as $cm) {
410 $info = new info_module($cm);
411 $changed = $info->update_dependency_id($table, $oldid, $newid);
412 $anychanged = $anychanged || $changed;
414 foreach ($modinfo->get_section_info_all() as $section) {
415 $info = new info_section($section);
416 $changed = $info->update_dependency_id($table, $oldid, $newid);
417 $anychanged = $anychanged || $changed;
419 $transaction->allow_commit();
420 if ($anychanged) {
421 get_fast_modinfo($courseorid, 0, true);
423 return $anychanged;
427 * Called on a single item. If necessary, updates availability data where
428 * it has a dependency on an item with a particular id.
430 * @param string $table Table name e.g. 'course_modules'
431 * @param int $oldid Previous ID
432 * @param int $newid New ID
433 * @return bool True if it changed, otherwise false
435 protected function update_dependency_id($table, $oldid, $newid) {
436 // Do nothing if there are no availability restrictions.
437 if (is_null($this->availability)) {
438 return false;
440 // Pass requirement on to tree object.
441 $tree = $this->get_availability_tree();
442 $changed = $tree->update_dependency_id($table, $oldid, $newid);
443 if ($changed) {
444 // Save modified data.
445 $structure = $tree->save();
446 $this->set_in_database(json_encode($structure));
448 return $changed;
452 * Converts legacy data from fields (if provided) into the new availability
453 * syntax.
455 * Supported fields: availablefrom, availableuntil, showavailability
456 * (and groupingid for sections).
458 * It also supports the groupmembersonly field for modules. This part was
459 * optional in 2.7 but now always runs (because groupmembersonly has been
460 * removed).
462 * @param \stdClass $rec Object possibly containing legacy fields
463 * @param bool $section True if this is a section
464 * @param bool $modgroupmembersonlyignored Ignored option, previously used
465 * @return string|null New availability value or null if none
467 public static function convert_legacy_fields($rec, $section, $modgroupmembersonlyignored = false) {
468 // Do nothing if the fields are not set.
469 if (empty($rec->availablefrom) && empty($rec->availableuntil) &&
470 (empty($rec->groupmembersonly)) &&
471 (!$section || empty($rec->groupingid))) {
472 return null;
475 // Handle legacy availability data.
476 $conditions = array();
477 $shows = array();
479 // Groupmembersonly condition (if enabled) for modules, groupingid for
480 // sections.
481 if (!empty($rec->groupmembersonly) ||
482 (!empty($rec->groupingid) && $section)) {
483 if (!empty($rec->groupingid)) {
484 $conditions[] = '{"type":"grouping"' .
485 ($rec->groupingid ? ',"id":' . $rec->groupingid : '') . '}';
486 } else {
487 // No grouping specified, so allow any group.
488 $conditions[] = '{"type":"group"}';
490 // Group members only condition was not displayed to students.
491 $shows[] = 'false';
494 // Date conditions.
495 if (!empty($rec->availablefrom)) {
496 $conditions[] = '{"type":"date","d":">=","t":' . $rec->availablefrom . '}';
497 $shows[] = !empty($rec->showavailability) ? 'true' : 'false';
499 if (!empty($rec->availableuntil)) {
500 $conditions[] = '{"type":"date","d":"<","t":' . $rec->availableuntil . '}';
501 // Until dates never showed to students.
502 $shows[] = 'false';
505 // If there are some conditions, return them.
506 if ($conditions) {
507 return '{"op":"&","showc":[' . implode(',', $shows) . '],' .
508 '"c":[' . implode(',', $conditions) . ']}';
509 } else {
510 return null;
515 * Adds a condition from the legacy availability condition.
517 * (For use during restore only.)
519 * This function assumes that the activity either has no conditions, or
520 * that it has an AND tree with one or more conditions.
522 * @param string|null $availability Current availability conditions
523 * @param \stdClass $rec Object containing information from old table
524 * @param bool $show True if 'show' option should be enabled
525 * @return string New availability conditions
527 public static function add_legacy_availability_condition($availability, $rec, $show) {
528 if (!empty($rec->sourcecmid)) {
529 // Completion condition.
530 $condition = '{"type":"completion","cm":' . $rec->sourcecmid .
531 ',"e":' . $rec->requiredcompletion . '}';
532 } else {
533 // Grade condition.
534 $minmax = '';
535 if (!empty($rec->grademin)) {
536 $minmax .= ',"min":' . sprintf('%.5f', $rec->grademin);
538 if (!empty($rec->grademax)) {
539 $minmax .= ',"max":' . sprintf('%.5f', $rec->grademax);
541 $condition = '{"type":"grade","id":' . $rec->gradeitemid . $minmax . '}';
544 return self::add_legacy_condition($availability, $condition, $show);
548 * Adds a condition from the legacy availability field condition.
550 * (For use during restore only.)
552 * This function assumes that the activity either has no conditions, or
553 * that it has an AND tree with one or more conditions.
555 * @param string|null $availability Current availability conditions
556 * @param \stdClass $rec Object containing information from old table
557 * @param bool $show True if 'show' option should be enabled
558 * @return string New availability conditions
560 public static function add_legacy_availability_field_condition($availability, $rec, $show) {
561 if (isset($rec->userfield)) {
562 // Standard field.
563 $fieldbit = ',"sf":' . json_encode($rec->userfield);
564 } else {
565 // Custom field.
566 $fieldbit = ',"cf":' . json_encode($rec->shortname);
568 // Value is not included for certain operators.
569 switch($rec->operator) {
570 case 'isempty':
571 case 'isnotempty':
572 $valuebit = '';
573 break;
575 default:
576 $valuebit = ',"v":' . json_encode($rec->value);
577 break;
579 $condition = '{"type":"profile","op":"' . $rec->operator . '"' .
580 $fieldbit . $valuebit . '}';
582 return self::add_legacy_condition($availability, $condition, $show);
586 * Adds a condition to an AND group.
588 * (For use during restore only.)
590 * This function assumes that the activity either has no conditions, or
591 * that it has only conditions added by this function.
593 * @param string|null $availability Current availability conditions
594 * @param string $condition Condition text '{...}'
595 * @param bool $show True if 'show' option should be enabled
596 * @return string New availability conditions
598 protected static function add_legacy_condition($availability, $condition, $show) {
599 $showtext = ($show ? 'true' : 'false');
600 if (is_null($availability)) {
601 $availability = '{"op":"&","showc":[' . $showtext .
602 '],"c":[' . $condition . ']}';
603 } else {
604 $matches = array();
605 if (!preg_match('~^({"op":"&","showc":\[(?:true|false)(?:,(?:true|false))*)' .
606 '(\],"c":\[.*)(\]})$~', $availability, $matches)) {
607 throw new \coding_exception('Unexpected availability value');
609 $availability = $matches[1] . ',' . $showtext . $matches[2] .
610 ',' . $condition . $matches[3];
612 return $availability;
616 * Tests against a user list. Users who cannot access the activity due to
617 * availability restrictions will be removed from the list.
619 * Note this only includes availability restrictions (those handled within
620 * this API) and not other ways of restricting access.
622 * This test ONLY includes conditions which are marked as being applied to
623 * user lists. For example, group conditions are included but date
624 * conditions are not included.
626 * The function operates reasonably efficiently i.e. should not do per-user
627 * database queries. It is however likely to be fairly slow.
629 * @param array $users Array of userid => object
630 * @return array Filtered version of input array
632 public function filter_user_list(array $users) {
633 global $CFG;
634 if (is_null($this->availability) || !$CFG->enableavailability) {
635 return $users;
637 $tree = $this->get_availability_tree();
638 $checker = new capability_checker($this->get_context());
640 // Filter using availability tree.
641 $this->modinfo = get_fast_modinfo($this->get_course());
642 $filtered = $tree->filter_user_list($users, false, $this, $checker);
643 $this->modinfo = null;
645 // Include users in the result if they're either in the filtered list,
646 // or they have viewhidden. This logic preserves ordering of the
647 // passed users array.
648 $result = array();
649 $canviewhidden = $checker->get_users_by_capability($this->get_view_hidden_capability());
650 foreach ($users as $userid => $data) {
651 if (array_key_exists($userid, $filtered) || array_key_exists($userid, $canviewhidden)) {
652 $result[$userid] = $users[$userid];
656 return $result;
660 * Gets the capability used to view hidden activities/sections (as
661 * appropriate).
663 * @return string Name of capability used to view hidden items of this type
665 abstract protected function get_view_hidden_capability();
668 * Obtains SQL that returns a list of enrolled users that has been filtered
669 * by the conditions applied in the availability API, similar to calling
670 * get_enrolled_users and then filter_user_list. As for filter_user_list,
671 * this ONLY filters out users with conditions that are marked as applying
672 * to user lists. For example, group conditions are included but date
673 * conditions are not included.
675 * The returned SQL is a query that returns a list of user IDs. It does not
676 * include brackets, so you neeed to add these to make it into a subquery.
677 * You would normally use it in an SQL phrase like "WHERE u.id IN ($sql)".
679 * The function returns an array with '' and an empty array, if there are
680 * no restrictions on users from these conditions.
682 * The SQL will be complex and may be slow. It uses named parameters (sorry,
683 * I know they are annoying, but it was unavoidable here).
685 * @param bool $onlyactive True if including only active enrolments
686 * @return array Array of SQL code (may be empty) and params
688 public function get_user_list_sql($onlyactive) {
689 global $CFG;
690 if (is_null($this->availability) || !$CFG->enableavailability) {
691 return array('', array());
694 // Get SQL for the availability filter.
695 $tree = $this->get_availability_tree();
696 list ($filtersql, $filterparams) = $tree->get_user_list_sql(false, $this, $onlyactive);
697 if ($filtersql === '') {
698 // No restrictions, so return empty query.
699 return array('', array());
702 // Get SQL for the view hidden list.
703 list ($viewhiddensql, $viewhiddenparams) = get_enrolled_sql(
704 $this->get_context(), $this->get_view_hidden_capability(), 0, $onlyactive);
706 // Result is a union of the two.
707 return array('(' . $filtersql . ') UNION (' . $viewhiddensql . ')',
708 array_merge($filterparams, $viewhiddenparams));
712 * Formats the $cm->availableinfo string for display. This includes
713 * filling in the names of any course-modules that might be mentioned.
714 * Should be called immediately prior to display, or at least somewhere
715 * that we can guarantee does not happen from within building the modinfo
716 * object.
718 * @param \renderable|string $inforenderable Info string or renderable
719 * @param int|\stdClass $courseorid
720 * @return string Correctly formatted info string
722 public static function format_info($inforenderable, $courseorid) {
723 global $PAGE, $OUTPUT;
725 // Use renderer if required.
726 if (is_string($inforenderable)) {
727 $info = $inforenderable;
728 } else {
729 $renderable = new \core_availability\output\availability_info($inforenderable);
730 $info = $OUTPUT->render($renderable);
733 // Don't waste time if there are no special tags.
734 if (strpos($info, '<AVAILABILITY_') === false) {
735 return $info;
738 // Handle CMNAME tags.
739 $modinfo = get_fast_modinfo($courseorid);
740 $context = \context_course::instance($modinfo->courseid);
741 $info = preg_replace_callback('~<AVAILABILITY_CMNAME_([0-9]+)/>~',
742 function($matches) use($modinfo, $context) {
743 $cm = $modinfo->get_cm($matches[1]);
744 $modulename = format_string($cm->get_name(), true, ['context' => $context]);
745 // We make sure that we add a data attribute to the name so we can change it later if the
746 // original module name changes.
747 if ($cm->has_view() && $cm->get_user_visible()) {
748 // Help student by providing a link to the module which is preventing availability.
749 return \html_writer::link($cm->get_url(), $modulename, ['data-cm-name-for' => $cm->id]);
750 } else {
751 return \html_writer::span($modulename, '', ['data-cm-name-for' => $cm->id]);
753 }, $info);
754 $info = preg_replace_callback('~<AVAILABILITY_FORMAT_STRING>(.*?)</AVAILABILITY_FORMAT_STRING>~s',
755 function($matches) use ($context) {
756 $decoded = htmlspecialchars_decode($matches[1], ENT_NOQUOTES);
757 return format_string($decoded, true, ['context' => $context]);
758 }, $info);
759 $info = preg_replace_callback('~<AVAILABILITY_CALLBACK type="([a-z0-9_]+)">(.*?)</AVAILABILITY_CALLBACK>~s',
760 function($matches) use ($modinfo, $context) {
761 // Find the class, it must have already been loaded by now.
762 $fullclassname = 'availability_' . $matches[1] . '\condition';
763 if (!class_exists($fullclassname, false)) {
764 return '<!-- Error finding class ' . $fullclassname .' -->';
766 // Load the parameters.
767 $params = [];
768 $encodedparams = preg_split('~<P/>~', $matches[2], 0);
769 foreach ($encodedparams as $encodedparam) {
770 $params[] = htmlspecialchars_decode($encodedparam, ENT_NOQUOTES);
772 return $fullclassname::get_description_callback_value($modinfo, $context, $params);
773 }, $info);
775 return $info;
779 * Used in course/lib.php because we need to disable the completion tickbox
780 * JS (using the non-JS version instead, which causes a page reload) if a
781 * completion tickbox value may affect a conditional activity.
783 * @param \stdClass $course Moodle course object
784 * @param int $cmid Course-module id
785 * @return bool True if this is used in a condition, false otherwise
787 public static function completion_value_used($course, $cmid) {
788 // Access all plugins. Normally only the completion plugin is going
789 // to affect this value, but it's potentially possible that some other
790 // plugin could also rely on the completion plugin.
791 $pluginmanager = \core_plugin_manager::instance();
792 $enabled = $pluginmanager->get_enabled_plugins('availability');
793 $componentparams = new \stdClass();
794 foreach ($enabled as $plugin => $info) {
795 // Use the static method.
796 $class = '\availability_' . $plugin . '\condition';
797 if ($class::completion_value_used($course, $cmid)) {
798 return true;
801 return false;