MDL-78324 core: Convert core/tag to esm
[moodle.git] / lib / modinfolib.php
blob834c381668c35a314340bae9fdcc22f29773d7e9
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;
37 /**
38 * Information about a course that is cached in the course table 'modinfo' field (and then in
39 * memory) in order to reduce the need for other database queries.
41 * This includes information about the course-modules and the sections on the course. It can also
42 * include dynamic data that has been updated for the current user.
44 * Use {@link get_fast_modinfo()} to retrieve the instance of the object for particular course
45 * and particular user.
47 * @property-read int $courseid Course ID
48 * @property-read int $userid User ID
49 * @property-read array $sections Array from section number (e.g. 0) to array of course-module IDs in that
50 * section; this only includes sections that contain at least one course-module
51 * @property-read cm_info[] $cms Array from course-module instance to cm_info object within this course, in
52 * order of appearance
53 * @property-read cm_info[][] $instances Array from string (modname) => int (instance id) => cm_info object
54 * @property-read array $groups Groups that the current user belongs to. Calculated on the first request.
55 * Is an array of grouping id => array of group id => group id. Includes grouping id 0 for 'all groups'
57 class course_modinfo {
58 /** @var int Maximum time the course cache building lock can be held */
59 const COURSE_CACHE_LOCK_EXPIRY = 180;
61 /** @var int Time to wait for the course cache building lock before throwing an exception */
62 const COURSE_CACHE_LOCK_WAIT = 60;
64 /**
65 * List of fields from DB table 'course' that are cached in MUC and are always present in course_modinfo::$course
66 * @var array
68 public static $cachedfields = array('shortname', 'fullname', 'format',
69 'enablecompletion', 'groupmode', 'groupmodeforce', 'cacherev');
71 /**
72 * For convenience we store the course object here as it is needed in other parts of code
73 * @var stdClass
75 private $course;
77 /**
78 * Array of section data from cache
79 * @var section_info[]
81 private $sectioninfo;
83 /**
84 * User ID
85 * @var int
87 private $userid;
89 /**
90 * Array from int (section num, e.g. 0) => array of int (course-module id); this list only
91 * includes sections that actually contain at least one course-module
92 * @var array
94 private $sections;
96 /**
97 * Array from section id => section num.
98 * @var array
100 private $sectionids;
103 * Array from int (cm id) => cm_info object
104 * @var cm_info[]
106 private $cms;
109 * Array from string (modname) => int (instance id) => cm_info object
110 * @var cm_info[][]
112 private $instances;
115 * Groups that the current user belongs to. This value is calculated on first
116 * request to the property or function.
117 * When set, it is an array of grouping id => array of group id => group id.
118 * Includes grouping id 0 for 'all groups'.
119 * @var int[][]
121 private $groups;
124 * List of class read-only properties and their getter methods.
125 * Used by magic functions __get(), __isset(), __empty()
126 * @var array
128 private static $standardproperties = array(
129 'courseid' => 'get_course_id',
130 'userid' => 'get_user_id',
131 'sections' => 'get_sections',
132 'cms' => 'get_cms',
133 'instances' => 'get_instances',
134 'groups' => 'get_groups_all',
138 * Magic method getter
140 * @param string $name
141 * @return mixed
143 public function __get($name) {
144 if (isset(self::$standardproperties[$name])) {
145 $method = self::$standardproperties[$name];
146 return $this->$method();
147 } else {
148 debugging('Invalid course_modinfo property accessed: '.$name);
149 return null;
154 * Magic method for function isset()
156 * @param string $name
157 * @return bool
159 public function __isset($name) {
160 if (isset(self::$standardproperties[$name])) {
161 $value = $this->__get($name);
162 return isset($value);
164 return false;
168 * Magic method for function empty()
170 * @param string $name
171 * @return bool
173 public function __empty($name) {
174 if (isset(self::$standardproperties[$name])) {
175 $value = $this->__get($name);
176 return empty($value);
178 return true;
182 * Magic method setter
184 * Will display the developer warning when trying to set/overwrite existing property.
186 * @param string $name
187 * @param mixed $value
189 public function __set($name, $value) {
190 debugging("It is not allowed to set the property course_modinfo::\${$name}", DEBUG_DEVELOPER);
194 * Returns course object that was used in the first {@link get_fast_modinfo()} call.
196 * It may not contain all fields from DB table {course} but always has at least the following:
197 * id,shortname,fullname,format,enablecompletion,groupmode,groupmodeforce,cacherev
199 * @return stdClass
201 public function get_course() {
202 return $this->course;
206 * @return int Course ID
208 public function get_course_id() {
209 return $this->course->id;
213 * @return int User ID
215 public function get_user_id() {
216 return $this->userid;
220 * @return array Array from section number (e.g. 0) to array of course-module IDs in that
221 * section; this only includes sections that contain at least one course-module
223 public function get_sections() {
224 return $this->sections;
228 * @return cm_info[] Array from course-module instance to cm_info object within this course, in
229 * order of appearance
231 public function get_cms() {
232 return $this->cms;
236 * Obtains a single course-module object (for a course-module that is on this course).
237 * @param int $cmid Course-module ID
238 * @return cm_info Information about that course-module
239 * @throws moodle_exception If the course-module does not exist
241 public function get_cm($cmid) {
242 if (empty($this->cms[$cmid])) {
243 throw new moodle_exception('invalidcoursemoduleid', 'error', '', $cmid);
245 return $this->cms[$cmid];
249 * Obtains all module instances on this course.
250 * @return cm_info[][] Array from module name => array from instance id => cm_info
252 public function get_instances() {
253 return $this->instances;
257 * Returns array of localised human-readable module names used in this course
259 * @param bool $plural if true returns the plural form of modules names
260 * @return array
262 public function get_used_module_names($plural = false) {
263 $modnames = get_module_types_names($plural);
264 $modnamesused = array();
265 foreach ($this->get_cms() as $cmid => $mod) {
266 if (!isset($modnamesused[$mod->modname]) && isset($modnames[$mod->modname]) && $mod->uservisible) {
267 $modnamesused[$mod->modname] = $modnames[$mod->modname];
270 return $modnamesused;
274 * Obtains all instances of a particular module on this course.
275 * @param string $modname Name of module (not full frankenstyle) e.g. 'label'
276 * @return cm_info[] Array from instance id => cm_info for modules on this course; empty if none
278 public function get_instances_of($modname) {
279 if (empty($this->instances[$modname])) {
280 return array();
282 return $this->instances[$modname];
286 * Groups that the current user belongs to organised by grouping id. Calculated on the first request.
287 * @return int[][] array of grouping id => array of group id => group id. Includes grouping id 0 for 'all groups'
289 private function get_groups_all() {
290 if (is_null($this->groups)) {
291 $this->groups = groups_get_user_groups($this->course->id, $this->userid);
293 return $this->groups;
297 * Returns groups that the current user belongs to on the course. Note: If not already
298 * available, this may make a database query.
299 * @param int $groupingid Grouping ID or 0 (default) for all groups
300 * @return int[] Array of int (group id) => int (same group id again); empty array if none
302 public function get_groups($groupingid = 0) {
303 $allgroups = $this->get_groups_all();
304 if (!isset($allgroups[$groupingid])) {
305 return array();
307 return $allgroups[$groupingid];
311 * Gets all sections as array from section number => data about section.
312 * @return section_info[] Array of section_info objects organised by section number
314 public function get_section_info_all() {
315 return $this->sectioninfo;
319 * Gets data about specific numbered section.
320 * @param int $sectionnumber Number (not id) of section
321 * @param int $strictness Use MUST_EXIST to throw exception if it doesn't
322 * @return section_info Information for numbered section or null if not found
324 public function get_section_info($sectionnumber, $strictness = IGNORE_MISSING) {
325 if (!array_key_exists($sectionnumber, $this->sectioninfo)) {
326 if ($strictness === MUST_EXIST) {
327 throw new moodle_exception('sectionnotexist');
328 } else {
329 return null;
332 return $this->sectioninfo[$sectionnumber];
336 * Gets data about specific section ID.
337 * @param int $sectionid ID (not number) of section
338 * @param int $strictness Use MUST_EXIST to throw exception if it doesn't
339 * @return section_info|null Information for numbered section or null if not found
341 public function get_section_info_by_id(int $sectionid, int $strictness = IGNORE_MISSING): ?section_info {
343 if (!isset($this->sectionids[$sectionid])) {
344 if ($strictness === MUST_EXIST) {
345 throw new moodle_exception('sectionnotexist');
346 } else {
347 return null;
350 return $this->get_section_info($this->sectionids[$sectionid], $strictness);
354 * Static cache for generated course_modinfo instances
356 * @see course_modinfo::instance()
357 * @see course_modinfo::clear_instance_cache()
358 * @var course_modinfo[]
360 protected static $instancecache = array();
363 * Timestamps (microtime) when the course_modinfo instances were last accessed
365 * It is used to remove the least recent accessed instances when static cache is full
367 * @var float[]
369 protected static $cacheaccessed = array();
372 * Clears the cache used in course_modinfo::instance()
374 * Used in {@link get_fast_modinfo()} when called with argument $reset = true
375 * and in {@link rebuild_course_cache()}
377 * @param null|int|stdClass $courseorid if specified removes only cached value for this course
379 public static function clear_instance_cache($courseorid = null) {
380 if (empty($courseorid)) {
381 self::$instancecache = array();
382 self::$cacheaccessed = array();
383 return;
385 if (is_object($courseorid)) {
386 $courseorid = $courseorid->id;
388 if (isset(self::$instancecache[$courseorid])) {
389 // Unsetting static variable in PHP is peculiar, it removes the reference,
390 // but data remain in memory. Prior to unsetting, the varable needs to be
391 // set to empty to remove its remains from memory.
392 self::$instancecache[$courseorid] = '';
393 unset(self::$instancecache[$courseorid]);
394 unset(self::$cacheaccessed[$courseorid]);
399 * Returns the instance of course_modinfo for the specified course and specified user
401 * This function uses static cache for the retrieved instances. The cache
402 * size is limited by MAX_MODINFO_CACHE_SIZE. If instance is not found in
403 * the static cache or it was created for another user or the cacherev validation
404 * failed - a new instance is constructed and returned.
406 * Used in {@link get_fast_modinfo()}
408 * @param int|stdClass $courseorid object from DB table 'course' (must have field 'id'
409 * and recommended to have field 'cacherev') or just a course id
410 * @param int $userid User id to populate 'availble' and 'uservisible' attributes of modules and sections.
411 * Set to 0 for current user (default). Set to -1 to avoid calculation of dynamic user-depended data.
412 * @return course_modinfo
414 public static function instance($courseorid, $userid = 0) {
415 global $USER;
416 if (is_object($courseorid)) {
417 $course = $courseorid;
418 } else {
419 $course = (object)array('id' => $courseorid);
421 if (empty($userid)) {
422 $userid = $USER->id;
425 if (!empty(self::$instancecache[$course->id])) {
426 if (self::$instancecache[$course->id]->userid == $userid &&
427 (!isset($course->cacherev) ||
428 $course->cacherev == self::$instancecache[$course->id]->get_course()->cacherev)) {
429 // This course's modinfo for the same user was recently retrieved, return cached.
430 self::$cacheaccessed[$course->id] = microtime(true);
431 return self::$instancecache[$course->id];
432 } else {
433 // Prevent potential reference problems when switching users.
434 self::clear_instance_cache($course->id);
437 $modinfo = new course_modinfo($course, $userid);
439 // We have a limit of MAX_MODINFO_CACHE_SIZE entries to store in static variable.
440 if (count(self::$instancecache) >= MAX_MODINFO_CACHE_SIZE) {
441 // Find the course that was the least recently accessed.
442 asort(self::$cacheaccessed, SORT_NUMERIC);
443 $courseidtoremove = key(array_reverse(self::$cacheaccessed, true));
444 self::clear_instance_cache($courseidtoremove);
447 // Add modinfo to the static cache.
448 self::$instancecache[$course->id] = $modinfo;
449 self::$cacheaccessed[$course->id] = microtime(true);
451 return $modinfo;
455 * Constructs based on course.
456 * Note: This constructor should not usually be called directly.
457 * Use get_fast_modinfo($course) instead as this maintains a cache.
458 * @param stdClass $course course object, only property id is required.
459 * @param int $userid User ID
460 * @throws moodle_exception if course is not found
462 public function __construct($course, $userid) {
463 global $CFG, $COURSE, $SITE, $DB;
465 if (!isset($course->cacherev)) {
466 // We require presence of property cacherev to validate the course cache.
467 // No need to clone the $COURSE or $SITE object here because we clone it below anyway.
468 $course = get_course($course->id, false);
471 $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
473 // Retrieve modinfo from cache. If not present or cacherev mismatches, call rebuild and retrieve again.
474 $coursemodinfo = $cachecoursemodinfo->get_versioned($course->id, $course->cacherev);
475 // Note the version comparison using the data in the cache should not be necessary, but the
476 // partial rebuild logic sometimes sets the $coursemodinfo->cacherev to -1 which is an
477 // indicator that it needs rebuilding.
478 if ($coursemodinfo === false || ($course->cacherev > $coursemodinfo->cacherev)) {
479 $coursemodinfo = self::build_course_cache($course);
482 // Set initial values
483 $this->userid = $userid;
484 $this->sections = array();
485 $this->sectionids = [];
486 $this->cms = array();
487 $this->instances = array();
488 $this->groups = null;
490 // If we haven't already preloaded contexts for the course, do it now
491 // Modules are also cached here as long as it's the first time this course has been preloaded.
492 context_helper::preload_course($course->id);
494 // Quick integrity check: as a result of race conditions modinfo may not be regenerated after the change.
495 // It is especially dangerous if modinfo contains the deleted course module, as it results in fatal error.
496 // We can check it very cheap by validating the existence of module context.
497 if ($course->id == $COURSE->id || $course->id == $SITE->id) {
498 // Only verify current course (or frontpage) as pages with many courses may not have module contexts cached.
499 // (Uncached modules will result in a very slow verification).
500 foreach ($coursemodinfo->modinfo as $mod) {
501 if (!context_module::instance($mod->cm, IGNORE_MISSING)) {
502 debugging('Course cache integrity check failed: course module with id '. $mod->cm.
503 ' does not have context. Rebuilding cache for course '. $course->id);
504 // Re-request the course record from DB as well, don't use get_course() here.
505 $course = $DB->get_record('course', array('id' => $course->id), '*', MUST_EXIST);
506 $coursemodinfo = self::build_course_cache($course, true);
507 break;
512 // Overwrite unset fields in $course object with cached values, store the course object.
513 $this->course = fullclone($course);
514 foreach ($coursemodinfo as $key => $value) {
515 if ($key !== 'modinfo' && $key !== 'sectioncache' &&
516 (!isset($this->course->$key) || $key === 'cacherev')) {
517 $this->course->$key = $value;
521 // Loop through each piece of module data, constructing it
522 static $modexists = array();
523 foreach ($coursemodinfo->modinfo as $mod) {
524 if (!isset($mod->name) || strval($mod->name) === '') {
525 // something is wrong here
526 continue;
529 // Skip modules which don't exist
530 if (!array_key_exists($mod->mod, $modexists)) {
531 $modexists[$mod->mod] = file_exists("$CFG->dirroot/mod/$mod->mod/lib.php");
533 if (!$modexists[$mod->mod]) {
534 continue;
537 // Construct info for this module
538 $cm = new cm_info($this, null, $mod, null);
540 // Store module in instances and cms array
541 if (!isset($this->instances[$cm->modname])) {
542 $this->instances[$cm->modname] = array();
544 $this->instances[$cm->modname][$cm->instance] = $cm;
545 $this->cms[$cm->id] = $cm;
547 // Reconstruct sections. This works because modules are stored in order
548 if (!isset($this->sections[$cm->sectionnum])) {
549 $this->sections[$cm->sectionnum] = array();
551 $this->sections[$cm->sectionnum][] = $cm->id;
554 // Expand section objects
555 $this->sectioninfo = array();
556 foreach ($coursemodinfo->sectioncache as $number => $data) {
557 $this->sectionids[$data->id] = $number;
558 $this->sectioninfo[$number] = new section_info($data, $number, null, null,
559 $this, null);
564 * This method can not be used anymore.
566 * @see course_modinfo::build_course_cache()
567 * @deprecated since 2.6
569 public static function build_section_cache($courseid) {
570 throw new coding_exception('Function course_modinfo::build_section_cache() can not be used anymore.' .
571 ' Please use course_modinfo::build_course_cache() whenever applicable.');
575 * Builds a list of information about sections on a course to be stored in
576 * the course cache. (Does not include information that is already cached
577 * in some other way.)
579 * @param stdClass $course Course object (must contain fields
580 * @param boolean $usecache use cached section info if exists, use true for partial course rebuild
581 * @return array Information about sections, indexed by section number (not id)
583 protected static function build_course_section_cache(\stdClass $course, bool $usecache = false): array {
584 global $DB;
586 // Get section data
587 $sections = $DB->get_records('course_sections', array('course' => $course->id), 'section',
588 'section, id, course, name, summary, summaryformat, sequence, visible, availability');
589 $compressedsections = [];
590 $courseformat = course_get_format($course);
592 if ($usecache) {
593 $cachecoursemodinfo = \cache::make('core', 'coursemodinfo');
594 $coursemodinfo = $cachecoursemodinfo->get_versioned($course->id, $course->cacherev);
595 if ($coursemodinfo !== false) {
596 $compressedsections = $coursemodinfo->sectioncache;
600 $formatoptionsdef = course_get_format($course)->section_format_options();
601 // Remove unnecessary data and add availability
602 foreach ($sections as $number => $section) {
603 $sectioninfocached = isset($compressedsections[$number]);
604 if ($sectioninfocached) {
605 continue;
607 // Add cached options from course format to $section object
608 foreach ($formatoptionsdef as $key => $option) {
609 if (!empty($option['cache'])) {
610 $formatoptions = $courseformat->get_format_options($section);
611 if (!array_key_exists('cachedefault', $option) || $option['cachedefault'] !== $formatoptions[$key]) {
612 $section->$key = $formatoptions[$key];
616 // Clone just in case it is reused elsewhere
617 $compressedsections[$number] = clone($section);
618 section_info::convert_for_section_cache($compressedsections[$number]);
621 ksort($compressedsections);
622 return $compressedsections;
626 * Builds and stores in MUC object containing information about course
627 * modules and sections together with cached fields from table course.
629 * @param stdClass $course object from DB table course. Must have property 'id'
630 * but preferably should have all cached fields.
631 * @param boolean $partialrebuild Indicate if it's partial course cache rebuild or not
632 * @return stdClass object with all cached keys of the course plus fields modinfo and sectioncache.
633 * The same object is stored in MUC
634 * @throws moodle_exception if course is not found (if $course object misses some of the
635 * necessary fields it is re-requested from database)
637 public static function build_course_cache(\stdClass $course, bool $partialrebuild = false): \stdClass {
638 if (empty($course->id)) {
639 throw new coding_exception('Object $course is missing required property \id\'');
642 $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
643 $cachekey = $course->id;
644 if (!$cachecoursemodinfo->acquire_lock($cachekey)) {
645 throw new moodle_exception('ex_unabletolock', 'cache', '', null,
646 'Unable to lock modinfo cache for course ' . $cachekey);
648 try {
649 // Only actually do the build if it's still needed after getting the lock (not if
650 // somebody else, who might have been holding the lock, built it already).
651 $coursemodinfo = $cachecoursemodinfo->get_versioned($course->id, $course->cacherev);
652 if ($coursemodinfo === false || ($course->cacherev > $coursemodinfo->cacherev)) {
653 $coursemodinfo = self::inner_build_course_cache($course);
655 } finally {
656 $cachecoursemodinfo->release_lock($cachekey);
658 return $coursemodinfo;
662 * Called to build course cache when there is already a lock obtained.
664 * @param stdClass $course object from DB table course
665 * @param bool $partialrebuild Indicate if it's partial course cache rebuild or not
666 * @return stdClass Course object that has been stored in MUC
668 protected static function inner_build_course_cache(\stdClass $course, bool $partialrebuild = false): \stdClass {
669 global $DB, $CFG;
670 require_once("{$CFG->dirroot}/course/lib.php");
672 $cachekey = $course->id;
673 $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
674 if (!$cachecoursemodinfo->check_lock_state($cachekey)) {
675 throw new coding_exception('You must acquire a lock on the course ID before calling inner_build_course_cache');
678 // Always reload the course object from database to ensure we have the latest possible
679 // value for cacherev.
680 $course = $DB->get_record('course', ['id' => $course->id],
681 implode(',', array_merge(['id'], self::$cachedfields)), MUST_EXIST);
682 // Retrieve all information about activities and sections.
683 $coursemodinfo = new stdClass();
684 $coursemodinfo->modinfo = self::get_array_of_activities($course, $partialrebuild);
685 $coursemodinfo->sectioncache = self::build_course_section_cache($course, $partialrebuild);
686 foreach (self::$cachedfields as $key) {
687 $coursemodinfo->$key = $course->$key;
689 // Set the accumulated activities and sections information in cache, together with cacherev.
690 $cachecoursemodinfo->set_versioned($cachekey, $course->cacherev, $coursemodinfo);
691 return $coursemodinfo;
695 * Purge the cache of a course section by its id.
697 * @param int $courseid The course to purge cache in
698 * @param int $sectionid The section _id_ to purge
700 public static function purge_course_section_cache_by_id(int $courseid, int $sectionid): void {
701 $course = get_course($courseid);
702 $cache = cache::make('core', 'coursemodinfo');
703 $cachekey = $course->id;
704 $cache->acquire_lock($cachekey);
705 $coursemodinfo = $cache->get_versioned($cachekey, $course->cacherev);
706 if ($coursemodinfo !== false) {
707 foreach ($coursemodinfo->sectioncache as $sectionno => $sectioncache) {
708 if ($sectioncache->id == $sectionid) {
709 $coursemodinfo->cacherev = -1;
710 unset($coursemodinfo->sectioncache[$sectionno]);
711 $cache->set_versioned($cachekey, $course->cacherev, $coursemodinfo);
712 break;
716 $cache->release_lock($cachekey);
720 * Purge the cache of a course section by its number.
722 * @param int $courseid The course to purge cache in
723 * @param int $sectionno The section number to purge
725 public static function purge_course_section_cache_by_number(int $courseid, int $sectionno): void {
726 $course = get_course($courseid);
727 $cache = cache::make('core', 'coursemodinfo');
728 $cachekey = $course->id;
729 $cache->acquire_lock($cachekey);
730 $coursemodinfo = $cache->get_versioned($cachekey, $course->cacherev);
731 if ($coursemodinfo !== false && array_key_exists($sectionno, $coursemodinfo->sectioncache)) {
732 $coursemodinfo->cacherev = -1;
733 unset($coursemodinfo->sectioncache[$sectionno]);
734 $cache->set_versioned($cachekey, $course->cacherev, $coursemodinfo);
736 $cache->release_lock($cachekey);
740 * Purge the cache of a course module.
742 * @param int $courseid Course id
743 * @param int $cmid Course module id
745 public static function purge_course_module_cache(int $courseid, int $cmid): void {
746 $course = get_course($courseid);
747 $cache = cache::make('core', 'coursemodinfo');
748 $cachekey = $course->id;
749 $cache->acquire_lock($cachekey);
750 $coursemodinfo = $cache->get_versioned($cachekey, $course->cacherev);
751 $hascache = ($coursemodinfo !== false) && array_key_exists($cmid, $coursemodinfo->modinfo);
752 if ($hascache) {
753 $coursemodinfo->cacherev = -1;
754 unset($coursemodinfo->modinfo[$cmid]);
755 $cache->set_versioned($cachekey, $course->cacherev, $coursemodinfo);
756 $coursemodinfo = $cache->get_versioned($cachekey, $course->cacherev);
758 $cache->release_lock($cachekey);
762 * For a given course, returns an array of course activity objects
764 * @param stdClass $course Course object
765 * @param bool $usecache get activities from cache if modinfo exists when $usecache is true
766 * @return array list of activities
768 public static function get_array_of_activities(stdClass $course, bool $usecache = false): array {
769 global $CFG, $DB;
771 if (empty($course)) {
772 throw new moodle_exception('courseidnotfound');
775 $rawmods = get_course_mods($course->id);
776 if (empty($rawmods)) {
777 return [];
780 $mods = [];
781 if ($usecache) {
782 // Get existing cache.
783 $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
784 $coursemodinfo = $cachecoursemodinfo->get_versioned($course->id, $course->cacherev);
785 if ($coursemodinfo !== false) {
786 $mods = $coursemodinfo->modinfo;
790 $courseformat = course_get_format($course);
792 if ($sections = $DB->get_records('course_sections', ['course' => $course->id],
793 'section ASC', 'id,section,sequence,visible')) {
794 // First check and correct obvious mismatches between course_sections.sequence and course_modules.section.
795 if ($errormessages = course_integrity_check($course->id, $rawmods, $sections)) {
796 debugging(join('<br>', $errormessages));
797 $rawmods = get_course_mods($course->id);
798 $sections = $DB->get_records('course_sections', ['course' => $course->id],
799 'section ASC', 'id,section,sequence,visible');
801 // Build array of activities.
802 foreach ($sections as $section) {
803 if (!empty($section->sequence)) {
804 $cmids = explode(",", $section->sequence);
805 $numberofmods = count($cmids);
806 foreach ($cmids as $cmid) {
807 // Activity does not exist in the database.
808 $notexistindb = empty($rawmods[$cmid]);
809 $activitycached = isset($mods[$cmid]);
810 if ($activitycached || $notexistindb) {
811 continue;
814 // Adjust visibleoncoursepage, value in DB may not respect format availability.
815 $rawmods[$cmid]->visibleoncoursepage = (!$rawmods[$cmid]->visible
816 || $rawmods[$cmid]->visibleoncoursepage
817 || empty($CFG->allowstealth)
818 || !$courseformat->allow_stealth_module_visibility($rawmods[$cmid], $section)) ? 1 : 0;
820 $mods[$cmid] = new stdClass();
821 $mods[$cmid]->id = $rawmods[$cmid]->instance;
822 $mods[$cmid]->cm = $rawmods[$cmid]->id;
823 $mods[$cmid]->mod = $rawmods[$cmid]->modname;
825 // Oh dear. Inconsistent names left here for backward compatibility.
826 $mods[$cmid]->section = $section->section;
827 $mods[$cmid]->sectionid = $rawmods[$cmid]->section;
829 $mods[$cmid]->module = $rawmods[$cmid]->module;
830 $mods[$cmid]->added = $rawmods[$cmid]->added;
831 $mods[$cmid]->score = $rawmods[$cmid]->score;
832 $mods[$cmid]->idnumber = $rawmods[$cmid]->idnumber;
833 $mods[$cmid]->visible = $rawmods[$cmid]->visible;
834 $mods[$cmid]->visibleoncoursepage = $rawmods[$cmid]->visibleoncoursepage;
835 $mods[$cmid]->visibleold = $rawmods[$cmid]->visibleold;
836 $mods[$cmid]->groupmode = $rawmods[$cmid]->groupmode;
837 $mods[$cmid]->groupingid = $rawmods[$cmid]->groupingid;
838 $mods[$cmid]->indent = $rawmods[$cmid]->indent;
839 $mods[$cmid]->completion = $rawmods[$cmid]->completion;
840 $mods[$cmid]->extra = "";
841 $mods[$cmid]->completiongradeitemnumber =
842 $rawmods[$cmid]->completiongradeitemnumber;
843 $mods[$cmid]->completionpassgrade = $rawmods[$cmid]->completionpassgrade;
844 $mods[$cmid]->completionview = $rawmods[$cmid]->completionview;
845 $mods[$cmid]->completionexpected = $rawmods[$cmid]->completionexpected;
846 $mods[$cmid]->showdescription = $rawmods[$cmid]->showdescription;
847 $mods[$cmid]->availability = $rawmods[$cmid]->availability;
848 $mods[$cmid]->deletioninprogress = $rawmods[$cmid]->deletioninprogress;
849 $mods[$cmid]->downloadcontent = $rawmods[$cmid]->downloadcontent;
850 $mods[$cmid]->lang = $rawmods[$cmid]->lang;
852 $modname = $mods[$cmid]->mod;
853 $functionname = $modname . "_get_coursemodule_info";
855 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
856 continue;
859 include_once("$CFG->dirroot/mod/$modname/lib.php");
861 if ($hasfunction = function_exists($functionname)) {
862 if ($info = $functionname($rawmods[$cmid])) {
863 if (!empty($info->icon)) {
864 $mods[$cmid]->icon = $info->icon;
866 if (!empty($info->iconcomponent)) {
867 $mods[$cmid]->iconcomponent = $info->iconcomponent;
869 if (!empty($info->name)) {
870 $mods[$cmid]->name = $info->name;
872 if ($info instanceof cached_cm_info) {
873 // When using cached_cm_info you can include three new fields.
874 // That aren't available for legacy code.
875 if (!empty($info->content)) {
876 $mods[$cmid]->content = $info->content;
878 if (!empty($info->extraclasses)) {
879 $mods[$cmid]->extraclasses = $info->extraclasses;
881 if (!empty($info->iconurl)) {
882 // Convert URL to string as it's easier to store.
883 // Also serialized object contains \0 byte,
884 // ... and can not be written to Postgres DB.
885 $url = new moodle_url($info->iconurl);
886 $mods[$cmid]->iconurl = $url->out(false);
888 if (!empty($info->onclick)) {
889 $mods[$cmid]->onclick = $info->onclick;
891 if (!empty($info->customdata)) {
892 $mods[$cmid]->customdata = $info->customdata;
894 } else {
895 // When using a stdclass, the (horrible) deprecated ->extra field,
896 // ... that is available for BC.
897 if (!empty($info->extra)) {
898 $mods[$cmid]->extra = $info->extra;
903 // When there is no modname_get_coursemodule_info function,
904 // ... but showdescriptions is enabled, then we use the 'intro',
905 // ... and 'introformat' fields in the module table.
906 if (!$hasfunction && $rawmods[$cmid]->showdescription) {
907 if ($modvalues = $DB->get_record($rawmods[$cmid]->modname,
908 ['id' => $rawmods[$cmid]->instance], 'name, intro, introformat')) {
909 // Set content from intro and introformat. Filters are disabled.
910 // Because we filter it with format_text at display time.
911 $mods[$cmid]->content = format_module_intro($rawmods[$cmid]->modname,
912 $modvalues, $rawmods[$cmid]->id, false);
914 // To save making another query just below, put name in here.
915 $mods[$cmid]->name = $modvalues->name;
918 if (!isset($mods[$cmid]->name)) {
919 $mods[$cmid]->name = $DB->get_field($rawmods[$cmid]->modname, "name",
920 ["id" => $rawmods[$cmid]->instance]);
923 // Minimise the database size by unsetting default options when they are 'empty'.
924 // This list corresponds to code in the cm_info constructor.
925 foreach (['idnumber', 'groupmode', 'groupingid',
926 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
927 'icon', 'iconcomponent', 'customdata', 'availability', 'completionview',
928 'completionexpected', 'score', 'showdescription', 'deletioninprogress'] as $property) {
929 if (property_exists($mods[$cmid], $property) &&
930 empty($mods[$cmid]->{$property})) {
931 unset($mods[$cmid]->{$property});
934 // Special case: this value is usually set to null, but may be 0.
935 if (property_exists($mods[$cmid], 'completiongradeitemnumber') &&
936 is_null($mods[$cmid]->completiongradeitemnumber)) {
937 unset($mods[$cmid]->completiongradeitemnumber);
943 return $mods;
947 * Purge the cache of a given course
949 * @param int $courseid Course id
951 public static function purge_course_cache(int $courseid): void {
952 increment_revision_number('course', 'cacherev', 'id = :id', array('id' => $courseid));
953 $cachemodinfo = cache::make('core', 'coursemodinfo');
954 $cachemodinfo->delete($courseid);
960 * Data about a single module on a course. This contains most of the fields in the course_modules
961 * table, plus additional data when required.
963 * The object can be accessed by core or any plugin (i.e. course format, block, filter, etc.) as
964 * get_fast_modinfo($courseorid)->cms[$coursemoduleid]
965 * or
966 * get_fast_modinfo($courseorid)->instances[$moduletype][$instanceid]
968 * There are three stages when activity module can add/modify data in this object:
970 * <b>Stage 1 - during building the cache.</b>
971 * Allows to add to the course cache static user-independent information about the module.
972 * Modules should try to include only absolutely necessary information that may be required
973 * when displaying course view page. The information is stored in application-level cache
974 * and reset when {@link rebuild_course_cache()} is called or cache is purged by admin.
976 * Modules can implement callback XXX_get_coursemodule_info() returning instance of object
977 * {@link cached_cm_info}
979 * <b>Stage 2 - dynamic data.</b>
980 * Dynamic data is user-dependent, it is stored in request-level cache. To reset this cache
981 * {@link get_fast_modinfo()} with $reset argument may be called.
983 * Dynamic data is obtained when any of the following properties/methods is requested:
984 * - {@link cm_info::$url}
985 * - {@link cm_info::$name}
986 * - {@link cm_info::$onclick}
987 * - {@link cm_info::get_icon_url()}
988 * - {@link cm_info::$uservisible}
989 * - {@link cm_info::$available}
990 * - {@link cm_info::$availableinfo}
991 * - plus any of the properties listed in Stage 3.
993 * Modules can implement callback <b>XXX_cm_info_dynamic()</b> and inside this callback they
994 * are allowed to use any of the following set methods:
995 * - {@link cm_info::set_available()}
996 * - {@link cm_info::set_name()}
997 * - {@link cm_info::set_no_view_link()}
998 * - {@link cm_info::set_user_visible()}
999 * - {@link cm_info::set_on_click()}
1000 * - {@link cm_info::set_icon_url()}
1001 * - {@link cm_info::override_customdata()}
1002 * Any methods affecting view elements can also be set in this callback.
1004 * <b>Stage 3 (view data).</b>
1005 * Also user-dependend data stored in request-level cache. Second stage is created
1006 * because populating the view data can be expensive as it may access much more
1007 * Moodle APIs such as filters, user information, output renderers and we
1008 * don't want to request it until necessary.
1009 * View data is obtained when any of the following properties/methods is requested:
1010 * - {@link cm_info::$afterediticons}
1011 * - {@link cm_info::$content}
1012 * - {@link cm_info::get_formatted_content()}
1013 * - {@link cm_info::$extraclasses}
1014 * - {@link cm_info::$afterlink}
1016 * Modules can implement callback <b>XXX_cm_info_view()</b> and inside this callback they
1017 * are allowed to use any of the following set methods:
1018 * - {@link cm_info::set_after_edit_icons()}
1019 * - {@link cm_info::set_after_link()}
1020 * - {@link cm_info::set_content()}
1021 * - {@link cm_info::set_extra_classes()}
1023 * @property-read int $id Course-module ID - from course_modules table
1024 * @property-read int $instance Module instance (ID within module table) - from course_modules table
1025 * @property-read int $course Course ID - from course_modules table
1026 * @property-read string $idnumber 'ID number' from course-modules table (arbitrary text set by user) - from
1027 * course_modules table
1028 * @property-read int $added Time that this course-module was added (unix time) - from course_modules table
1029 * @property-read int $visible Visible setting (0 or 1; if this is 0, students cannot see/access the activity) - from
1030 * course_modules table
1031 * @property-read int $visibleoncoursepage Visible on course page setting - from course_modules table, adjusted to
1032 * whether course format allows this module to have the "stealth" mode
1033 * @property-read int $visibleold Old visible setting (if the entire section is hidden, the previous value for
1034 * visible is stored in this field) - from course_modules table
1035 * @property-read int $groupmode Group mode (one of the constants NOGROUPS, SEPARATEGROUPS, or VISIBLEGROUPS) - from
1036 * course_modules table. Use {@link cm_info::$effectivegroupmode} to find the actual group mode that may be forced by course.
1037 * @property-read int $groupingid Grouping ID (0 = all groupings)
1038 * @property-read bool $coursegroupmodeforce Indicates whether the course containing the module has forced the groupmode
1039 * This means that cm_info::$groupmode should be ignored and cm_info::$coursegroupmode be used instead
1040 * @property-read int $coursegroupmode Group mode (one of the constants NOGROUPS, SEPARATEGROUPS, or VISIBLEGROUPS) - from
1041 * course table - as specified for the course containing the module
1042 * Effective only if {@link cm_info::$coursegroupmodeforce} is set
1043 * @property-read int $effectivegroupmode Effective group mode for this module (one of the constants NOGROUPS, SEPARATEGROUPS,
1044 * or VISIBLEGROUPS). This can be different from groupmode set for the module if the groupmode is forced for the course.
1045 * This value will always be NOGROUPS if module type does not support group mode.
1046 * @property-read int $indent Indent level on course page (0 = no indent) - from course_modules table
1047 * @property-read int $completion Activity completion setting for this activity, COMPLETION_TRACKING_xx constant - from
1048 * course_modules table
1049 * @property-read mixed $completiongradeitemnumber Set to the item number (usually 0) if completion depends on a particular
1050 * grade of this activity, or null if completion does not depend on a grade - from course_modules table
1051 * @property-read int $completionview 1 if 'on view' completion is enabled, 0 otherwise - from course_modules table
1052 * @property-read int $completionexpected Set to a unix time if completion of this activity is expected at a
1053 * particular time, 0 if no time set - from course_modules table
1054 * @property-read string $availability Availability information as JSON string or null if none -
1055 * from course_modules table
1056 * @property-read int $showdescription Controls whether the description of the activity displays on the course main page (in
1057 * addition to anywhere it might display within the activity itself). 0 = do not show
1058 * on main page, 1 = show on main page.
1059 * @property-read string $extra (deprecated) Extra HTML that is put in an unhelpful part of the HTML when displaying this module in
1060 * course page - from cached data in modinfo field. Deprecated, replaced by ->extraclasses and ->onclick
1061 * @property-read string $icon Name of icon to use - from cached data in modinfo field
1062 * @property-read string $iconcomponent Component that contains icon - from cached data in modinfo field
1063 * @property-read string $modname Name of module e.g. 'forum' (this is the same name as the module's main database
1064 * table) - from cached data in modinfo field
1065 * @property-read int $module ID of module type - from course_modules table
1066 * @property-read string $name Name of module instance for display on page e.g. 'General discussion forum' - from cached
1067 * data in modinfo field
1068 * @property-read int $sectionnum Section number that this course-module is in (section 0 = above the calendar, section 1
1069 * = week/topic 1, etc) - from cached data in modinfo field
1070 * @property-read int $section Section id - from course_modules table
1071 * @property-read array $conditionscompletion Availability conditions for this course-module based on the completion of other
1072 * course-modules (array from other course-module id to required completion state for that
1073 * module) - from cached data in modinfo field
1074 * @property-read array $conditionsgrade Availability conditions for this course-module based on course grades (array from
1075 * grade item id to object with ->min, ->max fields) - from cached data in modinfo field
1076 * @property-read array $conditionsfield Availability conditions for this course-module based on user fields
1077 * @property-read bool $available True if this course-module is available to students i.e. if all availability conditions
1078 * are met - obtained dynamically
1079 * @property-read string $availableinfo If course-module is not available to students, this string gives information about
1080 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
1081 * January 2010') for display on main page - obtained dynamically
1082 * @property-read bool $uservisible True if this course-module is available to the CURRENT user (for example, if current user
1083 * has viewhiddenactivities capability, they can access the course-module even if it is not
1084 * visible or not available, so this would be true in that case)
1085 * @property-read context_module $context Module context
1086 * @property-read string $modfullname Returns a localised human-readable name of the module type - calculated on request
1087 * @property-read string $modplural Returns a localised human-readable name of the module type in plural form - calculated on request
1088 * @property-read string $content Content to display on main (view) page - calculated on request
1089 * @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
1090 * @property-read string $extraclasses Extra CSS classes to add to html output for this activity on main page - calculated on request
1091 * @property-read string $onclick Content of HTML on-click attribute already escaped - calculated on request
1092 * @property-read mixed $customdata Optional custom data stored in modinfo cache for this activity, or null if none
1093 * @property-read string $afterlink Extra HTML code to display after link - calculated on request
1094 * @property-read string $afterediticons Extra HTML code to display after editing icons (e.g. more icons) - calculated on request
1095 * @property-read bool $deletioninprogress True if this course module is scheduled for deletion, false otherwise.
1096 * @property-read bool $downloadcontent True if content download is enabled for this course module, false otherwise.
1097 * @property-read bool $lang the forced language for this activity (language pack name). Null means not forced.
1099 class cm_info implements IteratorAggregate {
1101 * State: Only basic data from modinfo cache is available.
1103 const STATE_BASIC = 0;
1106 * State: In the process of building dynamic data (to avoid recursive calls to obtain_dynamic_data())
1108 const STATE_BUILDING_DYNAMIC = 1;
1111 * State: Dynamic data is available too.
1113 const STATE_DYNAMIC = 2;
1116 * State: In the process of building view data (to avoid recursive calls to obtain_view_data())
1118 const STATE_BUILDING_VIEW = 3;
1121 * State: View data (for course page) is available.
1123 const STATE_VIEW = 4;
1126 * Parent object
1127 * @var course_modinfo
1129 private $modinfo;
1132 * Level of information stored inside this object (STATE_xx constant)
1133 * @var int
1135 private $state;
1138 * Course-module ID - from course_modules table
1139 * @var int
1141 private $id;
1144 * Module instance (ID within module table) - from course_modules table
1145 * @var int
1147 private $instance;
1150 * 'ID number' from course-modules table (arbitrary text set by user) - from
1151 * course_modules table
1152 * @var string
1154 private $idnumber;
1157 * Time that this course-module was added (unix time) - from course_modules table
1158 * @var int
1160 private $added;
1163 * This variable is not used and is included here only so it can be documented.
1164 * Once the database entry is removed from course_modules, it should be deleted
1165 * here too.
1166 * @var int
1167 * @deprecated Do not use this variable
1169 private $score;
1172 * Visible setting (0 or 1; if this is 0, students cannot see/access the activity) - from
1173 * course_modules table
1174 * @var int
1176 private $visible;
1179 * Visible on course page setting - from course_modules table
1180 * @var int
1182 private $visibleoncoursepage;
1185 * Old visible setting (if the entire section is hidden, the previous value for
1186 * visible is stored in this field) - from course_modules table
1187 * @var int
1189 private $visibleold;
1192 * Group mode (one of the constants NONE, SEPARATEGROUPS, or VISIBLEGROUPS) - from
1193 * course_modules table
1194 * @var int
1196 private $groupmode;
1199 * Grouping ID (0 = all groupings)
1200 * @var int
1202 private $groupingid;
1205 * Indent level on course page (0 = no indent) - from course_modules table
1206 * @var int
1208 private $indent;
1211 * Activity completion setting for this activity, COMPLETION_TRACKING_xx constant - from
1212 * course_modules table
1213 * @var int
1215 private $completion;
1218 * Set to the item number (usually 0) if completion depends on a particular
1219 * grade of this activity, or null if completion does not depend on a grade - from
1220 * course_modules table
1221 * @var mixed
1223 private $completiongradeitemnumber;
1226 * 1 if pass grade completion is enabled, 0 otherwise - from course_modules table
1227 * @var int
1229 private $completionpassgrade;
1232 * 1 if 'on view' completion is enabled, 0 otherwise - from course_modules table
1233 * @var int
1235 private $completionview;
1238 * Set to a unix time if completion of this activity is expected at a
1239 * particular time, 0 if no time set - from course_modules table
1240 * @var int
1242 private $completionexpected;
1245 * Availability information as JSON string or null if none - from course_modules table
1246 * @var string
1248 private $availability;
1251 * Controls whether the description of the activity displays on the course main page (in
1252 * addition to anywhere it might display within the activity itself). 0 = do not show
1253 * on main page, 1 = show on main page.
1254 * @var int
1256 private $showdescription;
1259 * Extra HTML that is put in an unhelpful part of the HTML when displaying this module in
1260 * course page - from cached data in modinfo field
1261 * @deprecated This is crazy, don't use it. Replaced by ->extraclasses and ->onclick
1262 * @var string
1264 private $extra;
1267 * Name of icon to use - from cached data in modinfo field
1268 * @var string
1270 private $icon;
1273 * Component that contains icon - from cached data in modinfo field
1274 * @var string
1276 private $iconcomponent;
1279 * Name of module e.g. 'forum' (this is the same name as the module's main database
1280 * table) - from cached data in modinfo field
1281 * @var string
1283 private $modname;
1286 * ID of module - from course_modules table
1287 * @var int
1289 private $module;
1292 * Name of module instance for display on page e.g. 'General discussion forum' - from cached
1293 * data in modinfo field
1294 * @var string
1296 private $name;
1299 * Section number that this course-module is in (section 0 = above the calendar, section 1
1300 * = week/topic 1, etc) - from cached data in modinfo field
1301 * @var int
1303 private $sectionnum;
1306 * Section id - from course_modules table
1307 * @var int
1309 private $section;
1312 * Availability conditions for this course-module based on the completion of other
1313 * course-modules (array from other course-module id to required completion state for that
1314 * module) - from cached data in modinfo field
1315 * @var array
1317 private $conditionscompletion;
1320 * Availability conditions for this course-module based on course grades (array from
1321 * grade item id to object with ->min, ->max fields) - from cached data in modinfo field
1322 * @var array
1324 private $conditionsgrade;
1327 * Availability conditions for this course-module based on user fields
1328 * @var array
1330 private $conditionsfield;
1333 * True if this course-module is available to students i.e. if all availability conditions
1334 * are met - obtained dynamically
1335 * @var bool
1337 private $available;
1340 * If course-module is not available to students, this string gives information about
1341 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
1342 * January 2010') for display on main page - obtained dynamically
1343 * @var string
1345 private $availableinfo;
1348 * True if this course-module is available to the CURRENT user (for example, if current user
1349 * has viewhiddenactivities capability, they can access the course-module even if it is not
1350 * visible or not available, so this would be true in that case)
1351 * @var bool
1353 private $uservisible;
1356 * True if this course-module is visible to the CURRENT user on the course page
1357 * @var bool
1359 private $uservisibleoncoursepage;
1362 * @var moodle_url
1364 private $url;
1367 * @var string
1369 private $content;
1372 * @var bool
1374 private $contentisformatted;
1377 * @var bool True if the content has a special course item display like labels.
1379 private $customcmlistitem;
1382 * @var string
1384 private $extraclasses;
1387 * @var moodle_url full external url pointing to icon image for activity
1389 private $iconurl;
1392 * @var string
1394 private $onclick;
1397 * @var mixed
1399 private $customdata;
1402 * @var string
1404 private $afterlink;
1407 * @var string
1409 private $afterediticons;
1412 * @var bool representing the deletion state of the module. True if the mod is scheduled for deletion.
1414 private $deletioninprogress;
1417 * @var int enable/disable download content for this course module
1419 private $downloadcontent;
1422 * @var string|null the forced language for this activity (language pack name). Null means not forced.
1424 private $lang;
1427 * List of class read-only properties and their getter methods.
1428 * Used by magic functions __get(), __isset(), __empty()
1429 * @var array
1431 private static $standardproperties = [
1432 'url' => 'get_url',
1433 'content' => 'get_content',
1434 'extraclasses' => 'get_extra_classes',
1435 'onclick' => 'get_on_click',
1436 'customdata' => 'get_custom_data',
1437 'afterlink' => 'get_after_link',
1438 'afterediticons' => 'get_after_edit_icons',
1439 'modfullname' => 'get_module_type_name',
1440 'modplural' => 'get_module_type_name_plural',
1441 'id' => false,
1442 'added' => false,
1443 'availability' => false,
1444 'available' => 'get_available',
1445 'availableinfo' => 'get_available_info',
1446 'completion' => false,
1447 'completionexpected' => false,
1448 'completiongradeitemnumber' => false,
1449 'completionpassgrade' => false,
1450 'completionview' => false,
1451 'conditionscompletion' => false,
1452 'conditionsfield' => false,
1453 'conditionsgrade' => false,
1454 'context' => 'get_context',
1455 'course' => 'get_course_id',
1456 'coursegroupmode' => 'get_course_groupmode',
1457 'coursegroupmodeforce' => 'get_course_groupmodeforce',
1458 'customcmlistitem' => 'has_custom_cmlist_item',
1459 'effectivegroupmode' => 'get_effective_groupmode',
1460 'extra' => false,
1461 'groupingid' => false,
1462 'groupmembersonly' => 'get_deprecated_group_members_only',
1463 'groupmode' => false,
1464 'icon' => false,
1465 'iconcomponent' => false,
1466 'idnumber' => false,
1467 'indent' => false,
1468 'instance' => false,
1469 'modname' => false,
1470 'module' => false,
1471 'name' => 'get_name',
1472 'score' => false,
1473 'section' => false,
1474 'sectionnum' => false,
1475 'showdescription' => false,
1476 'uservisible' => 'get_user_visible',
1477 'visible' => false,
1478 'visibleoncoursepage' => false,
1479 'visibleold' => false,
1480 'deletioninprogress' => false,
1481 'downloadcontent' => false,
1482 'lang' => false,
1486 * List of methods with no arguments that were public prior to Moodle 2.6.
1488 * They can still be accessed publicly via magic __call() function with no warnings
1489 * but are not listed in the class methods list.
1490 * For the consistency of the code it is better to use corresponding properties.
1492 * These methods be deprecated completely in later versions.
1494 * @var array $standardmethods
1496 private static $standardmethods = array(
1497 // Following methods are not recommended to use because there have associated read-only properties.
1498 'get_url',
1499 'get_content',
1500 'get_extra_classes',
1501 'get_on_click',
1502 'get_custom_data',
1503 'get_after_link',
1504 'get_after_edit_icons',
1505 // Method obtain_dynamic_data() should not be called from outside of this class but it was public before Moodle 2.6.
1506 'obtain_dynamic_data',
1510 * Magic method to call functions that are now declared as private but were public in Moodle before 2.6.
1511 * These private methods can not be used anymore.
1513 * @param string $name
1514 * @param array $arguments
1515 * @return mixed
1516 * @throws coding_exception
1518 public function __call($name, $arguments) {
1519 if (in_array($name, self::$standardmethods)) {
1520 $message = "cm_info::$name() can not be used anymore.";
1521 if ($alternative = array_search($name, self::$standardproperties)) {
1522 $message .= " Please use the property cm_info->$alternative instead.";
1524 throw new coding_exception($message);
1526 throw new coding_exception("Method cm_info::{$name}() does not exist");
1530 * Magic method getter
1532 * @param string $name
1533 * @return mixed
1535 public function __get($name) {
1536 if (isset(self::$standardproperties[$name])) {
1537 if ($method = self::$standardproperties[$name]) {
1538 return $this->$method();
1539 } else {
1540 return $this->$name;
1542 } else {
1543 debugging('Invalid cm_info property accessed: '.$name);
1544 return null;
1549 * Implementation of IteratorAggregate::getIterator(), allows to cycle through properties
1550 * and use {@link convert_to_array()}
1552 * @return ArrayIterator
1554 public function getIterator(): Traversable {
1555 // Make sure dynamic properties are retrieved prior to view properties.
1556 $this->obtain_dynamic_data();
1557 $ret = array();
1559 // Do not iterate over deprecated properties.
1560 $props = self::$standardproperties;
1561 unset($props['groupmembersonly']);
1563 foreach ($props as $key => $unused) {
1564 $ret[$key] = $this->__get($key);
1566 return new ArrayIterator($ret);
1570 * Magic method for function isset()
1572 * @param string $name
1573 * @return bool
1575 public function __isset($name) {
1576 if (isset(self::$standardproperties[$name])) {
1577 $value = $this->__get($name);
1578 return isset($value);
1580 return false;
1584 * Magic method for function empty()
1586 * @param string $name
1587 * @return bool
1589 public function __empty($name) {
1590 if (isset(self::$standardproperties[$name])) {
1591 $value = $this->__get($name);
1592 return empty($value);
1594 return true;
1598 * Magic method setter
1600 * Will display the developer warning when trying to set/overwrite property.
1602 * @param string $name
1603 * @param mixed $value
1605 public function __set($name, $value) {
1606 debugging("It is not allowed to set the property cm_info::\${$name}", DEBUG_DEVELOPER);
1610 * @return bool True if this module has a 'view' page that should be linked to in navigation
1611 * etc (note: modules may still have a view.php file, but return false if this is not
1612 * intended to be linked to from 'normal' parts of the interface; this is what label does).
1614 public function has_view() {
1615 return !is_null($this->url);
1619 * Gets the URL to link to for this module.
1621 * This method is normally called by the property ->url, but can be called directly if
1622 * there is a case when it might be called recursively (you can't call property values
1623 * recursively).
1625 * @return moodle_url URL to link to for this module, or null if it doesn't have a view page
1627 public function get_url() {
1628 $this->obtain_dynamic_data();
1629 return $this->url;
1633 * Obtains content to display on main (view) page.
1634 * Note: Will collect view data, if not already obtained.
1635 * @return string Content to display on main page below link, or empty string if none
1637 private function get_content() {
1638 $this->obtain_view_data();
1639 return $this->content;
1643 * Returns the content to display on course/overview page, formatted and passed through filters
1645 * if $options['context'] is not specified, the module context is used
1647 * @param array|stdClass $options formatting options, see {@link format_text()}
1648 * @return string
1650 public function get_formatted_content($options = array()) {
1651 $this->obtain_view_data();
1652 if (empty($this->content)) {
1653 return '';
1655 if ($this->contentisformatted) {
1656 return $this->content;
1659 // Improve filter performance by preloading filter setttings for all
1660 // activities on the course (this does nothing if called multiple
1661 // times)
1662 filter_preload_activities($this->get_modinfo());
1664 $options = (array)$options;
1665 if (!isset($options['context'])) {
1666 $options['context'] = $this->get_context();
1668 return format_text($this->content, FORMAT_HTML, $options);
1672 * Return the module custom cmlist item flag.
1674 * Activities like label uses this flag to indicate that it should be
1675 * displayed as a custom course item instead of a tipical activity card.
1677 * @return bool
1679 public function has_custom_cmlist_item(): bool {
1680 $this->obtain_view_data();
1681 return $this->customcmlistitem ?? false;
1685 * Getter method for property $name, ensures that dynamic data is obtained.
1687 * This method is normally called by the property ->name, but can be called directly if there
1688 * is a case when it might be called recursively (you can't call property values recursively).
1690 * @return string
1692 public function get_name() {
1693 $this->obtain_dynamic_data();
1694 return $this->name;
1698 * Returns the name to display on course/overview page, formatted and passed through filters
1700 * if $options['context'] is not specified, the module context is used
1702 * @param array|stdClass $options formatting options, see {@link format_string()}
1703 * @return string
1705 public function get_formatted_name($options = array()) {
1706 global $CFG;
1707 $options = (array)$options;
1708 if (!isset($options['context'])) {
1709 $options['context'] = $this->get_context();
1711 // Improve filter performance by preloading filter setttings for all
1712 // activities on the course (this does nothing if called multiple
1713 // times).
1714 if (!empty($CFG->filterall)) {
1715 filter_preload_activities($this->get_modinfo());
1717 return format_string($this->get_name(), true, $options);
1721 * Note: Will collect view data, if not already obtained.
1722 * @return string Extra CSS classes to add to html output for this activity on main page
1724 private function get_extra_classes() {
1725 $this->obtain_view_data();
1726 return $this->extraclasses;
1730 * @return string Content of HTML on-click attribute. This string will be used literally
1731 * as a string so should be pre-escaped.
1733 private function get_on_click() {
1734 // Does not need view data; may be used by navigation
1735 $this->obtain_dynamic_data();
1736 return $this->onclick;
1739 * Getter method for property $customdata, ensures that dynamic data is retrieved.
1741 * This method is normally called by the property ->customdata, but can be called directly if there
1742 * is a case when it might be called recursively (you can't call property values recursively).
1744 * @return mixed Optional custom data stored in modinfo cache for this activity, or null if none
1746 public function get_custom_data() {
1747 $this->obtain_dynamic_data();
1748 return $this->customdata;
1752 * Note: Will collect view data, if not already obtained.
1753 * @return string Extra HTML code to display after link
1755 private function get_after_link() {
1756 $this->obtain_view_data();
1757 return $this->afterlink;
1761 * Get the activity badge data associated to this course module (if the module supports it).
1762 * Modules can use this method to provide additional data to be displayed in the activity badge.
1764 * @param renderer_base $output Output render to use, or null for default (global)
1765 * @return stdClass|null The activitybadge data (badgecontent, badgestyle...) or null if the module doesn't implement it.
1767 public function get_activitybadge(?renderer_base $output = null): ?stdClass {
1768 global $OUTPUT;
1770 $activibybadgeclass = activitybadge::create_instance($this);
1771 if (empty($activibybadgeclass)) {
1772 return null;
1775 if (!isset($output)) {
1776 $output = $OUTPUT;
1779 return $activibybadgeclass->export_for_template($output);
1783 * Note: Will collect view data, if not already obtained.
1784 * @return string Extra HTML code to display after editing icons (e.g. more icons)
1786 private function get_after_edit_icons() {
1787 $this->obtain_view_data();
1788 return $this->afterediticons;
1792 * Fetch the module's icon URL.
1794 * This function fetches the course module instance's icon URL.
1795 * This method adds a `filtericon` parameter in the URL when rendering the monologo version of the course module icon or when
1796 * the plugin declares, via its `filtericon` custom data, that the icon needs to be filtered.
1797 * This additional information can be used by plugins when rendering the module icon to determine whether to apply
1798 * CSS filtering to the icon.
1800 * @param core_renderer $output Output render to use, or null for default (global)
1801 * @return moodle_url Icon URL for a suitable icon to put beside this cm
1803 public function get_icon_url($output = null) {
1804 global $OUTPUT;
1805 $this->obtain_dynamic_data();
1806 if (!$output) {
1807 $output = $OUTPUT;
1810 $ismonologo = false;
1811 if (!empty($this->iconurl)) {
1812 // Support modules setting their own, external, icon image.
1813 $icon = $this->iconurl;
1814 } else if (!empty($this->icon)) {
1815 // Fallback to normal local icon + component processing.
1816 if (substr($this->icon, 0, 4) === 'mod/') {
1817 list($modname, $iconname) = explode('/', substr($this->icon, 4), 2);
1818 $icon = $output->image_url($iconname, $modname);
1819 } else {
1820 if (!empty($this->iconcomponent)) {
1821 // Icon has specified component.
1822 $icon = $output->image_url($this->icon, $this->iconcomponent);
1823 } else {
1824 // Icon does not have specified component, use default.
1825 $icon = $output->image_url($this->icon);
1828 } else {
1829 $icon = $output->image_url('monologo', $this->modname);
1830 // Activity modules may only have an `icon` icon instead of a `monologo` icon.
1831 // So we need to determine if the module really has a `monologo` icon.
1832 $ismonologo = core_component::has_monologo_icon('mod', $this->modname);
1835 // Determine whether the icon will be filtered in the CSS.
1836 // This can be controlled by the module by declaring a 'filtericon' custom data.
1837 // If the 'filtericon' custom data is not set, icon filtering will be determined whether the module has a `monologo` icon.
1838 // Additionally, we need to cast custom data to array as some modules may treat it as an object.
1839 $filtericon = ((array)$this->customdata)['filtericon'] ?? $ismonologo;
1840 if ($filtericon) {
1841 $icon->param('filtericon', 1);
1843 return $icon;
1847 * @param string $textclasses additionnal classes for grouping label
1848 * @return string An empty string or HTML grouping label span tag
1850 public function get_grouping_label($textclasses = '') {
1851 $groupinglabel = '';
1852 if ($this->effectivegroupmode != NOGROUPS && !empty($this->groupingid) &&
1853 has_capability('moodle/course:managegroups', context_course::instance($this->course))) {
1854 $groupings = groups_get_all_groupings($this->course);
1855 $groupinglabel = html_writer::tag('span', '('.format_string($groupings[$this->groupingid]->name).')',
1856 array('class' => 'groupinglabel '.$textclasses));
1858 return $groupinglabel;
1862 * Returns a localised human-readable name of the module type.
1864 * @param bool $plural If true, the function returns the plural form of the name.
1865 * @return lang_string
1867 public function get_module_type_name($plural = false) {
1868 $modnames = get_module_types_names($plural);
1869 if (isset($modnames[$this->modname])) {
1870 return $modnames[$this->modname];
1871 } else {
1872 return null;
1877 * Returns a localised human-readable name of the module type in plural form - calculated on request
1879 * @return string
1881 private function get_module_type_name_plural() {
1882 return $this->get_module_type_name(true);
1886 * @return course_modinfo Modinfo object that this came from
1888 public function get_modinfo() {
1889 return $this->modinfo;
1893 * Returns the section this module belongs to
1895 * @return section_info
1897 public function get_section_info() {
1898 return $this->modinfo->get_section_info($this->sectionnum);
1902 * Returns course object that was used in the first {@link get_fast_modinfo()} call.
1904 * It may not contain all fields from DB table {course} but always has at least the following:
1905 * id,shortname,fullname,format,enablecompletion,groupmode,groupmodeforce,cacherev
1907 * If the course object lacks the field you need you can use the global
1908 * function {@link get_course()} that will save extra query if you access
1909 * current course or frontpage course.
1911 * @return stdClass
1913 public function get_course() {
1914 return $this->modinfo->get_course();
1918 * Returns course id for which the modinfo was generated.
1920 * @return int
1922 private function get_course_id() {
1923 return $this->modinfo->get_course_id();
1927 * Returns group mode used for the course containing the module
1929 * @return int one of constants NOGROUPS, SEPARATEGROUPS, VISIBLEGROUPS
1931 private function get_course_groupmode() {
1932 return $this->modinfo->get_course()->groupmode;
1936 * Returns whether group mode is forced for the course containing the module
1938 * @return bool
1940 private function get_course_groupmodeforce() {
1941 return $this->modinfo->get_course()->groupmodeforce;
1945 * Returns effective groupmode of the module that may be overwritten by forced course groupmode.
1947 * @return int one of constants NOGROUPS, SEPARATEGROUPS, VISIBLEGROUPS
1949 private function get_effective_groupmode() {
1950 $groupmode = $this->groupmode;
1951 if ($this->modinfo->get_course()->groupmodeforce) {
1952 $groupmode = $this->modinfo->get_course()->groupmode;
1953 if ($groupmode != NOGROUPS && !plugin_supports('mod', $this->modname, FEATURE_GROUPS, false)) {
1954 $groupmode = NOGROUPS;
1957 return $groupmode;
1961 * @return context_module Current module context
1963 private function get_context() {
1964 return context_module::instance($this->id);
1968 * Returns itself in the form of stdClass.
1970 * The object includes all fields that table course_modules has and additionally
1971 * fields 'name', 'modname', 'sectionnum' (if requested).
1973 * This can be used as a faster alternative to {@link get_coursemodule_from_id()}
1975 * @param bool $additionalfields include additional fields 'name', 'modname', 'sectionnum'
1976 * @return stdClass
1978 public function get_course_module_record($additionalfields = false) {
1979 $cmrecord = new stdClass();
1981 // Standard fields from table course_modules.
1982 static $cmfields = array('id', 'course', 'module', 'instance', 'section', 'idnumber', 'added',
1983 'score', 'indent', 'visible', 'visibleoncoursepage', 'visibleold', 'groupmode', 'groupingid',
1984 'completion', 'completiongradeitemnumber', 'completionview', 'completionexpected', 'completionpassgrade',
1985 'showdescription', 'availability', 'deletioninprogress', 'downloadcontent', 'lang');
1987 foreach ($cmfields as $key) {
1988 $cmrecord->$key = $this->$key;
1991 // Additional fields that function get_coursemodule_from_id() adds.
1992 if ($additionalfields) {
1993 $cmrecord->name = $this->name;
1994 $cmrecord->modname = $this->modname;
1995 $cmrecord->sectionnum = $this->sectionnum;
1998 return $cmrecord;
2001 // Set functions
2002 ////////////////
2005 * Sets content to display on course view page below link (if present).
2006 * @param string $content New content as HTML string (empty string if none)
2007 * @param bool $isformatted Whether user content is already passed through format_text/format_string and should not
2008 * be formatted again. This can be useful when module adds interactive elements on top of formatted user text.
2009 * @return void
2011 public function set_content($content, $isformatted = false) {
2012 $this->content = $content;
2013 $this->contentisformatted = $isformatted;
2017 * Sets extra classes to include in CSS.
2018 * @param string $extraclasses Extra classes (empty string if none)
2019 * @return void
2021 public function set_extra_classes($extraclasses) {
2022 $this->extraclasses = $extraclasses;
2026 * Sets the external full url that points to the icon being used
2027 * by the activity. Useful for external-tool modules (lti...)
2028 * If set, takes precedence over $icon and $iconcomponent
2030 * @param moodle_url $iconurl full external url pointing to icon image for activity
2031 * @return void
2033 public function set_icon_url(moodle_url $iconurl) {
2034 $this->iconurl = $iconurl;
2038 * Sets value of on-click attribute for JavaScript.
2039 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
2040 * @param string $onclick New onclick attribute which should be HTML-escaped
2041 * (empty string if none)
2042 * @return void
2044 public function set_on_click($onclick) {
2045 $this->check_not_view_only();
2046 $this->onclick = $onclick;
2050 * Overrides the value of an element in the customdata array.
2052 * @param string $name The key in the customdata array
2053 * @param mixed $value The value
2055 public function override_customdata($name, $value) {
2056 if (!is_array($this->customdata)) {
2057 $this->customdata = [];
2059 $this->customdata[$name] = $value;
2063 * Sets HTML that displays after link on course view page.
2064 * @param string $afterlink HTML string (empty string if none)
2065 * @return void
2067 public function set_after_link($afterlink) {
2068 $this->afterlink = $afterlink;
2072 * Sets HTML that displays after edit icons on course view page.
2073 * @param string $afterediticons HTML string (empty string if none)
2074 * @return void
2076 public function set_after_edit_icons($afterediticons) {
2077 $this->afterediticons = $afterediticons;
2081 * Changes the name (text of link) for this module instance.
2082 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
2083 * @param string $name Name of activity / link text
2084 * @return void
2086 public function set_name($name) {
2087 if ($this->state < self::STATE_BUILDING_DYNAMIC) {
2088 $this->update_user_visible();
2090 $this->name = $name;
2094 * Turns off the view link for this module instance.
2095 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
2096 * @return void
2098 public function set_no_view_link() {
2099 $this->check_not_view_only();
2100 $this->url = null;
2104 * Sets the 'uservisible' flag. This can be used (by setting false) to prevent access and
2105 * display of this module link for the current user.
2106 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
2107 * @param bool $uservisible
2108 * @return void
2110 public function set_user_visible($uservisible) {
2111 $this->check_not_view_only();
2112 $this->uservisible = $uservisible;
2116 * Sets the 'customcmlistitem' flag
2118 * This can be used (by setting true) to prevent the course from rendering the
2119 * activity item as a regular activity card. This is applied to activities like labels.
2121 * @param bool $customcmlistitem if the cmlist item of that activity has a special dysplay other than a card.
2123 public function set_custom_cmlist_item(bool $customcmlistitem) {
2124 $this->customcmlistitem = $customcmlistitem;
2128 * Sets the 'available' flag and related details. This flag is normally used to make
2129 * course modules unavailable until a certain date or condition is met. (When a course
2130 * module is unavailable, it is still visible to users who have viewhiddenactivities
2131 * permission.)
2133 * When this is function is called, user-visible status is recalculated automatically.
2135 * The $showavailability flag does not really do anything any more, but is retained
2136 * for backward compatibility. Setting this to false will cause $availableinfo to
2137 * be ignored.
2139 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
2140 * @param bool $available False if this item is not 'available'
2141 * @param int $showavailability 0 = do not show this item at all if it's not available,
2142 * 1 = show this item greyed out with the following message
2143 * @param string $availableinfo Information about why this is not available, or
2144 * empty string if not displaying
2145 * @return void
2147 public function set_available($available, $showavailability=0, $availableinfo='') {
2148 $this->check_not_view_only();
2149 $this->available = $available;
2150 if (!$showavailability) {
2151 $availableinfo = '';
2153 $this->availableinfo = $availableinfo;
2154 $this->update_user_visible();
2158 * Some set functions can only be called from _cm_info_dynamic and not _cm_info_view.
2159 * This is because they may affect parts of this object which are used on pages other
2160 * than the view page (e.g. in the navigation block, or when checking access on
2161 * module pages).
2162 * @return void
2164 private function check_not_view_only() {
2165 if ($this->state >= self::STATE_DYNAMIC) {
2166 throw new coding_exception('Cannot set this data from _cm_info_view because it may ' .
2167 'affect other pages as well as view');
2172 * Constructor should not be called directly; use {@link get_fast_modinfo()}
2174 * @param course_modinfo $modinfo Parent object
2175 * @param stdClass $notused1 Argument not used
2176 * @param stdClass $mod Module object from the modinfo field of course table
2177 * @param stdClass $notused2 Argument not used
2179 public function __construct(course_modinfo $modinfo, $notused1, $mod, $notused2) {
2180 $this->modinfo = $modinfo;
2182 $this->id = $mod->cm;
2183 $this->instance = $mod->id;
2184 $this->modname = $mod->mod;
2185 $this->idnumber = isset($mod->idnumber) ? $mod->idnumber : '';
2186 $this->name = $mod->name;
2187 $this->visible = $mod->visible;
2188 $this->visibleoncoursepage = $mod->visibleoncoursepage;
2189 $this->sectionnum = $mod->section; // Note weirdness with name here
2190 $this->groupmode = isset($mod->groupmode) ? $mod->groupmode : 0;
2191 $this->groupingid = isset($mod->groupingid) ? $mod->groupingid : 0;
2192 $this->indent = isset($mod->indent) ? $mod->indent : 0;
2193 $this->extra = isset($mod->extra) ? $mod->extra : '';
2194 $this->extraclasses = isset($mod->extraclasses) ? $mod->extraclasses : '';
2195 // iconurl may be stored as either string or instance of moodle_url.
2196 $this->iconurl = isset($mod->iconurl) ? new moodle_url($mod->iconurl) : '';
2197 $this->onclick = isset($mod->onclick) ? $mod->onclick : '';
2198 $this->content = isset($mod->content) ? $mod->content : '';
2199 $this->icon = isset($mod->icon) ? $mod->icon : '';
2200 $this->iconcomponent = isset($mod->iconcomponent) ? $mod->iconcomponent : '';
2201 $this->customdata = isset($mod->customdata) ? $mod->customdata : '';
2202 $this->showdescription = isset($mod->showdescription) ? $mod->showdescription : 0;
2203 $this->state = self::STATE_BASIC;
2205 $this->section = isset($mod->sectionid) ? $mod->sectionid : 0;
2206 $this->module = isset($mod->module) ? $mod->module : 0;
2207 $this->added = isset($mod->added) ? $mod->added : 0;
2208 $this->score = isset($mod->score) ? $mod->score : 0;
2209 $this->visibleold = isset($mod->visibleold) ? $mod->visibleold : 0;
2210 $this->deletioninprogress = isset($mod->deletioninprogress) ? $mod->deletioninprogress : 0;
2211 $this->downloadcontent = $mod->downloadcontent ?? null;
2212 $this->lang = $mod->lang ?? null;
2214 // Note: it saves effort and database space to always include the
2215 // availability and completion fields, even if availability or completion
2216 // are actually disabled
2217 $this->completion = isset($mod->completion) ? $mod->completion : 0;
2218 $this->completionpassgrade = isset($mod->completionpassgrade) ? $mod->completionpassgrade : 0;
2219 $this->completiongradeitemnumber = isset($mod->completiongradeitemnumber)
2220 ? $mod->completiongradeitemnumber : null;
2221 $this->completionview = isset($mod->completionview)
2222 ? $mod->completionview : 0;
2223 $this->completionexpected = isset($mod->completionexpected)
2224 ? $mod->completionexpected : 0;
2225 $this->availability = isset($mod->availability) ? $mod->availability : null;
2226 $this->conditionscompletion = isset($mod->conditionscompletion)
2227 ? $mod->conditionscompletion : array();
2228 $this->conditionsgrade = isset($mod->conditionsgrade)
2229 ? $mod->conditionsgrade : array();
2230 $this->conditionsfield = isset($mod->conditionsfield)
2231 ? $mod->conditionsfield : array();
2233 static $modviews = array();
2234 if (!isset($modviews[$this->modname])) {
2235 $modviews[$this->modname] = !plugin_supports('mod', $this->modname,
2236 FEATURE_NO_VIEW_LINK);
2238 $this->url = $modviews[$this->modname]
2239 ? new moodle_url('/mod/' . $this->modname . '/view.php', array('id'=>$this->id))
2240 : null;
2244 * Creates a cm_info object from a database record (also accepts cm_info
2245 * in which case it is just returned unchanged).
2247 * @param stdClass|cm_info|null|bool $cm Stdclass or cm_info (or null or false)
2248 * @param int $userid Optional userid (default to current)
2249 * @return cm_info|null Object as cm_info, or null if input was null/false
2251 public static function create($cm, $userid = 0) {
2252 // Null, false, etc. gets passed through as null.
2253 if (!$cm) {
2254 return null;
2256 // If it is already a cm_info object, just return it.
2257 if ($cm instanceof cm_info) {
2258 return $cm;
2260 // Otherwise load modinfo.
2261 if (empty($cm->id) || empty($cm->course)) {
2262 throw new coding_exception('$cm must contain ->id and ->course');
2264 $modinfo = get_fast_modinfo($cm->course, $userid);
2265 return $modinfo->get_cm($cm->id);
2269 * If dynamic data for this course-module is not yet available, gets it.
2271 * This function is automatically called when requesting any course_modinfo property
2272 * that can be modified by modules (have a set_xxx method).
2274 * Dynamic data is data which does not come directly from the cache but is calculated at
2275 * runtime based on the current user. Primarily this concerns whether the user can access
2276 * the module or not.
2278 * As part of this function, the module's _cm_info_dynamic function from its lib.php will
2279 * be called (if it exists). Make sure that the functions that are called here do not use
2280 * any getter magic method from cm_info.
2281 * @return void
2283 private function obtain_dynamic_data() {
2284 global $CFG;
2285 $userid = $this->modinfo->get_user_id();
2286 if ($this->state >= self::STATE_BUILDING_DYNAMIC || $userid == -1) {
2287 return;
2289 $this->state = self::STATE_BUILDING_DYNAMIC;
2291 if (!empty($CFG->enableavailability)) {
2292 // Get availability information.
2293 $ci = new \core_availability\info_module($this);
2295 // Note that the modinfo currently available only includes minimal details (basic data)
2296 // but we know that this function does not need anything more than basic data.
2297 $this->available = $ci->is_available($this->availableinfo, true,
2298 $userid, $this->modinfo);
2299 } else {
2300 $this->available = true;
2303 // Check parent section.
2304 if ($this->available) {
2305 $parentsection = $this->modinfo->get_section_info($this->sectionnum);
2306 if (!$parentsection->get_available()) {
2307 // Do not store info from section here, as that is already
2308 // presented from the section (if appropriate) - just change
2309 // the flag
2310 $this->available = false;
2314 // Update visible state for current user.
2315 $this->update_user_visible();
2317 // Let module make dynamic changes at this point
2318 $this->call_mod_function('cm_info_dynamic');
2319 $this->state = self::STATE_DYNAMIC;
2323 * Getter method for property $uservisible, ensures that dynamic data is retrieved.
2325 * This method is normally called by the property ->uservisible, but can be called directly if
2326 * there is a case when it might be called recursively (you can't call property values
2327 * recursively).
2329 * @return bool
2331 public function get_user_visible() {
2332 $this->obtain_dynamic_data();
2333 return $this->uservisible;
2337 * Returns whether this module is visible to the current user on course page
2339 * Activity may be visible on the course page but not available, for example
2340 * when it is hidden conditionally but the condition information is displayed.
2342 * @return bool
2344 public function is_visible_on_course_page() {
2345 $this->obtain_dynamic_data();
2346 return $this->uservisibleoncoursepage;
2350 * Whether this module is available but hidden from course page
2352 * "Stealth" modules are the ones that are not shown on course page but available by following url.
2353 * They are normally also displayed in grade reports and other reports.
2354 * Module will be stealth either if visibleoncoursepage=0 or it is a visible module inside the hidden
2355 * section.
2357 * @return bool
2359 public function is_stealth() {
2360 return !$this->visibleoncoursepage ||
2361 ($this->visible && ($section = $this->get_section_info()) && !$section->visible);
2365 * Getter method for property $available, ensures that dynamic data is retrieved
2366 * @return bool
2368 private function get_available() {
2369 $this->obtain_dynamic_data();
2370 return $this->available;
2374 * This method can not be used anymore.
2376 * @see \core_availability\info_module::filter_user_list()
2377 * @deprecated Since Moodle 2.8
2379 private function get_deprecated_group_members_only() {
2380 throw new coding_exception('$cm->groupmembersonly can not be used anymore. ' .
2381 'If used to restrict a list of enrolled users to only those who can ' .
2382 'access the module, consider \core_availability\info_module::filter_user_list.');
2386 * Getter method for property $availableinfo, ensures that dynamic data is retrieved
2388 * @return string Available info (HTML)
2390 private function get_available_info() {
2391 $this->obtain_dynamic_data();
2392 return $this->availableinfo;
2396 * Works out whether activity is available to the current user
2398 * If the activity is unavailable, additional checks are required to determine if its hidden or greyed out
2400 * @return void
2402 private function update_user_visible() {
2403 $userid = $this->modinfo->get_user_id();
2404 if ($userid == -1) {
2405 return null;
2407 $this->uservisible = true;
2409 // If the module is being deleted, set the uservisible state to false and return.
2410 if ($this->deletioninprogress) {
2411 $this->uservisible = false;
2412 return null;
2415 // If the user cannot access the activity set the uservisible flag to false.
2416 // Additional checks are required to determine whether the activity is entirely hidden or just greyed out.
2417 if ((!$this->visible && !has_capability('moodle/course:viewhiddenactivities', $this->get_context(), $userid)) ||
2418 (!$this->get_available() &&
2419 !has_capability('moodle/course:ignoreavailabilityrestrictions', $this->get_context(), $userid))) {
2421 $this->uservisible = false;
2424 // Check group membership.
2425 if ($this->is_user_access_restricted_by_capability()) {
2427 $this->uservisible = false;
2428 // Ensure activity is completely hidden from the user.
2429 $this->availableinfo = '';
2432 $this->uservisibleoncoursepage = $this->uservisible &&
2433 ($this->visibleoncoursepage ||
2434 has_capability('moodle/course:manageactivities', $this->get_context(), $userid) ||
2435 has_capability('moodle/course:activityvisibility', $this->get_context(), $userid));
2436 // Activity that is not available, not hidden from course page and has availability
2437 // info is actually visible on the course page (with availability info and without a link).
2438 if (!$this->uservisible && $this->visibleoncoursepage && $this->availableinfo) {
2439 $this->uservisibleoncoursepage = true;
2444 * This method has been deprecated and should not be used.
2446 * @see $uservisible
2447 * @deprecated Since Moodle 2.8
2449 public function is_user_access_restricted_by_group() {
2450 throw new coding_exception('cm_info::is_user_access_restricted_by_group() can not be used any more.' .
2451 ' Use $cm->uservisible to decide whether the current user can access an activity.');
2455 * Checks whether mod/...:view capability restricts the current user's access.
2457 * @return bool True if the user access is restricted.
2459 public function is_user_access_restricted_by_capability() {
2460 $userid = $this->modinfo->get_user_id();
2461 if ($userid == -1) {
2462 return null;
2464 $capability = 'mod/' . $this->modname . ':view';
2465 $capabilityinfo = get_capability_info($capability);
2466 if (!$capabilityinfo) {
2467 // Capability does not exist, no one is prevented from seeing the activity.
2468 return false;
2471 // You are blocked if you don't have the capability.
2472 return !has_capability($capability, $this->get_context(), $userid);
2476 * Checks whether the module's conditional access settings mean that the
2477 * user cannot see the activity at all
2479 * @deprecated since 2.7 MDL-44070
2481 public function is_user_access_restricted_by_conditional_access() {
2482 throw new coding_exception('cm_info::is_user_access_restricted_by_conditional_access() ' .
2483 'can not be used any more; this function is not needed (use $cm->uservisible ' .
2484 'and $cm->availableinfo to decide whether it should be available ' .
2485 'or appear)');
2489 * Calls a module function (if exists), passing in one parameter: this object.
2490 * @param string $type Name of function e.g. if this is 'grooblezorb' and the modname is
2491 * 'forum' then it will try to call 'mod_forum_grooblezorb' or 'forum_grooblezorb'
2492 * @return void
2494 private function call_mod_function($type) {
2495 global $CFG;
2496 $libfile = $CFG->dirroot . '/mod/' . $this->modname . '/lib.php';
2497 if (file_exists($libfile)) {
2498 include_once($libfile);
2499 $function = 'mod_' . $this->modname . '_' . $type;
2500 if (function_exists($function)) {
2501 $function($this);
2502 } else {
2503 $function = $this->modname . '_' . $type;
2504 if (function_exists($function)) {
2505 $function($this);
2512 * If view data for this course-module is not yet available, obtains it.
2514 * This function is automatically called if any of the functions (marked) which require
2515 * view data are called.
2517 * View data is data which is needed only for displaying the course main page (& any similar
2518 * functionality on other pages) but is not needed in general. Obtaining view data may have
2519 * a performance cost.
2521 * As part of this function, the module's _cm_info_view function from its lib.php will
2522 * be called (if it exists).
2523 * @return void
2525 private function obtain_view_data() {
2526 if ($this->state >= self::STATE_BUILDING_VIEW || $this->modinfo->get_user_id() == -1) {
2527 return;
2529 $this->obtain_dynamic_data();
2530 $this->state = self::STATE_BUILDING_VIEW;
2532 // Let module make changes at this point
2533 $this->call_mod_function('cm_info_view');
2534 $this->state = self::STATE_VIEW;
2540 * Returns reference to full info about modules in course (including visibility).
2541 * Cached and as fast as possible (0 or 1 db query).
2543 * use get_fast_modinfo($courseid, 0, true) to reset the static cache for particular course
2544 * use get_fast_modinfo(0, 0, true) to reset the static cache for all courses
2546 * use rebuild_course_cache($courseid, true) to reset the application AND static cache
2547 * for particular course when it's contents has changed
2549 * @param int|stdClass $courseorid object from DB table 'course' (must have field 'id'
2550 * and recommended to have field 'cacherev') or just a course id. Just course id
2551 * is enough when calling get_fast_modinfo() for current course or site or when
2552 * calling for any other course for the second time.
2553 * @param int $userid User id to populate 'availble' and 'uservisible' attributes of modules and sections.
2554 * Set to 0 for current user (default). Set to -1 to avoid calculation of dynamic user-depended data.
2555 * @param bool $resetonly whether we want to get modinfo or just reset the cache
2556 * @return course_modinfo|null Module information for course, or null if resetting
2557 * @throws moodle_exception when course is not found (nothing is thrown if resetting)
2559 function get_fast_modinfo($courseorid, $userid = 0, $resetonly = false) {
2560 // compartibility with syntax prior to 2.4:
2561 if ($courseorid === 'reset') {
2562 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);
2563 $courseorid = 0;
2564 $resetonly = true;
2567 // Function get_fast_modinfo() can never be called during upgrade unless it is used for clearing cache only.
2568 if (!$resetonly) {
2569 upgrade_ensure_not_running();
2572 // Function is called with $reset = true
2573 if ($resetonly) {
2574 course_modinfo::clear_instance_cache($courseorid);
2575 return null;
2578 // Function is called with $reset = false, retrieve modinfo
2579 return course_modinfo::instance($courseorid, $userid);
2583 * Efficiently retrieves the $course (stdclass) and $cm (cm_info) objects, given
2584 * a cmid. If module name is also provided, it will ensure the cm is of that type.
2586 * Usage:
2587 * list($course, $cm) = get_course_and_cm_from_cmid($cmid, 'forum');
2589 * Using this method has a performance advantage because it works by loading
2590 * modinfo for the course - which will then be cached and it is needed later
2591 * in most requests. It also guarantees that the $cm object is a cm_info and
2592 * not a stdclass.
2594 * The $course object can be supplied if already known and will speed
2595 * up this function - although it is more efficient to use this function to
2596 * get the course if you are starting from a cmid.
2598 * To avoid security problems and obscure bugs, you should always specify
2599 * $modulename if the cmid value came from user input.
2601 * By default this obtains information (for example, whether user can access
2602 * the activity) for current user, but you can specify a userid if required.
2604 * @param stdClass|int $cmorid Id of course-module, or database object
2605 * @param string $modulename Optional modulename (improves security)
2606 * @param stdClass|int $courseorid Optional course object if already loaded
2607 * @param int $userid Optional userid (default = current)
2608 * @return array Array with 2 elements $course and $cm
2609 * @throws moodle_exception If the item doesn't exist or is of wrong module name
2611 function get_course_and_cm_from_cmid($cmorid, $modulename = '', $courseorid = 0, $userid = 0) {
2612 global $DB;
2613 if (is_object($cmorid)) {
2614 $cmid = $cmorid->id;
2615 if (isset($cmorid->course)) {
2616 $courseid = (int)$cmorid->course;
2617 } else {
2618 $courseid = 0;
2620 } else {
2621 $cmid = (int)$cmorid;
2622 $courseid = 0;
2625 // Validate module name if supplied.
2626 if ($modulename && !core_component::is_valid_plugin_name('mod', $modulename)) {
2627 throw new coding_exception('Invalid modulename parameter');
2630 // Get course from last parameter if supplied.
2631 $course = null;
2632 if (is_object($courseorid)) {
2633 $course = $courseorid;
2634 } else if ($courseorid) {
2635 $courseid = (int)$courseorid;
2638 if (!$course) {
2639 if ($courseid) {
2640 // If course ID is known, get it using normal function.
2641 $course = get_course($courseid);
2642 } else {
2643 // Get course record in a single query based on cmid.
2644 $course = $DB->get_record_sql("
2645 SELECT c.*
2646 FROM {course_modules} cm
2647 JOIN {course} c ON c.id = cm.course
2648 WHERE cm.id = ?", array($cmid), MUST_EXIST);
2652 // Get cm from get_fast_modinfo.
2653 $modinfo = get_fast_modinfo($course, $userid);
2654 $cm = $modinfo->get_cm($cmid);
2655 if ($modulename && $cm->modname !== $modulename) {
2656 throw new moodle_exception('invalidcoursemoduleid', 'error', '', $cmid);
2658 return array($course, $cm);
2662 * Efficiently retrieves the $course (stdclass) and $cm (cm_info) objects, given
2663 * an instance id or record and module name.
2665 * Usage:
2666 * list($course, $cm) = get_course_and_cm_from_instance($forum, 'forum');
2668 * Using this method has a performance advantage because it works by loading
2669 * modinfo for the course - which will then be cached and it is needed later
2670 * in most requests. It also guarantees that the $cm object is a cm_info and
2671 * not a stdclass.
2673 * The $course object can be supplied if already known and will speed
2674 * up this function - although it is more efficient to use this function to
2675 * get the course if you are starting from an instance id.
2677 * By default this obtains information (for example, whether user can access
2678 * the activity) for current user, but you can specify a userid if required.
2680 * @param stdclass|int $instanceorid Id of module instance, or database object
2681 * @param string $modulename Modulename (required)
2682 * @param stdClass|int $courseorid Optional course object if already loaded
2683 * @param int $userid Optional userid (default = current)
2684 * @return array Array with 2 elements $course and $cm
2685 * @throws moodle_exception If the item doesn't exist or is of wrong module name
2687 function get_course_and_cm_from_instance($instanceorid, $modulename, $courseorid = 0, $userid = 0) {
2688 global $DB;
2690 // Get data from parameter.
2691 if (is_object($instanceorid)) {
2692 $instanceid = $instanceorid->id;
2693 if (isset($instanceorid->course)) {
2694 $courseid = (int)$instanceorid->course;
2695 } else {
2696 $courseid = 0;
2698 } else {
2699 $instanceid = (int)$instanceorid;
2700 $courseid = 0;
2703 // Get course from last parameter if supplied.
2704 $course = null;
2705 if (is_object($courseorid)) {
2706 $course = $courseorid;
2707 } else if ($courseorid) {
2708 $courseid = (int)$courseorid;
2711 // Validate module name if supplied.
2712 if (!core_component::is_valid_plugin_name('mod', $modulename)) {
2713 throw new coding_exception('Invalid modulename parameter');
2716 if (!$course) {
2717 if ($courseid) {
2718 // If course ID is known, get it using normal function.
2719 $course = get_course($courseid);
2720 } else {
2721 // Get course record in a single query based on instance id.
2722 $pagetable = '{' . $modulename . '}';
2723 $course = $DB->get_record_sql("
2724 SELECT c.*
2725 FROM $pagetable instance
2726 JOIN {course} c ON c.id = instance.course
2727 WHERE instance.id = ?", array($instanceid), MUST_EXIST);
2731 // Get cm from get_fast_modinfo.
2732 $modinfo = get_fast_modinfo($course, $userid);
2733 $instances = $modinfo->get_instances_of($modulename);
2734 if (!array_key_exists($instanceid, $instances)) {
2735 throw new moodle_exception('invalidmoduleid', 'error', $instanceid);
2737 return array($course, $instances[$instanceid]);
2742 * Rebuilds or resets the cached list of course activities stored in MUC.
2744 * rebuild_course_cache() must NEVER be called from lib/db/upgrade.php.
2745 * At the same time course cache may ONLY be cleared using this function in
2746 * upgrade scripts of plugins.
2748 * During the bulk operations if it is necessary to reset cache of multiple
2749 * courses it is enough to call {@link increment_revision_number()} for the
2750 * table 'course' and field 'cacherev' specifying affected courses in select.
2752 * Cached course information is stored in MUC core/coursemodinfo and is
2753 * validated with the DB field {course}.cacherev
2755 * @global moodle_database $DB
2756 * @param int $courseid id of course to rebuild, empty means all
2757 * @param boolean $clearonly only clear the cache, gets rebuild automatically on the fly.
2758 * Recommended to set to true to avoid unnecessary multiple rebuilding.
2759 * @param boolean $partialrebuild will not delete the whole cache when it's true.
2760 * use purge_module_cache() or purge_section_cache() must be
2761 * called before when partialrebuild is true.
2762 * use purge_module_cache() to invalidate mod cache.
2763 * use purge_section_cache() to invalidate section cache.
2765 * @return void
2766 * @throws coding_exception
2768 function rebuild_course_cache(int $courseid = 0, bool $clearonly = false, bool $partialrebuild = false): void {
2769 global $COURSE, $SITE, $DB;
2771 if ($courseid == 0 and $partialrebuild) {
2772 throw new coding_exception('partialrebuild only works when a valid course id is provided.');
2775 // Function rebuild_course_cache() can not be called during upgrade unless it's clear only.
2776 if (!$clearonly && !upgrade_ensure_not_running(true)) {
2777 $clearonly = true;
2780 // Destroy navigation caches
2781 navigation_cache::destroy_volatile_caches();
2783 core_courseformat\base::reset_course_cache($courseid);
2785 $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
2786 if (empty($courseid)) {
2787 // Clearing caches for all courses.
2788 increment_revision_number('course', 'cacherev', '');
2789 if (!$partialrebuild) {
2790 $cachecoursemodinfo->purge();
2792 // Clear memory static cache.
2793 course_modinfo::clear_instance_cache();
2794 // Update global values too.
2795 $sitecacherev = $DB->get_field('course', 'cacherev', array('id' => SITEID));
2796 $SITE->cachrev = $sitecacherev;
2797 if ($COURSE->id == SITEID) {
2798 $COURSE->cacherev = $sitecacherev;
2799 } else {
2800 $COURSE->cacherev = $DB->get_field('course', 'cacherev', array('id' => $COURSE->id));
2802 } else {
2803 // Clearing cache for one course, make sure it is deleted from user request cache as well.
2804 increment_revision_number('course', 'cacherev', 'id = :id', array('id' => $courseid));
2805 if (!$partialrebuild) {
2806 // Purge all course modinfo.
2807 $cachecoursemodinfo->delete($courseid);
2809 // Clear memory static cache.
2810 course_modinfo::clear_instance_cache($courseid);
2811 // Update global values too.
2812 if ($courseid == $COURSE->id || $courseid == $SITE->id) {
2813 $cacherev = $DB->get_field('course', 'cacherev', array('id' => $courseid));
2814 if ($courseid == $COURSE->id) {
2815 $COURSE->cacherev = $cacherev;
2817 if ($courseid == $SITE->id) {
2818 $SITE->cachrev = $cacherev;
2823 if ($clearonly) {
2824 return;
2827 if ($courseid) {
2828 $select = array('id'=>$courseid);
2829 } else {
2830 $select = array();
2831 core_php_time_limit::raise(); // this could take a while! MDL-10954
2834 $fields = 'id,' . join(',', course_modinfo::$cachedfields);
2835 $sort = '';
2836 $rs = $DB->get_recordset("course", $select, $sort, $fields);
2838 // Rebuild cache for each course.
2839 foreach ($rs as $course) {
2840 course_modinfo::build_course_cache($course, $partialrebuild);
2842 $rs->close();
2847 * Class that is the return value for the _get_coursemodule_info module API function.
2849 * Note: For backward compatibility, you can also return a stdclass object from that function.
2850 * The difference is that the stdclass object may contain an 'extra' field (deprecated,
2851 * use extraclasses and onclick instead). The stdclass object may not contain
2852 * the new fields defined here (content, extraclasses, customdata).
2854 class cached_cm_info {
2856 * Name (text of link) for this activity; Leave unset to accept default name
2857 * @var string
2859 public $name;
2862 * Name of icon for this activity. Normally, this should be used together with $iconcomponent
2863 * to define the icon, as per image_url function.
2864 * For backward compatibility, if this value is of the form 'mod/forum/icon' then an icon
2865 * within that module will be used.
2866 * @see cm_info::get_icon_url()
2867 * @see renderer_base::image_url()
2868 * @var string
2870 public $icon;
2873 * Component for icon for this activity, as per image_url; leave blank to use default 'moodle'
2874 * component
2875 * @see renderer_base::image_url()
2876 * @var string
2878 public $iconcomponent;
2881 * HTML content to be displayed on the main page below the link (if any) for this course-module
2882 * @var string
2884 public $content;
2887 * Custom data to be stored in modinfo for this activity; useful if there are cases when
2888 * internal information for this activity type needs to be accessible from elsewhere on the
2889 * course without making database queries. May be of any type but should be short.
2890 * @var mixed
2892 public $customdata;
2895 * Extra CSS class or classes to be added when this activity is displayed on the main page;
2896 * space-separated string
2897 * @var string
2899 public $extraclasses;
2902 * External URL image to be used by activity as icon, useful for some external-tool modules
2903 * like lti. If set, takes precedence over $icon and $iconcomponent
2904 * @var $moodle_url
2906 public $iconurl;
2909 * Content of onclick JavaScript; escaped HTML to be inserted as attribute value
2910 * @var string
2912 public $onclick;
2917 * Data about a single section on a course. This contains the fields from the
2918 * course_sections table, plus additional data when required.
2920 * @property-read int $id Section ID - from course_sections table
2921 * @property-read int $course Course ID - from course_sections table
2922 * @property-read int $section Section number - from course_sections table
2923 * @property-read string $name Section name if specified - from course_sections table
2924 * @property-read int $visible Section visibility (1 = visible) - from course_sections table
2925 * @property-read string $summary Section summary text if specified - from course_sections table
2926 * @property-read int $summaryformat Section summary text format (FORMAT_xx constant) - from course_sections table
2927 * @property-read string $availability Availability information as JSON string -
2928 * from course_sections table
2929 * @property-read array $conditionscompletion Availability conditions for this section based on the completion of
2930 * course-modules (array from course-module id to required completion state
2931 * for that module) - from cached data in sectioncache field
2932 * @property-read array $conditionsgrade Availability conditions for this section based on course grades (array from
2933 * grade item id to object with ->min, ->max fields) - from cached data in
2934 * sectioncache field
2935 * @property-read array $conditionsfield Availability conditions for this section based on user fields
2936 * @property-read bool $available True if this section is available to the given user i.e. if all availability conditions
2937 * are met - obtained dynamically
2938 * @property-read string $availableinfo If section is not available to some users, this string gives information about
2939 * availability which can be displayed to students and/or staff (e.g. 'Available from 3 January 2010')
2940 * for display on main page - obtained dynamically
2941 * @property-read bool $uservisible True if this section is available to the given user (for example, if current user
2942 * has viewhiddensections capability, they can access the section even if it is not
2943 * visible or not available, so this would be true in that case) - obtained dynamically
2944 * @property-read string $sequence Comma-separated list of all modules in the section. Note, this field may not exactly
2945 * match course_sections.sequence if later has references to non-existing modules or not modules of not available module types.
2946 * @property-read course_modinfo $modinfo
2948 class section_info implements IteratorAggregate {
2950 * Section ID - from course_sections table
2951 * @var int
2953 private $_id;
2956 * Section number - from course_sections table
2957 * @var int
2959 private $_section;
2962 * Section name if specified - from course_sections table
2963 * @var string
2965 private $_name;
2968 * Section visibility (1 = visible) - from course_sections table
2969 * @var int
2971 private $_visible;
2974 * Section summary text if specified - from course_sections table
2975 * @var string
2977 private $_summary;
2980 * Section summary text format (FORMAT_xx constant) - from course_sections table
2981 * @var int
2983 private $_summaryformat;
2986 * Availability information as JSON string - from course_sections table
2987 * @var string
2989 private $_availability;
2992 * Availability conditions for this section based on the completion of
2993 * course-modules (array from course-module id to required completion state
2994 * for that module) - from cached data in sectioncache field
2995 * @var array
2997 private $_conditionscompletion;
3000 * Availability conditions for this section based on course grades (array from
3001 * grade item id to object with ->min, ->max fields) - from cached data in
3002 * sectioncache field
3003 * @var array
3005 private $_conditionsgrade;
3008 * Availability conditions for this section based on user fields
3009 * @var array
3011 private $_conditionsfield;
3014 * True if this section is available to students i.e. if all availability conditions
3015 * are met - obtained dynamically on request, see function {@link section_info::get_available()}
3016 * @var bool|null
3018 private $_available;
3021 * If section is not available to some users, this string gives information about
3022 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
3023 * January 2010') for display on main page - obtained dynamically on request, see
3024 * function {@link section_info::get_availableinfo()}
3025 * @var string
3027 private $_availableinfo;
3030 * True if this section is available to the CURRENT user (for example, if current user
3031 * has viewhiddensections capability, they can access the section even if it is not
3032 * visible or not available, so this would be true in that case) - obtained dynamically
3033 * on request, see function {@link section_info::get_uservisible()}
3034 * @var bool|null
3036 private $_uservisible;
3039 * Default values for sectioncache fields; if a field has this value, it won't
3040 * be stored in the sectioncache cache, to save space. Checks are done by ===
3041 * which means values must all be strings.
3042 * @var array
3044 private static $sectioncachedefaults = array(
3045 'name' => null,
3046 'summary' => '',
3047 'summaryformat' => '1', // FORMAT_HTML, but must be a string
3048 'visible' => '1',
3049 'availability' => null
3053 * Stores format options that have been cached when building 'coursecache'
3054 * When the format option is requested we look first if it has been cached
3055 * @var array
3057 private $cachedformatoptions = array();
3060 * Stores the list of all possible section options defined in each used course format.
3061 * @var array
3063 static private $sectionformatoptions = array();
3066 * Stores the modinfo object passed in constructor, may be used when requesting
3067 * dynamically obtained attributes such as available, availableinfo, uservisible.
3068 * Also used to retrun information about current course or user.
3069 * @var course_modinfo
3071 private $modinfo;
3074 * True if has activities, otherwise false.
3075 * @var bool
3077 public $hasactivites;
3080 * Constructs object from database information plus extra required data.
3081 * @param object $data Array entry from cached sectioncache
3082 * @param int $number Section number (array key)
3083 * @param int $notused1 argument not used (informaion is available in $modinfo)
3084 * @param int $notused2 argument not used (informaion is available in $modinfo)
3085 * @param course_modinfo $modinfo Owner (needed for checking availability)
3086 * @param int $notused3 argument not used (informaion is available in $modinfo)
3088 public function __construct($data, $number, $notused1, $notused2, $modinfo, $notused3) {
3089 global $CFG;
3090 require_once($CFG->dirroot.'/course/lib.php');
3092 // Data that is always present
3093 $this->_id = $data->id;
3095 $defaults = self::$sectioncachedefaults +
3096 array('conditionscompletion' => array(),
3097 'conditionsgrade' => array(),
3098 'conditionsfield' => array());
3100 // Data that may use default values to save cache size
3101 foreach ($defaults as $field => $value) {
3102 if (isset($data->{$field})) {
3103 $this->{'_'.$field} = $data->{$field};
3104 } else {
3105 $this->{'_'.$field} = $value;
3109 // Other data from constructor arguments.
3110 $this->_section = $number;
3111 $this->modinfo = $modinfo;
3113 // Cached course format data.
3114 $course = $modinfo->get_course();
3115 if (!isset(self::$sectionformatoptions[$course->format])) {
3116 // Store list of section format options defined in each used course format.
3117 // They do not depend on particular course but only on its format.
3118 self::$sectionformatoptions[$course->format] =
3119 course_get_format($course)->section_format_options();
3121 foreach (self::$sectionformatoptions[$course->format] as $field => $option) {
3122 if (!empty($option['cache'])) {
3123 if (isset($data->{$field})) {
3124 $this->cachedformatoptions[$field] = $data->{$field};
3125 } else if (array_key_exists('cachedefault', $option)) {
3126 $this->cachedformatoptions[$field] = $option['cachedefault'];
3133 * Magic method to check if the property is set
3135 * @param string $name name of the property
3136 * @return bool
3138 public function __isset($name) {
3139 if (method_exists($this, 'get_'.$name) ||
3140 property_exists($this, '_'.$name) ||
3141 array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
3142 $value = $this->__get($name);
3143 return isset($value);
3145 return false;
3149 * Magic method to check if the property is empty
3151 * @param string $name name of the property
3152 * @return bool
3154 public function __empty($name) {
3155 if (method_exists($this, 'get_'.$name) ||
3156 property_exists($this, '_'.$name) ||
3157 array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
3158 $value = $this->__get($name);
3159 return empty($value);
3161 return true;
3165 * Magic method to retrieve the property, this is either basic section property
3166 * or availability information or additional properties added by course format
3168 * @param string $name name of the property
3169 * @return bool
3171 public function __get($name) {
3172 if (method_exists($this, 'get_'.$name)) {
3173 return $this->{'get_'.$name}();
3175 if (property_exists($this, '_'.$name)) {
3176 return $this->{'_'.$name};
3178 if (array_key_exists($name, $this->cachedformatoptions)) {
3179 return $this->cachedformatoptions[$name];
3181 // precheck if the option is defined in format to avoid unnecessary DB queries in get_format_options()
3182 if (array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
3183 $formatoptions = course_get_format($this->modinfo->get_course())->get_format_options($this);
3184 return $formatoptions[$name];
3186 debugging('Invalid section_info property accessed! '.$name);
3187 return null;
3191 * Finds whether this section is available at the moment for the current user.
3193 * The value can be accessed publicly as $sectioninfo->available, but can be called directly if there
3194 * is a case when it might be called recursively (you can't call property values recursively).
3196 * @return bool
3198 public function get_available() {
3199 global $CFG;
3200 $userid = $this->modinfo->get_user_id();
3201 if ($this->_available !== null || $userid == -1) {
3202 // Has already been calculated or does not need calculation.
3203 return $this->_available;
3205 $this->_available = true;
3206 $this->_availableinfo = '';
3207 if (!empty($CFG->enableavailability)) {
3208 // Get availability information.
3209 $ci = new \core_availability\info_section($this);
3210 $this->_available = $ci->is_available($this->_availableinfo, true,
3211 $userid, $this->modinfo);
3213 // Execute the hook from the course format that may override the available/availableinfo properties.
3214 $currentavailable = $this->_available;
3215 course_get_format($this->modinfo->get_course())->
3216 section_get_available_hook($this, $this->_available, $this->_availableinfo);
3217 if (!$currentavailable && $this->_available) {
3218 debugging('section_get_available_hook() can not make unavailable section available', DEBUG_DEVELOPER);
3219 $this->_available = $currentavailable;
3221 return $this->_available;
3225 * Returns the availability text shown next to the section on course page.
3227 * @return string
3229 private function get_availableinfo() {
3230 // Calling get_available() will also fill the availableinfo property
3231 // (or leave it null if there is no userid).
3232 $this->get_available();
3233 return $this->_availableinfo;
3237 * Implementation of IteratorAggregate::getIterator(), allows to cycle through properties
3238 * and use {@link convert_to_array()}
3240 * @return ArrayIterator
3242 public function getIterator(): Traversable {
3243 $ret = array();
3244 foreach (get_object_vars($this) as $key => $value) {
3245 if (substr($key, 0, 1) == '_') {
3246 if (method_exists($this, 'get'.$key)) {
3247 $ret[substr($key, 1)] = $this->{'get'.$key}();
3248 } else {
3249 $ret[substr($key, 1)] = $this->$key;
3253 $ret['sequence'] = $this->get_sequence();
3254 $ret['course'] = $this->get_course();
3255 $ret = array_merge($ret, course_get_format($this->modinfo->get_course())->get_format_options($this->_section));
3256 return new ArrayIterator($ret);
3260 * Works out whether activity is visible *for current user* - if this is false, they
3261 * aren't allowed to access it.
3263 * @return bool
3265 private function get_uservisible() {
3266 $userid = $this->modinfo->get_user_id();
3267 if ($this->_uservisible !== null || $userid == -1) {
3268 // Has already been calculated or does not need calculation.
3269 return $this->_uservisible;
3271 $this->_uservisible = true;
3272 if (!$this->_visible || !$this->get_available()) {
3273 $coursecontext = context_course::instance($this->get_course());
3274 if (!$this->_visible && !has_capability('moodle/course:viewhiddensections', $coursecontext, $userid) ||
3275 (!$this->get_available() &&
3276 !has_capability('moodle/course:ignoreavailabilityrestrictions', $coursecontext, $userid))) {
3278 $this->_uservisible = false;
3281 return $this->_uservisible;
3285 * Restores the course_sections.sequence value
3287 * @return string
3289 private function get_sequence() {
3290 if (!empty($this->modinfo->sections[$this->_section])) {
3291 return implode(',', $this->modinfo->sections[$this->_section]);
3292 } else {
3293 return '';
3298 * Returns course ID - from course_sections table
3300 * @return int
3302 private function get_course() {
3303 return $this->modinfo->get_course_id();
3307 * Modinfo object
3309 * @return course_modinfo
3311 private function get_modinfo() {
3312 return $this->modinfo;
3316 * Prepares section data for inclusion in sectioncache cache, removing items
3317 * that are set to defaults, and adding availability data if required.
3319 * Called by build_section_cache in course_modinfo only; do not use otherwise.
3320 * @param object $section Raw section data object
3322 public static function convert_for_section_cache($section) {
3323 global $CFG;
3325 // Course id stored in course table
3326 unset($section->course);
3327 // Section number stored in array key
3328 unset($section->section);
3329 // Sequence stored implicity in modinfo $sections array
3330 unset($section->sequence);
3332 // Remove default data
3333 foreach (self::$sectioncachedefaults as $field => $value) {
3334 // Exact compare as strings to avoid problems if some strings are set
3335 // to "0" etc.
3336 if (isset($section->{$field}) && $section->{$field} === $value) {
3337 unset($section->{$field});