Merge branch 'MDL-81713-main' of https://github.com/junpataleta/moodle
[moodle.git] / lib / modinfolib.php
blob06ed6cc8ddc657637ffa1ec0b2014774b5ea5f1b
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 * Purges the coursemodinfo caches stored in MUC.
856 * @param int[] $courseids Array of course ids to purge the course caches
857 * for (or all courses if empty array).
860 public static function purge_course_caches(array $courseids = []): void {
861 global $DB;
863 // Purging might purge all course caches, so use a recordset and close it.
864 $select = '';
865 $params = null;
866 if (!empty($courseids)) {
867 [$sql, $params] = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
868 $select = 'id ' . $sql;
871 $courses = $DB->get_recordset_select(
872 table: 'course',
873 select: $select,
874 params: $params,
875 fields: 'id',
878 // Purge each course's cache to make sure cache is recalculated next time
879 // the course is viewed.
880 foreach ($courses as $course) {
881 self::purge_course_cache($course->id);
883 $courses->close();
887 * Purge the cache of multiple course modules.
889 * @param int $courseid Course id
890 * @param int[] $cmids List of course module ids
891 * @return void
893 public static function purge_course_modules_cache(int $courseid, array $cmids): void {
894 $course = get_course($courseid);
895 $cache = cache::make('core', 'coursemodinfo');
896 $cachekey = $course->id;
897 $cache->acquire_lock($cachekey);
898 try {
899 $coursemodinfo = $cache->get_versioned($cachekey, $course->cacherev);
900 $hascache = ($coursemodinfo !== false);
901 $updatedcache = false;
902 if ($hascache) {
903 foreach ($cmids as $cmid) {
904 if (array_key_exists($cmid, $coursemodinfo->modinfo)) {
905 unset($coursemodinfo->modinfo[$cmid]);
906 $updatedcache = true;
909 if ($updatedcache) {
910 $coursemodinfo->cacherev = -1;
911 $cache->set_versioned($cachekey, $course->cacherev, $coursemodinfo);
912 $cache->get_versioned($cachekey, $course->cacherev);
915 } finally {
916 $cache->release_lock($cachekey);
921 * For a given course, returns an array of course activity objects
923 * @param stdClass $course Course object
924 * @param bool $usecache get activities from cache if modinfo exists when $usecache is true
925 * @return array list of activities
927 public static function get_array_of_activities(stdClass $course, bool $usecache = false): array {
928 global $CFG, $DB;
930 if (empty($course)) {
931 throw new moodle_exception('courseidnotfound');
934 $rawmods = get_course_mods($course->id);
935 if (empty($rawmods)) {
936 return [];
939 $mods = [];
940 if ($usecache) {
941 // Get existing cache.
942 $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
943 $coursemodinfo = $cachecoursemodinfo->get_versioned($course->id, $course->cacherev);
944 if ($coursemodinfo !== false) {
945 $mods = $coursemodinfo->modinfo;
949 $courseformat = course_get_format($course);
951 if ($sections = $DB->get_records('course_sections', ['course' => $course->id],
952 'section ASC', 'id,section,sequence,visible')) {
953 // First check and correct obvious mismatches between course_sections.sequence and course_modules.section.
954 if ($errormessages = course_integrity_check($course->id, $rawmods, $sections)) {
955 debugging(join('<br>', $errormessages));
956 $rawmods = get_course_mods($course->id);
957 $sections = $DB->get_records('course_sections', ['course' => $course->id],
958 'section ASC', 'id,section,sequence,visible');
960 // Build array of activities.
961 foreach ($sections as $section) {
962 if (!empty($section->sequence)) {
963 $cmids = explode(",", $section->sequence);
964 $numberofmods = count($cmids);
965 foreach ($cmids as $cmid) {
966 // Activity does not exist in the database.
967 $notexistindb = empty($rawmods[$cmid]);
968 $activitycached = isset($mods[$cmid]);
969 if ($activitycached || $notexistindb) {
970 continue;
973 // Adjust visibleoncoursepage, value in DB may not respect format availability.
974 $rawmods[$cmid]->visibleoncoursepage = (!$rawmods[$cmid]->visible
975 || $rawmods[$cmid]->visibleoncoursepage
976 || empty($CFG->allowstealth)
977 || !$courseformat->allow_stealth_module_visibility($rawmods[$cmid], $section)) ? 1 : 0;
979 $mods[$cmid] = new stdClass();
980 $mods[$cmid]->id = $rawmods[$cmid]->instance;
981 $mods[$cmid]->cm = $rawmods[$cmid]->id;
982 $mods[$cmid]->mod = $rawmods[$cmid]->modname;
984 // Oh dear. Inconsistent names left 'section' here for backward compatibility,
985 // but also save sectionid and sectionnumber.
986 $mods[$cmid]->section = $section->section;
987 $mods[$cmid]->sectionnumber = $section->section;
988 $mods[$cmid]->sectionid = $rawmods[$cmid]->section;
990 $mods[$cmid]->module = $rawmods[$cmid]->module;
991 $mods[$cmid]->added = $rawmods[$cmid]->added;
992 $mods[$cmid]->score = $rawmods[$cmid]->score;
993 $mods[$cmid]->idnumber = $rawmods[$cmid]->idnumber;
994 $mods[$cmid]->visible = $rawmods[$cmid]->visible;
995 $mods[$cmid]->visibleoncoursepage = $rawmods[$cmid]->visibleoncoursepage;
996 $mods[$cmid]->visibleold = $rawmods[$cmid]->visibleold;
997 $mods[$cmid]->groupmode = $rawmods[$cmid]->groupmode;
998 $mods[$cmid]->groupingid = $rawmods[$cmid]->groupingid;
999 $mods[$cmid]->indent = $rawmods[$cmid]->indent;
1000 $mods[$cmid]->completion = $rawmods[$cmid]->completion;
1001 $mods[$cmid]->extra = "";
1002 $mods[$cmid]->completiongradeitemnumber =
1003 $rawmods[$cmid]->completiongradeitemnumber;
1004 $mods[$cmid]->completionpassgrade = $rawmods[$cmid]->completionpassgrade;
1005 $mods[$cmid]->completionview = $rawmods[$cmid]->completionview;
1006 $mods[$cmid]->completionexpected = $rawmods[$cmid]->completionexpected;
1007 $mods[$cmid]->showdescription = $rawmods[$cmid]->showdescription;
1008 $mods[$cmid]->availability = $rawmods[$cmid]->availability;
1009 $mods[$cmid]->deletioninprogress = $rawmods[$cmid]->deletioninprogress;
1010 $mods[$cmid]->downloadcontent = $rawmods[$cmid]->downloadcontent;
1011 $mods[$cmid]->lang = $rawmods[$cmid]->lang;
1013 $modname = $mods[$cmid]->mod;
1014 $functionname = $modname . "_get_coursemodule_info";
1016 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
1017 continue;
1020 include_once("$CFG->dirroot/mod/$modname/lib.php");
1022 if ($hasfunction = function_exists($functionname)) {
1023 if ($info = $functionname($rawmods[$cmid])) {
1024 if (!empty($info->icon)) {
1025 $mods[$cmid]->icon = $info->icon;
1027 if (!empty($info->iconcomponent)) {
1028 $mods[$cmid]->iconcomponent = $info->iconcomponent;
1030 if (!empty($info->name)) {
1031 $mods[$cmid]->name = $info->name;
1033 if ($info instanceof cached_cm_info) {
1034 // When using cached_cm_info you can include three new fields.
1035 // That aren't available for legacy code.
1036 if (!empty($info->content)) {
1037 $mods[$cmid]->content = $info->content;
1039 if (!empty($info->extraclasses)) {
1040 $mods[$cmid]->extraclasses = $info->extraclasses;
1042 if (!empty($info->iconurl)) {
1043 // Convert URL to string as it's easier to store.
1044 // Also serialized object contains \0 byte,
1045 // ... and can not be written to Postgres DB.
1046 $url = new moodle_url($info->iconurl);
1047 $mods[$cmid]->iconurl = $url->out(false);
1049 if (!empty($info->onclick)) {
1050 $mods[$cmid]->onclick = $info->onclick;
1052 if (!empty($info->customdata)) {
1053 $mods[$cmid]->customdata = $info->customdata;
1055 } else {
1056 // When using a stdclass, the (horrible) deprecated ->extra field,
1057 // ... that is available for BC.
1058 if (!empty($info->extra)) {
1059 $mods[$cmid]->extra = $info->extra;
1064 // When there is no modname_get_coursemodule_info function,
1065 // ... but showdescriptions is enabled, then we use the 'intro',
1066 // ... and 'introformat' fields in the module table.
1067 if (!$hasfunction && $rawmods[$cmid]->showdescription) {
1068 if ($modvalues = $DB->get_record($rawmods[$cmid]->modname,
1069 ['id' => $rawmods[$cmid]->instance], 'name, intro, introformat')) {
1070 // Set content from intro and introformat. Filters are disabled.
1071 // Because we filter it with format_text at display time.
1072 $mods[$cmid]->content = format_module_intro($rawmods[$cmid]->modname,
1073 $modvalues, $rawmods[$cmid]->id, false);
1075 // To save making another query just below, put name in here.
1076 $mods[$cmid]->name = $modvalues->name;
1079 if (!isset($mods[$cmid]->name)) {
1080 $mods[$cmid]->name = $DB->get_field($rawmods[$cmid]->modname, "name",
1081 ["id" => $rawmods[$cmid]->instance]);
1084 // Minimise the database size by unsetting default options when they are 'empty'.
1085 // This list corresponds to code in the cm_info constructor.
1086 foreach (['idnumber', 'groupmode', 'groupingid',
1087 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
1088 'icon', 'iconcomponent', 'customdata', 'availability', 'completionview',
1089 'completionexpected', 'score', 'showdescription', 'deletioninprogress'] as $property) {
1090 if (property_exists($mods[$cmid], $property) &&
1091 empty($mods[$cmid]->{$property})) {
1092 unset($mods[$cmid]->{$property});
1095 // Special case: this value is usually set to null, but may be 0.
1096 if (property_exists($mods[$cmid], 'completiongradeitemnumber') &&
1097 is_null($mods[$cmid]->completiongradeitemnumber)) {
1098 unset($mods[$cmid]->completiongradeitemnumber);
1104 return $mods;
1108 * Purge the cache of a given course
1110 * @param int $courseid Course id
1112 public static function purge_course_cache(int $courseid): void {
1113 increment_revision_number('course', 'cacherev', 'id = :id', array('id' => $courseid));
1114 // Because this is a versioned cache, there is no need to actually delete the cache item,
1115 // only increase the required version number.
1121 * Data about a single module on a course. This contains most of the fields in the course_modules
1122 * table, plus additional data when required.
1124 * The object can be accessed by core or any plugin (i.e. course format, block, filter, etc.) as
1125 * get_fast_modinfo($courseorid)->cms[$coursemoduleid]
1126 * or
1127 * get_fast_modinfo($courseorid)->instances[$moduletype][$instanceid]
1129 * There are three stages when activity module can add/modify data in this object:
1131 * <b>Stage 1 - during building the cache.</b>
1132 * Allows to add to the course cache static user-independent information about the module.
1133 * Modules should try to include only absolutely necessary information that may be required
1134 * when displaying course view page. The information is stored in application-level cache
1135 * and reset when {@link rebuild_course_cache()} is called or cache is purged by admin.
1137 * Modules can implement callback XXX_get_coursemodule_info() returning instance of object
1138 * {@link cached_cm_info}
1140 * <b>Stage 2 - dynamic data.</b>
1141 * Dynamic data is user-dependent, it is stored in request-level cache. To reset this cache
1142 * {@link get_fast_modinfo()} with $reset argument may be called.
1144 * Dynamic data is obtained when any of the following properties/methods is requested:
1145 * - {@link cm_info::$url}
1146 * - {@link cm_info::$name}
1147 * - {@link cm_info::$onclick}
1148 * - {@link cm_info::get_icon_url()}
1149 * - {@link cm_info::$uservisible}
1150 * - {@link cm_info::$available}
1151 * - {@link cm_info::$availableinfo}
1152 * - plus any of the properties listed in Stage 3.
1154 * Modules can implement callback <b>XXX_cm_info_dynamic()</b> and inside this callback they
1155 * are allowed to use any of the following set methods:
1156 * - {@link cm_info::set_available()}
1157 * - {@link cm_info::set_name()}
1158 * - {@link cm_info::set_no_view_link()}
1159 * - {@link cm_info::set_user_visible()}
1160 * - {@link cm_info::set_on_click()}
1161 * - {@link cm_info::set_icon_url()}
1162 * - {@link cm_info::override_customdata()}
1163 * Any methods affecting view elements can also be set in this callback.
1165 * <b>Stage 3 (view data).</b>
1166 * Also user-dependend data stored in request-level cache. Second stage is created
1167 * because populating the view data can be expensive as it may access much more
1168 * Moodle APIs such as filters, user information, output renderers and we
1169 * don't want to request it until necessary.
1170 * View data is obtained when any of the following properties/methods is requested:
1171 * - {@link cm_info::$afterediticons}
1172 * - {@link cm_info::$content}
1173 * - {@link cm_info::get_formatted_content()}
1174 * - {@link cm_info::$extraclasses}
1175 * - {@link cm_info::$afterlink}
1177 * Modules can implement callback <b>XXX_cm_info_view()</b> and inside this callback they
1178 * are allowed to use any of the following set methods:
1179 * - {@link cm_info::set_after_edit_icons()}
1180 * - {@link cm_info::set_after_link()}
1181 * - {@link cm_info::set_content()}
1182 * - {@link cm_info::set_extra_classes()}
1184 * @property-read int $id Course-module ID - from course_modules table
1185 * @property-read int $instance Module instance (ID within module table) - from course_modules table
1186 * @property-read int $course Course ID - from course_modules table
1187 * @property-read string $idnumber 'ID number' from course-modules table (arbitrary text set by user) - from
1188 * course_modules table
1189 * @property-read int $added Time that this course-module was added (unix time) - from course_modules table
1190 * @property-read int $visible Visible setting (0 or 1; if this is 0, students cannot see/access the activity) - from
1191 * course_modules table
1192 * @property-read int $visibleoncoursepage Visible on course page setting - from course_modules table, adjusted to
1193 * whether course format allows this module to have the "stealth" mode
1194 * @property-read int $visibleold Old visible setting (if the entire section is hidden, the previous value for
1195 * visible is stored in this field) - from course_modules table
1196 * @property-read int $groupmode Group mode (one of the constants NOGROUPS, SEPARATEGROUPS, or VISIBLEGROUPS) - from
1197 * course_modules table. Use {@link cm_info::$effectivegroupmode} to find the actual group mode that may be forced by course.
1198 * @property-read int $groupingid Grouping ID (0 = all groupings)
1199 * @property-read bool $coursegroupmodeforce Indicates whether the course containing the module has forced the groupmode
1200 * This means that cm_info::$groupmode should be ignored and cm_info::$coursegroupmode be used instead
1201 * @property-read int $coursegroupmode Group mode (one of the constants NOGROUPS, SEPARATEGROUPS, or VISIBLEGROUPS) - from
1202 * course table - as specified for the course containing the module
1203 * Effective only if {@link cm_info::$coursegroupmodeforce} is set
1204 * @property-read int $effectivegroupmode Effective group mode for this module (one of the constants NOGROUPS, SEPARATEGROUPS,
1205 * or VISIBLEGROUPS). This can be different from groupmode set for the module if the groupmode is forced for the course.
1206 * This value will always be NOGROUPS if module type does not support group mode.
1207 * @property-read int $indent Indent level on course page (0 = no indent) - from course_modules table
1208 * @property-read int $completion Activity completion setting for this activity, COMPLETION_TRACKING_xx constant - from
1209 * course_modules table
1210 * @property-read mixed $completiongradeitemnumber Set to the item number (usually 0) if completion depends on a particular
1211 * grade of this activity, or null if completion does not depend on a grade - from course_modules table
1212 * @property-read int $completionview 1 if 'on view' completion is enabled, 0 otherwise - from course_modules table
1213 * @property-read int $completionexpected Set to a unix time if completion of this activity is expected at a
1214 * particular time, 0 if no time set - from course_modules table
1215 * @property-read string $availability Availability information as JSON string or null if none -
1216 * from course_modules table
1217 * @property-read int $showdescription Controls whether the description of the activity displays on the course main page (in
1218 * addition to anywhere it might display within the activity itself). 0 = do not show
1219 * on main page, 1 = show on main page.
1220 * @property-read string $extra (deprecated) Extra HTML that is put in an unhelpful part of the HTML when displaying this module in
1221 * course page - from cached data in modinfo field. Deprecated, replaced by ->extraclasses and ->onclick
1222 * @property-read string $icon Name of icon to use - from cached data in modinfo field
1223 * @property-read string $iconcomponent Component that contains icon - from cached data in modinfo field
1224 * @property-read string $modname Name of module e.g. 'forum' (this is the same name as the module's main database
1225 * table) - from cached data in modinfo field
1226 * @property-read int $module ID of module type - from course_modules table
1227 * @property-read string $name Name of module instance for display on page e.g. 'General discussion forum' - from cached
1228 * data in modinfo field
1229 * @property-read int $sectionnum Section number that this course-module is in (section 0 = above the calendar, section 1
1230 * = week/topic 1, etc) - from cached data in modinfo field
1231 * @property-read int $sectionid Section id - from course_modules table
1232 * @property-read array $conditionscompletion Availability conditions for this course-module based on the completion of other
1233 * course-modules (array from other course-module id to required completion state for that
1234 * module) - from cached data in modinfo field
1235 * @property-read array $conditionsgrade Availability conditions for this course-module based on course grades (array from
1236 * grade item id to object with ->min, ->max fields) - from cached data in modinfo field
1237 * @property-read array $conditionsfield Availability conditions for this course-module based on user fields
1238 * @property-read bool $available True if this course-module is available to students i.e. if all availability conditions
1239 * are met - obtained dynamically
1240 * @property-read string $availableinfo If course-module is not available to students, this string gives information about
1241 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
1242 * January 2010') for display on main page - obtained dynamically
1243 * @property-read bool $uservisible True if this course-module is available to the CURRENT user (for example, if current user
1244 * has viewhiddenactivities capability, they can access the course-module even if it is not
1245 * visible or not available, so this would be true in that case)
1246 * @property-read context_module $context Module context
1247 * @property-read string $modfullname Returns a localised human-readable name of the module type - calculated on request
1248 * @property-read string $modplural Returns a localised human-readable name of the module type in plural form - calculated on request
1249 * @property-read string $content Content to display on main (view) page - calculated on request
1250 * @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
1251 * @property-read string $extraclasses Extra CSS classes to add to html output for this activity on main page - calculated on request
1252 * @property-read string $onclick Content of HTML on-click attribute already escaped - calculated on request
1253 * @property-read mixed $customdata Optional custom data stored in modinfo cache for this activity, or null if none
1254 * @property-read string $afterlink Extra HTML code to display after link - calculated on request
1255 * @property-read string $afterediticons Extra HTML code to display after editing icons (e.g. more icons) - calculated on request
1256 * @property-read bool $deletioninprogress True if this course module is scheduled for deletion, false otherwise.
1257 * @property-read bool $downloadcontent True if content download is enabled for this course module, false otherwise.
1258 * @property-read bool $lang the forced language for this activity (language pack name). Null means not forced.
1260 class cm_info implements IteratorAggregate {
1262 * State: Only basic data from modinfo cache is available.
1264 const STATE_BASIC = 0;
1267 * State: In the process of building dynamic data (to avoid recursive calls to obtain_dynamic_data())
1269 const STATE_BUILDING_DYNAMIC = 1;
1272 * State: Dynamic data is available too.
1274 const STATE_DYNAMIC = 2;
1277 * State: In the process of building view data (to avoid recursive calls to obtain_view_data())
1279 const STATE_BUILDING_VIEW = 3;
1282 * State: View data (for course page) is available.
1284 const STATE_VIEW = 4;
1287 * Parent object
1288 * @var course_modinfo
1290 private $modinfo;
1293 * Level of information stored inside this object (STATE_xx constant)
1294 * @var int
1296 private $state;
1299 * Course-module ID - from course_modules table
1300 * @var int
1302 private $id;
1305 * Module instance (ID within module table) - from course_modules table
1306 * @var int
1308 private $instance;
1311 * 'ID number' from course-modules table (arbitrary text set by user) - from
1312 * course_modules table
1313 * @var string
1315 private $idnumber;
1318 * Time that this course-module was added (unix time) - from course_modules table
1319 * @var int
1321 private $added;
1324 * This variable is not used and is included here only so it can be documented.
1325 * Once the database entry is removed from course_modules, it should be deleted
1326 * here too.
1327 * @var int
1328 * @deprecated Do not use this variable
1330 private $score;
1333 * Visible setting (0 or 1; if this is 0, students cannot see/access the activity) - from
1334 * course_modules table
1335 * @var int
1337 private $visible;
1340 * Visible on course page setting - from course_modules table
1341 * @var int
1343 private $visibleoncoursepage;
1346 * Old visible setting (if the entire section is hidden, the previous value for
1347 * visible is stored in this field) - from course_modules table
1348 * @var int
1350 private $visibleold;
1353 * Group mode (one of the constants NONE, SEPARATEGROUPS, or VISIBLEGROUPS) - from
1354 * course_modules table
1355 * @var int
1357 private $groupmode;
1360 * Grouping ID (0 = all groupings)
1361 * @var int
1363 private $groupingid;
1366 * Indent level on course page (0 = no indent) - from course_modules table
1367 * @var int
1369 private $indent;
1372 * Activity completion setting for this activity, COMPLETION_TRACKING_xx constant - from
1373 * course_modules table
1374 * @var int
1376 private $completion;
1379 * Set to the item number (usually 0) if completion depends on a particular
1380 * grade of this activity, or null if completion does not depend on a grade - from
1381 * course_modules table
1382 * @var mixed
1384 private $completiongradeitemnumber;
1387 * 1 if pass grade completion is enabled, 0 otherwise - from course_modules table
1388 * @var int
1390 private $completionpassgrade;
1393 * 1 if 'on view' completion is enabled, 0 otherwise - from course_modules table
1394 * @var int
1396 private $completionview;
1399 * Set to a unix time if completion of this activity is expected at a
1400 * particular time, 0 if no time set - from course_modules table
1401 * @var int
1403 private $completionexpected;
1406 * Availability information as JSON string or null if none - from course_modules table
1407 * @var string
1409 private $availability;
1412 * Controls whether the description of the activity displays on the course main page (in
1413 * addition to anywhere it might display within the activity itself). 0 = do not show
1414 * on main page, 1 = show on main page.
1415 * @var int
1417 private $showdescription;
1420 * Extra HTML that is put in an unhelpful part of the HTML when displaying this module in
1421 * course page - from cached data in modinfo field
1422 * @deprecated This is crazy, don't use it. Replaced by ->extraclasses and ->onclick
1423 * @var string
1425 private $extra;
1428 * Name of icon to use - from cached data in modinfo field
1429 * @var string
1431 private $icon;
1434 * Component that contains icon - from cached data in modinfo field
1435 * @var string
1437 private $iconcomponent;
1440 * Name of module e.g. 'forum' (this is the same name as the module's main database
1441 * table) - from cached data in modinfo field
1442 * @var string
1444 private $modname;
1447 * ID of module - from course_modules table
1448 * @var int
1450 private $module;
1453 * Name of module instance for display on page e.g. 'General discussion forum' - from cached
1454 * data in modinfo field
1455 * @var string
1457 private $name;
1460 * Section number that this course-module is in (section 0 = above the calendar, section 1
1461 * = week/topic 1, etc) - from cached data in modinfo field
1462 * @var int
1464 private $sectionnum;
1467 * Section id - from course_modules table
1468 * @var int
1470 private $sectionid;
1473 * Availability conditions for this course-module based on the completion of other
1474 * course-modules (array from other course-module id to required completion state for that
1475 * module) - from cached data in modinfo field
1476 * @var array
1478 private $conditionscompletion;
1481 * Availability conditions for this course-module based on course grades (array from
1482 * grade item id to object with ->min, ->max fields) - from cached data in modinfo field
1483 * @var array
1485 private $conditionsgrade;
1488 * Availability conditions for this course-module based on user fields
1489 * @var array
1491 private $conditionsfield;
1494 * True if this course-module is available to students i.e. if all availability conditions
1495 * are met - obtained dynamically
1496 * @var bool
1498 private $available;
1501 * If course-module is not available to students, this string gives information about
1502 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
1503 * January 2010') for display on main page - obtained dynamically
1504 * @var string
1506 private $availableinfo;
1509 * True if this course-module is available to the CURRENT user (for example, if current user
1510 * has viewhiddenactivities capability, they can access the course-module even if it is not
1511 * visible or not available, so this would be true in that case)
1512 * @var bool
1514 private $uservisible;
1517 * True if this course-module is visible to the CURRENT user on the course page
1518 * @var bool
1520 private $uservisibleoncoursepage;
1523 * @var moodle_url
1525 private $url;
1528 * @var string
1530 private $content;
1533 * @var bool
1535 private $contentisformatted;
1538 * @var bool True if the content has a special course item display like labels.
1540 private $customcmlistitem;
1543 * @var string
1545 private $extraclasses;
1548 * @var moodle_url full external url pointing to icon image for activity
1550 private $iconurl;
1553 * @var string
1555 private $onclick;
1558 * @var mixed
1560 private $customdata;
1563 * @var string
1565 private $afterlink;
1568 * @var string
1570 private $afterediticons;
1573 * @var bool representing the deletion state of the module. True if the mod is scheduled for deletion.
1575 private $deletioninprogress;
1578 * @var int enable/disable download content for this course module
1580 private $downloadcontent;
1583 * @var string|null the forced language for this activity (language pack name). Null means not forced.
1585 private $lang;
1588 * List of class read-only properties and their getter methods.
1589 * Used by magic functions __get(), __isset(), __empty()
1590 * @var array
1592 private static $standardproperties = [
1593 'url' => 'get_url',
1594 'content' => 'get_content',
1595 'extraclasses' => 'get_extra_classes',
1596 'onclick' => 'get_on_click',
1597 'customdata' => 'get_custom_data',
1598 'afterlink' => 'get_after_link',
1599 'afterediticons' => 'get_after_edit_icons',
1600 'modfullname' => 'get_module_type_name',
1601 'modplural' => 'get_module_type_name_plural',
1602 'id' => false,
1603 'added' => false,
1604 'availability' => false,
1605 'available' => 'get_available',
1606 'availableinfo' => 'get_available_info',
1607 'completion' => false,
1608 'completionexpected' => false,
1609 'completiongradeitemnumber' => false,
1610 'completionpassgrade' => false,
1611 'completionview' => false,
1612 'conditionscompletion' => false,
1613 'conditionsfield' => false,
1614 'conditionsgrade' => false,
1615 'context' => 'get_context',
1616 'course' => 'get_course_id',
1617 'coursegroupmode' => 'get_course_groupmode',
1618 'coursegroupmodeforce' => 'get_course_groupmodeforce',
1619 'customcmlistitem' => 'has_custom_cmlist_item',
1620 'effectivegroupmode' => 'get_effective_groupmode',
1621 'extra' => false,
1622 'groupingid' => false,
1623 'groupmembersonly' => 'get_deprecated_group_members_only',
1624 'groupmode' => false,
1625 'icon' => false,
1626 'iconcomponent' => false,
1627 'idnumber' => false,
1628 'indent' => false,
1629 'instance' => false,
1630 'modname' => false,
1631 'module' => false,
1632 'name' => 'get_name',
1633 'score' => false,
1634 'section' => 'get_section_id',
1635 'sectionid' => false,
1636 'sectionnum' => false,
1637 'showdescription' => false,
1638 'uservisible' => 'get_user_visible',
1639 'visible' => false,
1640 'visibleoncoursepage' => false,
1641 'visibleold' => false,
1642 'deletioninprogress' => false,
1643 'downloadcontent' => false,
1644 'lang' => false,
1648 * List of methods with no arguments that were public prior to Moodle 2.6.
1650 * They can still be accessed publicly via magic __call() function with no warnings
1651 * but are not listed in the class methods list.
1652 * For the consistency of the code it is better to use corresponding properties.
1654 * These methods be deprecated completely in later versions.
1656 * @var array $standardmethods
1658 private static $standardmethods = array(
1659 // Following methods are not recommended to use because there have associated read-only properties.
1660 'get_url',
1661 'get_content',
1662 'get_extra_classes',
1663 'get_on_click',
1664 'get_custom_data',
1665 'get_after_link',
1666 'get_after_edit_icons',
1667 // Method obtain_dynamic_data() should not be called from outside of this class but it was public before Moodle 2.6.
1668 'obtain_dynamic_data',
1672 * Magic method to call functions that are now declared as private but were public in Moodle before 2.6.
1673 * These private methods can not be used anymore.
1675 * @param string $name
1676 * @param array $arguments
1677 * @return mixed
1678 * @throws coding_exception
1680 public function __call($name, $arguments) {
1681 if (in_array($name, self::$standardmethods)) {
1682 $message = "cm_info::$name() can not be used anymore.";
1683 if ($alternative = array_search($name, self::$standardproperties)) {
1684 $message .= " Please use the property cm_info->$alternative instead.";
1686 throw new coding_exception($message);
1688 throw new coding_exception("Method cm_info::{$name}() does not exist");
1692 * Magic method getter
1694 * @param string $name
1695 * @return mixed
1697 public function __get($name) {
1698 if (isset(self::$standardproperties[$name])) {
1699 if ($method = self::$standardproperties[$name]) {
1700 return $this->$method();
1701 } else {
1702 return $this->$name;
1704 } else {
1705 debugging('Invalid cm_info property accessed: '.$name);
1706 return null;
1711 * Implementation of IteratorAggregate::getIterator(), allows to cycle through properties
1712 * and use {@link convert_to_array()}
1714 * @return ArrayIterator
1716 public function getIterator(): Traversable {
1717 // Make sure dynamic properties are retrieved prior to view properties.
1718 $this->obtain_dynamic_data();
1719 $ret = array();
1721 // Do not iterate over deprecated properties.
1722 $props = self::$standardproperties;
1723 unset($props['groupmembersonly']);
1725 foreach ($props as $key => $unused) {
1726 $ret[$key] = $this->__get($key);
1728 return new ArrayIterator($ret);
1732 * Magic method for function isset()
1734 * @param string $name
1735 * @return bool
1737 public function __isset($name) {
1738 if (isset(self::$standardproperties[$name])) {
1739 $value = $this->__get($name);
1740 return isset($value);
1742 return false;
1746 * Magic method for function empty()
1748 * @param string $name
1749 * @return bool
1751 public function __empty($name) {
1752 if (isset(self::$standardproperties[$name])) {
1753 $value = $this->__get($name);
1754 return empty($value);
1756 return true;
1760 * Magic method setter
1762 * Will display the developer warning when trying to set/overwrite property.
1764 * @param string $name
1765 * @param mixed $value
1767 public function __set($name, $value) {
1768 debugging("It is not allowed to set the property cm_info::\${$name}", DEBUG_DEVELOPER);
1772 * @return bool True if this module has a 'view' page that should be linked to in navigation
1773 * etc (note: modules may still have a view.php file, but return false if this is not
1774 * intended to be linked to from 'normal' parts of the interface; this is what label does).
1776 public function has_view() {
1777 return !is_null($this->url);
1781 * Gets the URL to link to for this module.
1783 * This method is normally called by the property ->url, but can be called directly if
1784 * there is a case when it might be called recursively (you can't call property values
1785 * recursively).
1787 * @return moodle_url URL to link to for this module, or null if it doesn't have a view page
1789 public function get_url() {
1790 $this->obtain_dynamic_data();
1791 return $this->url;
1795 * Obtains content to display on main (view) page.
1796 * Note: Will collect view data, if not already obtained.
1797 * @return string Content to display on main page below link, or empty string if none
1799 private function get_content() {
1800 $this->obtain_view_data();
1801 return $this->content;
1805 * Returns the content to display on course/overview page, formatted and passed through filters
1807 * if $options['context'] is not specified, the module context is used
1809 * @param array|stdClass $options formatting options, see {@link format_text()}
1810 * @return string
1812 public function get_formatted_content($options = array()) {
1813 $this->obtain_view_data();
1814 if (empty($this->content)) {
1815 return '';
1817 if ($this->contentisformatted) {
1818 return $this->content;
1821 // Improve filter performance by preloading filter setttings for all
1822 // activities on the course (this does nothing if called multiple
1823 // times)
1824 filter_preload_activities($this->get_modinfo());
1826 $options = (array)$options;
1827 if (!isset($options['context'])) {
1828 $options['context'] = $this->get_context();
1830 return format_text($this->content, FORMAT_HTML, $options);
1834 * Return the module custom cmlist item flag.
1836 * Activities like label uses this flag to indicate that it should be
1837 * displayed as a custom course item instead of a tipical activity card.
1839 * @return bool
1841 public function has_custom_cmlist_item(): bool {
1842 $this->obtain_view_data();
1843 return $this->customcmlistitem ?? false;
1847 * Getter method for property $name, ensures that dynamic data is obtained.
1849 * This method is normally called by the property ->name, but can be called directly if there
1850 * is a case when it might be called recursively (you can't call property values recursively).
1852 * @return string
1854 public function get_name() {
1855 $this->obtain_dynamic_data();
1856 return $this->name;
1860 * Returns the name to display on course/overview page, formatted and passed through filters
1862 * if $options['context'] is not specified, the module context is used
1864 * @param array|stdClass $options formatting options, see {@link format_string()}
1865 * @return string
1867 public function get_formatted_name($options = array()) {
1868 global $CFG;
1869 $options = (array)$options;
1870 if (!isset($options['context'])) {
1871 $options['context'] = $this->get_context();
1873 // Improve filter performance by preloading filter setttings for all
1874 // activities on the course (this does nothing if called multiple
1875 // times).
1876 if (!empty($CFG->filterall)) {
1877 filter_preload_activities($this->get_modinfo());
1879 return format_string($this->get_name(), true, $options);
1883 * Note: Will collect view data, if not already obtained.
1884 * @return string Extra CSS classes to add to html output for this activity on main page
1886 private function get_extra_classes() {
1887 $this->obtain_view_data();
1888 return $this->extraclasses;
1892 * @return string Content of HTML on-click attribute. This string will be used literally
1893 * as a string so should be pre-escaped.
1895 private function get_on_click() {
1896 // Does not need view data; may be used by navigation
1897 $this->obtain_dynamic_data();
1898 return $this->onclick;
1901 * Getter method for property $customdata, ensures that dynamic data is retrieved.
1903 * This method is normally called by the property ->customdata, but can be called directly if there
1904 * is a case when it might be called recursively (you can't call property values recursively).
1906 * @return mixed Optional custom data stored in modinfo cache for this activity, or null if none
1908 public function get_custom_data() {
1909 $this->obtain_dynamic_data();
1910 return $this->customdata;
1914 * Note: Will collect view data, if not already obtained.
1915 * @return string Extra HTML code to display after link
1917 private function get_after_link() {
1918 $this->obtain_view_data();
1919 return $this->afterlink;
1923 * Get the activity badge data associated to this course module (if the module supports it).
1924 * Modules can use this method to provide additional data to be displayed in the activity badge.
1926 * @param renderer_base $output Output render to use, or null for default (global)
1927 * @return stdClass|null The activitybadge data (badgecontent, badgestyle...) or null if the module doesn't implement it.
1929 public function get_activitybadge(?renderer_base $output = null): ?stdClass {
1930 global $OUTPUT;
1932 $activibybadgeclass = activitybadge::create_instance($this);
1933 if (empty($activibybadgeclass)) {
1934 return null;
1937 if (!isset($output)) {
1938 $output = $OUTPUT;
1941 return $activibybadgeclass->export_for_template($output);
1945 * Note: Will collect view data, if not already obtained.
1946 * @return string Extra HTML code to display after editing icons (e.g. more icons)
1948 private function get_after_edit_icons() {
1949 $this->obtain_view_data();
1950 return $this->afterediticons;
1954 * Fetch the module's icon URL.
1956 * This function fetches the course module instance's icon URL.
1957 * This method adds a `filtericon` parameter in the URL when rendering the monologo version of the course module icon or when
1958 * the plugin declares, via its `filtericon` custom data, that the icon needs to be filtered.
1959 * This additional information can be used by plugins when rendering the module icon to determine whether to apply
1960 * CSS filtering to the icon.
1962 * @param core_renderer $output Output render to use, or null for default (global)
1963 * @return moodle_url Icon URL for a suitable icon to put beside this cm
1965 public function get_icon_url($output = null) {
1966 global $OUTPUT;
1967 $this->obtain_dynamic_data();
1968 if (!$output) {
1969 $output = $OUTPUT;
1972 $ismonologo = false;
1973 if (!empty($this->iconurl)) {
1974 // Support modules setting their own, external, icon image.
1975 $icon = $this->iconurl;
1976 } else if (!empty($this->icon)) {
1977 // Fallback to normal local icon + component processing.
1978 if (substr($this->icon, 0, 4) === 'mod/') {
1979 list($modname, $iconname) = explode('/', substr($this->icon, 4), 2);
1980 $icon = $output->image_url($iconname, $modname);
1981 } else {
1982 if (!empty($this->iconcomponent)) {
1983 // Icon has specified component.
1984 $icon = $output->image_url($this->icon, $this->iconcomponent);
1985 } else {
1986 // Icon does not have specified component, use default.
1987 $icon = $output->image_url($this->icon);
1990 } else {
1991 $icon = $output->image_url('monologo', $this->modname);
1992 // Activity modules may only have an `icon` icon instead of a `monologo` icon.
1993 // So we need to determine if the module really has a `monologo` icon.
1994 $ismonologo = core_component::has_monologo_icon('mod', $this->modname);
1997 // Determine whether the icon will be filtered in the CSS.
1998 // This can be controlled by the module by declaring a 'filtericon' custom data.
1999 // If the 'filtericon' custom data is not set, icon filtering will be determined whether the module has a `monologo` icon.
2000 // Additionally, we need to cast custom data to array as some modules may treat it as an object.
2001 $filtericon = ((array)$this->customdata)['filtericon'] ?? $ismonologo;
2002 if ($filtericon) {
2003 $icon->param('filtericon', 1);
2005 return $icon;
2009 * @param string $textclasses additionnal classes for grouping label
2010 * @return string An empty string or HTML grouping label span tag
2012 public function get_grouping_label($textclasses = '') {
2013 $groupinglabel = '';
2014 if ($this->effectivegroupmode != NOGROUPS && !empty($this->groupingid) &&
2015 has_capability('moodle/course:managegroups', context_course::instance($this->course))) {
2016 $groupings = groups_get_all_groupings($this->course);
2017 $groupinglabel = html_writer::tag('span', '('.format_string($groupings[$this->groupingid]->name).')',
2018 array('class' => 'groupinglabel '.$textclasses));
2020 return $groupinglabel;
2024 * Returns a localised human-readable name of the module type.
2026 * @param bool $plural If true, the function returns the plural form of the name.
2027 * @return ?lang_string
2029 public function get_module_type_name($plural = false) {
2030 $modnames = get_module_types_names($plural);
2031 if (isset($modnames[$this->modname])) {
2032 return $modnames[$this->modname];
2033 } else {
2034 return null;
2039 * Returns a localised human-readable name of the module type in plural form - calculated on request
2041 * @return string
2043 private function get_module_type_name_plural() {
2044 return $this->get_module_type_name(true);
2048 * @return course_modinfo Modinfo object that this came from
2050 public function get_modinfo() {
2051 return $this->modinfo;
2055 * Returns the section this module belongs to
2057 * @return section_info
2059 public function get_section_info() {
2060 return $this->modinfo->get_section_info_by_id($this->sectionid);
2064 * Getter method for property $section that returns section id.
2066 * This method is called by the property ->section.
2068 * @return int
2070 private function get_section_id(): int {
2071 return $this->sectionid;
2075 * Returns course object that was used in the first {@link get_fast_modinfo()} call.
2077 * It may not contain all fields from DB table {course} but always has at least the following:
2078 * id,shortname,fullname,format,enablecompletion,groupmode,groupmodeforce,cacherev
2080 * If the course object lacks the field you need you can use the global
2081 * function {@link get_course()} that will save extra query if you access
2082 * current course or frontpage course.
2084 * @return stdClass
2086 public function get_course() {
2087 return $this->modinfo->get_course();
2091 * Returns course id for which the modinfo was generated.
2093 * @return int
2095 private function get_course_id() {
2096 return $this->modinfo->get_course_id();
2100 * Returns group mode used for the course containing the module
2102 * @return int one of constants NOGROUPS, SEPARATEGROUPS, VISIBLEGROUPS
2104 private function get_course_groupmode() {
2105 return $this->modinfo->get_course()->groupmode;
2109 * Returns whether group mode is forced for the course containing the module
2111 * @return bool
2113 private function get_course_groupmodeforce() {
2114 return $this->modinfo->get_course()->groupmodeforce;
2118 * Returns effective groupmode of the module that may be overwritten by forced course groupmode.
2120 * @return int one of constants NOGROUPS, SEPARATEGROUPS, VISIBLEGROUPS
2122 private function get_effective_groupmode() {
2123 $groupmode = $this->groupmode;
2124 if ($this->modinfo->get_course()->groupmodeforce) {
2125 $groupmode = $this->modinfo->get_course()->groupmode;
2126 if ($groupmode != NOGROUPS && !plugin_supports('mod', $this->modname, FEATURE_GROUPS, false)) {
2127 $groupmode = NOGROUPS;
2130 return $groupmode;
2134 * @return context_module Current module context
2136 private function get_context() {
2137 return context_module::instance($this->id);
2141 * Returns itself in the form of stdClass.
2143 * The object includes all fields that table course_modules has and additionally
2144 * fields 'name', 'modname', 'sectionnum' (if requested).
2146 * This can be used as a faster alternative to {@link get_coursemodule_from_id()}
2148 * @param bool $additionalfields include additional fields 'name', 'modname', 'sectionnum'
2149 * @return stdClass
2151 public function get_course_module_record($additionalfields = false) {
2152 $cmrecord = new stdClass();
2154 // Standard fields from table course_modules.
2155 static $cmfields = array('id', 'course', 'module', 'instance', 'section', 'idnumber', 'added',
2156 'score', 'indent', 'visible', 'visibleoncoursepage', 'visibleold', 'groupmode', 'groupingid',
2157 'completion', 'completiongradeitemnumber', 'completionview', 'completionexpected', 'completionpassgrade',
2158 'showdescription', 'availability', 'deletioninprogress', 'downloadcontent', 'lang');
2160 foreach ($cmfields as $key) {
2161 $cmrecord->$key = $this->$key;
2164 // Additional fields that function get_coursemodule_from_id() adds.
2165 if ($additionalfields) {
2166 $cmrecord->name = $this->name;
2167 $cmrecord->modname = $this->modname;
2168 $cmrecord->sectionnum = $this->sectionnum;
2171 return $cmrecord;
2174 // Set functions
2175 ////////////////
2178 * Sets content to display on course view page below link (if present).
2179 * @param string $content New content as HTML string (empty string if none)
2180 * @param bool $isformatted Whether user content is already passed through format_text/format_string and should not
2181 * be formatted again. This can be useful when module adds interactive elements on top of formatted user text.
2182 * @return void
2184 public function set_content($content, $isformatted = false) {
2185 $this->content = $content;
2186 $this->contentisformatted = $isformatted;
2190 * Sets extra classes to include in CSS.
2191 * @param string $extraclasses Extra classes (empty string if none)
2192 * @return void
2194 public function set_extra_classes($extraclasses) {
2195 $this->extraclasses = $extraclasses;
2199 * Sets the external full url that points to the icon being used
2200 * by the activity. Useful for external-tool modules (lti...)
2201 * If set, takes precedence over $icon and $iconcomponent
2203 * @param moodle_url $iconurl full external url pointing to icon image for activity
2204 * @return void
2206 public function set_icon_url(moodle_url $iconurl) {
2207 $this->iconurl = $iconurl;
2211 * Sets value of on-click attribute for JavaScript.
2212 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
2213 * @param string $onclick New onclick attribute which should be HTML-escaped
2214 * (empty string if none)
2215 * @return void
2217 public function set_on_click($onclick) {
2218 $this->check_not_view_only();
2219 $this->onclick = $onclick;
2223 * Overrides the value of an element in the customdata array.
2225 * @param string $name The key in the customdata array
2226 * @param mixed $value The value
2228 public function override_customdata($name, $value) {
2229 if (!is_array($this->customdata)) {
2230 $this->customdata = [];
2232 $this->customdata[$name] = $value;
2236 * Sets HTML that displays after link on course view page.
2237 * @param string $afterlink HTML string (empty string if none)
2238 * @return void
2240 public function set_after_link($afterlink) {
2241 $this->afterlink = $afterlink;
2245 * Sets HTML that displays after edit icons on course view page.
2246 * @param string $afterediticons HTML string (empty string if none)
2247 * @return void
2249 public function set_after_edit_icons($afterediticons) {
2250 $this->afterediticons = $afterediticons;
2254 * Changes the name (text of link) for this module instance.
2255 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
2256 * @param string $name Name of activity / link text
2257 * @return void
2259 public function set_name($name) {
2260 if ($this->state < self::STATE_BUILDING_DYNAMIC) {
2261 $this->update_user_visible();
2263 $this->name = $name;
2267 * Turns off the view link for this module instance.
2268 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
2269 * @return void
2271 public function set_no_view_link() {
2272 $this->check_not_view_only();
2273 $this->url = null;
2277 * Sets the 'uservisible' flag. This can be used (by setting false) to prevent access and
2278 * display of this module link for the current user.
2279 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
2280 * @param bool $uservisible
2281 * @return void
2283 public function set_user_visible($uservisible) {
2284 $this->check_not_view_only();
2285 $this->uservisible = $uservisible;
2289 * Sets the 'customcmlistitem' flag
2291 * This can be used (by setting true) to prevent the course from rendering the
2292 * activity item as a regular activity card. This is applied to activities like labels.
2294 * @param bool $customcmlistitem if the cmlist item of that activity has a special dysplay other than a card.
2296 public function set_custom_cmlist_item(bool $customcmlistitem) {
2297 $this->customcmlistitem = $customcmlistitem;
2301 * Sets the 'available' flag and related details. This flag is normally used to make
2302 * course modules unavailable until a certain date or condition is met. (When a course
2303 * module is unavailable, it is still visible to users who have viewhiddenactivities
2304 * permission.)
2306 * When this is function is called, user-visible status is recalculated automatically.
2308 * The $showavailability flag does not really do anything any more, but is retained
2309 * for backward compatibility. Setting this to false will cause $availableinfo to
2310 * be ignored.
2312 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
2313 * @param bool $available False if this item is not 'available'
2314 * @param int $showavailability 0 = do not show this item at all if it's not available,
2315 * 1 = show this item greyed out with the following message
2316 * @param string $availableinfo Information about why this is not available, or
2317 * empty string if not displaying
2318 * @return void
2320 public function set_available($available, $showavailability=0, $availableinfo='') {
2321 $this->check_not_view_only();
2322 $this->available = $available;
2323 if (!$showavailability) {
2324 $availableinfo = '';
2326 $this->availableinfo = $availableinfo;
2327 $this->update_user_visible();
2331 * Some set functions can only be called from _cm_info_dynamic and not _cm_info_view.
2332 * This is because they may affect parts of this object which are used on pages other
2333 * than the view page (e.g. in the navigation block, or when checking access on
2334 * module pages).
2335 * @return void
2337 private function check_not_view_only() {
2338 if ($this->state >= self::STATE_DYNAMIC) {
2339 throw new coding_exception('Cannot set this data from _cm_info_view because it may ' .
2340 'affect other pages as well as view');
2345 * Constructor should not be called directly; use {@link get_fast_modinfo()}
2347 * @param course_modinfo $modinfo Parent object
2348 * @param mixed $notused1 Argument not used
2349 * @param stdClass $mod Module object from the modinfo field of course table
2350 * @param mixed $notused2 Argument not used
2352 public function __construct(course_modinfo $modinfo, $notused1, $mod, $notused2) {
2353 $this->modinfo = $modinfo;
2355 $this->id = $mod->cm;
2356 $this->instance = $mod->id;
2357 $this->modname = $mod->mod;
2358 $this->idnumber = isset($mod->idnumber) ? $mod->idnumber : '';
2359 $this->name = $mod->name;
2360 $this->visible = $mod->visible;
2361 $this->visibleoncoursepage = $mod->visibleoncoursepage;
2362 $this->sectionnum = $mod->section; // Note weirdness with name here. Keeping for backwards compatibility.
2363 $this->groupmode = isset($mod->groupmode) ? $mod->groupmode : 0;
2364 $this->groupingid = isset($mod->groupingid) ? $mod->groupingid : 0;
2365 $this->indent = isset($mod->indent) ? $mod->indent : 0;
2366 $this->extra = isset($mod->extra) ? $mod->extra : '';
2367 $this->extraclasses = isset($mod->extraclasses) ? $mod->extraclasses : '';
2368 // iconurl may be stored as either string or instance of moodle_url.
2369 $this->iconurl = isset($mod->iconurl) ? new moodle_url($mod->iconurl) : '';
2370 $this->onclick = isset($mod->onclick) ? $mod->onclick : '';
2371 $this->content = isset($mod->content) ? $mod->content : '';
2372 $this->icon = isset($mod->icon) ? $mod->icon : '';
2373 $this->iconcomponent = isset($mod->iconcomponent) ? $mod->iconcomponent : '';
2374 $this->customdata = isset($mod->customdata) ? $mod->customdata : '';
2375 $this->showdescription = isset($mod->showdescription) ? $mod->showdescription : 0;
2376 $this->state = self::STATE_BASIC;
2378 $this->sectionid = isset($mod->sectionid) ? $mod->sectionid : 0;
2379 $this->module = isset($mod->module) ? $mod->module : 0;
2380 $this->added = isset($mod->added) ? $mod->added : 0;
2381 $this->score = isset($mod->score) ? $mod->score : 0;
2382 $this->visibleold = isset($mod->visibleold) ? $mod->visibleold : 0;
2383 $this->deletioninprogress = isset($mod->deletioninprogress) ? $mod->deletioninprogress : 0;
2384 $this->downloadcontent = $mod->downloadcontent ?? null;
2385 $this->lang = $mod->lang ?? null;
2387 // Note: it saves effort and database space to always include the
2388 // availability and completion fields, even if availability or completion
2389 // are actually disabled
2390 $this->completion = isset($mod->completion) ? $mod->completion : 0;
2391 $this->completionpassgrade = isset($mod->completionpassgrade) ? $mod->completionpassgrade : 0;
2392 $this->completiongradeitemnumber = isset($mod->completiongradeitemnumber)
2393 ? $mod->completiongradeitemnumber : null;
2394 $this->completionview = isset($mod->completionview)
2395 ? $mod->completionview : 0;
2396 $this->completionexpected = isset($mod->completionexpected)
2397 ? $mod->completionexpected : 0;
2398 $this->availability = isset($mod->availability) ? $mod->availability : null;
2399 $this->conditionscompletion = isset($mod->conditionscompletion)
2400 ? $mod->conditionscompletion : array();
2401 $this->conditionsgrade = isset($mod->conditionsgrade)
2402 ? $mod->conditionsgrade : array();
2403 $this->conditionsfield = isset($mod->conditionsfield)
2404 ? $mod->conditionsfield : array();
2406 static $modviews = array();
2407 if (!isset($modviews[$this->modname])) {
2408 $modviews[$this->modname] = !plugin_supports('mod', $this->modname,
2409 FEATURE_NO_VIEW_LINK);
2411 $this->url = $modviews[$this->modname]
2412 ? new moodle_url('/mod/' . $this->modname . '/view.php', array('id'=>$this->id))
2413 : null;
2417 * Creates a cm_info object from a database record (also accepts cm_info
2418 * in which case it is just returned unchanged).
2420 * @param stdClass|cm_info|null|bool $cm Stdclass or cm_info (or null or false)
2421 * @param int $userid Optional userid (default to current)
2422 * @return cm_info|null Object as cm_info, or null if input was null/false
2424 public static function create($cm, $userid = 0) {
2425 // Null, false, etc. gets passed through as null.
2426 if (!$cm) {
2427 return null;
2429 // If it is already a cm_info object, just return it.
2430 if ($cm instanceof cm_info) {
2431 return $cm;
2433 // Otherwise load modinfo.
2434 if (empty($cm->id) || empty($cm->course)) {
2435 throw new coding_exception('$cm must contain ->id and ->course');
2437 $modinfo = get_fast_modinfo($cm->course, $userid);
2438 return $modinfo->get_cm($cm->id);
2442 * If dynamic data for this course-module is not yet available, gets it.
2444 * This function is automatically called when requesting any course_modinfo property
2445 * that can be modified by modules (have a set_xxx method).
2447 * Dynamic data is data which does not come directly from the cache but is calculated at
2448 * runtime based on the current user. Primarily this concerns whether the user can access
2449 * the module or not.
2451 * As part of this function, the module's _cm_info_dynamic function from its lib.php will
2452 * be called (if it exists). Make sure that the functions that are called here do not use
2453 * any getter magic method from cm_info.
2454 * @return void
2456 private function obtain_dynamic_data() {
2457 global $CFG;
2458 $userid = $this->modinfo->get_user_id();
2459 if ($this->state >= self::STATE_BUILDING_DYNAMIC || $userid == -1) {
2460 return;
2462 $this->state = self::STATE_BUILDING_DYNAMIC;
2464 if (!empty($CFG->enableavailability)) {
2465 // Get availability information.
2466 $ci = new \core_availability\info_module($this);
2468 // Note that the modinfo currently available only includes minimal details (basic data)
2469 // but we know that this function does not need anything more than basic data.
2470 $this->available = $ci->is_available($this->availableinfo, true,
2471 $userid, $this->modinfo);
2472 } else {
2473 $this->available = true;
2476 // Check parent section.
2477 if ($this->available) {
2478 $parentsection = $this->modinfo->get_section_info($this->sectionnum);
2479 if (!$parentsection->get_available()) {
2480 // Do not store info from section here, as that is already
2481 // presented from the section (if appropriate) - just change
2482 // the flag
2483 $this->available = false;
2487 // Update visible state for current user.
2488 $this->update_user_visible();
2490 // Let module make dynamic changes at this point
2491 $this->call_mod_function('cm_info_dynamic');
2492 $this->state = self::STATE_DYNAMIC;
2496 * Getter method for property $uservisible, ensures that dynamic data is retrieved.
2498 * This method is normally called by the property ->uservisible, but can be called directly if
2499 * there is a case when it might be called recursively (you can't call property values
2500 * recursively).
2502 * @return bool
2504 public function get_user_visible() {
2505 $this->obtain_dynamic_data();
2506 return $this->uservisible;
2510 * Returns whether this module is visible to the current user on course page
2512 * Activity may be visible on the course page but not available, for example
2513 * when it is hidden conditionally but the condition information is displayed.
2515 * @return bool
2517 public function is_visible_on_course_page() {
2518 $this->obtain_dynamic_data();
2519 return $this->uservisibleoncoursepage;
2523 * Whether this module is available but hidden from course page
2525 * "Stealth" modules are the ones that are not shown on course page but available by following url.
2526 * They are normally also displayed in grade reports and other reports.
2527 * Module will be stealth either if visibleoncoursepage=0 or it is a visible module inside the hidden
2528 * section.
2530 * @return bool
2532 public function is_stealth() {
2533 return !$this->visibleoncoursepage ||
2534 ($this->visible && ($section = $this->get_section_info()) && !$section->visible);
2538 * Getter method for property $available, ensures that dynamic data is retrieved
2539 * @return bool
2541 private function get_available() {
2542 $this->obtain_dynamic_data();
2543 return $this->available;
2547 * This method can not be used anymore.
2549 * @see \core_availability\info_module::filter_user_list()
2550 * @deprecated Since Moodle 2.8
2552 private function get_deprecated_group_members_only() {
2553 throw new coding_exception('$cm->groupmembersonly can not be used anymore. ' .
2554 'If used to restrict a list of enrolled users to only those who can ' .
2555 'access the module, consider \core_availability\info_module::filter_user_list.');
2559 * Getter method for property $availableinfo, ensures that dynamic data is retrieved
2561 * @return string Available info (HTML)
2563 private function get_available_info() {
2564 $this->obtain_dynamic_data();
2565 return $this->availableinfo;
2569 * Works out whether activity is available to the current user
2571 * If the activity is unavailable, additional checks are required to determine if its hidden or greyed out
2573 * @return void
2575 private function update_user_visible() {
2576 $userid = $this->modinfo->get_user_id();
2577 if ($userid == -1) {
2578 return null;
2580 $this->uservisible = true;
2582 // If the module is being deleted, set the uservisible state to false and return.
2583 if ($this->deletioninprogress) {
2584 $this->uservisible = false;
2585 return null;
2588 // If the user cannot access the activity set the uservisible flag to false.
2589 // Additional checks are required to determine whether the activity is entirely hidden or just greyed out.
2590 if ((!$this->visible && !has_capability('moodle/course:viewhiddenactivities', $this->get_context(), $userid)) ||
2591 (!$this->get_available() &&
2592 !has_capability('moodle/course:ignoreavailabilityrestrictions', $this->get_context(), $userid))) {
2594 $this->uservisible = false;
2597 // Check group membership.
2598 if ($this->is_user_access_restricted_by_capability()) {
2600 $this->uservisible = false;
2601 // Ensure activity is completely hidden from the user.
2602 $this->availableinfo = '';
2605 $this->uservisibleoncoursepage = $this->uservisible &&
2606 ($this->visibleoncoursepage ||
2607 has_capability('moodle/course:manageactivities', $this->get_context(), $userid) ||
2608 has_capability('moodle/course:activityvisibility', $this->get_context(), $userid));
2609 // Activity that is not available, not hidden from course page and has availability
2610 // info is actually visible on the course page (with availability info and without a link).
2611 if (!$this->uservisible && $this->visibleoncoursepage && $this->availableinfo) {
2612 $this->uservisibleoncoursepage = true;
2617 * This method has been deprecated and should not be used.
2619 * @see $uservisible
2620 * @deprecated Since Moodle 2.8
2622 public function is_user_access_restricted_by_group() {
2623 throw new coding_exception('cm_info::is_user_access_restricted_by_group() can not be used any more.' .
2624 ' Use $cm->uservisible to decide whether the current user can access an activity.');
2628 * Checks whether mod/...:view capability restricts the current user's access.
2630 * @return bool True if the user access is restricted.
2632 public function is_user_access_restricted_by_capability() {
2633 $userid = $this->modinfo->get_user_id();
2634 if ($userid == -1) {
2635 return null;
2637 $capability = 'mod/' . $this->modname . ':view';
2638 $capabilityinfo = get_capability_info($capability);
2639 if (!$capabilityinfo) {
2640 // Capability does not exist, no one is prevented from seeing the activity.
2641 return false;
2644 // You are blocked if you don't have the capability.
2645 return !has_capability($capability, $this->get_context(), $userid);
2649 * Checks whether the module's conditional access settings mean that the
2650 * user cannot see the activity at all
2652 * @deprecated since 2.7 MDL-44070
2654 public function is_user_access_restricted_by_conditional_access() {
2655 throw new coding_exception('cm_info::is_user_access_restricted_by_conditional_access() ' .
2656 'can not be used any more; this function is not needed (use $cm->uservisible ' .
2657 'and $cm->availableinfo to decide whether it should be available ' .
2658 'or appear)');
2662 * Calls a module function (if exists), passing in one parameter: this object.
2663 * @param string $type Name of function e.g. if this is 'grooblezorb' and the modname is
2664 * 'forum' then it will try to call 'mod_forum_grooblezorb' or 'forum_grooblezorb'
2665 * @return void
2667 private function call_mod_function($type) {
2668 global $CFG;
2669 $libfile = $CFG->dirroot . '/mod/' . $this->modname . '/lib.php';
2670 if (file_exists($libfile)) {
2671 include_once($libfile);
2672 $function = 'mod_' . $this->modname . '_' . $type;
2673 if (function_exists($function)) {
2674 $function($this);
2675 } else {
2676 $function = $this->modname . '_' . $type;
2677 if (function_exists($function)) {
2678 $function($this);
2685 * If view data for this course-module is not yet available, obtains it.
2687 * This function is automatically called if any of the functions (marked) which require
2688 * view data are called.
2690 * View data is data which is needed only for displaying the course main page (& any similar
2691 * functionality on other pages) but is not needed in general. Obtaining view data may have
2692 * a performance cost.
2694 * As part of this function, the module's _cm_info_view function from its lib.php will
2695 * be called (if it exists).
2696 * @return void
2698 private function obtain_view_data() {
2699 if ($this->state >= self::STATE_BUILDING_VIEW || $this->modinfo->get_user_id() == -1) {
2700 return;
2702 $this->obtain_dynamic_data();
2703 $this->state = self::STATE_BUILDING_VIEW;
2705 // Let module make changes at this point
2706 $this->call_mod_function('cm_info_view');
2707 $this->state = self::STATE_VIEW;
2713 * Returns reference to full info about modules in course (including visibility).
2714 * Cached and as fast as possible (0 or 1 db query).
2716 * use get_fast_modinfo($courseid, 0, true) to reset the static cache for particular course
2717 * use get_fast_modinfo(0, 0, true) to reset the static cache for all courses
2719 * use rebuild_course_cache($courseid, true) to reset the application AND static cache
2720 * for particular course when it's contents has changed
2722 * @param int|stdClass $courseorid object from DB table 'course' (must have field 'id'
2723 * and recommended to have field 'cacherev') or just a course id. Just course id
2724 * is enough when calling get_fast_modinfo() for current course or site or when
2725 * calling for any other course for the second time.
2726 * @param int $userid User id to populate 'availble' and 'uservisible' attributes of modules and sections.
2727 * Set to 0 for current user (default). Set to -1 to avoid calculation of dynamic user-depended data.
2728 * @param bool $resetonly whether we want to get modinfo or just reset the cache
2729 * @return course_modinfo|null Module information for course, or null if resetting
2730 * @throws moodle_exception when course is not found (nothing is thrown if resetting)
2732 function get_fast_modinfo($courseorid, $userid = 0, $resetonly = false) {
2733 // compartibility with syntax prior to 2.4:
2734 if ($courseorid === 'reset') {
2735 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);
2736 $courseorid = 0;
2737 $resetonly = true;
2740 // Function get_fast_modinfo() can never be called during upgrade unless it is used for clearing cache only.
2741 if (!$resetonly) {
2742 upgrade_ensure_not_running();
2745 // Function is called with $reset = true
2746 if ($resetonly) {
2747 course_modinfo::clear_instance_cache($courseorid);
2748 return null;
2751 // Function is called with $reset = false, retrieve modinfo
2752 return course_modinfo::instance($courseorid, $userid);
2756 * Efficiently retrieves the $course (stdclass) and $cm (cm_info) objects, given
2757 * a cmid. If module name is also provided, it will ensure the cm is of that type.
2759 * Usage:
2760 * list($course, $cm) = get_course_and_cm_from_cmid($cmid, 'forum');
2762 * Using this method has a performance advantage because it works by loading
2763 * modinfo for the course - which will then be cached and it is needed later
2764 * in most requests. It also guarantees that the $cm object is a cm_info and
2765 * not a stdclass.
2767 * The $course object can be supplied if already known and will speed
2768 * up this function - although it is more efficient to use this function to
2769 * get the course if you are starting from a cmid.
2771 * To avoid security problems and obscure bugs, you should always specify
2772 * $modulename if the cmid value came from user input.
2774 * By default this obtains information (for example, whether user can access
2775 * the activity) for current user, but you can specify a userid if required.
2777 * @param stdClass|int $cmorid Id of course-module, or database object
2778 * @param string $modulename Optional modulename (improves security)
2779 * @param stdClass|int $courseorid Optional course object if already loaded
2780 * @param int $userid Optional userid (default = current)
2781 * @return array Array with 2 elements $course and $cm
2782 * @throws moodle_exception If the item doesn't exist or is of wrong module name
2784 function get_course_and_cm_from_cmid($cmorid, $modulename = '', $courseorid = 0, $userid = 0) {
2785 global $DB;
2786 if (is_object($cmorid)) {
2787 $cmid = $cmorid->id;
2788 if (isset($cmorid->course)) {
2789 $courseid = (int)$cmorid->course;
2790 } else {
2791 $courseid = 0;
2793 } else {
2794 $cmid = (int)$cmorid;
2795 $courseid = 0;
2798 // Validate module name if supplied.
2799 if ($modulename && !core_component::is_valid_plugin_name('mod', $modulename)) {
2800 throw new coding_exception('Invalid modulename parameter');
2803 // Get course from last parameter if supplied.
2804 $course = null;
2805 if (is_object($courseorid)) {
2806 $course = $courseorid;
2807 } else if ($courseorid) {
2808 $courseid = (int)$courseorid;
2811 if (!$course) {
2812 if ($courseid) {
2813 // If course ID is known, get it using normal function.
2814 $course = get_course($courseid);
2815 } else {
2816 // Get course record in a single query based on cmid.
2817 $course = $DB->get_record_sql("
2818 SELECT c.*
2819 FROM {course_modules} cm
2820 JOIN {course} c ON c.id = cm.course
2821 WHERE cm.id = ?", array($cmid), MUST_EXIST);
2825 // Get cm from get_fast_modinfo.
2826 $modinfo = get_fast_modinfo($course, $userid);
2827 $cm = $modinfo->get_cm($cmid);
2828 if ($modulename && $cm->modname !== $modulename) {
2829 throw new moodle_exception('invalidcoursemoduleid', 'error', '', $cmid);
2831 return array($course, $cm);
2835 * Efficiently retrieves the $course (stdclass) and $cm (cm_info) objects, given
2836 * an instance id or record and module name.
2838 * Usage:
2839 * list($course, $cm) = get_course_and_cm_from_instance($forum, 'forum');
2841 * Using this method has a performance advantage because it works by loading
2842 * modinfo for the course - which will then be cached and it is needed later
2843 * in most requests. It also guarantees that the $cm object is a cm_info and
2844 * not a stdclass.
2846 * The $course object can be supplied if already known and will speed
2847 * up this function - although it is more efficient to use this function to
2848 * get the course if you are starting from an instance id.
2850 * By default this obtains information (for example, whether user can access
2851 * the activity) for current user, but you can specify a userid if required.
2853 * @param stdclass|int $instanceorid Id of module instance, or database object
2854 * @param string $modulename Modulename (required)
2855 * @param stdClass|int $courseorid Optional course object if already loaded
2856 * @param int $userid Optional userid (default = current)
2857 * @return array Array with 2 elements $course and $cm
2858 * @throws moodle_exception If the item doesn't exist or is of wrong module name
2860 function get_course_and_cm_from_instance($instanceorid, $modulename, $courseorid = 0, $userid = 0) {
2861 global $DB;
2863 // Get data from parameter.
2864 if (is_object($instanceorid)) {
2865 $instanceid = $instanceorid->id;
2866 if (isset($instanceorid->course)) {
2867 $courseid = (int)$instanceorid->course;
2868 } else {
2869 $courseid = 0;
2871 } else {
2872 $instanceid = (int)$instanceorid;
2873 $courseid = 0;
2876 // Get course from last parameter if supplied.
2877 $course = null;
2878 if (is_object($courseorid)) {
2879 $course = $courseorid;
2880 } else if ($courseorid) {
2881 $courseid = (int)$courseorid;
2884 // Validate module name if supplied.
2885 if (!core_component::is_valid_plugin_name('mod', $modulename)) {
2886 throw new coding_exception('Invalid modulename parameter');
2889 if (!$course) {
2890 if ($courseid) {
2891 // If course ID is known, get it using normal function.
2892 $course = get_course($courseid);
2893 } else {
2894 // Get course record in a single query based on instance id.
2895 $pagetable = '{' . $modulename . '}';
2896 $course = $DB->get_record_sql("
2897 SELECT c.*
2898 FROM $pagetable instance
2899 JOIN {course} c ON c.id = instance.course
2900 WHERE instance.id = ?", array($instanceid), MUST_EXIST);
2904 // Get cm from get_fast_modinfo.
2905 $modinfo = get_fast_modinfo($course, $userid);
2906 $instances = $modinfo->get_instances_of($modulename);
2907 if (!array_key_exists($instanceid, $instances)) {
2908 throw new moodle_exception('invalidmoduleid', 'error', '', $instanceid);
2910 return array($course, $instances[$instanceid]);
2915 * Rebuilds or resets the cached list of course activities stored in MUC.
2917 * rebuild_course_cache() must NEVER be called from lib/db/upgrade.php.
2918 * At the same time course cache may ONLY be cleared using this function in
2919 * upgrade scripts of plugins.
2921 * During the bulk operations if it is necessary to reset cache of multiple
2922 * courses it is enough to call {@link increment_revision_number()} for the
2923 * table 'course' and field 'cacherev' specifying affected courses in select.
2925 * Cached course information is stored in MUC core/coursemodinfo and is
2926 * validated with the DB field {course}.cacherev
2928 * @global moodle_database $DB
2929 * @param int $courseid id of course to rebuild, empty means all
2930 * @param boolean $clearonly only clear the cache, gets rebuild automatically on the fly.
2931 * Recommended to set to true to avoid unnecessary multiple rebuilding.
2932 * @param boolean $partialrebuild will not delete the whole cache when it's true.
2933 * use purge_module_cache() or purge_section_cache() must be
2934 * called before when partialrebuild is true.
2935 * use purge_module_cache() to invalidate mod cache.
2936 * use purge_section_cache() to invalidate section cache.
2938 * @return void
2939 * @throws coding_exception
2941 function rebuild_course_cache(int $courseid = 0, bool $clearonly = false, bool $partialrebuild = false): void {
2942 global $COURSE, $SITE, $DB;
2944 if ($courseid == 0 and $partialrebuild) {
2945 throw new coding_exception('partialrebuild only works when a valid course id is provided.');
2948 // Function rebuild_course_cache() can not be called during upgrade unless it's clear only.
2949 if (!$clearonly && !upgrade_ensure_not_running(true)) {
2950 $clearonly = true;
2953 // Destroy navigation caches
2954 navigation_cache::destroy_volatile_caches();
2956 core_courseformat\base::reset_course_cache($courseid);
2958 $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
2959 if (empty($courseid)) {
2960 // Clearing caches for all courses.
2961 increment_revision_number('course', 'cacherev', '');
2962 if (!$partialrebuild) {
2963 $cachecoursemodinfo->purge();
2965 // Clear memory static cache.
2966 course_modinfo::clear_instance_cache();
2967 // Update global values too.
2968 $sitecacherev = $DB->get_field('course', 'cacherev', array('id' => SITEID));
2969 $SITE->cachrev = $sitecacherev;
2970 if ($COURSE->id == SITEID) {
2971 $COURSE->cacherev = $sitecacherev;
2972 } else {
2973 $COURSE->cacherev = $DB->get_field('course', 'cacherev', array('id' => $COURSE->id));
2975 } else {
2976 // Clearing cache for one course, make sure it is deleted from user request cache as well.
2977 // Because this is a versioned cache, there is no need to actually delete the cache item,
2978 // only increase the required version number.
2979 increment_revision_number('course', 'cacherev', 'id = :id', array('id' => $courseid));
2980 $cacherev = $DB->get_field('course', 'cacherev', ['id' => $courseid]);
2981 // Clear memory static cache.
2982 course_modinfo::clear_instance_cache($courseid, $cacherev);
2983 // Update global values too.
2984 if ($courseid == $COURSE->id || $courseid == $SITE->id) {
2985 if ($courseid == $COURSE->id) {
2986 $COURSE->cacherev = $cacherev;
2988 if ($courseid == $SITE->id) {
2989 $SITE->cacherev = $cacherev;
2994 if ($clearonly) {
2995 return;
2998 if ($courseid) {
2999 $select = array('id'=>$courseid);
3000 } else {
3001 $select = array();
3002 core_php_time_limit::raise(); // this could take a while! MDL-10954
3005 $fields = 'id,' . join(',', course_modinfo::$cachedfields);
3006 $sort = '';
3007 $rs = $DB->get_recordset("course", $select, $sort, $fields);
3009 // Rebuild cache for each course.
3010 foreach ($rs as $course) {
3011 course_modinfo::build_course_cache($course, $partialrebuild);
3013 $rs->close();
3018 * Class that is the return value for the _get_coursemodule_info module API function.
3020 * Note: For backward compatibility, you can also return a stdclass object from that function.
3021 * The difference is that the stdclass object may contain an 'extra' field (deprecated,
3022 * use extraclasses and onclick instead). The stdclass object may not contain
3023 * the new fields defined here (content, extraclasses, customdata).
3025 class cached_cm_info {
3027 * Name (text of link) for this activity; Leave unset to accept default name
3028 * @var string
3030 public $name;
3033 * Name of icon for this activity. Normally, this should be used together with $iconcomponent
3034 * to define the icon, as per image_url function.
3035 * For backward compatibility, if this value is of the form 'mod/forum/icon' then an icon
3036 * within that module will be used.
3037 * @see cm_info::get_icon_url()
3038 * @see renderer_base::image_url()
3039 * @var string
3041 public $icon;
3044 * Component for icon for this activity, as per image_url; leave blank to use default 'moodle'
3045 * component
3046 * @see renderer_base::image_url()
3047 * @var string
3049 public $iconcomponent;
3052 * HTML content to be displayed on the main page below the link (if any) for this course-module
3053 * @var string
3055 public $content;
3058 * Custom data to be stored in modinfo for this activity; useful if there are cases when
3059 * internal information for this activity type needs to be accessible from elsewhere on the
3060 * course without making database queries. May be of any type but should be short.
3061 * @var mixed
3063 public $customdata;
3066 * Extra CSS class or classes to be added when this activity is displayed on the main page;
3067 * space-separated string
3068 * @var string
3070 public $extraclasses;
3073 * External URL image to be used by activity as icon, useful for some external-tool modules
3074 * like lti. If set, takes precedence over $icon and $iconcomponent
3075 * @var $moodle_url
3077 public $iconurl;
3080 * Content of onclick JavaScript; escaped HTML to be inserted as attribute value
3081 * @var string
3083 public $onclick;
3088 * Data about a single section on a course. This contains the fields from the
3089 * course_sections table, plus additional data when required.
3091 * @property-read int $id Section ID - from course_sections table
3092 * @property-read int $course Course ID - from course_sections table
3093 * @property-read int $sectionnum Section number - from course_sections table
3094 * @property-read string $name Section name if specified - from course_sections table
3095 * @property-read int $visible Section visibility (1 = visible) - from course_sections table
3096 * @property-read string $summary Section summary text if specified - from course_sections table
3097 * @property-read int $summaryformat Section summary text format (FORMAT_xx constant) - from course_sections table
3098 * @property-read string $availability Availability information as JSON string - from course_sections table
3099 * @property-read string|null $component Optional section delegate component - from course_sections table
3100 * @property-read int|null $itemid Optional section delegate item id - from course_sections table
3101 * @property-read array $conditionscompletion Availability conditions for this section based on the completion of
3102 * course-modules (array from course-module id to required completion state
3103 * for that module) - from cached data in sectioncache field
3104 * @property-read array $conditionsgrade Availability conditions for this section based on course grades (array from
3105 * grade item id to object with ->min, ->max fields) - from cached data in
3106 * sectioncache field
3107 * @property-read array $conditionsfield Availability conditions for this section based on user fields
3108 * @property-read bool $available True if this section is available to the given user i.e. if all availability conditions
3109 * are met - obtained dynamically
3110 * @property-read string $availableinfo If section is not available to some users, this string gives information about
3111 * availability which can be displayed to students and/or staff (e.g. 'Available from 3 January 2010')
3112 * for display on main page - obtained dynamically
3113 * @property-read bool $uservisible True if this section is available to the given user (for example, if current user
3114 * has viewhiddensections capability, they can access the section even if it is not
3115 * visible or not available, so this would be true in that case) - obtained dynamically
3116 * @property-read string $sequence Comma-separated list of all modules in the section. Note, this field may not exactly
3117 * match course_sections.sequence if later has references to non-existing modules or not modules of not available module types.
3118 * @property-read course_modinfo $modinfo
3120 class section_info implements IteratorAggregate {
3122 * Section ID - from course_sections table
3123 * @var int
3125 private $_id;
3128 * Section number - from course_sections table
3129 * @var int
3131 private $_sectionnum;
3134 * Section name if specified - from course_sections table
3135 * @var string
3137 private $_name;
3140 * Section visibility (1 = visible) - from course_sections table
3141 * @var int
3143 private $_visible;
3146 * Section summary text if specified - from course_sections table
3147 * @var string
3149 private $_summary;
3152 * Section summary text format (FORMAT_xx constant) - from course_sections table
3153 * @var int
3155 private $_summaryformat;
3158 * Availability information as JSON string - from course_sections table
3159 * @var string
3161 private $_availability;
3164 * @var string|null the delegated component if any.
3166 private ?string $_component = null;
3169 * @var int|null the delegated instance item id if any.
3171 private ?int $_itemid = null;
3174 * @var sectiondelegate|null Section delegate instance if any.
3176 private ?sectiondelegate $_delegateinstance = null;
3179 * Availability conditions for this section based on the completion of
3180 * course-modules (array from course-module id to required completion state
3181 * for that module) - from cached data in sectioncache field
3182 * @var array
3184 private $_conditionscompletion;
3187 * Availability conditions for this section based on course grades (array from
3188 * grade item id to object with ->min, ->max fields) - from cached data in
3189 * sectioncache field
3190 * @var array
3192 private $_conditionsgrade;
3195 * Availability conditions for this section based on user fields
3196 * @var array
3198 private $_conditionsfield;
3201 * True if this section is available to students i.e. if all availability conditions
3202 * are met - obtained dynamically on request, see function {@link section_info::get_available()}
3203 * @var bool|null
3205 private $_available;
3208 * If section is not available to some users, this string gives information about
3209 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
3210 * January 2010') for display on main page - obtained dynamically on request, see
3211 * function {@link section_info::get_availableinfo()}
3212 * @var string
3214 private $_availableinfo;
3217 * True if this section is available to the CURRENT user (for example, if current user
3218 * has viewhiddensections capability, they can access the section even if it is not
3219 * visible or not available, so this would be true in that case) - obtained dynamically
3220 * on request, see function {@link section_info::get_uservisible()}
3221 * @var bool|null
3223 private $_uservisible;
3226 * Default values for sectioncache fields; if a field has this value, it won't
3227 * be stored in the sectioncache cache, to save space. Checks are done by ===
3228 * which means values must all be strings.
3229 * @var array
3231 private static $sectioncachedefaults = array(
3232 'name' => null,
3233 'summary' => '',
3234 'summaryformat' => '1', // FORMAT_HTML, but must be a string
3235 'visible' => '1',
3236 'availability' => null,
3237 'component' => null,
3238 'itemid' => null,
3242 * Stores format options that have been cached when building 'coursecache'
3243 * When the format option is requested we look first if it has been cached
3244 * @var array
3246 private $cachedformatoptions = array();
3249 * Stores the list of all possible section options defined in each used course format.
3250 * @var array
3252 static private $sectionformatoptions = array();
3255 * Stores the modinfo object passed in constructor, may be used when requesting
3256 * dynamically obtained attributes such as available, availableinfo, uservisible.
3257 * Also used to retrun information about current course or user.
3258 * @var course_modinfo
3260 private $modinfo;
3263 * True if has activities, otherwise false.
3264 * @var bool
3266 public $hasactivites;
3269 * List of class read-only properties' getter methods.
3270 * Used by magic functions __get(), __isset(), __empty()
3271 * @var array
3273 private static $standardproperties = [
3274 'section' => 'get_section_number',
3278 * Constructs object from database information plus extra required data.
3279 * @param object $data Array entry from cached sectioncache
3280 * @param int $number Section number (array key)
3281 * @param mixed $notused1 argument not used (informaion is available in $modinfo)
3282 * @param mixed $notused2 argument not used (informaion is available in $modinfo)
3283 * @param course_modinfo $modinfo Owner (needed for checking availability)
3284 * @param mixed $notused3 argument not used (informaion is available in $modinfo)
3286 public function __construct($data, $number, $notused1, $notused2, $modinfo, $notused3) {
3287 global $CFG;
3288 require_once($CFG->dirroot.'/course/lib.php');
3290 // Data that is always present
3291 $this->_id = $data->id;
3293 $defaults = self::$sectioncachedefaults +
3294 array('conditionscompletion' => array(),
3295 'conditionsgrade' => array(),
3296 'conditionsfield' => array());
3298 // Data that may use default values to save cache size
3299 foreach ($defaults as $field => $value) {
3300 if (isset($data->{$field})) {
3301 $this->{'_'.$field} = $data->{$field};
3302 } else {
3303 $this->{'_'.$field} = $value;
3307 // Other data from constructor arguments.
3308 $this->_sectionnum = $number;
3309 $this->modinfo = $modinfo;
3311 // Cached course format data.
3312 $course = $modinfo->get_course();
3313 if (!isset(self::$sectionformatoptions[$course->format])) {
3314 // Store list of section format options defined in each used course format.
3315 // They do not depend on particular course but only on its format.
3316 self::$sectionformatoptions[$course->format] =
3317 course_get_format($course)->section_format_options();
3319 foreach (self::$sectionformatoptions[$course->format] as $field => $option) {
3320 if (!empty($option['cache'])) {
3321 if (isset($data->{$field})) {
3322 $this->cachedformatoptions[$field] = $data->{$field};
3323 } else if (array_key_exists('cachedefault', $option)) {
3324 $this->cachedformatoptions[$field] = $option['cachedefault'];
3331 * Magic method to check if the property is set
3333 * @param string $name name of the property
3334 * @return bool
3336 public function __isset($name) {
3337 if (isset(self::$standardproperties[$name])) {
3338 $value = $this->__get($name);
3339 return isset($value);
3341 if (method_exists($this, 'get_'.$name) ||
3342 property_exists($this, '_'.$name) ||
3343 array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
3344 $value = $this->__get($name);
3345 return isset($value);
3347 return false;
3351 * Magic method to check if the property is empty
3353 * @param string $name name of the property
3354 * @return bool
3356 public function __empty($name) {
3357 if (isset(self::$standardproperties[$name])) {
3358 $value = $this->__get($name);
3359 return empty($value);
3361 if (method_exists($this, 'get_'.$name) ||
3362 property_exists($this, '_'.$name) ||
3363 array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
3364 $value = $this->__get($name);
3365 return empty($value);
3367 return true;
3371 * Magic method to retrieve the property, this is either basic section property
3372 * or availability information or additional properties added by course format
3374 * @param string $name name of the property
3375 * @return mixed
3377 public function __get($name) {
3378 if (isset(self::$standardproperties[$name])) {
3379 if ($method = self::$standardproperties[$name]) {
3380 return $this->$method();
3383 if (method_exists($this, 'get_'.$name)) {
3384 return $this->{'get_'.$name}();
3386 if (property_exists($this, '_'.$name)) {
3387 return $this->{'_'.$name};
3389 if (array_key_exists($name, $this->cachedformatoptions)) {
3390 return $this->cachedformatoptions[$name];
3392 // precheck if the option is defined in format to avoid unnecessary DB queries in get_format_options()
3393 if (array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
3394 $formatoptions = course_get_format($this->modinfo->get_course())->get_format_options($this);
3395 return $formatoptions[$name];
3397 debugging('Invalid section_info property accessed! '.$name);
3398 return null;
3402 * Finds whether this section is available at the moment for the current user.
3404 * The value can be accessed publicly as $sectioninfo->available, but can be called directly if there
3405 * is a case when it might be called recursively (you can't call property values recursively).
3407 * @return bool
3409 public function get_available() {
3410 global $CFG;
3411 $userid = $this->modinfo->get_user_id();
3412 if ($this->_available !== null || $userid == -1) {
3413 // Has already been calculated or does not need calculation.
3414 return $this->_available;
3416 $this->_available = true;
3417 $this->_availableinfo = '';
3418 if (!empty($CFG->enableavailability)) {
3419 // Get availability information.
3420 $ci = new \core_availability\info_section($this);
3421 $this->_available = $ci->is_available($this->_availableinfo, true,
3422 $userid, $this->modinfo);
3424 // Execute the hook from the course format that may override the available/availableinfo properties.
3425 $currentavailable = $this->_available;
3426 course_get_format($this->modinfo->get_course())->
3427 section_get_available_hook($this, $this->_available, $this->_availableinfo);
3428 if (!$currentavailable && $this->_available) {
3429 debugging('section_get_available_hook() can not make unavailable section available', DEBUG_DEVELOPER);
3430 $this->_available = $currentavailable;
3432 return $this->_available;
3436 * Returns the availability text shown next to the section on course page.
3438 * @return string
3440 private function get_availableinfo() {
3441 // Calling get_available() will also fill the availableinfo property
3442 // (or leave it null if there is no userid).
3443 $this->get_available();
3444 return $this->_availableinfo;
3448 * Implementation of IteratorAggregate::getIterator(), allows to cycle through properties
3449 * and use {@link convert_to_array()}
3451 * @return ArrayIterator
3453 public function getIterator(): Traversable {
3454 $ret = array();
3455 foreach (get_object_vars($this) as $key => $value) {
3456 if (substr($key, 0, 1) == '_') {
3457 if (method_exists($this, 'get'.$key)) {
3458 $ret[substr($key, 1)] = $this->{'get'.$key}();
3459 } else {
3460 $ret[substr($key, 1)] = $this->$key;
3464 $ret['sequence'] = $this->get_sequence();
3465 $ret['course'] = $this->get_course();
3466 $ret = array_merge($ret, course_get_format($this->modinfo->get_course())->get_format_options($this));
3467 return new ArrayIterator($ret);
3471 * Works out whether activity is visible *for current user* - if this is false, they
3472 * aren't allowed to access it.
3474 * @return bool
3476 private function get_uservisible() {
3477 $userid = $this->modinfo->get_user_id();
3478 if ($this->_uservisible !== null || $userid == -1) {
3479 // Has already been calculated or does not need calculation.
3480 return $this->_uservisible;
3482 $this->_uservisible = true;
3483 if (!$this->_visible || !$this->get_available()) {
3484 $coursecontext = context_course::instance($this->get_course());
3485 if (!$this->_visible && !has_capability('moodle/course:viewhiddensections', $coursecontext, $userid) ||
3486 (!$this->get_available() &&
3487 !has_capability('moodle/course:ignoreavailabilityrestrictions', $coursecontext, $userid))) {
3489 $this->_uservisible = false;
3492 return $this->_uservisible;
3496 * Restores the course_sections.sequence value
3498 * @return string
3500 private function get_sequence() {
3501 if (!empty($this->modinfo->sections[$this->_sectionnum])) {
3502 return implode(',', $this->modinfo->sections[$this->_sectionnum]);
3503 } else {
3504 return '';
3509 * Returns course ID - from course_sections table
3511 * @return int
3513 private function get_course() {
3514 return $this->modinfo->get_course_id();
3518 * Modinfo object
3520 * @return course_modinfo
3522 private function get_modinfo() {
3523 return $this->modinfo;
3527 * Returns section number.
3529 * This method is called by the property ->section.
3531 * @return int
3533 private function get_section_number(): int {
3534 return $this->sectionnum;
3538 * Get the delegate component instance.
3540 public function get_component_instance(): ?sectiondelegate {
3541 if (empty($this->_component)) {
3542 return null;
3544 if ($this->_delegateinstance !== null) {
3545 return $this->_delegateinstance;
3547 $this->_delegateinstance = sectiondelegate::instance($this);
3548 return $this->_delegateinstance;
3552 * Returns true if this section is a delegate to a component.
3553 * @return bool
3555 public function is_delegated(): bool {
3556 return !empty($this->_component);
3560 * Prepares section data for inclusion in sectioncache cache, removing items
3561 * that are set to defaults, and adding availability data if required.
3563 * Called by build_section_cache in course_modinfo only; do not use otherwise.
3564 * @param object $section Raw section data object
3566 public static function convert_for_section_cache($section) {
3567 global $CFG;
3569 // Course id stored in course table
3570 unset($section->course);
3571 // Sequence stored implicity in modinfo $sections array
3572 unset($section->sequence);
3574 // Remove default data
3575 foreach (self::$sectioncachedefaults as $field => $value) {
3576 // Exact compare as strings to avoid problems if some strings are set
3577 // to "0" etc.
3578 if (isset($section->{$field}) && $section->{$field} === $value) {
3579 unset($section->{$field});