Merge branch 'MDL-81127-main' of https://github.com/izendegi/moodle
[moodle.git] / lib / modinfolib.php
blob6531d775d6f94b09c9a694e2e2298f5b20a59095
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 * modinfolib.php - Functions/classes relating to cached information about module instances on
19 * a course.
20 * @package core
21 * @subpackage lib
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 * @author sam marshall
27 // Maximum number of modinfo items to keep in memory cache. Do not increase this to a large
28 // number because:
29 // a) modinfo can be big (megabyte range) for some courses
30 // b) performance of cache will deteriorate if there are very many items in it
31 if (!defined('MAX_MODINFO_CACHE_SIZE')) {
32 define('MAX_MODINFO_CACHE_SIZE', 10);
35 use core_courseformat\output\activitybadge;
36 use core_courseformat\sectiondelegate;
38 /**
39 * Information about a course that is cached in the course table 'modinfo' field (and then in
40 * memory) in order to reduce the need for other database queries.
42 * This includes information about the course-modules and the sections on the course. It can also
43 * include dynamic data that has been updated for the current user.
45 * Use {@link get_fast_modinfo()} to retrieve the instance of the object for particular course
46 * and particular user.
48 * @property-read int $courseid Course ID
49 * @property-read int $userid User ID
50 * @property-read array $sections Array from section number (e.g. 0) to array of course-module IDs in that
51 * section; this only includes sections that contain at least one course-module
52 * @property-read cm_info[] $cms Array from course-module instance to cm_info object within this course, in
53 * order of appearance
54 * @property-read cm_info[][] $instances Array from string (modname) => int (instance id) => cm_info object
55 * @property-read array $groups Groups that the current user belongs to. Calculated on the first request.
56 * Is an array of grouping id => array of group id => group id. Includes grouping id 0 for 'all groups'
58 class course_modinfo {
59 /** @var int Maximum time the course cache building lock can be held */
60 const COURSE_CACHE_LOCK_EXPIRY = 180;
62 /** @var int Time to wait for the course cache building lock before throwing an exception */
63 const COURSE_CACHE_LOCK_WAIT = 60;
65 /**
66 * List of fields from DB table 'course' that are cached in MUC and are always present in course_modinfo::$course
67 * @var array
69 public static $cachedfields = array('shortname', 'fullname', 'format',
70 'enablecompletion', 'groupmode', 'groupmodeforce', 'cacherev');
72 /**
73 * For convenience we store the course object here as it is needed in other parts of code
74 * @var stdClass
76 private $course;
78 /**
79 * Array of section data from cache indexed by section number.
80 * @var section_info[]
82 private $sectioninfobynum;
84 /**
85 * Array of section data from cache indexed by id.
86 * @var section_info[]
88 private $sectioninfobyid;
90 /**
91 * Index of delegated sections (indexed by component and itemid)
92 * @var array
94 private $delegatedsections;
96 /**
97 * User ID
98 * @var int
100 private $userid;
103 * Array indexed by section num (e.g. 0) => array of course-module ids
104 * This list only includes sections that actually contain at least one course-module
105 * @var array
107 private $sectionmodules;
110 * Array from int (cm id) => cm_info object
111 * @var cm_info[]
113 private $cms;
116 * Array from string (modname) => int (instance id) => cm_info object
117 * @var cm_info[][]
119 private $instances;
122 * Groups that the current user belongs to. This value is calculated on first
123 * request to the property or function.
124 * When set, it is an array of grouping id => array of group id => group id.
125 * Includes grouping id 0 for 'all groups'.
126 * @var int[][]
128 private $groups;
131 * List of class read-only properties and their getter methods.
132 * Used by magic functions __get(), __isset(), __empty()
133 * @var array
135 private static $standardproperties = array(
136 'courseid' => 'get_course_id',
137 'userid' => 'get_user_id',
138 'sections' => 'get_sections',
139 'cms' => 'get_cms',
140 'instances' => 'get_instances',
141 'groups' => 'get_groups_all',
145 * Magic method getter
147 * @param string $name
148 * @return mixed
150 public function __get($name) {
151 if (isset(self::$standardproperties[$name])) {
152 $method = self::$standardproperties[$name];
153 return $this->$method();
154 } else {
155 debugging('Invalid course_modinfo property accessed: '.$name);
156 return null;
161 * Magic method for function isset()
163 * @param string $name
164 * @return bool
166 public function __isset($name) {
167 if (isset(self::$standardproperties[$name])) {
168 $value = $this->__get($name);
169 return isset($value);
171 return false;
175 * Magic method for function empty()
177 * @param string $name
178 * @return bool
180 public function __empty($name) {
181 if (isset(self::$standardproperties[$name])) {
182 $value = $this->__get($name);
183 return empty($value);
185 return true;
189 * Magic method setter
191 * Will display the developer warning when trying to set/overwrite existing property.
193 * @param string $name
194 * @param mixed $value
196 public function __set($name, $value) {
197 debugging("It is not allowed to set the property course_modinfo::\${$name}", DEBUG_DEVELOPER);
201 * Returns course object that was used in the first {@link get_fast_modinfo()} call.
203 * It may not contain all fields from DB table {course} but always has at least the following:
204 * id,shortname,fullname,format,enablecompletion,groupmode,groupmodeforce,cacherev
206 * @return stdClass
208 public function get_course() {
209 return $this->course;
213 * @return int Course ID
215 public function get_course_id() {
216 return $this->course->id;
220 * @return int User ID
222 public function get_user_id() {
223 return $this->userid;
227 * @return array Array from section number (e.g. 0) to array of course-module IDs in that
228 * section; this only includes sections that contain at least one course-module
230 public function get_sections() {
231 return $this->sectionmodules;
235 * @return cm_info[] Array from course-module instance to cm_info object within this course, in
236 * order of appearance
238 public function get_cms() {
239 return $this->cms;
243 * Obtains a single course-module object (for a course-module that is on this course).
244 * @param int $cmid Course-module ID
245 * @return cm_info Information about that course-module
246 * @throws moodle_exception If the course-module does not exist
248 public function get_cm($cmid) {
249 if (empty($this->cms[$cmid])) {
250 throw new moodle_exception('invalidcoursemoduleid', 'error', '', $cmid);
252 return $this->cms[$cmid];
256 * Obtains all module instances on this course.
257 * @return cm_info[][] Array from module name => array from instance id => cm_info
259 public function get_instances() {
260 return $this->instances;
264 * Returns array of localised human-readable module names used in this course
266 * @param bool $plural if true returns the plural form of modules names
267 * @return array
269 public function get_used_module_names($plural = false) {
270 $modnames = get_module_types_names($plural);
271 $modnamesused = array();
272 foreach ($this->get_cms() as $cmid => $mod) {
273 if (!isset($modnamesused[$mod->modname]) && isset($modnames[$mod->modname]) && $mod->uservisible) {
274 $modnamesused[$mod->modname] = $modnames[$mod->modname];
277 return $modnamesused;
281 * Obtains all instances of a particular module on this course.
282 * @param string $modname Name of module (not full frankenstyle) e.g. 'label'
283 * @return cm_info[] Array from instance id => cm_info for modules on this course; empty if none
285 public function get_instances_of($modname) {
286 if (empty($this->instances[$modname])) {
287 return array();
289 return $this->instances[$modname];
293 * Groups that the current user belongs to organised by grouping id. Calculated on the first request.
294 * @return int[][] array of grouping id => array of group id => group id. Includes grouping id 0 for 'all groups'
296 private function get_groups_all() {
297 if (is_null($this->groups)) {
298 $this->groups = groups_get_user_groups($this->course->id, $this->userid);
300 return $this->groups;
304 * Returns groups that the current user belongs to on the course. Note: If not already
305 * available, this may make a database query.
306 * @param int $groupingid Grouping ID or 0 (default) for all groups
307 * @return int[] Array of int (group id) => int (same group id again); empty array if none
309 public function get_groups($groupingid = 0) {
310 $allgroups = $this->get_groups_all();
311 if (!isset($allgroups[$groupingid])) {
312 return array();
314 return $allgroups[$groupingid];
318 * Gets all sections as array from section number => data about section.
320 * The method will return all sections of the course, including the ones
321 * delegated to a component.
323 * @return section_info[] Array of section_info objects organised by section number
325 public function get_section_info_all() {
326 return $this->sectioninfobynum;
330 * Gets all sections listed in course page as array from section number => data about section.
332 * The method is similar to get_section_info_all but filtering all sections delegated to components.
334 * @return section_info[] Array of section_info objects organised by section number
336 public function get_listed_section_info_all() {
337 if (empty($this->delegatedsections)) {
338 return $this->sectioninfobynum;
340 $sections = [];
341 foreach ($this->sectioninfobynum as $section) {
342 if (!$section->is_delegated()) {
343 $sections[$section->section] = $section;
346 return $sections;
350 * Gets data about specific numbered section.
351 * @param int $sectionnumber Number (not id) of section
352 * @param int $strictness Use MUST_EXIST to throw exception if it doesn't
353 * @return section_info Information for numbered section or null if not found
355 public function get_section_info($sectionnumber, $strictness = IGNORE_MISSING) {
356 if (!array_key_exists($sectionnumber, $this->sectioninfobynum)) {
357 if ($strictness === MUST_EXIST) {
358 throw new moodle_exception('sectionnotexist');
359 } else {
360 return null;
363 return $this->sectioninfobynum[$sectionnumber];
367 * Gets data about specific section ID.
368 * @param int $sectionid ID (not number) of section
369 * @param int $strictness Use MUST_EXIST to throw exception if it doesn't
370 * @return section_info|null Information for numbered section or null if not found
372 public function get_section_info_by_id(int $sectionid, int $strictness = IGNORE_MISSING): ?section_info {
373 if (!array_key_exists($sectionid, $this->sectioninfobyid)) {
374 if ($strictness === MUST_EXIST) {
375 throw new moodle_exception('sectionnotexist');
376 } else {
377 return null;
380 return $this->sectioninfobyid[$sectionid];
384 * Gets data about specific delegated section.
385 * @param string $component Component name
386 * @param int $itemid Item id
387 * @param int $strictness Use MUST_EXIST to throw exception if it doesn't
388 * @return section_info|null Information for numbered section or null if not found
390 public function get_section_info_by_component(
391 string $component,
392 int $itemid,
393 int $strictness = IGNORE_MISSING
394 ): ?section_info {
395 if (!isset($this->delegatedsections[$component][$itemid])) {
396 if ($strictness === MUST_EXIST) {
397 throw new moodle_exception('sectionnotexist');
398 } else {
399 return null;
402 return $this->delegatedsections[$component][$itemid];
406 * Check if the course has delegated sections.
407 * @return bool
409 public function has_delegated_sections(): bool {
410 return !empty($this->delegatedsections);
414 * Static cache for generated course_modinfo instances
416 * @see course_modinfo::instance()
417 * @see course_modinfo::clear_instance_cache()
418 * @var course_modinfo[]
420 protected static $instancecache = array();
423 * Timestamps (microtime) when the course_modinfo instances were last accessed
425 * It is used to remove the least recent accessed instances when static cache is full
427 * @var float[]
429 protected static $cacheaccessed = array();
432 * Store a list of known course cacherev values. This is in case people reuse a course object
433 * (with an old cacherev value) within the same request when calling things like
434 * get_fast_modinfo, after rebuild_course_cache.
436 * @var int[]
438 protected static $mincacherevs = [];
441 * Clears the cache used in course_modinfo::instance()
443 * Used in {@link get_fast_modinfo()} when called with argument $reset = true
444 * and in {@link rebuild_course_cache()}
446 * If the cacherev for the course is known to have updated (i.e. when doing
447 * rebuild_course_cache), it should be specified here.
449 * @param null|int|stdClass $courseorid if specified removes only cached value for this course
450 * @param int $newcacherev If specified, the known cache rev for this course id will be updated
452 public static function clear_instance_cache($courseorid = null, int $newcacherev = 0) {
453 if (empty($courseorid)) {
454 self::$instancecache = array();
455 self::$cacheaccessed = array();
456 // This is called e.g. in phpunit when we just want to reset the caches, so also
457 // reset the mincacherevs static cache.
458 self::$mincacherevs = [];
459 return;
461 if (is_object($courseorid)) {
462 $courseorid = $courseorid->id;
464 if (isset(self::$instancecache[$courseorid])) {
465 // Unsetting static variable in PHP is peculiar, it removes the reference,
466 // but data remain in memory. Prior to unsetting, the varable needs to be
467 // set to empty to remove its remains from memory.
468 self::$instancecache[$courseorid] = '';
469 unset(self::$instancecache[$courseorid]);
470 unset(self::$cacheaccessed[$courseorid]);
472 // When clearing cache for a course, we record the new cacherev version, to make
473 // sure that any future requests for the cache use at least this version.
474 if ($newcacherev) {
475 self::$mincacherevs[(int)$courseorid] = $newcacherev;
480 * Returns the instance of course_modinfo for the specified course and specified user
482 * This function uses static cache for the retrieved instances. The cache
483 * size is limited by MAX_MODINFO_CACHE_SIZE. If instance is not found in
484 * the static cache or it was created for another user or the cacherev validation
485 * failed - a new instance is constructed and returned.
487 * Used in {@link get_fast_modinfo()}
489 * @param int|stdClass $courseorid object from DB table 'course' (must have field 'id'
490 * and recommended to have field 'cacherev') or just a course id
491 * @param int $userid User id to populate 'availble' and 'uservisible' attributes of modules and sections.
492 * Set to 0 for current user (default). Set to -1 to avoid calculation of dynamic user-depended data.
493 * @return course_modinfo
495 public static function instance($courseorid, $userid = 0) {
496 global $USER;
497 if (is_object($courseorid)) {
498 $course = $courseorid;
499 } else {
500 $course = (object)array('id' => $courseorid);
502 if (empty($userid)) {
503 $userid = $USER->id;
506 if (!empty(self::$instancecache[$course->id])) {
507 if (self::$instancecache[$course->id]->userid == $userid &&
508 (!isset($course->cacherev) ||
509 $course->cacherev == self::$instancecache[$course->id]->get_course()->cacherev)) {
510 // This course's modinfo for the same user was recently retrieved, return cached.
511 self::$cacheaccessed[$course->id] = microtime(true);
512 return self::$instancecache[$course->id];
513 } else {
514 // Prevent potential reference problems when switching users.
515 self::clear_instance_cache($course->id);
518 $modinfo = new course_modinfo($course, $userid);
520 // We have a limit of MAX_MODINFO_CACHE_SIZE entries to store in static variable.
521 if (count(self::$instancecache) >= MAX_MODINFO_CACHE_SIZE) {
522 // Find the course that was the least recently accessed.
523 asort(self::$cacheaccessed, SORT_NUMERIC);
524 $courseidtoremove = key(array_reverse(self::$cacheaccessed, true));
525 self::clear_instance_cache($courseidtoremove);
528 // Add modinfo to the static cache.
529 self::$instancecache[$course->id] = $modinfo;
530 self::$cacheaccessed[$course->id] = microtime(true);
532 return $modinfo;
536 * Constructs based on course.
537 * Note: This constructor should not usually be called directly.
538 * Use get_fast_modinfo($course) instead as this maintains a cache.
539 * @param stdClass $course course object, only property id is required.
540 * @param int $userid User ID
541 * @throws moodle_exception if course is not found
543 public function __construct($course, $userid) {
544 global $CFG, $COURSE, $SITE, $DB;
546 if (!isset($course->cacherev)) {
547 // We require presence of property cacherev to validate the course cache.
548 // No need to clone the $COURSE or $SITE object here because we clone it below anyway.
549 $course = get_course($course->id, false);
552 // If we have rebuilt the course cache in this request, ensure that requested cacherev is
553 // at least that value. This ensures that we're not reusing a course object with old
554 // cacherev, which could result in using old cached data.
555 if (array_key_exists($course->id, self::$mincacherevs) &&
556 $course->cacherev < self::$mincacherevs[$course->id]) {
557 $course->cacherev = self::$mincacherevs[$course->id];
560 $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
562 // Retrieve modinfo from cache. If not present or cacherev mismatches, call rebuild and retrieve again.
563 $coursemodinfo = $cachecoursemodinfo->get_versioned($course->id, $course->cacherev);
564 // Note the version comparison using the data in the cache should not be necessary, but the
565 // partial rebuild logic sometimes sets the $coursemodinfo->cacherev to -1 which is an
566 // indicator that it needs rebuilding.
567 if ($coursemodinfo === false || ($course->cacherev > $coursemodinfo->cacherev)) {
568 $coursemodinfo = self::build_course_cache($course);
571 // Set initial values
572 $this->userid = $userid;
573 $this->sectionmodules = [];
574 $this->cms = [];
575 $this->instances = [];
576 $this->groups = null;
578 // If we haven't already preloaded contexts for the course, do it now
579 // Modules are also cached here as long as it's the first time this course has been preloaded.
580 context_helper::preload_course($course->id);
582 // Quick integrity check: as a result of race conditions modinfo may not be regenerated after the change.
583 // It is especially dangerous if modinfo contains the deleted course module, as it results in fatal error.
584 // We can check it very cheap by validating the existence of module context.
585 if ($course->id == $COURSE->id || $course->id == $SITE->id) {
586 // Only verify current course (or frontpage) as pages with many courses may not have module contexts cached.
587 // (Uncached modules will result in a very slow verification).
588 foreach ($coursemodinfo->modinfo as $mod) {
589 if (!context_module::instance($mod->cm, IGNORE_MISSING)) {
590 debugging('Course cache integrity check failed: course module with id '. $mod->cm.
591 ' does not have context. Rebuilding cache for course '. $course->id);
592 // Re-request the course record from DB as well, don't use get_course() here.
593 $course = $DB->get_record('course', array('id' => $course->id), '*', MUST_EXIST);
594 $coursemodinfo = self::build_course_cache($course, true);
595 break;
600 // Overwrite unset fields in $course object with cached values, store the course object.
601 $this->course = fullclone($course);
602 foreach ($coursemodinfo as $key => $value) {
603 if ($key !== 'modinfo' && $key !== 'sectioncache' &&
604 (!isset($this->course->$key) || $key === 'cacherev')) {
605 $this->course->$key = $value;
609 // Loop through each piece of module data, constructing it
610 static $modexists = array();
611 foreach ($coursemodinfo->modinfo as $mod) {
612 if (!isset($mod->name) || strval($mod->name) === '') {
613 // something is wrong here
614 continue;
617 // Skip modules which don't exist
618 if (!array_key_exists($mod->mod, $modexists)) {
619 $modexists[$mod->mod] = file_exists("$CFG->dirroot/mod/$mod->mod/lib.php");
621 if (!$modexists[$mod->mod]) {
622 continue;
625 // Construct info for this module
626 $cm = new cm_info($this, null, $mod, null);
628 // Store module in instances and cms array
629 if (!isset($this->instances[$cm->modname])) {
630 $this->instances[$cm->modname] = array();
632 $this->instances[$cm->modname][$cm->instance] = $cm;
633 $this->cms[$cm->id] = $cm;
635 // Reconstruct sections. This works because modules are stored in order
636 if (!isset($this->sectionmodules[$cm->sectionnum])) {
637 $this->sectionmodules[$cm->sectionnum] = [];
639 $this->sectionmodules[$cm->sectionnum][] = $cm->id;
642 // Expand section objects
643 $this->sectioninfobynum = [];
644 $this->sectioninfobyid = [];
645 $this->delegatedsections = [];
646 foreach ($coursemodinfo->sectioncache as $data) {
647 $sectioninfo = new section_info($data, $data->section, null, null,
648 $this, null);
649 $this->sectioninfobynum[$data->section] = $sectioninfo;
650 $this->sectioninfobyid[$data->id] = $sectioninfo;
651 if (!empty($sectioninfo->component)) {
652 if (!isset($this->delegatedsections[$sectioninfo->component])) {
653 $this->delegatedsections[$sectioninfo->component] = [];
655 $this->delegatedsections[$sectioninfo->component][$sectioninfo->itemid] = $sectioninfo;
658 ksort($this->sectioninfobynum);
662 * This method can not be used anymore.
664 * @see course_modinfo::build_course_cache()
665 * @deprecated since 2.6
667 public static function build_section_cache($courseid) {
668 throw new coding_exception('Function course_modinfo::build_section_cache() can not be used anymore.' .
669 ' Please use course_modinfo::build_course_cache() whenever applicable.');
673 * Builds a list of information about sections on a course to be stored in
674 * the course cache. (Does not include information that is already cached
675 * in some other way.)
677 * @param stdClass $course Course object (must contain fields id and cacherev)
678 * @param boolean $usecache use cached section info if exists, use true for partial course rebuild
679 * @return array Information about sections, indexed by section id (not number)
681 protected static function build_course_section_cache(\stdClass $course, bool $usecache = false): array {
682 global $DB;
684 // Get section data.
685 $sections = $DB->get_records(
686 'course_sections',
687 ['course' => $course->id],
688 'section',
689 'id, section, course, name, summary, summaryformat, sequence, visible, availability, component, itemid'
691 $compressedsections = [];
692 $courseformat = course_get_format($course);
694 if ($usecache) {
695 $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
696 $coursemodinfo = $cachecoursemodinfo->get_versioned($course->id, $course->cacherev);
697 if ($coursemodinfo !== false) {
698 $compressedsections = $coursemodinfo->sectioncache;
702 $formatoptionsdef = course_get_format($course)->section_format_options();
703 // Remove unnecessary data and add availability.
704 foreach ($sections as $section) {
705 $sectionid = $section->id;
706 $sectioninfocached = isset($compressedsections[$sectionid]);
707 if ($sectioninfocached) {
708 continue;
710 // Add cached options from course format to $section object.
711 foreach ($formatoptionsdef as $key => $option) {
712 if (!empty($option['cache'])) {
713 $formatoptions = $courseformat->get_format_options($section);
714 if (!array_key_exists('cachedefault', $option) || $option['cachedefault'] !== $formatoptions[$key]) {
715 $section->$key = $formatoptions[$key];
719 // Clone just in case it is reused elsewhere.
720 $compressedsections[$sectionid] = clone($section);
721 section_info::convert_for_section_cache($compressedsections[$sectionid]);
723 return $compressedsections;
727 * Builds and stores in MUC object containing information about course
728 * modules and sections together with cached fields from table course.
730 * @param stdClass $course object from DB table course. Must have property 'id'
731 * but preferably should have all cached fields.
732 * @param boolean $partialrebuild Indicate if it's partial course cache rebuild or not
733 * @return stdClass object with all cached keys of the course plus fields modinfo and sectioncache.
734 * The same object is stored in MUC
735 * @throws moodle_exception if course is not found (if $course object misses some of the
736 * necessary fields it is re-requested from database)
738 public static function build_course_cache(\stdClass $course, bool $partialrebuild = false): \stdClass {
739 if (empty($course->id)) {
740 throw new coding_exception('Object $course is missing required property \id\'');
743 $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
744 $cachekey = $course->id;
745 $cachecoursemodinfo->acquire_lock($cachekey);
746 try {
747 // Only actually do the build if it's still needed after getting the lock (not if
748 // somebody else, who might have been holding the lock, built it already).
749 $coursemodinfo = $cachecoursemodinfo->get_versioned($course->id, $course->cacherev);
750 if ($coursemodinfo === false || ($course->cacherev > $coursemodinfo->cacherev)) {
751 $coursemodinfo = self::inner_build_course_cache($course);
753 } finally {
754 $cachecoursemodinfo->release_lock($cachekey);
756 return $coursemodinfo;
760 * Called to build course cache when there is already a lock obtained.
762 * @param stdClass $course object from DB table course
763 * @param bool $partialrebuild Indicate if it's partial course cache rebuild or not
764 * @return stdClass Course object that has been stored in MUC
766 protected static function inner_build_course_cache(\stdClass $course, bool $partialrebuild = false): \stdClass {
767 global $DB, $CFG;
768 require_once("{$CFG->dirroot}/course/lib.php");
770 $cachekey = $course->id;
771 $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
772 if (!$cachecoursemodinfo->check_lock_state($cachekey)) {
773 throw new coding_exception('You must acquire a lock on the course ID before calling inner_build_course_cache');
776 // Always reload the course object from database to ensure we have the latest possible
777 // value for cacherev.
778 $course = $DB->get_record('course', ['id' => $course->id],
779 implode(',', array_merge(['id'], self::$cachedfields)), MUST_EXIST);
780 // Retrieve all information about activities and sections.
781 $coursemodinfo = new stdClass();
782 $coursemodinfo->modinfo = self::get_array_of_activities($course, $partialrebuild);
783 $coursemodinfo->sectioncache = self::build_course_section_cache($course, $partialrebuild);
784 foreach (self::$cachedfields as $key) {
785 $coursemodinfo->$key = $course->$key;
787 // Set the accumulated activities and sections information in cache, together with cacherev.
788 $cachecoursemodinfo->set_versioned($cachekey, $course->cacherev, $coursemodinfo);
789 return $coursemodinfo;
793 * Purge the cache of a course section by its id.
795 * @param int $courseid The course to purge cache in
796 * @param int $sectionid The section _id_ to purge
798 public static function purge_course_section_cache_by_id(int $courseid, int $sectionid): void {
799 $course = get_course($courseid);
800 $cache = cache::make('core', 'coursemodinfo');
801 $cachekey = $course->id;
802 $cache->acquire_lock($cachekey);
803 try {
804 $coursemodinfo = $cache->get_versioned($cachekey, $course->cacherev);
805 if ($coursemodinfo !== false && array_key_exists($sectionid, $coursemodinfo->sectioncache)) {
806 $coursemodinfo->cacherev = -1;
807 unset($coursemodinfo->sectioncache[$sectionid]);
808 $cache->set_versioned($cachekey, $course->cacherev, $coursemodinfo);
810 } finally {
811 $cache->release_lock($cachekey);
816 * Purge the cache of a course section by its number.
818 * @param int $courseid The course to purge cache in
819 * @param int $sectionno The section number to purge
821 public static function purge_course_section_cache_by_number(int $courseid, int $sectionno): void {
822 $course = get_course($courseid);
823 $cache = cache::make('core', 'coursemodinfo');
824 $cachekey = $course->id;
825 $cache->acquire_lock($cachekey);
826 try {
827 $coursemodinfo = $cache->get_versioned($cachekey, $course->cacherev);
828 if ($coursemodinfo !== false) {
829 foreach ($coursemodinfo->sectioncache as $sectionid => $sectioncache) {
830 if ($sectioncache->section == $sectionno) {
831 $coursemodinfo->cacherev = -1;
832 unset($coursemodinfo->sectioncache[$sectionid]);
833 $cache->set_versioned($cachekey, $course->cacherev, $coursemodinfo);
834 break;
838 } finally {
839 $cache->release_lock($cachekey);
844 * Purge the cache of a course module.
846 * @param int $courseid Course id
847 * @param int $cmid Course module id
849 public static function purge_course_module_cache(int $courseid, int $cmid): void {
850 self::purge_course_modules_cache($courseid, [$cmid]);
854 * Purge the cache of multiple course modules.
856 * @param int $courseid Course id
857 * @param int[] $cmids List of course module ids
858 * @return void
860 public static function purge_course_modules_cache(int $courseid, array $cmids): void {
861 $course = get_course($courseid);
862 $cache = cache::make('core', 'coursemodinfo');
863 $cachekey = $course->id;
864 $cache->acquire_lock($cachekey);
865 try {
866 $coursemodinfo = $cache->get_versioned($cachekey, $course->cacherev);
867 $hascache = ($coursemodinfo !== false);
868 $updatedcache = false;
869 if ($hascache) {
870 foreach ($cmids as $cmid) {
871 if (array_key_exists($cmid, $coursemodinfo->modinfo)) {
872 unset($coursemodinfo->modinfo[$cmid]);
873 $updatedcache = true;
876 if ($updatedcache) {
877 $coursemodinfo->cacherev = -1;
878 $cache->set_versioned($cachekey, $course->cacherev, $coursemodinfo);
879 $cache->get_versioned($cachekey, $course->cacherev);
882 } finally {
883 $cache->release_lock($cachekey);
888 * For a given course, returns an array of course activity objects
890 * @param stdClass $course Course object
891 * @param bool $usecache get activities from cache if modinfo exists when $usecache is true
892 * @return array list of activities
894 public static function get_array_of_activities(stdClass $course, bool $usecache = false): array {
895 global $CFG, $DB;
897 if (empty($course)) {
898 throw new moodle_exception('courseidnotfound');
901 $rawmods = get_course_mods($course->id);
902 if (empty($rawmods)) {
903 return [];
906 $mods = [];
907 if ($usecache) {
908 // Get existing cache.
909 $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
910 $coursemodinfo = $cachecoursemodinfo->get_versioned($course->id, $course->cacherev);
911 if ($coursemodinfo !== false) {
912 $mods = $coursemodinfo->modinfo;
916 $courseformat = course_get_format($course);
918 if ($sections = $DB->get_records('course_sections', ['course' => $course->id],
919 'section ASC', 'id,section,sequence,visible')) {
920 // First check and correct obvious mismatches between course_sections.sequence and course_modules.section.
921 if ($errormessages = course_integrity_check($course->id, $rawmods, $sections)) {
922 debugging(join('<br>', $errormessages));
923 $rawmods = get_course_mods($course->id);
924 $sections = $DB->get_records('course_sections', ['course' => $course->id],
925 'section ASC', 'id,section,sequence,visible');
927 // Build array of activities.
928 foreach ($sections as $section) {
929 if (!empty($section->sequence)) {
930 $cmids = explode(",", $section->sequence);
931 $numberofmods = count($cmids);
932 foreach ($cmids as $cmid) {
933 // Activity does not exist in the database.
934 $notexistindb = empty($rawmods[$cmid]);
935 $activitycached = isset($mods[$cmid]);
936 if ($activitycached || $notexistindb) {
937 continue;
940 // Adjust visibleoncoursepage, value in DB may not respect format availability.
941 $rawmods[$cmid]->visibleoncoursepage = (!$rawmods[$cmid]->visible
942 || $rawmods[$cmid]->visibleoncoursepage
943 || empty($CFG->allowstealth)
944 || !$courseformat->allow_stealth_module_visibility($rawmods[$cmid], $section)) ? 1 : 0;
946 $mods[$cmid] = new stdClass();
947 $mods[$cmid]->id = $rawmods[$cmid]->instance;
948 $mods[$cmid]->cm = $rawmods[$cmid]->id;
949 $mods[$cmid]->mod = $rawmods[$cmid]->modname;
951 // Oh dear. Inconsistent names left 'section' here for backward compatibility,
952 // but also save sectionid and sectionnumber.
953 $mods[$cmid]->section = $section->section;
954 $mods[$cmid]->sectionnumber = $section->section;
955 $mods[$cmid]->sectionid = $rawmods[$cmid]->section;
957 $mods[$cmid]->module = $rawmods[$cmid]->module;
958 $mods[$cmid]->added = $rawmods[$cmid]->added;
959 $mods[$cmid]->score = $rawmods[$cmid]->score;
960 $mods[$cmid]->idnumber = $rawmods[$cmid]->idnumber;
961 $mods[$cmid]->visible = $rawmods[$cmid]->visible;
962 $mods[$cmid]->visibleoncoursepage = $rawmods[$cmid]->visibleoncoursepage;
963 $mods[$cmid]->visibleold = $rawmods[$cmid]->visibleold;
964 $mods[$cmid]->groupmode = $rawmods[$cmid]->groupmode;
965 $mods[$cmid]->groupingid = $rawmods[$cmid]->groupingid;
966 $mods[$cmid]->indent = $rawmods[$cmid]->indent;
967 $mods[$cmid]->completion = $rawmods[$cmid]->completion;
968 $mods[$cmid]->extra = "";
969 $mods[$cmid]->completiongradeitemnumber =
970 $rawmods[$cmid]->completiongradeitemnumber;
971 $mods[$cmid]->completionpassgrade = $rawmods[$cmid]->completionpassgrade;
972 $mods[$cmid]->completionview = $rawmods[$cmid]->completionview;
973 $mods[$cmid]->completionexpected = $rawmods[$cmid]->completionexpected;
974 $mods[$cmid]->showdescription = $rawmods[$cmid]->showdescription;
975 $mods[$cmid]->availability = $rawmods[$cmid]->availability;
976 $mods[$cmid]->deletioninprogress = $rawmods[$cmid]->deletioninprogress;
977 $mods[$cmid]->downloadcontent = $rawmods[$cmid]->downloadcontent;
978 $mods[$cmid]->lang = $rawmods[$cmid]->lang;
980 $modname = $mods[$cmid]->mod;
981 $functionname = $modname . "_get_coursemodule_info";
983 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
984 continue;
987 include_once("$CFG->dirroot/mod/$modname/lib.php");
989 if ($hasfunction = function_exists($functionname)) {
990 if ($info = $functionname($rawmods[$cmid])) {
991 if (!empty($info->icon)) {
992 $mods[$cmid]->icon = $info->icon;
994 if (!empty($info->iconcomponent)) {
995 $mods[$cmid]->iconcomponent = $info->iconcomponent;
997 if (!empty($info->name)) {
998 $mods[$cmid]->name = $info->name;
1000 if ($info instanceof cached_cm_info) {
1001 // When using cached_cm_info you can include three new fields.
1002 // That aren't available for legacy code.
1003 if (!empty($info->content)) {
1004 $mods[$cmid]->content = $info->content;
1006 if (!empty($info->extraclasses)) {
1007 $mods[$cmid]->extraclasses = $info->extraclasses;
1009 if (!empty($info->iconurl)) {
1010 // Convert URL to string as it's easier to store.
1011 // Also serialized object contains \0 byte,
1012 // ... and can not be written to Postgres DB.
1013 $url = new moodle_url($info->iconurl);
1014 $mods[$cmid]->iconurl = $url->out(false);
1016 if (!empty($info->onclick)) {
1017 $mods[$cmid]->onclick = $info->onclick;
1019 if (!empty($info->customdata)) {
1020 $mods[$cmid]->customdata = $info->customdata;
1022 } else {
1023 // When using a stdclass, the (horrible) deprecated ->extra field,
1024 // ... that is available for BC.
1025 if (!empty($info->extra)) {
1026 $mods[$cmid]->extra = $info->extra;
1031 // When there is no modname_get_coursemodule_info function,
1032 // ... but showdescriptions is enabled, then we use the 'intro',
1033 // ... and 'introformat' fields in the module table.
1034 if (!$hasfunction && $rawmods[$cmid]->showdescription) {
1035 if ($modvalues = $DB->get_record($rawmods[$cmid]->modname,
1036 ['id' => $rawmods[$cmid]->instance], 'name, intro, introformat')) {
1037 // Set content from intro and introformat. Filters are disabled.
1038 // Because we filter it with format_text at display time.
1039 $mods[$cmid]->content = format_module_intro($rawmods[$cmid]->modname,
1040 $modvalues, $rawmods[$cmid]->id, false);
1042 // To save making another query just below, put name in here.
1043 $mods[$cmid]->name = $modvalues->name;
1046 if (!isset($mods[$cmid]->name)) {
1047 $mods[$cmid]->name = $DB->get_field($rawmods[$cmid]->modname, "name",
1048 ["id" => $rawmods[$cmid]->instance]);
1051 // Minimise the database size by unsetting default options when they are 'empty'.
1052 // This list corresponds to code in the cm_info constructor.
1053 foreach (['idnumber', 'groupmode', 'groupingid',
1054 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
1055 'icon', 'iconcomponent', 'customdata', 'availability', 'completionview',
1056 'completionexpected', 'score', 'showdescription', 'deletioninprogress'] as $property) {
1057 if (property_exists($mods[$cmid], $property) &&
1058 empty($mods[$cmid]->{$property})) {
1059 unset($mods[$cmid]->{$property});
1062 // Special case: this value is usually set to null, but may be 0.
1063 if (property_exists($mods[$cmid], 'completiongradeitemnumber') &&
1064 is_null($mods[$cmid]->completiongradeitemnumber)) {
1065 unset($mods[$cmid]->completiongradeitemnumber);
1071 return $mods;
1075 * Purge the cache of a given course
1077 * @param int $courseid Course id
1079 public static function purge_course_cache(int $courseid): void {
1080 increment_revision_number('course', 'cacherev', 'id = :id', array('id' => $courseid));
1081 // Because this is a versioned cache, there is no need to actually delete the cache item,
1082 // only increase the required version number.
1088 * Data about a single module on a course. This contains most of the fields in the course_modules
1089 * table, plus additional data when required.
1091 * The object can be accessed by core or any plugin (i.e. course format, block, filter, etc.) as
1092 * get_fast_modinfo($courseorid)->cms[$coursemoduleid]
1093 * or
1094 * get_fast_modinfo($courseorid)->instances[$moduletype][$instanceid]
1096 * There are three stages when activity module can add/modify data in this object:
1098 * <b>Stage 1 - during building the cache.</b>
1099 * Allows to add to the course cache static user-independent information about the module.
1100 * Modules should try to include only absolutely necessary information that may be required
1101 * when displaying course view page. The information is stored in application-level cache
1102 * and reset when {@link rebuild_course_cache()} is called or cache is purged by admin.
1104 * Modules can implement callback XXX_get_coursemodule_info() returning instance of object
1105 * {@link cached_cm_info}
1107 * <b>Stage 2 - dynamic data.</b>
1108 * Dynamic data is user-dependent, it is stored in request-level cache. To reset this cache
1109 * {@link get_fast_modinfo()} with $reset argument may be called.
1111 * Dynamic data is obtained when any of the following properties/methods is requested:
1112 * - {@link cm_info::$url}
1113 * - {@link cm_info::$name}
1114 * - {@link cm_info::$onclick}
1115 * - {@link cm_info::get_icon_url()}
1116 * - {@link cm_info::$uservisible}
1117 * - {@link cm_info::$available}
1118 * - {@link cm_info::$availableinfo}
1119 * - plus any of the properties listed in Stage 3.
1121 * Modules can implement callback <b>XXX_cm_info_dynamic()</b> and inside this callback they
1122 * are allowed to use any of the following set methods:
1123 * - {@link cm_info::set_available()}
1124 * - {@link cm_info::set_name()}
1125 * - {@link cm_info::set_no_view_link()}
1126 * - {@link cm_info::set_user_visible()}
1127 * - {@link cm_info::set_on_click()}
1128 * - {@link cm_info::set_icon_url()}
1129 * - {@link cm_info::override_customdata()}
1130 * Any methods affecting view elements can also be set in this callback.
1132 * <b>Stage 3 (view data).</b>
1133 * Also user-dependend data stored in request-level cache. Second stage is created
1134 * because populating the view data can be expensive as it may access much more
1135 * Moodle APIs such as filters, user information, output renderers and we
1136 * don't want to request it until necessary.
1137 * View data is obtained when any of the following properties/methods is requested:
1138 * - {@link cm_info::$afterediticons}
1139 * - {@link cm_info::$content}
1140 * - {@link cm_info::get_formatted_content()}
1141 * - {@link cm_info::$extraclasses}
1142 * - {@link cm_info::$afterlink}
1144 * Modules can implement callback <b>XXX_cm_info_view()</b> and inside this callback they
1145 * are allowed to use any of the following set methods:
1146 * - {@link cm_info::set_after_edit_icons()}
1147 * - {@link cm_info::set_after_link()}
1148 * - {@link cm_info::set_content()}
1149 * - {@link cm_info::set_extra_classes()}
1151 * @property-read int $id Course-module ID - from course_modules table
1152 * @property-read int $instance Module instance (ID within module table) - from course_modules table
1153 * @property-read int $course Course ID - from course_modules table
1154 * @property-read string $idnumber 'ID number' from course-modules table (arbitrary text set by user) - from
1155 * course_modules table
1156 * @property-read int $added Time that this course-module was added (unix time) - from course_modules table
1157 * @property-read int $visible Visible setting (0 or 1; if this is 0, students cannot see/access the activity) - from
1158 * course_modules table
1159 * @property-read int $visibleoncoursepage Visible on course page setting - from course_modules table, adjusted to
1160 * whether course format allows this module to have the "stealth" mode
1161 * @property-read int $visibleold Old visible setting (if the entire section is hidden, the previous value for
1162 * visible is stored in this field) - from course_modules table
1163 * @property-read int $groupmode Group mode (one of the constants NOGROUPS, SEPARATEGROUPS, or VISIBLEGROUPS) - from
1164 * course_modules table. Use {@link cm_info::$effectivegroupmode} to find the actual group mode that may be forced by course.
1165 * @property-read int $groupingid Grouping ID (0 = all groupings)
1166 * @property-read bool $coursegroupmodeforce Indicates whether the course containing the module has forced the groupmode
1167 * This means that cm_info::$groupmode should be ignored and cm_info::$coursegroupmode be used instead
1168 * @property-read int $coursegroupmode Group mode (one of the constants NOGROUPS, SEPARATEGROUPS, or VISIBLEGROUPS) - from
1169 * course table - as specified for the course containing the module
1170 * Effective only if {@link cm_info::$coursegroupmodeforce} is set
1171 * @property-read int $effectivegroupmode Effective group mode for this module (one of the constants NOGROUPS, SEPARATEGROUPS,
1172 * or VISIBLEGROUPS). This can be different from groupmode set for the module if the groupmode is forced for the course.
1173 * This value will always be NOGROUPS if module type does not support group mode.
1174 * @property-read int $indent Indent level on course page (0 = no indent) - from course_modules table
1175 * @property-read int $completion Activity completion setting for this activity, COMPLETION_TRACKING_xx constant - from
1176 * course_modules table
1177 * @property-read mixed $completiongradeitemnumber Set to the item number (usually 0) if completion depends on a particular
1178 * grade of this activity, or null if completion does not depend on a grade - from course_modules table
1179 * @property-read int $completionview 1 if 'on view' completion is enabled, 0 otherwise - from course_modules table
1180 * @property-read int $completionexpected Set to a unix time if completion of this activity is expected at a
1181 * particular time, 0 if no time set - from course_modules table
1182 * @property-read string $availability Availability information as JSON string or null if none -
1183 * from course_modules table
1184 * @property-read int $showdescription Controls whether the description of the activity displays on the course main page (in
1185 * addition to anywhere it might display within the activity itself). 0 = do not show
1186 * on main page, 1 = show on main page.
1187 * @property-read string $extra (deprecated) Extra HTML that is put in an unhelpful part of the HTML when displaying this module in
1188 * course page - from cached data in modinfo field. Deprecated, replaced by ->extraclasses and ->onclick
1189 * @property-read string $icon Name of icon to use - from cached data in modinfo field
1190 * @property-read string $iconcomponent Component that contains icon - from cached data in modinfo field
1191 * @property-read string $modname Name of module e.g. 'forum' (this is the same name as the module's main database
1192 * table) - from cached data in modinfo field
1193 * @property-read int $module ID of module type - from course_modules table
1194 * @property-read string $name Name of module instance for display on page e.g. 'General discussion forum' - from cached
1195 * data in modinfo field
1196 * @property-read int $sectionnum Section number that this course-module is in (section 0 = above the calendar, section 1
1197 * = week/topic 1, etc) - from cached data in modinfo field
1198 * @property-read int $sectionid Section id - from course_modules table
1199 * @property-read array $conditionscompletion Availability conditions for this course-module based on the completion of other
1200 * course-modules (array from other course-module id to required completion state for that
1201 * module) - from cached data in modinfo field
1202 * @property-read array $conditionsgrade Availability conditions for this course-module based on course grades (array from
1203 * grade item id to object with ->min, ->max fields) - from cached data in modinfo field
1204 * @property-read array $conditionsfield Availability conditions for this course-module based on user fields
1205 * @property-read bool $available True if this course-module is available to students i.e. if all availability conditions
1206 * are met - obtained dynamically
1207 * @property-read string $availableinfo If course-module is not available to students, this string gives information about
1208 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
1209 * January 2010') for display on main page - obtained dynamically
1210 * @property-read bool $uservisible True if this course-module is available to the CURRENT user (for example, if current user
1211 * has viewhiddenactivities capability, they can access the course-module even if it is not
1212 * visible or not available, so this would be true in that case)
1213 * @property-read context_module $context Module context
1214 * @property-read string $modfullname Returns a localised human-readable name of the module type - calculated on request
1215 * @property-read string $modplural Returns a localised human-readable name of the module type in plural form - calculated on request
1216 * @property-read string $content Content to display on main (view) page - calculated on request
1217 * @property-read moodle_url $url URL to link to for this module, or null if it doesn't have a view page - calculated on request
1218 * @property-read string $extraclasses Extra CSS classes to add to html output for this activity on main page - calculated on request
1219 * @property-read string $onclick Content of HTML on-click attribute already escaped - calculated on request
1220 * @property-read mixed $customdata Optional custom data stored in modinfo cache for this activity, or null if none
1221 * @property-read string $afterlink Extra HTML code to display after link - calculated on request
1222 * @property-read string $afterediticons Extra HTML code to display after editing icons (e.g. more icons) - calculated on request
1223 * @property-read bool $deletioninprogress True if this course module is scheduled for deletion, false otherwise.
1224 * @property-read bool $downloadcontent True if content download is enabled for this course module, false otherwise.
1225 * @property-read bool $lang the forced language for this activity (language pack name). Null means not forced.
1227 class cm_info implements IteratorAggregate {
1229 * State: Only basic data from modinfo cache is available.
1231 const STATE_BASIC = 0;
1234 * State: In the process of building dynamic data (to avoid recursive calls to obtain_dynamic_data())
1236 const STATE_BUILDING_DYNAMIC = 1;
1239 * State: Dynamic data is available too.
1241 const STATE_DYNAMIC = 2;
1244 * State: In the process of building view data (to avoid recursive calls to obtain_view_data())
1246 const STATE_BUILDING_VIEW = 3;
1249 * State: View data (for course page) is available.
1251 const STATE_VIEW = 4;
1254 * Parent object
1255 * @var course_modinfo
1257 private $modinfo;
1260 * Level of information stored inside this object (STATE_xx constant)
1261 * @var int
1263 private $state;
1266 * Course-module ID - from course_modules table
1267 * @var int
1269 private $id;
1272 * Module instance (ID within module table) - from course_modules table
1273 * @var int
1275 private $instance;
1278 * 'ID number' from course-modules table (arbitrary text set by user) - from
1279 * course_modules table
1280 * @var string
1282 private $idnumber;
1285 * Time that this course-module was added (unix time) - from course_modules table
1286 * @var int
1288 private $added;
1291 * This variable is not used and is included here only so it can be documented.
1292 * Once the database entry is removed from course_modules, it should be deleted
1293 * here too.
1294 * @var int
1295 * @deprecated Do not use this variable
1297 private $score;
1300 * Visible setting (0 or 1; if this is 0, students cannot see/access the activity) - from
1301 * course_modules table
1302 * @var int
1304 private $visible;
1307 * Visible on course page setting - from course_modules table
1308 * @var int
1310 private $visibleoncoursepage;
1313 * Old visible setting (if the entire section is hidden, the previous value for
1314 * visible is stored in this field) - from course_modules table
1315 * @var int
1317 private $visibleold;
1320 * Group mode (one of the constants NONE, SEPARATEGROUPS, or VISIBLEGROUPS) - from
1321 * course_modules table
1322 * @var int
1324 private $groupmode;
1327 * Grouping ID (0 = all groupings)
1328 * @var int
1330 private $groupingid;
1333 * Indent level on course page (0 = no indent) - from course_modules table
1334 * @var int
1336 private $indent;
1339 * Activity completion setting for this activity, COMPLETION_TRACKING_xx constant - from
1340 * course_modules table
1341 * @var int
1343 private $completion;
1346 * Set to the item number (usually 0) if completion depends on a particular
1347 * grade of this activity, or null if completion does not depend on a grade - from
1348 * course_modules table
1349 * @var mixed
1351 private $completiongradeitemnumber;
1354 * 1 if pass grade completion is enabled, 0 otherwise - from course_modules table
1355 * @var int
1357 private $completionpassgrade;
1360 * 1 if 'on view' completion is enabled, 0 otherwise - from course_modules table
1361 * @var int
1363 private $completionview;
1366 * Set to a unix time if completion of this activity is expected at a
1367 * particular time, 0 if no time set - from course_modules table
1368 * @var int
1370 private $completionexpected;
1373 * Availability information as JSON string or null if none - from course_modules table
1374 * @var string
1376 private $availability;
1379 * Controls whether the description of the activity displays on the course main page (in
1380 * addition to anywhere it might display within the activity itself). 0 = do not show
1381 * on main page, 1 = show on main page.
1382 * @var int
1384 private $showdescription;
1387 * Extra HTML that is put in an unhelpful part of the HTML when displaying this module in
1388 * course page - from cached data in modinfo field
1389 * @deprecated This is crazy, don't use it. Replaced by ->extraclasses and ->onclick
1390 * @var string
1392 private $extra;
1395 * Name of icon to use - from cached data in modinfo field
1396 * @var string
1398 private $icon;
1401 * Component that contains icon - from cached data in modinfo field
1402 * @var string
1404 private $iconcomponent;
1407 * Name of module e.g. 'forum' (this is the same name as the module's main database
1408 * table) - from cached data in modinfo field
1409 * @var string
1411 private $modname;
1414 * ID of module - from course_modules table
1415 * @var int
1417 private $module;
1420 * Name of module instance for display on page e.g. 'General discussion forum' - from cached
1421 * data in modinfo field
1422 * @var string
1424 private $name;
1427 * Section number that this course-module is in (section 0 = above the calendar, section 1
1428 * = week/topic 1, etc) - from cached data in modinfo field
1429 * @var int
1431 private $sectionnum;
1434 * Section id - from course_modules table
1435 * @var int
1437 private $sectionid;
1440 * Availability conditions for this course-module based on the completion of other
1441 * course-modules (array from other course-module id to required completion state for that
1442 * module) - from cached data in modinfo field
1443 * @var array
1445 private $conditionscompletion;
1448 * Availability conditions for this course-module based on course grades (array from
1449 * grade item id to object with ->min, ->max fields) - from cached data in modinfo field
1450 * @var array
1452 private $conditionsgrade;
1455 * Availability conditions for this course-module based on user fields
1456 * @var array
1458 private $conditionsfield;
1461 * True if this course-module is available to students i.e. if all availability conditions
1462 * are met - obtained dynamically
1463 * @var bool
1465 private $available;
1468 * If course-module is not available to students, this string gives information about
1469 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
1470 * January 2010') for display on main page - obtained dynamically
1471 * @var string
1473 private $availableinfo;
1476 * True if this course-module is available to the CURRENT user (for example, if current user
1477 * has viewhiddenactivities capability, they can access the course-module even if it is not
1478 * visible or not available, so this would be true in that case)
1479 * @var bool
1481 private $uservisible;
1484 * True if this course-module is visible to the CURRENT user on the course page
1485 * @var bool
1487 private $uservisibleoncoursepage;
1490 * @var moodle_url
1492 private $url;
1495 * @var string
1497 private $content;
1500 * @var bool
1502 private $contentisformatted;
1505 * @var bool True if the content has a special course item display like labels.
1507 private $customcmlistitem;
1510 * @var string
1512 private $extraclasses;
1515 * @var moodle_url full external url pointing to icon image for activity
1517 private $iconurl;
1520 * @var string
1522 private $onclick;
1525 * @var mixed
1527 private $customdata;
1530 * @var string
1532 private $afterlink;
1535 * @var string
1537 private $afterediticons;
1540 * @var bool representing the deletion state of the module. True if the mod is scheduled for deletion.
1542 private $deletioninprogress;
1545 * @var int enable/disable download content for this course module
1547 private $downloadcontent;
1550 * @var string|null the forced language for this activity (language pack name). Null means not forced.
1552 private $lang;
1555 * List of class read-only properties and their getter methods.
1556 * Used by magic functions __get(), __isset(), __empty()
1557 * @var array
1559 private static $standardproperties = [
1560 'url' => 'get_url',
1561 'content' => 'get_content',
1562 'extraclasses' => 'get_extra_classes',
1563 'onclick' => 'get_on_click',
1564 'customdata' => 'get_custom_data',
1565 'afterlink' => 'get_after_link',
1566 'afterediticons' => 'get_after_edit_icons',
1567 'modfullname' => 'get_module_type_name',
1568 'modplural' => 'get_module_type_name_plural',
1569 'id' => false,
1570 'added' => false,
1571 'availability' => false,
1572 'available' => 'get_available',
1573 'availableinfo' => 'get_available_info',
1574 'completion' => false,
1575 'completionexpected' => false,
1576 'completiongradeitemnumber' => false,
1577 'completionpassgrade' => false,
1578 'completionview' => false,
1579 'conditionscompletion' => false,
1580 'conditionsfield' => false,
1581 'conditionsgrade' => false,
1582 'context' => 'get_context',
1583 'course' => 'get_course_id',
1584 'coursegroupmode' => 'get_course_groupmode',
1585 'coursegroupmodeforce' => 'get_course_groupmodeforce',
1586 'customcmlistitem' => 'has_custom_cmlist_item',
1587 'effectivegroupmode' => 'get_effective_groupmode',
1588 'extra' => false,
1589 'groupingid' => false,
1590 'groupmembersonly' => 'get_deprecated_group_members_only',
1591 'groupmode' => false,
1592 'icon' => false,
1593 'iconcomponent' => false,
1594 'idnumber' => false,
1595 'indent' => false,
1596 'instance' => false,
1597 'modname' => false,
1598 'module' => false,
1599 'name' => 'get_name',
1600 'score' => false,
1601 'section' => 'get_section_id',
1602 'sectionid' => false,
1603 'sectionnum' => false,
1604 'showdescription' => false,
1605 'uservisible' => 'get_user_visible',
1606 'visible' => false,
1607 'visibleoncoursepage' => false,
1608 'visibleold' => false,
1609 'deletioninprogress' => false,
1610 'downloadcontent' => false,
1611 'lang' => false,
1615 * List of methods with no arguments that were public prior to Moodle 2.6.
1617 * They can still be accessed publicly via magic __call() function with no warnings
1618 * but are not listed in the class methods list.
1619 * For the consistency of the code it is better to use corresponding properties.
1621 * These methods be deprecated completely in later versions.
1623 * @var array $standardmethods
1625 private static $standardmethods = array(
1626 // Following methods are not recommended to use because there have associated read-only properties.
1627 'get_url',
1628 'get_content',
1629 'get_extra_classes',
1630 'get_on_click',
1631 'get_custom_data',
1632 'get_after_link',
1633 'get_after_edit_icons',
1634 // Method obtain_dynamic_data() should not be called from outside of this class but it was public before Moodle 2.6.
1635 'obtain_dynamic_data',
1639 * Magic method to call functions that are now declared as private but were public in Moodle before 2.6.
1640 * These private methods can not be used anymore.
1642 * @param string $name
1643 * @param array $arguments
1644 * @return mixed
1645 * @throws coding_exception
1647 public function __call($name, $arguments) {
1648 if (in_array($name, self::$standardmethods)) {
1649 $message = "cm_info::$name() can not be used anymore.";
1650 if ($alternative = array_search($name, self::$standardproperties)) {
1651 $message .= " Please use the property cm_info->$alternative instead.";
1653 throw new coding_exception($message);
1655 throw new coding_exception("Method cm_info::{$name}() does not exist");
1659 * Magic method getter
1661 * @param string $name
1662 * @return mixed
1664 public function __get($name) {
1665 if (isset(self::$standardproperties[$name])) {
1666 if ($method = self::$standardproperties[$name]) {
1667 return $this->$method();
1668 } else {
1669 return $this->$name;
1671 } else {
1672 debugging('Invalid cm_info property accessed: '.$name);
1673 return null;
1678 * Implementation of IteratorAggregate::getIterator(), allows to cycle through properties
1679 * and use {@link convert_to_array()}
1681 * @return ArrayIterator
1683 public function getIterator(): Traversable {
1684 // Make sure dynamic properties are retrieved prior to view properties.
1685 $this->obtain_dynamic_data();
1686 $ret = array();
1688 // Do not iterate over deprecated properties.
1689 $props = self::$standardproperties;
1690 unset($props['groupmembersonly']);
1692 foreach ($props as $key => $unused) {
1693 $ret[$key] = $this->__get($key);
1695 return new ArrayIterator($ret);
1699 * Magic method for function isset()
1701 * @param string $name
1702 * @return bool
1704 public function __isset($name) {
1705 if (isset(self::$standardproperties[$name])) {
1706 $value = $this->__get($name);
1707 return isset($value);
1709 return false;
1713 * Magic method for function empty()
1715 * @param string $name
1716 * @return bool
1718 public function __empty($name) {
1719 if (isset(self::$standardproperties[$name])) {
1720 $value = $this->__get($name);
1721 return empty($value);
1723 return true;
1727 * Magic method setter
1729 * Will display the developer warning when trying to set/overwrite property.
1731 * @param string $name
1732 * @param mixed $value
1734 public function __set($name, $value) {
1735 debugging("It is not allowed to set the property cm_info::\${$name}", DEBUG_DEVELOPER);
1739 * @return bool True if this module has a 'view' page that should be linked to in navigation
1740 * etc (note: modules may still have a view.php file, but return false if this is not
1741 * intended to be linked to from 'normal' parts of the interface; this is what label does).
1743 public function has_view() {
1744 return !is_null($this->url);
1748 * Gets the URL to link to for this module.
1750 * This method is normally called by the property ->url, but can be called directly if
1751 * there is a case when it might be called recursively (you can't call property values
1752 * recursively).
1754 * @return moodle_url URL to link to for this module, or null if it doesn't have a view page
1756 public function get_url() {
1757 $this->obtain_dynamic_data();
1758 return $this->url;
1762 * Obtains content to display on main (view) page.
1763 * Note: Will collect view data, if not already obtained.
1764 * @return string Content to display on main page below link, or empty string if none
1766 private function get_content() {
1767 $this->obtain_view_data();
1768 return $this->content;
1772 * Returns the content to display on course/overview page, formatted and passed through filters
1774 * if $options['context'] is not specified, the module context is used
1776 * @param array|stdClass $options formatting options, see {@link format_text()}
1777 * @return string
1779 public function get_formatted_content($options = array()) {
1780 $this->obtain_view_data();
1781 if (empty($this->content)) {
1782 return '';
1784 if ($this->contentisformatted) {
1785 return $this->content;
1788 // Improve filter performance by preloading filter setttings for all
1789 // activities on the course (this does nothing if called multiple
1790 // times)
1791 filter_preload_activities($this->get_modinfo());
1793 $options = (array)$options;
1794 if (!isset($options['context'])) {
1795 $options['context'] = $this->get_context();
1797 return format_text($this->content, FORMAT_HTML, $options);
1801 * Return the module custom cmlist item flag.
1803 * Activities like label uses this flag to indicate that it should be
1804 * displayed as a custom course item instead of a tipical activity card.
1806 * @return bool
1808 public function has_custom_cmlist_item(): bool {
1809 $this->obtain_view_data();
1810 return $this->customcmlistitem ?? false;
1814 * Getter method for property $name, ensures that dynamic data is obtained.
1816 * This method is normally called by the property ->name, but can be called directly if there
1817 * is a case when it might be called recursively (you can't call property values recursively).
1819 * @return string
1821 public function get_name() {
1822 $this->obtain_dynamic_data();
1823 return $this->name;
1827 * Returns the name to display on course/overview page, formatted and passed through filters
1829 * if $options['context'] is not specified, the module context is used
1831 * @param array|stdClass $options formatting options, see {@link format_string()}
1832 * @return string
1834 public function get_formatted_name($options = array()) {
1835 global $CFG;
1836 $options = (array)$options;
1837 if (!isset($options['context'])) {
1838 $options['context'] = $this->get_context();
1840 // Improve filter performance by preloading filter setttings for all
1841 // activities on the course (this does nothing if called multiple
1842 // times).
1843 if (!empty($CFG->filterall)) {
1844 filter_preload_activities($this->get_modinfo());
1846 return format_string($this->get_name(), true, $options);
1850 * Note: Will collect view data, if not already obtained.
1851 * @return string Extra CSS classes to add to html output for this activity on main page
1853 private function get_extra_classes() {
1854 $this->obtain_view_data();
1855 return $this->extraclasses;
1859 * @return string Content of HTML on-click attribute. This string will be used literally
1860 * as a string so should be pre-escaped.
1862 private function get_on_click() {
1863 // Does not need view data; may be used by navigation
1864 $this->obtain_dynamic_data();
1865 return $this->onclick;
1868 * Getter method for property $customdata, ensures that dynamic data is retrieved.
1870 * This method is normally called by the property ->customdata, but can be called directly if there
1871 * is a case when it might be called recursively (you can't call property values recursively).
1873 * @return mixed Optional custom data stored in modinfo cache for this activity, or null if none
1875 public function get_custom_data() {
1876 $this->obtain_dynamic_data();
1877 return $this->customdata;
1881 * Note: Will collect view data, if not already obtained.
1882 * @return string Extra HTML code to display after link
1884 private function get_after_link() {
1885 $this->obtain_view_data();
1886 return $this->afterlink;
1890 * Get the activity badge data associated to this course module (if the module supports it).
1891 * Modules can use this method to provide additional data to be displayed in the activity badge.
1893 * @param renderer_base $output Output render to use, or null for default (global)
1894 * @return stdClass|null The activitybadge data (badgecontent, badgestyle...) or null if the module doesn't implement it.
1896 public function get_activitybadge(?renderer_base $output = null): ?stdClass {
1897 global $OUTPUT;
1899 $activibybadgeclass = activitybadge::create_instance($this);
1900 if (empty($activibybadgeclass)) {
1901 return null;
1904 if (!isset($output)) {
1905 $output = $OUTPUT;
1908 return $activibybadgeclass->export_for_template($output);
1912 * Note: Will collect view data, if not already obtained.
1913 * @return string Extra HTML code to display after editing icons (e.g. more icons)
1915 private function get_after_edit_icons() {
1916 $this->obtain_view_data();
1917 return $this->afterediticons;
1921 * Fetch the module's icon URL.
1923 * This function fetches the course module instance's icon URL.
1924 * This method adds a `filtericon` parameter in the URL when rendering the monologo version of the course module icon or when
1925 * the plugin declares, via its `filtericon` custom data, that the icon needs to be filtered.
1926 * This additional information can be used by plugins when rendering the module icon to determine whether to apply
1927 * CSS filtering to the icon.
1929 * @param core_renderer $output Output render to use, or null for default (global)
1930 * @return moodle_url Icon URL for a suitable icon to put beside this cm
1932 public function get_icon_url($output = null) {
1933 global $OUTPUT;
1934 $this->obtain_dynamic_data();
1935 if (!$output) {
1936 $output = $OUTPUT;
1939 $ismonologo = false;
1940 if (!empty($this->iconurl)) {
1941 // Support modules setting their own, external, icon image.
1942 $icon = $this->iconurl;
1943 } else if (!empty($this->icon)) {
1944 // Fallback to normal local icon + component processing.
1945 if (substr($this->icon, 0, 4) === 'mod/') {
1946 list($modname, $iconname) = explode('/', substr($this->icon, 4), 2);
1947 $icon = $output->image_url($iconname, $modname);
1948 } else {
1949 if (!empty($this->iconcomponent)) {
1950 // Icon has specified component.
1951 $icon = $output->image_url($this->icon, $this->iconcomponent);
1952 } else {
1953 // Icon does not have specified component, use default.
1954 $icon = $output->image_url($this->icon);
1957 } else {
1958 $icon = $output->image_url('monologo', $this->modname);
1959 // Activity modules may only have an `icon` icon instead of a `monologo` icon.
1960 // So we need to determine if the module really has a `monologo` icon.
1961 $ismonologo = core_component::has_monologo_icon('mod', $this->modname);
1964 // Determine whether the icon will be filtered in the CSS.
1965 // This can be controlled by the module by declaring a 'filtericon' custom data.
1966 // If the 'filtericon' custom data is not set, icon filtering will be determined whether the module has a `monologo` icon.
1967 // Additionally, we need to cast custom data to array as some modules may treat it as an object.
1968 $filtericon = ((array)$this->customdata)['filtericon'] ?? $ismonologo;
1969 if ($filtericon) {
1970 $icon->param('filtericon', 1);
1972 return $icon;
1976 * @param string $textclasses additionnal classes for grouping label
1977 * @return string An empty string or HTML grouping label span tag
1979 public function get_grouping_label($textclasses = '') {
1980 $groupinglabel = '';
1981 if ($this->effectivegroupmode != NOGROUPS && !empty($this->groupingid) &&
1982 has_capability('moodle/course:managegroups', context_course::instance($this->course))) {
1983 $groupings = groups_get_all_groupings($this->course);
1984 $groupinglabel = html_writer::tag('span', '('.format_string($groupings[$this->groupingid]->name).')',
1985 array('class' => 'groupinglabel '.$textclasses));
1987 return $groupinglabel;
1991 * Returns a localised human-readable name of the module type.
1993 * @param bool $plural If true, the function returns the plural form of the name.
1994 * @return lang_string
1996 public function get_module_type_name($plural = false) {
1997 $modnames = get_module_types_names($plural);
1998 if (isset($modnames[$this->modname])) {
1999 return $modnames[$this->modname];
2000 } else {
2001 return null;
2006 * Returns a localised human-readable name of the module type in plural form - calculated on request
2008 * @return string
2010 private function get_module_type_name_plural() {
2011 return $this->get_module_type_name(true);
2015 * @return course_modinfo Modinfo object that this came from
2017 public function get_modinfo() {
2018 return $this->modinfo;
2022 * Returns the section this module belongs to
2024 * @return section_info
2026 public function get_section_info() {
2027 return $this->modinfo->get_section_info_by_id($this->sectionid);
2031 * Getter method for property $section that returns section id.
2033 * This method is called by the property ->section.
2035 * @return int
2037 private function get_section_id(): int {
2038 return $this->sectionid;
2042 * Returns course object that was used in the first {@link get_fast_modinfo()} call.
2044 * It may not contain all fields from DB table {course} but always has at least the following:
2045 * id,shortname,fullname,format,enablecompletion,groupmode,groupmodeforce,cacherev
2047 * If the course object lacks the field you need you can use the global
2048 * function {@link get_course()} that will save extra query if you access
2049 * current course or frontpage course.
2051 * @return stdClass
2053 public function get_course() {
2054 return $this->modinfo->get_course();
2058 * Returns course id for which the modinfo was generated.
2060 * @return int
2062 private function get_course_id() {
2063 return $this->modinfo->get_course_id();
2067 * Returns group mode used for the course containing the module
2069 * @return int one of constants NOGROUPS, SEPARATEGROUPS, VISIBLEGROUPS
2071 private function get_course_groupmode() {
2072 return $this->modinfo->get_course()->groupmode;
2076 * Returns whether group mode is forced for the course containing the module
2078 * @return bool
2080 private function get_course_groupmodeforce() {
2081 return $this->modinfo->get_course()->groupmodeforce;
2085 * Returns effective groupmode of the module that may be overwritten by forced course groupmode.
2087 * @return int one of constants NOGROUPS, SEPARATEGROUPS, VISIBLEGROUPS
2089 private function get_effective_groupmode() {
2090 $groupmode = $this->groupmode;
2091 if ($this->modinfo->get_course()->groupmodeforce) {
2092 $groupmode = $this->modinfo->get_course()->groupmode;
2093 if ($groupmode != NOGROUPS && !plugin_supports('mod', $this->modname, FEATURE_GROUPS, false)) {
2094 $groupmode = NOGROUPS;
2097 return $groupmode;
2101 * @return context_module Current module context
2103 private function get_context() {
2104 return context_module::instance($this->id);
2108 * Returns itself in the form of stdClass.
2110 * The object includes all fields that table course_modules has and additionally
2111 * fields 'name', 'modname', 'sectionnum' (if requested).
2113 * This can be used as a faster alternative to {@link get_coursemodule_from_id()}
2115 * @param bool $additionalfields include additional fields 'name', 'modname', 'sectionnum'
2116 * @return stdClass
2118 public function get_course_module_record($additionalfields = false) {
2119 $cmrecord = new stdClass();
2121 // Standard fields from table course_modules.
2122 static $cmfields = array('id', 'course', 'module', 'instance', 'section', 'idnumber', 'added',
2123 'score', 'indent', 'visible', 'visibleoncoursepage', 'visibleold', 'groupmode', 'groupingid',
2124 'completion', 'completiongradeitemnumber', 'completionview', 'completionexpected', 'completionpassgrade',
2125 'showdescription', 'availability', 'deletioninprogress', 'downloadcontent', 'lang');
2127 foreach ($cmfields as $key) {
2128 $cmrecord->$key = $this->$key;
2131 // Additional fields that function get_coursemodule_from_id() adds.
2132 if ($additionalfields) {
2133 $cmrecord->name = $this->name;
2134 $cmrecord->modname = $this->modname;
2135 $cmrecord->sectionnum = $this->sectionnum;
2138 return $cmrecord;
2141 // Set functions
2142 ////////////////
2145 * Sets content to display on course view page below link (if present).
2146 * @param string $content New content as HTML string (empty string if none)
2147 * @param bool $isformatted Whether user content is already passed through format_text/format_string and should not
2148 * be formatted again. This can be useful when module adds interactive elements on top of formatted user text.
2149 * @return void
2151 public function set_content($content, $isformatted = false) {
2152 $this->content = $content;
2153 $this->contentisformatted = $isformatted;
2157 * Sets extra classes to include in CSS.
2158 * @param string $extraclasses Extra classes (empty string if none)
2159 * @return void
2161 public function set_extra_classes($extraclasses) {
2162 $this->extraclasses = $extraclasses;
2166 * Sets the external full url that points to the icon being used
2167 * by the activity. Useful for external-tool modules (lti...)
2168 * If set, takes precedence over $icon and $iconcomponent
2170 * @param moodle_url $iconurl full external url pointing to icon image for activity
2171 * @return void
2173 public function set_icon_url(moodle_url $iconurl) {
2174 $this->iconurl = $iconurl;
2178 * Sets value of on-click attribute for JavaScript.
2179 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
2180 * @param string $onclick New onclick attribute which should be HTML-escaped
2181 * (empty string if none)
2182 * @return void
2184 public function set_on_click($onclick) {
2185 $this->check_not_view_only();
2186 $this->onclick = $onclick;
2190 * Overrides the value of an element in the customdata array.
2192 * @param string $name The key in the customdata array
2193 * @param mixed $value The value
2195 public function override_customdata($name, $value) {
2196 if (!is_array($this->customdata)) {
2197 $this->customdata = [];
2199 $this->customdata[$name] = $value;
2203 * Sets HTML that displays after link on course view page.
2204 * @param string $afterlink HTML string (empty string if none)
2205 * @return void
2207 public function set_after_link($afterlink) {
2208 $this->afterlink = $afterlink;
2212 * Sets HTML that displays after edit icons on course view page.
2213 * @param string $afterediticons HTML string (empty string if none)
2214 * @return void
2216 public function set_after_edit_icons($afterediticons) {
2217 $this->afterediticons = $afterediticons;
2221 * Changes the name (text of link) for this module instance.
2222 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
2223 * @param string $name Name of activity / link text
2224 * @return void
2226 public function set_name($name) {
2227 if ($this->state < self::STATE_BUILDING_DYNAMIC) {
2228 $this->update_user_visible();
2230 $this->name = $name;
2234 * Turns off the view link for this module instance.
2235 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
2236 * @return void
2238 public function set_no_view_link() {
2239 $this->check_not_view_only();
2240 $this->url = null;
2244 * Sets the 'uservisible' flag. This can be used (by setting false) to prevent access and
2245 * display of this module link for the current user.
2246 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
2247 * @param bool $uservisible
2248 * @return void
2250 public function set_user_visible($uservisible) {
2251 $this->check_not_view_only();
2252 $this->uservisible = $uservisible;
2256 * Sets the 'customcmlistitem' flag
2258 * This can be used (by setting true) to prevent the course from rendering the
2259 * activity item as a regular activity card. This is applied to activities like labels.
2261 * @param bool $customcmlistitem if the cmlist item of that activity has a special dysplay other than a card.
2263 public function set_custom_cmlist_item(bool $customcmlistitem) {
2264 $this->customcmlistitem = $customcmlistitem;
2268 * Sets the 'available' flag and related details. This flag is normally used to make
2269 * course modules unavailable until a certain date or condition is met. (When a course
2270 * module is unavailable, it is still visible to users who have viewhiddenactivities
2271 * permission.)
2273 * When this is function is called, user-visible status is recalculated automatically.
2275 * The $showavailability flag does not really do anything any more, but is retained
2276 * for backward compatibility. Setting this to false will cause $availableinfo to
2277 * be ignored.
2279 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
2280 * @param bool $available False if this item is not 'available'
2281 * @param int $showavailability 0 = do not show this item at all if it's not available,
2282 * 1 = show this item greyed out with the following message
2283 * @param string $availableinfo Information about why this is not available, or
2284 * empty string if not displaying
2285 * @return void
2287 public function set_available($available, $showavailability=0, $availableinfo='') {
2288 $this->check_not_view_only();
2289 $this->available = $available;
2290 if (!$showavailability) {
2291 $availableinfo = '';
2293 $this->availableinfo = $availableinfo;
2294 $this->update_user_visible();
2298 * Some set functions can only be called from _cm_info_dynamic and not _cm_info_view.
2299 * This is because they may affect parts of this object which are used on pages other
2300 * than the view page (e.g. in the navigation block, or when checking access on
2301 * module pages).
2302 * @return void
2304 private function check_not_view_only() {
2305 if ($this->state >= self::STATE_DYNAMIC) {
2306 throw new coding_exception('Cannot set this data from _cm_info_view because it may ' .
2307 'affect other pages as well as view');
2312 * Constructor should not be called directly; use {@link get_fast_modinfo()}
2314 * @param course_modinfo $modinfo Parent object
2315 * @param stdClass $notused1 Argument not used
2316 * @param stdClass $mod Module object from the modinfo field of course table
2317 * @param stdClass $notused2 Argument not used
2319 public function __construct(course_modinfo $modinfo, $notused1, $mod, $notused2) {
2320 $this->modinfo = $modinfo;
2322 $this->id = $mod->cm;
2323 $this->instance = $mod->id;
2324 $this->modname = $mod->mod;
2325 $this->idnumber = isset($mod->idnumber) ? $mod->idnumber : '';
2326 $this->name = $mod->name;
2327 $this->visible = $mod->visible;
2328 $this->visibleoncoursepage = $mod->visibleoncoursepage;
2329 $this->sectionnum = $mod->section; // Note weirdness with name here. Keeping for backwards compatibility.
2330 $this->groupmode = isset($mod->groupmode) ? $mod->groupmode : 0;
2331 $this->groupingid = isset($mod->groupingid) ? $mod->groupingid : 0;
2332 $this->indent = isset($mod->indent) ? $mod->indent : 0;
2333 $this->extra = isset($mod->extra) ? $mod->extra : '';
2334 $this->extraclasses = isset($mod->extraclasses) ? $mod->extraclasses : '';
2335 // iconurl may be stored as either string or instance of moodle_url.
2336 $this->iconurl = isset($mod->iconurl) ? new moodle_url($mod->iconurl) : '';
2337 $this->onclick = isset($mod->onclick) ? $mod->onclick : '';
2338 $this->content = isset($mod->content) ? $mod->content : '';
2339 $this->icon = isset($mod->icon) ? $mod->icon : '';
2340 $this->iconcomponent = isset($mod->iconcomponent) ? $mod->iconcomponent : '';
2341 $this->customdata = isset($mod->customdata) ? $mod->customdata : '';
2342 $this->showdescription = isset($mod->showdescription) ? $mod->showdescription : 0;
2343 $this->state = self::STATE_BASIC;
2345 $this->sectionid = isset($mod->sectionid) ? $mod->sectionid : 0;
2346 $this->module = isset($mod->module) ? $mod->module : 0;
2347 $this->added = isset($mod->added) ? $mod->added : 0;
2348 $this->score = isset($mod->score) ? $mod->score : 0;
2349 $this->visibleold = isset($mod->visibleold) ? $mod->visibleold : 0;
2350 $this->deletioninprogress = isset($mod->deletioninprogress) ? $mod->deletioninprogress : 0;
2351 $this->downloadcontent = $mod->downloadcontent ?? null;
2352 $this->lang = $mod->lang ?? null;
2354 // Note: it saves effort and database space to always include the
2355 // availability and completion fields, even if availability or completion
2356 // are actually disabled
2357 $this->completion = isset($mod->completion) ? $mod->completion : 0;
2358 $this->completionpassgrade = isset($mod->completionpassgrade) ? $mod->completionpassgrade : 0;
2359 $this->completiongradeitemnumber = isset($mod->completiongradeitemnumber)
2360 ? $mod->completiongradeitemnumber : null;
2361 $this->completionview = isset($mod->completionview)
2362 ? $mod->completionview : 0;
2363 $this->completionexpected = isset($mod->completionexpected)
2364 ? $mod->completionexpected : 0;
2365 $this->availability = isset($mod->availability) ? $mod->availability : null;
2366 $this->conditionscompletion = isset($mod->conditionscompletion)
2367 ? $mod->conditionscompletion : array();
2368 $this->conditionsgrade = isset($mod->conditionsgrade)
2369 ? $mod->conditionsgrade : array();
2370 $this->conditionsfield = isset($mod->conditionsfield)
2371 ? $mod->conditionsfield : array();
2373 static $modviews = array();
2374 if (!isset($modviews[$this->modname])) {
2375 $modviews[$this->modname] = !plugin_supports('mod', $this->modname,
2376 FEATURE_NO_VIEW_LINK);
2378 $this->url = $modviews[$this->modname]
2379 ? new moodle_url('/mod/' . $this->modname . '/view.php', array('id'=>$this->id))
2380 : null;
2384 * Creates a cm_info object from a database record (also accepts cm_info
2385 * in which case it is just returned unchanged).
2387 * @param stdClass|cm_info|null|bool $cm Stdclass or cm_info (or null or false)
2388 * @param int $userid Optional userid (default to current)
2389 * @return cm_info|null Object as cm_info, or null if input was null/false
2391 public static function create($cm, $userid = 0) {
2392 // Null, false, etc. gets passed through as null.
2393 if (!$cm) {
2394 return null;
2396 // If it is already a cm_info object, just return it.
2397 if ($cm instanceof cm_info) {
2398 return $cm;
2400 // Otherwise load modinfo.
2401 if (empty($cm->id) || empty($cm->course)) {
2402 throw new coding_exception('$cm must contain ->id and ->course');
2404 $modinfo = get_fast_modinfo($cm->course, $userid);
2405 return $modinfo->get_cm($cm->id);
2409 * If dynamic data for this course-module is not yet available, gets it.
2411 * This function is automatically called when requesting any course_modinfo property
2412 * that can be modified by modules (have a set_xxx method).
2414 * Dynamic data is data which does not come directly from the cache but is calculated at
2415 * runtime based on the current user. Primarily this concerns whether the user can access
2416 * the module or not.
2418 * As part of this function, the module's _cm_info_dynamic function from its lib.php will
2419 * be called (if it exists). Make sure that the functions that are called here do not use
2420 * any getter magic method from cm_info.
2421 * @return void
2423 private function obtain_dynamic_data() {
2424 global $CFG;
2425 $userid = $this->modinfo->get_user_id();
2426 if ($this->state >= self::STATE_BUILDING_DYNAMIC || $userid == -1) {
2427 return;
2429 $this->state = self::STATE_BUILDING_DYNAMIC;
2431 if (!empty($CFG->enableavailability)) {
2432 // Get availability information.
2433 $ci = new \core_availability\info_module($this);
2435 // Note that the modinfo currently available only includes minimal details (basic data)
2436 // but we know that this function does not need anything more than basic data.
2437 $this->available = $ci->is_available($this->availableinfo, true,
2438 $userid, $this->modinfo);
2439 } else {
2440 $this->available = true;
2443 // Check parent section.
2444 if ($this->available) {
2445 $parentsection = $this->modinfo->get_section_info($this->sectionnum);
2446 if (!$parentsection->get_available()) {
2447 // Do not store info from section here, as that is already
2448 // presented from the section (if appropriate) - just change
2449 // the flag
2450 $this->available = false;
2454 // Update visible state for current user.
2455 $this->update_user_visible();
2457 // Let module make dynamic changes at this point
2458 $this->call_mod_function('cm_info_dynamic');
2459 $this->state = self::STATE_DYNAMIC;
2463 * Getter method for property $uservisible, ensures that dynamic data is retrieved.
2465 * This method is normally called by the property ->uservisible, but can be called directly if
2466 * there is a case when it might be called recursively (you can't call property values
2467 * recursively).
2469 * @return bool
2471 public function get_user_visible() {
2472 $this->obtain_dynamic_data();
2473 return $this->uservisible;
2477 * Returns whether this module is visible to the current user on course page
2479 * Activity may be visible on the course page but not available, for example
2480 * when it is hidden conditionally but the condition information is displayed.
2482 * @return bool
2484 public function is_visible_on_course_page() {
2485 $this->obtain_dynamic_data();
2486 return $this->uservisibleoncoursepage;
2490 * Whether this module is available but hidden from course page
2492 * "Stealth" modules are the ones that are not shown on course page but available by following url.
2493 * They are normally also displayed in grade reports and other reports.
2494 * Module will be stealth either if visibleoncoursepage=0 or it is a visible module inside the hidden
2495 * section.
2497 * @return bool
2499 public function is_stealth() {
2500 return !$this->visibleoncoursepage ||
2501 ($this->visible && ($section = $this->get_section_info()) && !$section->visible);
2505 * Getter method for property $available, ensures that dynamic data is retrieved
2506 * @return bool
2508 private function get_available() {
2509 $this->obtain_dynamic_data();
2510 return $this->available;
2514 * This method can not be used anymore.
2516 * @see \core_availability\info_module::filter_user_list()
2517 * @deprecated Since Moodle 2.8
2519 private function get_deprecated_group_members_only() {
2520 throw new coding_exception('$cm->groupmembersonly can not be used anymore. ' .
2521 'If used to restrict a list of enrolled users to only those who can ' .
2522 'access the module, consider \core_availability\info_module::filter_user_list.');
2526 * Getter method for property $availableinfo, ensures that dynamic data is retrieved
2528 * @return string Available info (HTML)
2530 private function get_available_info() {
2531 $this->obtain_dynamic_data();
2532 return $this->availableinfo;
2536 * Works out whether activity is available to the current user
2538 * If the activity is unavailable, additional checks are required to determine if its hidden or greyed out
2540 * @return void
2542 private function update_user_visible() {
2543 $userid = $this->modinfo->get_user_id();
2544 if ($userid == -1) {
2545 return null;
2547 $this->uservisible = true;
2549 // If the module is being deleted, set the uservisible state to false and return.
2550 if ($this->deletioninprogress) {
2551 $this->uservisible = false;
2552 return null;
2555 // If the user cannot access the activity set the uservisible flag to false.
2556 // Additional checks are required to determine whether the activity is entirely hidden or just greyed out.
2557 if ((!$this->visible && !has_capability('moodle/course:viewhiddenactivities', $this->get_context(), $userid)) ||
2558 (!$this->get_available() &&
2559 !has_capability('moodle/course:ignoreavailabilityrestrictions', $this->get_context(), $userid))) {
2561 $this->uservisible = false;
2564 // Check group membership.
2565 if ($this->is_user_access_restricted_by_capability()) {
2567 $this->uservisible = false;
2568 // Ensure activity is completely hidden from the user.
2569 $this->availableinfo = '';
2572 $this->uservisibleoncoursepage = $this->uservisible &&
2573 ($this->visibleoncoursepage ||
2574 has_capability('moodle/course:manageactivities', $this->get_context(), $userid) ||
2575 has_capability('moodle/course:activityvisibility', $this->get_context(), $userid));
2576 // Activity that is not available, not hidden from course page and has availability
2577 // info is actually visible on the course page (with availability info and without a link).
2578 if (!$this->uservisible && $this->visibleoncoursepage && $this->availableinfo) {
2579 $this->uservisibleoncoursepage = true;
2584 * This method has been deprecated and should not be used.
2586 * @see $uservisible
2587 * @deprecated Since Moodle 2.8
2589 public function is_user_access_restricted_by_group() {
2590 throw new coding_exception('cm_info::is_user_access_restricted_by_group() can not be used any more.' .
2591 ' Use $cm->uservisible to decide whether the current user can access an activity.');
2595 * Checks whether mod/...:view capability restricts the current user's access.
2597 * @return bool True if the user access is restricted.
2599 public function is_user_access_restricted_by_capability() {
2600 $userid = $this->modinfo->get_user_id();
2601 if ($userid == -1) {
2602 return null;
2604 $capability = 'mod/' . $this->modname . ':view';
2605 $capabilityinfo = get_capability_info($capability);
2606 if (!$capabilityinfo) {
2607 // Capability does not exist, no one is prevented from seeing the activity.
2608 return false;
2611 // You are blocked if you don't have the capability.
2612 return !has_capability($capability, $this->get_context(), $userid);
2616 * Checks whether the module's conditional access settings mean that the
2617 * user cannot see the activity at all
2619 * @deprecated since 2.7 MDL-44070
2621 public function is_user_access_restricted_by_conditional_access() {
2622 throw new coding_exception('cm_info::is_user_access_restricted_by_conditional_access() ' .
2623 'can not be used any more; this function is not needed (use $cm->uservisible ' .
2624 'and $cm->availableinfo to decide whether it should be available ' .
2625 'or appear)');
2629 * Calls a module function (if exists), passing in one parameter: this object.
2630 * @param string $type Name of function e.g. if this is 'grooblezorb' and the modname is
2631 * 'forum' then it will try to call 'mod_forum_grooblezorb' or 'forum_grooblezorb'
2632 * @return void
2634 private function call_mod_function($type) {
2635 global $CFG;
2636 $libfile = $CFG->dirroot . '/mod/' . $this->modname . '/lib.php';
2637 if (file_exists($libfile)) {
2638 include_once($libfile);
2639 $function = 'mod_' . $this->modname . '_' . $type;
2640 if (function_exists($function)) {
2641 $function($this);
2642 } else {
2643 $function = $this->modname . '_' . $type;
2644 if (function_exists($function)) {
2645 $function($this);
2652 * If view data for this course-module is not yet available, obtains it.
2654 * This function is automatically called if any of the functions (marked) which require
2655 * view data are called.
2657 * View data is data which is needed only for displaying the course main page (& any similar
2658 * functionality on other pages) but is not needed in general. Obtaining view data may have
2659 * a performance cost.
2661 * As part of this function, the module's _cm_info_view function from its lib.php will
2662 * be called (if it exists).
2663 * @return void
2665 private function obtain_view_data() {
2666 if ($this->state >= self::STATE_BUILDING_VIEW || $this->modinfo->get_user_id() == -1) {
2667 return;
2669 $this->obtain_dynamic_data();
2670 $this->state = self::STATE_BUILDING_VIEW;
2672 // Let module make changes at this point
2673 $this->call_mod_function('cm_info_view');
2674 $this->state = self::STATE_VIEW;
2680 * Returns reference to full info about modules in course (including visibility).
2681 * Cached and as fast as possible (0 or 1 db query).
2683 * use get_fast_modinfo($courseid, 0, true) to reset the static cache for particular course
2684 * use get_fast_modinfo(0, 0, true) to reset the static cache for all courses
2686 * use rebuild_course_cache($courseid, true) to reset the application AND static cache
2687 * for particular course when it's contents has changed
2689 * @param int|stdClass $courseorid object from DB table 'course' (must have field 'id'
2690 * and recommended to have field 'cacherev') or just a course id. Just course id
2691 * is enough when calling get_fast_modinfo() for current course or site or when
2692 * calling for any other course for the second time.
2693 * @param int $userid User id to populate 'availble' and 'uservisible' attributes of modules and sections.
2694 * Set to 0 for current user (default). Set to -1 to avoid calculation of dynamic user-depended data.
2695 * @param bool $resetonly whether we want to get modinfo or just reset the cache
2696 * @return course_modinfo|null Module information for course, or null if resetting
2697 * @throws moodle_exception when course is not found (nothing is thrown if resetting)
2699 function get_fast_modinfo($courseorid, $userid = 0, $resetonly = false) {
2700 // compartibility with syntax prior to 2.4:
2701 if ($courseorid === 'reset') {
2702 debugging("Using the string 'reset' as the first argument of get_fast_modinfo() is deprecated. Use get_fast_modinfo(0,0,true) instead.", DEBUG_DEVELOPER);
2703 $courseorid = 0;
2704 $resetonly = true;
2707 // Function get_fast_modinfo() can never be called during upgrade unless it is used for clearing cache only.
2708 if (!$resetonly) {
2709 upgrade_ensure_not_running();
2712 // Function is called with $reset = true
2713 if ($resetonly) {
2714 course_modinfo::clear_instance_cache($courseorid);
2715 return null;
2718 // Function is called with $reset = false, retrieve modinfo
2719 return course_modinfo::instance($courseorid, $userid);
2723 * Efficiently retrieves the $course (stdclass) and $cm (cm_info) objects, given
2724 * a cmid. If module name is also provided, it will ensure the cm is of that type.
2726 * Usage:
2727 * list($course, $cm) = get_course_and_cm_from_cmid($cmid, 'forum');
2729 * Using this method has a performance advantage because it works by loading
2730 * modinfo for the course - which will then be cached and it is needed later
2731 * in most requests. It also guarantees that the $cm object is a cm_info and
2732 * not a stdclass.
2734 * The $course object can be supplied if already known and will speed
2735 * up this function - although it is more efficient to use this function to
2736 * get the course if you are starting from a cmid.
2738 * To avoid security problems and obscure bugs, you should always specify
2739 * $modulename if the cmid value came from user input.
2741 * By default this obtains information (for example, whether user can access
2742 * the activity) for current user, but you can specify a userid if required.
2744 * @param stdClass|int $cmorid Id of course-module, or database object
2745 * @param string $modulename Optional modulename (improves security)
2746 * @param stdClass|int $courseorid Optional course object if already loaded
2747 * @param int $userid Optional userid (default = current)
2748 * @return array Array with 2 elements $course and $cm
2749 * @throws moodle_exception If the item doesn't exist or is of wrong module name
2751 function get_course_and_cm_from_cmid($cmorid, $modulename = '', $courseorid = 0, $userid = 0) {
2752 global $DB;
2753 if (is_object($cmorid)) {
2754 $cmid = $cmorid->id;
2755 if (isset($cmorid->course)) {
2756 $courseid = (int)$cmorid->course;
2757 } else {
2758 $courseid = 0;
2760 } else {
2761 $cmid = (int)$cmorid;
2762 $courseid = 0;
2765 // Validate module name if supplied.
2766 if ($modulename && !core_component::is_valid_plugin_name('mod', $modulename)) {
2767 throw new coding_exception('Invalid modulename parameter');
2770 // Get course from last parameter if supplied.
2771 $course = null;
2772 if (is_object($courseorid)) {
2773 $course = $courseorid;
2774 } else if ($courseorid) {
2775 $courseid = (int)$courseorid;
2778 if (!$course) {
2779 if ($courseid) {
2780 // If course ID is known, get it using normal function.
2781 $course = get_course($courseid);
2782 } else {
2783 // Get course record in a single query based on cmid.
2784 $course = $DB->get_record_sql("
2785 SELECT c.*
2786 FROM {course_modules} cm
2787 JOIN {course} c ON c.id = cm.course
2788 WHERE cm.id = ?", array($cmid), MUST_EXIST);
2792 // Get cm from get_fast_modinfo.
2793 $modinfo = get_fast_modinfo($course, $userid);
2794 $cm = $modinfo->get_cm($cmid);
2795 if ($modulename && $cm->modname !== $modulename) {
2796 throw new moodle_exception('invalidcoursemoduleid', 'error', '', $cmid);
2798 return array($course, $cm);
2802 * Efficiently retrieves the $course (stdclass) and $cm (cm_info) objects, given
2803 * an instance id or record and module name.
2805 * Usage:
2806 * list($course, $cm) = get_course_and_cm_from_instance($forum, 'forum');
2808 * Using this method has a performance advantage because it works by loading
2809 * modinfo for the course - which will then be cached and it is needed later
2810 * in most requests. It also guarantees that the $cm object is a cm_info and
2811 * not a stdclass.
2813 * The $course object can be supplied if already known and will speed
2814 * up this function - although it is more efficient to use this function to
2815 * get the course if you are starting from an instance id.
2817 * By default this obtains information (for example, whether user can access
2818 * the activity) for current user, but you can specify a userid if required.
2820 * @param stdclass|int $instanceorid Id of module instance, or database object
2821 * @param string $modulename Modulename (required)
2822 * @param stdClass|int $courseorid Optional course object if already loaded
2823 * @param int $userid Optional userid (default = current)
2824 * @return array Array with 2 elements $course and $cm
2825 * @throws moodle_exception If the item doesn't exist or is of wrong module name
2827 function get_course_and_cm_from_instance($instanceorid, $modulename, $courseorid = 0, $userid = 0) {
2828 global $DB;
2830 // Get data from parameter.
2831 if (is_object($instanceorid)) {
2832 $instanceid = $instanceorid->id;
2833 if (isset($instanceorid->course)) {
2834 $courseid = (int)$instanceorid->course;
2835 } else {
2836 $courseid = 0;
2838 } else {
2839 $instanceid = (int)$instanceorid;
2840 $courseid = 0;
2843 // Get course from last parameter if supplied.
2844 $course = null;
2845 if (is_object($courseorid)) {
2846 $course = $courseorid;
2847 } else if ($courseorid) {
2848 $courseid = (int)$courseorid;
2851 // Validate module name if supplied.
2852 if (!core_component::is_valid_plugin_name('mod', $modulename)) {
2853 throw new coding_exception('Invalid modulename parameter');
2856 if (!$course) {
2857 if ($courseid) {
2858 // If course ID is known, get it using normal function.
2859 $course = get_course($courseid);
2860 } else {
2861 // Get course record in a single query based on instance id.
2862 $pagetable = '{' . $modulename . '}';
2863 $course = $DB->get_record_sql("
2864 SELECT c.*
2865 FROM $pagetable instance
2866 JOIN {course} c ON c.id = instance.course
2867 WHERE instance.id = ?", array($instanceid), MUST_EXIST);
2871 // Get cm from get_fast_modinfo.
2872 $modinfo = get_fast_modinfo($course, $userid);
2873 $instances = $modinfo->get_instances_of($modulename);
2874 if (!array_key_exists($instanceid, $instances)) {
2875 throw new moodle_exception('invalidmoduleid', 'error', '', $instanceid);
2877 return array($course, $instances[$instanceid]);
2882 * Rebuilds or resets the cached list of course activities stored in MUC.
2884 * rebuild_course_cache() must NEVER be called from lib/db/upgrade.php.
2885 * At the same time course cache may ONLY be cleared using this function in
2886 * upgrade scripts of plugins.
2888 * During the bulk operations if it is necessary to reset cache of multiple
2889 * courses it is enough to call {@link increment_revision_number()} for the
2890 * table 'course' and field 'cacherev' specifying affected courses in select.
2892 * Cached course information is stored in MUC core/coursemodinfo and is
2893 * validated with the DB field {course}.cacherev
2895 * @global moodle_database $DB
2896 * @param int $courseid id of course to rebuild, empty means all
2897 * @param boolean $clearonly only clear the cache, gets rebuild automatically on the fly.
2898 * Recommended to set to true to avoid unnecessary multiple rebuilding.
2899 * @param boolean $partialrebuild will not delete the whole cache when it's true.
2900 * use purge_module_cache() or purge_section_cache() must be
2901 * called before when partialrebuild is true.
2902 * use purge_module_cache() to invalidate mod cache.
2903 * use purge_section_cache() to invalidate section cache.
2905 * @return void
2906 * @throws coding_exception
2908 function rebuild_course_cache(int $courseid = 0, bool $clearonly = false, bool $partialrebuild = false): void {
2909 global $COURSE, $SITE, $DB;
2911 if ($courseid == 0 and $partialrebuild) {
2912 throw new coding_exception('partialrebuild only works when a valid course id is provided.');
2915 // Function rebuild_course_cache() can not be called during upgrade unless it's clear only.
2916 if (!$clearonly && !upgrade_ensure_not_running(true)) {
2917 $clearonly = true;
2920 // Destroy navigation caches
2921 navigation_cache::destroy_volatile_caches();
2923 core_courseformat\base::reset_course_cache($courseid);
2925 $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
2926 if (empty($courseid)) {
2927 // Clearing caches for all courses.
2928 increment_revision_number('course', 'cacherev', '');
2929 if (!$partialrebuild) {
2930 $cachecoursemodinfo->purge();
2932 // Clear memory static cache.
2933 course_modinfo::clear_instance_cache();
2934 // Update global values too.
2935 $sitecacherev = $DB->get_field('course', 'cacherev', array('id' => SITEID));
2936 $SITE->cachrev = $sitecacherev;
2937 if ($COURSE->id == SITEID) {
2938 $COURSE->cacherev = $sitecacherev;
2939 } else {
2940 $COURSE->cacherev = $DB->get_field('course', 'cacherev', array('id' => $COURSE->id));
2942 } else {
2943 // Clearing cache for one course, make sure it is deleted from user request cache as well.
2944 // Because this is a versioned cache, there is no need to actually delete the cache item,
2945 // only increase the required version number.
2946 increment_revision_number('course', 'cacherev', 'id = :id', array('id' => $courseid));
2947 $cacherev = $DB->get_field('course', 'cacherev', ['id' => $courseid]);
2948 // Clear memory static cache.
2949 course_modinfo::clear_instance_cache($courseid, $cacherev);
2950 // Update global values too.
2951 if ($courseid == $COURSE->id || $courseid == $SITE->id) {
2952 if ($courseid == $COURSE->id) {
2953 $COURSE->cacherev = $cacherev;
2955 if ($courseid == $SITE->id) {
2956 $SITE->cacherev = $cacherev;
2961 if ($clearonly) {
2962 return;
2965 if ($courseid) {
2966 $select = array('id'=>$courseid);
2967 } else {
2968 $select = array();
2969 core_php_time_limit::raise(); // this could take a while! MDL-10954
2972 $fields = 'id,' . join(',', course_modinfo::$cachedfields);
2973 $sort = '';
2974 $rs = $DB->get_recordset("course", $select, $sort, $fields);
2976 // Rebuild cache for each course.
2977 foreach ($rs as $course) {
2978 course_modinfo::build_course_cache($course, $partialrebuild);
2980 $rs->close();
2985 * Class that is the return value for the _get_coursemodule_info module API function.
2987 * Note: For backward compatibility, you can also return a stdclass object from that function.
2988 * The difference is that the stdclass object may contain an 'extra' field (deprecated,
2989 * use extraclasses and onclick instead). The stdclass object may not contain
2990 * the new fields defined here (content, extraclasses, customdata).
2992 class cached_cm_info {
2994 * Name (text of link) for this activity; Leave unset to accept default name
2995 * @var string
2997 public $name;
3000 * Name of icon for this activity. Normally, this should be used together with $iconcomponent
3001 * to define the icon, as per image_url function.
3002 * For backward compatibility, if this value is of the form 'mod/forum/icon' then an icon
3003 * within that module will be used.
3004 * @see cm_info::get_icon_url()
3005 * @see renderer_base::image_url()
3006 * @var string
3008 public $icon;
3011 * Component for icon for this activity, as per image_url; leave blank to use default 'moodle'
3012 * component
3013 * @see renderer_base::image_url()
3014 * @var string
3016 public $iconcomponent;
3019 * HTML content to be displayed on the main page below the link (if any) for this course-module
3020 * @var string
3022 public $content;
3025 * Custom data to be stored in modinfo for this activity; useful if there are cases when
3026 * internal information for this activity type needs to be accessible from elsewhere on the
3027 * course without making database queries. May be of any type but should be short.
3028 * @var mixed
3030 public $customdata;
3033 * Extra CSS class or classes to be added when this activity is displayed on the main page;
3034 * space-separated string
3035 * @var string
3037 public $extraclasses;
3040 * External URL image to be used by activity as icon, useful for some external-tool modules
3041 * like lti. If set, takes precedence over $icon and $iconcomponent
3042 * @var $moodle_url
3044 public $iconurl;
3047 * Content of onclick JavaScript; escaped HTML to be inserted as attribute value
3048 * @var string
3050 public $onclick;
3055 * Data about a single section on a course. This contains the fields from the
3056 * course_sections table, plus additional data when required.
3058 * @property-read int $id Section ID - from course_sections table
3059 * @property-read int $course Course ID - from course_sections table
3060 * @property-read int $sectionnum Section number - from course_sections table
3061 * @property-read string $name Section name if specified - from course_sections table
3062 * @property-read int $visible Section visibility (1 = visible) - from course_sections table
3063 * @property-read string $summary Section summary text if specified - from course_sections table
3064 * @property-read int $summaryformat Section summary text format (FORMAT_xx constant) - from course_sections table
3065 * @property-read string $availability Availability information as JSON string - from course_sections table
3066 * @property-read string|null $component Optional section delegate component - from course_sections table
3067 * @property-read int|null $itemid Optional section delegate item id - from course_sections table
3068 * @property-read array $conditionscompletion Availability conditions for this section based on the completion of
3069 * course-modules (array from course-module id to required completion state
3070 * for that module) - from cached data in sectioncache field
3071 * @property-read array $conditionsgrade Availability conditions for this section based on course grades (array from
3072 * grade item id to object with ->min, ->max fields) - from cached data in
3073 * sectioncache field
3074 * @property-read array $conditionsfield Availability conditions for this section based on user fields
3075 * @property-read bool $available True if this section is available to the given user i.e. if all availability conditions
3076 * are met - obtained dynamically
3077 * @property-read string $availableinfo If section is not available to some users, this string gives information about
3078 * availability which can be displayed to students and/or staff (e.g. 'Available from 3 January 2010')
3079 * for display on main page - obtained dynamically
3080 * @property-read bool $uservisible True if this section is available to the given user (for example, if current user
3081 * has viewhiddensections capability, they can access the section even if it is not
3082 * visible or not available, so this would be true in that case) - obtained dynamically
3083 * @property-read string $sequence Comma-separated list of all modules in the section. Note, this field may not exactly
3084 * match course_sections.sequence if later has references to non-existing modules or not modules of not available module types.
3085 * @property-read course_modinfo $modinfo
3087 class section_info implements IteratorAggregate {
3089 * Section ID - from course_sections table
3090 * @var int
3092 private $_id;
3095 * Section number - from course_sections table
3096 * @var int
3098 private $_sectionnum;
3101 * Section name if specified - from course_sections table
3102 * @var string
3104 private $_name;
3107 * Section visibility (1 = visible) - from course_sections table
3108 * @var int
3110 private $_visible;
3113 * Section summary text if specified - from course_sections table
3114 * @var string
3116 private $_summary;
3119 * Section summary text format (FORMAT_xx constant) - from course_sections table
3120 * @var int
3122 private $_summaryformat;
3125 * Availability information as JSON string - from course_sections table
3126 * @var string
3128 private $_availability;
3131 * @var string|null the delegated component if any.
3133 private ?string $_component = null;
3136 * @var int|null the delegated instance item id if any.
3138 private ?int $_itemid = null;
3141 * @var sectiondelegate|null Section delegate instance if any.
3143 private ?sectiondelegate $_delegateinstance = null;
3146 * Availability conditions for this section based on the completion of
3147 * course-modules (array from course-module id to required completion state
3148 * for that module) - from cached data in sectioncache field
3149 * @var array
3151 private $_conditionscompletion;
3154 * Availability conditions for this section based on course grades (array from
3155 * grade item id to object with ->min, ->max fields) - from cached data in
3156 * sectioncache field
3157 * @var array
3159 private $_conditionsgrade;
3162 * Availability conditions for this section based on user fields
3163 * @var array
3165 private $_conditionsfield;
3168 * True if this section is available to students i.e. if all availability conditions
3169 * are met - obtained dynamically on request, see function {@link section_info::get_available()}
3170 * @var bool|null
3172 private $_available;
3175 * If section is not available to some users, this string gives information about
3176 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
3177 * January 2010') for display on main page - obtained dynamically on request, see
3178 * function {@link section_info::get_availableinfo()}
3179 * @var string
3181 private $_availableinfo;
3184 * True if this section is available to the CURRENT user (for example, if current user
3185 * has viewhiddensections capability, they can access the section even if it is not
3186 * visible or not available, so this would be true in that case) - obtained dynamically
3187 * on request, see function {@link section_info::get_uservisible()}
3188 * @var bool|null
3190 private $_uservisible;
3193 * Default values for sectioncache fields; if a field has this value, it won't
3194 * be stored in the sectioncache cache, to save space. Checks are done by ===
3195 * which means values must all be strings.
3196 * @var array
3198 private static $sectioncachedefaults = array(
3199 'name' => null,
3200 'summary' => '',
3201 'summaryformat' => '1', // FORMAT_HTML, but must be a string
3202 'visible' => '1',
3203 'availability' => null,
3204 'component' => null,
3205 'itemid' => null,
3209 * Stores format options that have been cached when building 'coursecache'
3210 * When the format option is requested we look first if it has been cached
3211 * @var array
3213 private $cachedformatoptions = array();
3216 * Stores the list of all possible section options defined in each used course format.
3217 * @var array
3219 static private $sectionformatoptions = array();
3222 * Stores the modinfo object passed in constructor, may be used when requesting
3223 * dynamically obtained attributes such as available, availableinfo, uservisible.
3224 * Also used to retrun information about current course or user.
3225 * @var course_modinfo
3227 private $modinfo;
3230 * True if has activities, otherwise false.
3231 * @var bool
3233 public $hasactivites;
3236 * List of class read-only properties' getter methods.
3237 * Used by magic functions __get(), __isset(), __empty()
3238 * @var array
3240 private static $standardproperties = [
3241 'section' => 'get_section_number',
3245 * Constructs object from database information plus extra required data.
3246 * @param object $data Array entry from cached sectioncache
3247 * @param int $number Section number (array key)
3248 * @param int $notused1 argument not used (informaion is available in $modinfo)
3249 * @param int $notused2 argument not used (informaion is available in $modinfo)
3250 * @param course_modinfo $modinfo Owner (needed for checking availability)
3251 * @param int $notused3 argument not used (informaion is available in $modinfo)
3253 public function __construct($data, $number, $notused1, $notused2, $modinfo, $notused3) {
3254 global $CFG;
3255 require_once($CFG->dirroot.'/course/lib.php');
3257 // Data that is always present
3258 $this->_id = $data->id;
3260 $defaults = self::$sectioncachedefaults +
3261 array('conditionscompletion' => array(),
3262 'conditionsgrade' => array(),
3263 'conditionsfield' => array());
3265 // Data that may use default values to save cache size
3266 foreach ($defaults as $field => $value) {
3267 if (isset($data->{$field})) {
3268 $this->{'_'.$field} = $data->{$field};
3269 } else {
3270 $this->{'_'.$field} = $value;
3274 // Other data from constructor arguments.
3275 $this->_sectionnum = $number;
3276 $this->modinfo = $modinfo;
3278 // Cached course format data.
3279 $course = $modinfo->get_course();
3280 if (!isset(self::$sectionformatoptions[$course->format])) {
3281 // Store list of section format options defined in each used course format.
3282 // They do not depend on particular course but only on its format.
3283 self::$sectionformatoptions[$course->format] =
3284 course_get_format($course)->section_format_options();
3286 foreach (self::$sectionformatoptions[$course->format] as $field => $option) {
3287 if (!empty($option['cache'])) {
3288 if (isset($data->{$field})) {
3289 $this->cachedformatoptions[$field] = $data->{$field};
3290 } else if (array_key_exists('cachedefault', $option)) {
3291 $this->cachedformatoptions[$field] = $option['cachedefault'];
3298 * Magic method to check if the property is set
3300 * @param string $name name of the property
3301 * @return bool
3303 public function __isset($name) {
3304 if (isset(self::$standardproperties[$name])) {
3305 $value = $this->__get($name);
3306 return isset($value);
3308 if (method_exists($this, 'get_'.$name) ||
3309 property_exists($this, '_'.$name) ||
3310 array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
3311 $value = $this->__get($name);
3312 return isset($value);
3314 return false;
3318 * Magic method to check if the property is empty
3320 * @param string $name name of the property
3321 * @return bool
3323 public function __empty($name) {
3324 if (isset(self::$standardproperties[$name])) {
3325 $value = $this->__get($name);
3326 return empty($value);
3328 if (method_exists($this, 'get_'.$name) ||
3329 property_exists($this, '_'.$name) ||
3330 array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
3331 $value = $this->__get($name);
3332 return empty($value);
3334 return true;
3338 * Magic method to retrieve the property, this is either basic section property
3339 * or availability information or additional properties added by course format
3341 * @param string $name name of the property
3342 * @return bool
3344 public function __get($name) {
3345 if (isset(self::$standardproperties[$name])) {
3346 if ($method = self::$standardproperties[$name]) {
3347 return $this->$method();
3350 if (method_exists($this, 'get_'.$name)) {
3351 return $this->{'get_'.$name}();
3353 if (property_exists($this, '_'.$name)) {
3354 return $this->{'_'.$name};
3356 if (array_key_exists($name, $this->cachedformatoptions)) {
3357 return $this->cachedformatoptions[$name];
3359 // precheck if the option is defined in format to avoid unnecessary DB queries in get_format_options()
3360 if (array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
3361 $formatoptions = course_get_format($this->modinfo->get_course())->get_format_options($this);
3362 return $formatoptions[$name];
3364 debugging('Invalid section_info property accessed! '.$name);
3365 return null;
3369 * Finds whether this section is available at the moment for the current user.
3371 * The value can be accessed publicly as $sectioninfo->available, but can be called directly if there
3372 * is a case when it might be called recursively (you can't call property values recursively).
3374 * @return bool
3376 public function get_available() {
3377 global $CFG;
3378 $userid = $this->modinfo->get_user_id();
3379 if ($this->_available !== null || $userid == -1) {
3380 // Has already been calculated or does not need calculation.
3381 return $this->_available;
3383 $this->_available = true;
3384 $this->_availableinfo = '';
3385 if (!empty($CFG->enableavailability)) {
3386 // Get availability information.
3387 $ci = new \core_availability\info_section($this);
3388 $this->_available = $ci->is_available($this->_availableinfo, true,
3389 $userid, $this->modinfo);
3391 // Execute the hook from the course format that may override the available/availableinfo properties.
3392 $currentavailable = $this->_available;
3393 course_get_format($this->modinfo->get_course())->
3394 section_get_available_hook($this, $this->_available, $this->_availableinfo);
3395 if (!$currentavailable && $this->_available) {
3396 debugging('section_get_available_hook() can not make unavailable section available', DEBUG_DEVELOPER);
3397 $this->_available = $currentavailable;
3399 return $this->_available;
3403 * Returns the availability text shown next to the section on course page.
3405 * @return string
3407 private function get_availableinfo() {
3408 // Calling get_available() will also fill the availableinfo property
3409 // (or leave it null if there is no userid).
3410 $this->get_available();
3411 return $this->_availableinfo;
3415 * Implementation of IteratorAggregate::getIterator(), allows to cycle through properties
3416 * and use {@link convert_to_array()}
3418 * @return ArrayIterator
3420 public function getIterator(): Traversable {
3421 $ret = array();
3422 foreach (get_object_vars($this) as $key => $value) {
3423 if (substr($key, 0, 1) == '_') {
3424 if (method_exists($this, 'get'.$key)) {
3425 $ret[substr($key, 1)] = $this->{'get'.$key}();
3426 } else {
3427 $ret[substr($key, 1)] = $this->$key;
3431 $ret['sequence'] = $this->get_sequence();
3432 $ret['course'] = $this->get_course();
3433 $ret = array_merge($ret, course_get_format($this->modinfo->get_course())->get_format_options($this));
3434 return new ArrayIterator($ret);
3438 * Works out whether activity is visible *for current user* - if this is false, they
3439 * aren't allowed to access it.
3441 * @return bool
3443 private function get_uservisible() {
3444 $userid = $this->modinfo->get_user_id();
3445 if ($this->_uservisible !== null || $userid == -1) {
3446 // Has already been calculated or does not need calculation.
3447 return $this->_uservisible;
3449 $this->_uservisible = true;
3450 if (!$this->_visible || !$this->get_available()) {
3451 $coursecontext = context_course::instance($this->get_course());
3452 if (!$this->_visible && !has_capability('moodle/course:viewhiddensections', $coursecontext, $userid) ||
3453 (!$this->get_available() &&
3454 !has_capability('moodle/course:ignoreavailabilityrestrictions', $coursecontext, $userid))) {
3456 $this->_uservisible = false;
3459 return $this->_uservisible;
3463 * Restores the course_sections.sequence value
3465 * @return string
3467 private function get_sequence() {
3468 if (!empty($this->modinfo->sections[$this->_sectionnum])) {
3469 return implode(',', $this->modinfo->sections[$this->_sectionnum]);
3470 } else {
3471 return '';
3476 * Returns course ID - from course_sections table
3478 * @return int
3480 private function get_course() {
3481 return $this->modinfo->get_course_id();
3485 * Modinfo object
3487 * @return course_modinfo
3489 private function get_modinfo() {
3490 return $this->modinfo;
3494 * Returns section number.
3496 * This method is called by the property ->section.
3498 * @return int
3500 private function get_section_number(): int {
3501 return $this->sectionnum;
3505 * Get the delegate component instance.
3507 public function get_component_instance(): ?sectiondelegate {
3508 if (empty($this->_component)) {
3509 return null;
3511 if ($this->_delegateinstance !== null) {
3512 return $this->_delegateinstance;
3514 $this->_delegateinstance = sectiondelegate::instance($this);
3515 return $this->_delegateinstance;
3519 * Returns true if this section is a delegate to a component.
3520 * @return bool
3522 public function is_delegated(): bool {
3523 return !empty($this->_component);
3527 * Prepares section data for inclusion in sectioncache cache, removing items
3528 * that are set to defaults, and adding availability data if required.
3530 * Called by build_section_cache in course_modinfo only; do not use otherwise.
3531 * @param object $section Raw section data object
3533 public static function convert_for_section_cache($section) {
3534 global $CFG;
3536 // Course id stored in course table
3537 unset($section->course);
3538 // Sequence stored implicity in modinfo $sections array
3539 unset($section->sequence);
3541 // Remove default data
3542 foreach (self::$sectioncachedefaults as $field => $value) {
3543 // Exact compare as strings to avoid problems if some strings are set
3544 // to "0" etc.
3545 if (isset($section->{$field}) && $section->{$field} === $value) {
3546 unset($section->{$field});