MDL-75012 js: Bump stylelint and components
[moodle.git] / lib / modinfolib.php
blobd0eb3e29b8be16c2256e7960afd69b3b59fac6e3
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);
36 /**
37 * Information about a course that is cached in the course table 'modinfo' field (and then in
38 * memory) in order to reduce the need for other database queries.
40 * This includes information about the course-modules and the sections on the course. It can also
41 * include dynamic data that has been updated for the current user.
43 * Use {@link get_fast_modinfo()} to retrieve the instance of the object for particular course
44 * and particular user.
46 * @property-read int $courseid Course ID
47 * @property-read int $userid User ID
48 * @property-read array $sections Array from section number (e.g. 0) to array of course-module IDs in that
49 * section; this only includes sections that contain at least one course-module
50 * @property-read cm_info[] $cms Array from course-module instance to cm_info object within this course, in
51 * order of appearance
52 * @property-read cm_info[][] $instances Array from string (modname) => int (instance id) => cm_info object
53 * @property-read array $groups Groups that the current user belongs to. Calculated on the first request.
54 * Is an array of grouping id => array of group id => group id. Includes grouping id 0 for 'all groups'
56 class course_modinfo {
57 /** @var int Maximum time the course cache building lock can be held */
58 const COURSE_CACHE_LOCK_EXPIRY = 180;
60 /** @var int Time to wait for the course cache building lock before throwing an exception */
61 const COURSE_CACHE_LOCK_WAIT = 60;
63 /**
64 * List of fields from DB table 'course' that are cached in MUC and are always present in course_modinfo::$course
65 * @var array
67 public static $cachedfields = array('shortname', 'fullname', 'format',
68 'enablecompletion', 'groupmode', 'groupmodeforce', 'cacherev');
70 /**
71 * For convenience we store the course object here as it is needed in other parts of code
72 * @var stdClass
74 private $course;
76 /**
77 * Array of section data from cache
78 * @var section_info[]
80 private $sectioninfo;
82 /**
83 * User ID
84 * @var int
86 private $userid;
88 /**
89 * Array from int (section num, e.g. 0) => array of int (course-module id); this list only
90 * includes sections that actually contain at least one course-module
91 * @var array
93 private $sections;
95 /**
96 * Array from section id => section num.
97 * @var array
99 private $sectionids;
102 * Array from int (cm id) => cm_info object
103 * @var cm_info[]
105 private $cms;
108 * Array from string (modname) => int (instance id) => cm_info object
109 * @var cm_info[][]
111 private $instances;
114 * Groups that the current user belongs to. This value is calculated on first
115 * request to the property or function.
116 * When set, it is an array of grouping id => array of group id => group id.
117 * Includes grouping id 0 for 'all groups'.
118 * @var int[][]
120 private $groups;
123 * List of class read-only properties and their getter methods.
124 * Used by magic functions __get(), __isset(), __empty()
125 * @var array
127 private static $standardproperties = array(
128 'courseid' => 'get_course_id',
129 'userid' => 'get_user_id',
130 'sections' => 'get_sections',
131 'cms' => 'get_cms',
132 'instances' => 'get_instances',
133 'groups' => 'get_groups_all',
137 * Magic method getter
139 * @param string $name
140 * @return mixed
142 public function __get($name) {
143 if (isset(self::$standardproperties[$name])) {
144 $method = self::$standardproperties[$name];
145 return $this->$method();
146 } else {
147 debugging('Invalid course_modinfo property accessed: '.$name);
148 return null;
153 * Magic method for function isset()
155 * @param string $name
156 * @return bool
158 public function __isset($name) {
159 if (isset(self::$standardproperties[$name])) {
160 $value = $this->__get($name);
161 return isset($value);
163 return false;
167 * Magic method for function empty()
169 * @param string $name
170 * @return bool
172 public function __empty($name) {
173 if (isset(self::$standardproperties[$name])) {
174 $value = $this->__get($name);
175 return empty($value);
177 return true;
181 * Magic method setter
183 * Will display the developer warning when trying to set/overwrite existing property.
185 * @param string $name
186 * @param mixed $value
188 public function __set($name, $value) {
189 debugging("It is not allowed to set the property course_modinfo::\${$name}", DEBUG_DEVELOPER);
193 * Returns course object that was used in the first {@link get_fast_modinfo()} call.
195 * It may not contain all fields from DB table {course} but always has at least the following:
196 * id,shortname,fullname,format,enablecompletion,groupmode,groupmodeforce,cacherev
198 * @return stdClass
200 public function get_course() {
201 return $this->course;
205 * @return int Course ID
207 public function get_course_id() {
208 return $this->course->id;
212 * @return int User ID
214 public function get_user_id() {
215 return $this->userid;
219 * @return array Array from section number (e.g. 0) to array of course-module IDs in that
220 * section; this only includes sections that contain at least one course-module
222 public function get_sections() {
223 return $this->sections;
227 * @return cm_info[] Array from course-module instance to cm_info object within this course, in
228 * order of appearance
230 public function get_cms() {
231 return $this->cms;
235 * Obtains a single course-module object (for a course-module that is on this course).
236 * @param int $cmid Course-module ID
237 * @return cm_info Information about that course-module
238 * @throws moodle_exception If the course-module does not exist
240 public function get_cm($cmid) {
241 if (empty($this->cms[$cmid])) {
242 throw new moodle_exception('invalidcoursemoduleid', 'error', '', $cmid);
244 return $this->cms[$cmid];
248 * Obtains all module instances on this course.
249 * @return cm_info[][] Array from module name => array from instance id => cm_info
251 public function get_instances() {
252 return $this->instances;
256 * Returns array of localised human-readable module names used in this course
258 * @param bool $plural if true returns the plural form of modules names
259 * @return array
261 public function get_used_module_names($plural = false) {
262 $modnames = get_module_types_names($plural);
263 $modnamesused = array();
264 foreach ($this->get_cms() as $cmid => $mod) {
265 if (!isset($modnamesused[$mod->modname]) && isset($modnames[$mod->modname]) && $mod->uservisible) {
266 $modnamesused[$mod->modname] = $modnames[$mod->modname];
269 return $modnamesused;
273 * Obtains all instances of a particular module on this course.
274 * @param string $modname Name of module (not full frankenstyle) e.g. 'label'
275 * @return cm_info[] Array from instance id => cm_info for modules on this course; empty if none
277 public function get_instances_of($modname) {
278 if (empty($this->instances[$modname])) {
279 return array();
281 return $this->instances[$modname];
285 * Groups that the current user belongs to organised by grouping id. Calculated on the first request.
286 * @return int[][] array of grouping id => array of group id => group id. Includes grouping id 0 for 'all groups'
288 private function get_groups_all() {
289 if (is_null($this->groups)) {
290 $this->groups = groups_get_user_groups($this->course->id, $this->userid);
292 return $this->groups;
296 * Returns groups that the current user belongs to on the course. Note: If not already
297 * available, this may make a database query.
298 * @param int $groupingid Grouping ID or 0 (default) for all groups
299 * @return int[] Array of int (group id) => int (same group id again); empty array if none
301 public function get_groups($groupingid = 0) {
302 $allgroups = $this->get_groups_all();
303 if (!isset($allgroups[$groupingid])) {
304 return array();
306 return $allgroups[$groupingid];
310 * Gets all sections as array from section number => data about section.
311 * @return section_info[] Array of section_info objects organised by section number
313 public function get_section_info_all() {
314 return $this->sectioninfo;
318 * Gets data about specific numbered section.
319 * @param int $sectionnumber Number (not id) of section
320 * @param int $strictness Use MUST_EXIST to throw exception if it doesn't
321 * @return section_info Information for numbered section or null if not found
323 public function get_section_info($sectionnumber, $strictness = IGNORE_MISSING) {
324 if (!array_key_exists($sectionnumber, $this->sectioninfo)) {
325 if ($strictness === MUST_EXIST) {
326 throw new moodle_exception('sectionnotexist');
327 } else {
328 return null;
331 return $this->sectioninfo[$sectionnumber];
335 * Gets data about specific section ID.
336 * @param int $sectionid ID (not number) of section
337 * @param int $strictness Use MUST_EXIST to throw exception if it doesn't
338 * @return section_info|null Information for numbered section or null if not found
340 public function get_section_info_by_id(int $sectionid, int $strictness = IGNORE_MISSING): ?section_info {
342 if (!isset($this->sectionids[$sectionid])) {
343 if ($strictness === MUST_EXIST) {
344 throw new moodle_exception('sectionnotexist');
345 } else {
346 return null;
349 return $this->get_section_info($this->sectionids[$sectionid], $strictness);
353 * Static cache for generated course_modinfo instances
355 * @see course_modinfo::instance()
356 * @see course_modinfo::clear_instance_cache()
357 * @var course_modinfo[]
359 protected static $instancecache = array();
362 * Timestamps (microtime) when the course_modinfo instances were last accessed
364 * It is used to remove the least recent accessed instances when static cache is full
366 * @var float[]
368 protected static $cacheaccessed = array();
371 * Clears the cache used in course_modinfo::instance()
373 * Used in {@link get_fast_modinfo()} when called with argument $reset = true
374 * and in {@link rebuild_course_cache()}
376 * @param null|int|stdClass $courseorid if specified removes only cached value for this course
378 public static function clear_instance_cache($courseorid = null) {
379 if (empty($courseorid)) {
380 self::$instancecache = array();
381 self::$cacheaccessed = array();
382 return;
384 if (is_object($courseorid)) {
385 $courseorid = $courseorid->id;
387 if (isset(self::$instancecache[$courseorid])) {
388 // Unsetting static variable in PHP is peculiar, it removes the reference,
389 // but data remain in memory. Prior to unsetting, the varable needs to be
390 // set to empty to remove its remains from memory.
391 self::$instancecache[$courseorid] = '';
392 unset(self::$instancecache[$courseorid]);
393 unset(self::$cacheaccessed[$courseorid]);
398 * Returns the instance of course_modinfo for the specified course and specified user
400 * This function uses static cache for the retrieved instances. The cache
401 * size is limited by MAX_MODINFO_CACHE_SIZE. If instance is not found in
402 * the static cache or it was created for another user or the cacherev validation
403 * failed - a new instance is constructed and returned.
405 * Used in {@link get_fast_modinfo()}
407 * @param int|stdClass $courseorid object from DB table 'course' (must have field 'id'
408 * and recommended to have field 'cacherev') or just a course id
409 * @param int $userid User id to populate 'availble' and 'uservisible' attributes of modules and sections.
410 * Set to 0 for current user (default). Set to -1 to avoid calculation of dynamic user-depended data.
411 * @return course_modinfo
413 public static function instance($courseorid, $userid = 0) {
414 global $USER;
415 if (is_object($courseorid)) {
416 $course = $courseorid;
417 } else {
418 $course = (object)array('id' => $courseorid);
420 if (empty($userid)) {
421 $userid = $USER->id;
424 if (!empty(self::$instancecache[$course->id])) {
425 if (self::$instancecache[$course->id]->userid == $userid &&
426 (!isset($course->cacherev) ||
427 $course->cacherev == self::$instancecache[$course->id]->get_course()->cacherev)) {
428 // This course's modinfo for the same user was recently retrieved, return cached.
429 self::$cacheaccessed[$course->id] = microtime(true);
430 return self::$instancecache[$course->id];
431 } else {
432 // Prevent potential reference problems when switching users.
433 self::clear_instance_cache($course->id);
436 $modinfo = new course_modinfo($course, $userid);
438 // We have a limit of MAX_MODINFO_CACHE_SIZE entries to store in static variable.
439 if (count(self::$instancecache) >= MAX_MODINFO_CACHE_SIZE) {
440 // Find the course that was the least recently accessed.
441 asort(self::$cacheaccessed, SORT_NUMERIC);
442 $courseidtoremove = key(array_reverse(self::$cacheaccessed, true));
443 self::clear_instance_cache($courseidtoremove);
446 // Add modinfo to the static cache.
447 self::$instancecache[$course->id] = $modinfo;
448 self::$cacheaccessed[$course->id] = microtime(true);
450 return $modinfo;
454 * Constructs based on course.
455 * Note: This constructor should not usually be called directly.
456 * Use get_fast_modinfo($course) instead as this maintains a cache.
457 * @param stdClass $course course object, only property id is required.
458 * @param int $userid User ID
459 * @throws moodle_exception if course is not found
461 public function __construct($course, $userid) {
462 global $CFG, $COURSE, $SITE, $DB;
464 if (!isset($course->cacherev)) {
465 // We require presence of property cacherev to validate the course cache.
466 // No need to clone the $COURSE or $SITE object here because we clone it below anyway.
467 $course = get_course($course->id, false);
470 $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
472 // Retrieve modinfo from cache. If not present or cacherev mismatches, call rebuild and retrieve again.
473 $coursemodinfo = $cachecoursemodinfo->get_versioned($course->id, $course->cacherev);
474 // Note the version comparison using the data in the cache should not be necessary, but the
475 // partial rebuild logic sometimes sets the $coursemodinfo->cacherev to -1 which is an
476 // indicator that it needs rebuilding.
477 if ($coursemodinfo === false || ($course->cacherev > $coursemodinfo->cacherev)) {
478 $coursemodinfo = self::build_course_cache($course);
481 // Set initial values
482 $this->userid = $userid;
483 $this->sections = array();
484 $this->sectionids = [];
485 $this->cms = array();
486 $this->instances = array();
487 $this->groups = null;
489 // If we haven't already preloaded contexts for the course, do it now
490 // Modules are also cached here as long as it's the first time this course has been preloaded.
491 context_helper::preload_course($course->id);
493 // Quick integrity check: as a result of race conditions modinfo may not be regenerated after the change.
494 // It is especially dangerous if modinfo contains the deleted course module, as it results in fatal error.
495 // We can check it very cheap by validating the existence of module context.
496 if ($course->id == $COURSE->id || $course->id == $SITE->id) {
497 // Only verify current course (or frontpage) as pages with many courses may not have module contexts cached.
498 // (Uncached modules will result in a very slow verification).
499 foreach ($coursemodinfo->modinfo as $mod) {
500 if (!context_module::instance($mod->cm, IGNORE_MISSING)) {
501 debugging('Course cache integrity check failed: course module with id '. $mod->cm.
502 ' does not have context. Rebuilding cache for course '. $course->id);
503 // Re-request the course record from DB as well, don't use get_course() here.
504 $course = $DB->get_record('course', array('id' => $course->id), '*', MUST_EXIST);
505 $coursemodinfo = self::build_course_cache($course, true);
506 break;
511 // Overwrite unset fields in $course object with cached values, store the course object.
512 $this->course = fullclone($course);
513 foreach ($coursemodinfo as $key => $value) {
514 if ($key !== 'modinfo' && $key !== 'sectioncache' &&
515 (!isset($this->course->$key) || $key === 'cacherev')) {
516 $this->course->$key = $value;
520 // Loop through each piece of module data, constructing it
521 static $modexists = array();
522 foreach ($coursemodinfo->modinfo as $mod) {
523 if (!isset($mod->name) || strval($mod->name) === '') {
524 // something is wrong here
525 continue;
528 // Skip modules which don't exist
529 if (!array_key_exists($mod->mod, $modexists)) {
530 $modexists[$mod->mod] = file_exists("$CFG->dirroot/mod/$mod->mod/lib.php");
532 if (!$modexists[$mod->mod]) {
533 continue;
536 // Construct info for this module
537 $cm = new cm_info($this, null, $mod, null);
539 // Store module in instances and cms array
540 if (!isset($this->instances[$cm->modname])) {
541 $this->instances[$cm->modname] = array();
543 $this->instances[$cm->modname][$cm->instance] = $cm;
544 $this->cms[$cm->id] = $cm;
546 // Reconstruct sections. This works because modules are stored in order
547 if (!isset($this->sections[$cm->sectionnum])) {
548 $this->sections[$cm->sectionnum] = array();
550 $this->sections[$cm->sectionnum][] = $cm->id;
553 // Expand section objects
554 $this->sectioninfo = array();
555 foreach ($coursemodinfo->sectioncache as $number => $data) {
556 $this->sectionids[$data->id] = $number;
557 $this->sectioninfo[$number] = new section_info($data, $number, null, null,
558 $this, null);
563 * This method can not be used anymore.
565 * @see course_modinfo::build_course_cache()
566 * @deprecated since 2.6
568 public static function build_section_cache($courseid) {
569 throw new coding_exception('Function course_modinfo::build_section_cache() can not be used anymore.' .
570 ' Please use course_modinfo::build_course_cache() whenever applicable.');
574 * Builds a list of information about sections on a course to be stored in
575 * the course cache. (Does not include information that is already cached
576 * in some other way.)
578 * @param stdClass $course Course object (must contain fields
579 * @param boolean $usecache use cached section info if exists, use true for partial course rebuild
580 * @return array Information about sections, indexed by section number (not id)
582 protected static function build_course_section_cache(\stdClass $course, bool $usecache = false): array {
583 global $DB;
585 // Get section data
586 $sections = $DB->get_records('course_sections', array('course' => $course->id), 'section',
587 'section, id, course, name, summary, summaryformat, sequence, visible, availability');
588 $compressedsections = [];
589 $courseformat = course_get_format($course);
591 if ($usecache) {
592 $cachecoursemodinfo = \cache::make('core', 'coursemodinfo');
593 $coursemodinfo = $cachecoursemodinfo->get_versioned($course->id, $course->cacherev);
594 if ($coursemodinfo !== false) {
595 $compressedsections = $coursemodinfo->sectioncache;
599 $formatoptionsdef = course_get_format($course)->section_format_options();
600 // Remove unnecessary data and add availability
601 foreach ($sections as $number => $section) {
602 $sectioninfocached = isset($compressedsections[$number]);
603 if ($sectioninfocached) {
604 continue;
606 // Add cached options from course format to $section object
607 foreach ($formatoptionsdef as $key => $option) {
608 if (!empty($option['cache'])) {
609 $formatoptions = $courseformat->get_format_options($section);
610 if (!array_key_exists('cachedefault', $option) || $option['cachedefault'] !== $formatoptions[$key]) {
611 $section->$key = $formatoptions[$key];
615 // Clone just in case it is reused elsewhere
616 $compressedsections[$number] = clone($section);
617 section_info::convert_for_section_cache($compressedsections[$number]);
620 ksort($compressedsections);
621 return $compressedsections;
625 * Builds and stores in MUC object containing information about course
626 * modules and sections together with cached fields from table course.
628 * @param stdClass $course object from DB table course. Must have property 'id'
629 * but preferably should have all cached fields.
630 * @param boolean $partialrebuild Indicate if it's partial course cache rebuild or not
631 * @return stdClass object with all cached keys of the course plus fields modinfo and sectioncache.
632 * The same object is stored in MUC
633 * @throws moodle_exception if course is not found (if $course object misses some of the
634 * necessary fields it is re-requested from database)
636 public static function build_course_cache(\stdClass $course, bool $partialrebuild = false): \stdClass {
637 if (empty($course->id)) {
638 throw new coding_exception('Object $course is missing required property \id\'');
641 $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
642 $cachekey = $course->id;
643 $cachecoursemodinfo->acquire_lock($cachekey);
644 try {
645 // Only actually do the build if it's still needed after getting the lock (not if
646 // somebody else, who might have been holding the lock, built it already).
647 $coursemodinfo = $cachecoursemodinfo->get_versioned($course->id, $course->cacherev);
648 if ($coursemodinfo === false || ($course->cacherev > $coursemodinfo->cacherev)) {
649 $coursemodinfo = self::inner_build_course_cache($course);
651 } finally {
652 $cachecoursemodinfo->release_lock($cachekey);
654 return $coursemodinfo;
658 * Called to build course cache when there is already a lock obtained.
660 * @param stdClass $course object from DB table course
661 * @param bool $partialrebuild Indicate if it's partial course cache rebuild or not
662 * @return stdClass Course object that has been stored in MUC
664 protected static function inner_build_course_cache(\stdClass $course, bool $partialrebuild = false): \stdClass {
665 global $DB, $CFG;
666 require_once("{$CFG->dirroot}/course/lib.php");
668 $cachekey = $course->id;
669 $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
670 if (!$cachecoursemodinfo->check_lock_state($cachekey)) {
671 throw new coding_exception('You must acquire a lock on the course ID before calling inner_build_course_cache');
674 // Always reload the course object from database to ensure we have the latest possible
675 // value for cacherev.
676 $course = $DB->get_record('course', ['id' => $course->id],
677 implode(',', array_merge(['id'], self::$cachedfields)), MUST_EXIST);
678 // Retrieve all information about activities and sections.
679 $coursemodinfo = new stdClass();
680 $coursemodinfo->modinfo = self::get_array_of_activities($course, $partialrebuild);
681 $coursemodinfo->sectioncache = self::build_course_section_cache($course, $partialrebuild);
682 foreach (self::$cachedfields as $key) {
683 $coursemodinfo->$key = $course->$key;
685 // Set the accumulated activities and sections information in cache, together with cacherev.
686 $cachecoursemodinfo->set_versioned($cachekey, $course->cacherev, $coursemodinfo);
687 return $coursemodinfo;
691 * Purge the cache of a course section by its id.
693 * @param int $courseid The course to purge cache in
694 * @param int $sectionid The section _id_ to purge
696 public static function purge_course_section_cache_by_id(int $courseid, int $sectionid): void {
697 $course = get_course($courseid);
698 $cache = cache::make('core', 'coursemodinfo');
699 $cachekey = $course->id;
700 $cache->acquire_lock($cachekey);
701 $coursemodinfo = $cache->get_versioned($cachekey, $course->cacherev);
702 if ($coursemodinfo !== false) {
703 foreach ($coursemodinfo->sectioncache as $sectionno => $sectioncache) {
704 if ($sectioncache->id == $sectionid) {
705 $coursemodinfo->cacherev = -1;
706 unset($coursemodinfo->sectioncache[$sectionno]);
707 $cache->set_versioned($cachekey, $course->cacherev, $coursemodinfo);
708 break;
712 $cache->release_lock($cachekey);
716 * Purge the cache of a course section by its number.
718 * @param int $courseid The course to purge cache in
719 * @param int $sectionno The section number to purge
721 public static function purge_course_section_cache_by_number(int $courseid, int $sectionno): void {
722 $course = get_course($courseid);
723 $cache = cache::make('core', 'coursemodinfo');
724 $cachekey = $course->id;
725 $cache->acquire_lock($cachekey);
726 $coursemodinfo = $cache->get_versioned($cachekey, $course->cacherev);
727 if ($coursemodinfo !== false && array_key_exists($sectionno, $coursemodinfo->sectioncache)) {
728 $coursemodinfo->cacherev = -1;
729 unset($coursemodinfo->sectioncache[$sectionno]);
730 $cache->set_versioned($cachekey, $course->cacherev, $coursemodinfo);
732 $cache->release_lock($cachekey);
736 * Purge the cache of a course module.
738 * @param int $courseid Course id
739 * @param int $cmid Course module id
741 public static function purge_course_module_cache(int $courseid, int $cmid): void {
742 $course = get_course($courseid);
743 $cache = cache::make('core', 'coursemodinfo');
744 $cachekey = $course->id;
745 $cache->acquire_lock($cachekey);
746 $coursemodinfo = $cache->get_versioned($cachekey, $course->cacherev);
747 $hascache = ($coursemodinfo !== false) && array_key_exists($cmid, $coursemodinfo->modinfo);
748 if ($hascache) {
749 $coursemodinfo->cacherev = -1;
750 unset($coursemodinfo->modinfo[$cmid]);
751 $cache->set_versioned($cachekey, $course->cacherev, $coursemodinfo);
752 $coursemodinfo = $cache->get_versioned($cachekey, $course->cacherev);
754 $cache->release_lock($cachekey);
758 * For a given course, returns an array of course activity objects
760 * @param stdClass $course Course object
761 * @param bool $usecache get activities from cache if modinfo exists when $usecache is true
762 * @return array list of activities
764 public static function get_array_of_activities(stdClass $course, bool $usecache = false): array {
765 global $CFG, $DB;
767 if (empty($course)) {
768 throw new moodle_exception('courseidnotfound');
771 $rawmods = get_course_mods($course->id);
772 if (empty($rawmods)) {
773 return [];
776 $mods = [];
777 if ($usecache) {
778 // Get existing cache.
779 $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
780 $coursemodinfo = $cachecoursemodinfo->get_versioned($course->id, $course->cacherev);
781 if ($coursemodinfo !== false) {
782 $mods = $coursemodinfo->modinfo;
786 $courseformat = course_get_format($course);
788 if ($sections = $DB->get_records('course_sections', ['course' => $course->id],
789 'section ASC', 'id,section,sequence,visible')) {
790 // First check and correct obvious mismatches between course_sections.sequence and course_modules.section.
791 if ($errormessages = course_integrity_check($course->id, $rawmods, $sections)) {
792 debugging(join('<br>', $errormessages));
793 $rawmods = get_course_mods($course->id);
794 $sections = $DB->get_records('course_sections', ['course' => $course->id],
795 'section ASC', 'id,section,sequence,visible');
797 // Build array of activities.
798 foreach ($sections as $section) {
799 if (!empty($section->sequence)) {
800 $cmids = explode(",", $section->sequence);
801 $numberofmods = count($cmids);
802 foreach ($cmids as $cmid) {
803 // Activity does not exist in the database.
804 $notexistindb = empty($rawmods[$cmid]);
805 $activitycached = isset($mods[$cmid]);
806 if ($activitycached || $notexistindb) {
807 continue;
810 // Adjust visibleoncoursepage, value in DB may not respect format availability.
811 $rawmods[$cmid]->visibleoncoursepage = (!$rawmods[$cmid]->visible
812 || $rawmods[$cmid]->visibleoncoursepage
813 || empty($CFG->allowstealth)
814 || !$courseformat->allow_stealth_module_visibility($rawmods[$cmid], $section)) ? 1 : 0;
816 $mods[$cmid] = new stdClass();
817 $mods[$cmid]->id = $rawmods[$cmid]->instance;
818 $mods[$cmid]->cm = $rawmods[$cmid]->id;
819 $mods[$cmid]->mod = $rawmods[$cmid]->modname;
821 // Oh dear. Inconsistent names left here for backward compatibility.
822 $mods[$cmid]->section = $section->section;
823 $mods[$cmid]->sectionid = $rawmods[$cmid]->section;
825 $mods[$cmid]->module = $rawmods[$cmid]->module;
826 $mods[$cmid]->added = $rawmods[$cmid]->added;
827 $mods[$cmid]->score = $rawmods[$cmid]->score;
828 $mods[$cmid]->idnumber = $rawmods[$cmid]->idnumber;
829 $mods[$cmid]->visible = $rawmods[$cmid]->visible;
830 $mods[$cmid]->visibleoncoursepage = $rawmods[$cmid]->visibleoncoursepage;
831 $mods[$cmid]->visibleold = $rawmods[$cmid]->visibleold;
832 $mods[$cmid]->groupmode = $rawmods[$cmid]->groupmode;
833 $mods[$cmid]->groupingid = $rawmods[$cmid]->groupingid;
834 $mods[$cmid]->indent = $rawmods[$cmid]->indent;
835 $mods[$cmid]->completion = $rawmods[$cmid]->completion;
836 $mods[$cmid]->extra = "";
837 $mods[$cmid]->completiongradeitemnumber =
838 $rawmods[$cmid]->completiongradeitemnumber;
839 $mods[$cmid]->completionpassgrade = $rawmods[$cmid]->completionpassgrade;
840 $mods[$cmid]->completionview = $rawmods[$cmid]->completionview;
841 $mods[$cmid]->completionexpected = $rawmods[$cmid]->completionexpected;
842 $mods[$cmid]->showdescription = $rawmods[$cmid]->showdescription;
843 $mods[$cmid]->availability = $rawmods[$cmid]->availability;
844 $mods[$cmid]->deletioninprogress = $rawmods[$cmid]->deletioninprogress;
845 $mods[$cmid]->downloadcontent = $rawmods[$cmid]->downloadcontent;
846 $mods[$cmid]->lang = $rawmods[$cmid]->lang;
848 $modname = $mods[$cmid]->mod;
849 $functionname = $modname . "_get_coursemodule_info";
851 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
852 continue;
855 include_once("$CFG->dirroot/mod/$modname/lib.php");
857 if ($hasfunction = function_exists($functionname)) {
858 if ($info = $functionname($rawmods[$cmid])) {
859 if (!empty($info->icon)) {
860 $mods[$cmid]->icon = $info->icon;
862 if (!empty($info->iconcomponent)) {
863 $mods[$cmid]->iconcomponent = $info->iconcomponent;
865 if (!empty($info->name)) {
866 $mods[$cmid]->name = $info->name;
868 if ($info instanceof cached_cm_info) {
869 // When using cached_cm_info you can include three new fields.
870 // That aren't available for legacy code.
871 if (!empty($info->content)) {
872 $mods[$cmid]->content = $info->content;
874 if (!empty($info->extraclasses)) {
875 $mods[$cmid]->extraclasses = $info->extraclasses;
877 if (!empty($info->iconurl)) {
878 // Convert URL to string as it's easier to store.
879 // Also serialized object contains \0 byte,
880 // ... and can not be written to Postgres DB.
881 $url = new moodle_url($info->iconurl);
882 $mods[$cmid]->iconurl = $url->out(false);
884 if (!empty($info->onclick)) {
885 $mods[$cmid]->onclick = $info->onclick;
887 if (!empty($info->customdata)) {
888 $mods[$cmid]->customdata = $info->customdata;
890 } else {
891 // When using a stdclass, the (horrible) deprecated ->extra field,
892 // ... that is available for BC.
893 if (!empty($info->extra)) {
894 $mods[$cmid]->extra = $info->extra;
899 // When there is no modname_get_coursemodule_info function,
900 // ... but showdescriptions is enabled, then we use the 'intro',
901 // ... and 'introformat' fields in the module table.
902 if (!$hasfunction && $rawmods[$cmid]->showdescription) {
903 if ($modvalues = $DB->get_record($rawmods[$cmid]->modname,
904 ['id' => $rawmods[$cmid]->instance], 'name, intro, introformat')) {
905 // Set content from intro and introformat. Filters are disabled.
906 // Because we filter it with format_text at display time.
907 $mods[$cmid]->content = format_module_intro($rawmods[$cmid]->modname,
908 $modvalues, $rawmods[$cmid]->id, false);
910 // To save making another query just below, put name in here.
911 $mods[$cmid]->name = $modvalues->name;
914 if (!isset($mods[$cmid]->name)) {
915 $mods[$cmid]->name = $DB->get_field($rawmods[$cmid]->modname, "name",
916 ["id" => $rawmods[$cmid]->instance]);
919 // Minimise the database size by unsetting default options when they are 'empty'.
920 // This list corresponds to code in the cm_info constructor.
921 foreach (['idnumber', 'groupmode', 'groupingid',
922 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
923 'icon', 'iconcomponent', 'customdata', 'availability', 'completionview',
924 'completionexpected', 'score', 'showdescription', 'deletioninprogress'] as $property) {
925 if (property_exists($mods[$cmid], $property) &&
926 empty($mods[$cmid]->{$property})) {
927 unset($mods[$cmid]->{$property});
930 // Special case: this value is usually set to null, but may be 0.
931 if (property_exists($mods[$cmid], 'completiongradeitemnumber') &&
932 is_null($mods[$cmid]->completiongradeitemnumber)) {
933 unset($mods[$cmid]->completiongradeitemnumber);
939 return $mods;
943 * Purge the cache of a given course
945 * @param int $courseid Course id
947 public static function purge_course_cache(int $courseid): void {
948 increment_revision_number('course', 'cacherev', 'id = :id', array('id' => $courseid));
949 $cachemodinfo = cache::make('core', 'coursemodinfo');
950 $cachemodinfo->delete($courseid);
956 * Data about a single module on a course. This contains most of the fields in the course_modules
957 * table, plus additional data when required.
959 * The object can be accessed by core or any plugin (i.e. course format, block, filter, etc.) as
960 * get_fast_modinfo($courseorid)->cms[$coursemoduleid]
961 * or
962 * get_fast_modinfo($courseorid)->instances[$moduletype][$instanceid]
964 * There are three stages when activity module can add/modify data in this object:
966 * <b>Stage 1 - during building the cache.</b>
967 * Allows to add to the course cache static user-independent information about the module.
968 * Modules should try to include only absolutely necessary information that may be required
969 * when displaying course view page. The information is stored in application-level cache
970 * and reset when {@link rebuild_course_cache()} is called or cache is purged by admin.
972 * Modules can implement callback XXX_get_coursemodule_info() returning instance of object
973 * {@link cached_cm_info}
975 * <b>Stage 2 - dynamic data.</b>
976 * Dynamic data is user-dependent, it is stored in request-level cache. To reset this cache
977 * {@link get_fast_modinfo()} with $reset argument may be called.
979 * Dynamic data is obtained when any of the following properties/methods is requested:
980 * - {@link cm_info::$url}
981 * - {@link cm_info::$name}
982 * - {@link cm_info::$onclick}
983 * - {@link cm_info::get_icon_url()}
984 * - {@link cm_info::$uservisible}
985 * - {@link cm_info::$available}
986 * - {@link cm_info::$availableinfo}
987 * - plus any of the properties listed in Stage 3.
989 * Modules can implement callback <b>XXX_cm_info_dynamic()</b> and inside this callback they
990 * are allowed to use any of the following set methods:
991 * - {@link cm_info::set_available()}
992 * - {@link cm_info::set_name()}
993 * - {@link cm_info::set_no_view_link()}
994 * - {@link cm_info::set_user_visible()}
995 * - {@link cm_info::set_on_click()}
996 * - {@link cm_info::set_icon_url()}
997 * - {@link cm_info::override_customdata()}
998 * Any methods affecting view elements can also be set in this callback.
1000 * <b>Stage 3 (view data).</b>
1001 * Also user-dependend data stored in request-level cache. Second stage is created
1002 * because populating the view data can be expensive as it may access much more
1003 * Moodle APIs such as filters, user information, output renderers and we
1004 * don't want to request it until necessary.
1005 * View data is obtained when any of the following properties/methods is requested:
1006 * - {@link cm_info::$afterediticons}
1007 * - {@link cm_info::$content}
1008 * - {@link cm_info::get_formatted_content()}
1009 * - {@link cm_info::$extraclasses}
1010 * - {@link cm_info::$afterlink}
1012 * Modules can implement callback <b>XXX_cm_info_view()</b> and inside this callback they
1013 * are allowed to use any of the following set methods:
1014 * - {@link cm_info::set_after_edit_icons()}
1015 * - {@link cm_info::set_after_link()}
1016 * - {@link cm_info::set_content()}
1017 * - {@link cm_info::set_extra_classes()}
1019 * @property-read int $id Course-module ID - from course_modules table
1020 * @property-read int $instance Module instance (ID within module table) - from course_modules table
1021 * @property-read int $course Course ID - from course_modules table
1022 * @property-read string $idnumber 'ID number' from course-modules table (arbitrary text set by user) - from
1023 * course_modules table
1024 * @property-read int $added Time that this course-module was added (unix time) - from course_modules table
1025 * @property-read int $visible Visible setting (0 or 1; if this is 0, students cannot see/access the activity) - from
1026 * course_modules table
1027 * @property-read int $visibleoncoursepage Visible on course page setting - from course_modules table, adjusted to
1028 * whether course format allows this module to have the "stealth" mode
1029 * @property-read int $visibleold Old visible setting (if the entire section is hidden, the previous value for
1030 * visible is stored in this field) - from course_modules table
1031 * @property-read int $groupmode Group mode (one of the constants NOGROUPS, SEPARATEGROUPS, or VISIBLEGROUPS) - from
1032 * course_modules table. Use {@link cm_info::$effectivegroupmode} to find the actual group mode that may be forced by course.
1033 * @property-read int $groupingid Grouping ID (0 = all groupings)
1034 * @property-read bool $coursegroupmodeforce Indicates whether the course containing the module has forced the groupmode
1035 * This means that cm_info::$groupmode should be ignored and cm_info::$coursegroupmode be used instead
1036 * @property-read int $coursegroupmode Group mode (one of the constants NOGROUPS, SEPARATEGROUPS, or VISIBLEGROUPS) - from
1037 * course table - as specified for the course containing the module
1038 * Effective only if {@link cm_info::$coursegroupmodeforce} is set
1039 * @property-read int $effectivegroupmode Effective group mode for this module (one of the constants NOGROUPS, SEPARATEGROUPS,
1040 * or VISIBLEGROUPS). This can be different from groupmode set for the module if the groupmode is forced for the course.
1041 * This value will always be NOGROUPS if module type does not support group mode.
1042 * @property-read int $indent Indent level on course page (0 = no indent) - from course_modules table
1043 * @property-read int $completion Activity completion setting for this activity, COMPLETION_TRACKING_xx constant - from
1044 * course_modules table
1045 * @property-read mixed $completiongradeitemnumber Set to the item number (usually 0) if completion depends on a particular
1046 * grade of this activity, or null if completion does not depend on a grade - from course_modules table
1047 * @property-read int $completionview 1 if 'on view' completion is enabled, 0 otherwise - from course_modules table
1048 * @property-read int $completionexpected Set to a unix time if completion of this activity is expected at a
1049 * particular time, 0 if no time set - from course_modules table
1050 * @property-read string $availability Availability information as JSON string or null if none -
1051 * from course_modules table
1052 * @property-read int $showdescription Controls whether the description of the activity displays on the course main page (in
1053 * addition to anywhere it might display within the activity itself). 0 = do not show
1054 * on main page, 1 = show on main page.
1055 * @property-read string $extra (deprecated) Extra HTML that is put in an unhelpful part of the HTML when displaying this module in
1056 * course page - from cached data in modinfo field. Deprecated, replaced by ->extraclasses and ->onclick
1057 * @property-read string $icon Name of icon to use - from cached data in modinfo field
1058 * @property-read string $iconcomponent Component that contains icon - from cached data in modinfo field
1059 * @property-read string $modname Name of module e.g. 'forum' (this is the same name as the module's main database
1060 * table) - from cached data in modinfo field
1061 * @property-read int $module ID of module type - from course_modules table
1062 * @property-read string $name Name of module instance for display on page e.g. 'General discussion forum' - from cached
1063 * data in modinfo field
1064 * @property-read int $sectionnum Section number that this course-module is in (section 0 = above the calendar, section 1
1065 * = week/topic 1, etc) - from cached data in modinfo field
1066 * @property-read int $section Section id - from course_modules table
1067 * @property-read array $conditionscompletion Availability conditions for this course-module based on the completion of other
1068 * course-modules (array from other course-module id to required completion state for that
1069 * module) - from cached data in modinfo field
1070 * @property-read array $conditionsgrade Availability conditions for this course-module based on course grades (array from
1071 * grade item id to object with ->min, ->max fields) - from cached data in modinfo field
1072 * @property-read array $conditionsfield Availability conditions for this course-module based on user fields
1073 * @property-read bool $available True if this course-module is available to students i.e. if all availability conditions
1074 * are met - obtained dynamically
1075 * @property-read string $availableinfo If course-module is not available to students, this string gives information about
1076 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
1077 * January 2010') for display on main page - obtained dynamically
1078 * @property-read bool $uservisible True if this course-module is available to the CURRENT user (for example, if current user
1079 * has viewhiddenactivities capability, they can access the course-module even if it is not
1080 * visible or not available, so this would be true in that case)
1081 * @property-read context_module $context Module context
1082 * @property-read string $modfullname Returns a localised human-readable name of the module type - calculated on request
1083 * @property-read string $modplural Returns a localised human-readable name of the module type in plural form - calculated on request
1084 * @property-read string $content Content to display on main (view) page - calculated on request
1085 * @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
1086 * @property-read string $extraclasses Extra CSS classes to add to html output for this activity on main page - calculated on request
1087 * @property-read string $onclick Content of HTML on-click attribute already escaped - calculated on request
1088 * @property-read mixed $customdata Optional custom data stored in modinfo cache for this activity, or null if none
1089 * @property-read string $afterlink Extra HTML code to display after link - calculated on request
1090 * @property-read string $afterediticons Extra HTML code to display after editing icons (e.g. more icons) - calculated on request
1091 * @property-read bool $deletioninprogress True if this course module is scheduled for deletion, false otherwise.
1092 * @property-read bool $downloadcontent True if content download is enabled for this course module, false otherwise.
1093 * @property-read bool $lang the forced language for this activity (language pack name). Null means not forced.
1095 class cm_info implements IteratorAggregate {
1097 * State: Only basic data from modinfo cache is available.
1099 const STATE_BASIC = 0;
1102 * State: In the process of building dynamic data (to avoid recursive calls to obtain_dynamic_data())
1104 const STATE_BUILDING_DYNAMIC = 1;
1107 * State: Dynamic data is available too.
1109 const STATE_DYNAMIC = 2;
1112 * State: In the process of building view data (to avoid recursive calls to obtain_view_data())
1114 const STATE_BUILDING_VIEW = 3;
1117 * State: View data (for course page) is available.
1119 const STATE_VIEW = 4;
1122 * Parent object
1123 * @var course_modinfo
1125 private $modinfo;
1128 * Level of information stored inside this object (STATE_xx constant)
1129 * @var int
1131 private $state;
1134 * Course-module ID - from course_modules table
1135 * @var int
1137 private $id;
1140 * Module instance (ID within module table) - from course_modules table
1141 * @var int
1143 private $instance;
1146 * 'ID number' from course-modules table (arbitrary text set by user) - from
1147 * course_modules table
1148 * @var string
1150 private $idnumber;
1153 * Time that this course-module was added (unix time) - from course_modules table
1154 * @var int
1156 private $added;
1159 * This variable is not used and is included here only so it can be documented.
1160 * Once the database entry is removed from course_modules, it should be deleted
1161 * here too.
1162 * @var int
1163 * @deprecated Do not use this variable
1165 private $score;
1168 * Visible setting (0 or 1; if this is 0, students cannot see/access the activity) - from
1169 * course_modules table
1170 * @var int
1172 private $visible;
1175 * Visible on course page setting - from course_modules table
1176 * @var int
1178 private $visibleoncoursepage;
1181 * Old visible setting (if the entire section is hidden, the previous value for
1182 * visible is stored in this field) - from course_modules table
1183 * @var int
1185 private $visibleold;
1188 * Group mode (one of the constants NONE, SEPARATEGROUPS, or VISIBLEGROUPS) - from
1189 * course_modules table
1190 * @var int
1192 private $groupmode;
1195 * Grouping ID (0 = all groupings)
1196 * @var int
1198 private $groupingid;
1201 * Indent level on course page (0 = no indent) - from course_modules table
1202 * @var int
1204 private $indent;
1207 * Activity completion setting for this activity, COMPLETION_TRACKING_xx constant - from
1208 * course_modules table
1209 * @var int
1211 private $completion;
1214 * Set to the item number (usually 0) if completion depends on a particular
1215 * grade of this activity, or null if completion does not depend on a grade - from
1216 * course_modules table
1217 * @var mixed
1219 private $completiongradeitemnumber;
1222 * 1 if pass grade completion is enabled, 0 otherwise - from course_modules table
1223 * @var int
1225 private $completionpassgrade;
1228 * 1 if 'on view' completion is enabled, 0 otherwise - from course_modules table
1229 * @var int
1231 private $completionview;
1234 * Set to a unix time if completion of this activity is expected at a
1235 * particular time, 0 if no time set - from course_modules table
1236 * @var int
1238 private $completionexpected;
1241 * Availability information as JSON string or null if none - from course_modules table
1242 * @var string
1244 private $availability;
1247 * Controls whether the description of the activity displays on the course main page (in
1248 * addition to anywhere it might display within the activity itself). 0 = do not show
1249 * on main page, 1 = show on main page.
1250 * @var int
1252 private $showdescription;
1255 * Extra HTML that is put in an unhelpful part of the HTML when displaying this module in
1256 * course page - from cached data in modinfo field
1257 * @deprecated This is crazy, don't use it. Replaced by ->extraclasses and ->onclick
1258 * @var string
1260 private $extra;
1263 * Name of icon to use - from cached data in modinfo field
1264 * @var string
1266 private $icon;
1269 * Component that contains icon - from cached data in modinfo field
1270 * @var string
1272 private $iconcomponent;
1275 * Name of module e.g. 'forum' (this is the same name as the module's main database
1276 * table) - from cached data in modinfo field
1277 * @var string
1279 private $modname;
1282 * ID of module - from course_modules table
1283 * @var int
1285 private $module;
1288 * Name of module instance for display on page e.g. 'General discussion forum' - from cached
1289 * data in modinfo field
1290 * @var string
1292 private $name;
1295 * Section number that this course-module is in (section 0 = above the calendar, section 1
1296 * = week/topic 1, etc) - from cached data in modinfo field
1297 * @var int
1299 private $sectionnum;
1302 * Section id - from course_modules table
1303 * @var int
1305 private $section;
1308 * Availability conditions for this course-module based on the completion of other
1309 * course-modules (array from other course-module id to required completion state for that
1310 * module) - from cached data in modinfo field
1311 * @var array
1313 private $conditionscompletion;
1316 * Availability conditions for this course-module based on course grades (array from
1317 * grade item id to object with ->min, ->max fields) - from cached data in modinfo field
1318 * @var array
1320 private $conditionsgrade;
1323 * Availability conditions for this course-module based on user fields
1324 * @var array
1326 private $conditionsfield;
1329 * True if this course-module is available to students i.e. if all availability conditions
1330 * are met - obtained dynamically
1331 * @var bool
1333 private $available;
1336 * If course-module is not available to students, this string gives information about
1337 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
1338 * January 2010') for display on main page - obtained dynamically
1339 * @var string
1341 private $availableinfo;
1344 * True if this course-module is available to the CURRENT user (for example, if current user
1345 * has viewhiddenactivities capability, they can access the course-module even if it is not
1346 * visible or not available, so this would be true in that case)
1347 * @var bool
1349 private $uservisible;
1352 * True if this course-module is visible to the CURRENT user on the course page
1353 * @var bool
1355 private $uservisibleoncoursepage;
1358 * @var moodle_url
1360 private $url;
1363 * @var string
1365 private $content;
1368 * @var bool
1370 private $contentisformatted;
1373 * @var bool True if the content has a special course item display like labels.
1375 private $customcmlistitem;
1378 * @var string
1380 private $extraclasses;
1383 * @var moodle_url full external url pointing to icon image for activity
1385 private $iconurl;
1388 * @var string
1390 private $onclick;
1393 * @var mixed
1395 private $customdata;
1398 * @var string
1400 private $afterlink;
1403 * @var string
1405 private $afterediticons;
1408 * @var bool representing the deletion state of the module. True if the mod is scheduled for deletion.
1410 private $deletioninprogress;
1413 * @var int enable/disable download content for this course module
1415 private $downloadcontent;
1418 * @var string|null the forced language for this activity (language pack name). Null means not forced.
1420 private $lang;
1423 * List of class read-only properties and their getter methods.
1424 * Used by magic functions __get(), __isset(), __empty()
1425 * @var array
1427 private static $standardproperties = [
1428 'url' => 'get_url',
1429 'content' => 'get_content',
1430 'extraclasses' => 'get_extra_classes',
1431 'onclick' => 'get_on_click',
1432 'customdata' => 'get_custom_data',
1433 'afterlink' => 'get_after_link',
1434 'afterediticons' => 'get_after_edit_icons',
1435 'modfullname' => 'get_module_type_name',
1436 'modplural' => 'get_module_type_name_plural',
1437 'id' => false,
1438 'added' => false,
1439 'availability' => false,
1440 'available' => 'get_available',
1441 'availableinfo' => 'get_available_info',
1442 'completion' => false,
1443 'completionexpected' => false,
1444 'completiongradeitemnumber' => false,
1445 'completionpassgrade' => false,
1446 'completionview' => false,
1447 'conditionscompletion' => false,
1448 'conditionsfield' => false,
1449 'conditionsgrade' => false,
1450 'context' => 'get_context',
1451 'course' => 'get_course_id',
1452 'coursegroupmode' => 'get_course_groupmode',
1453 'coursegroupmodeforce' => 'get_course_groupmodeforce',
1454 'customcmlistitem' => 'has_custom_cmlist_item',
1455 'effectivegroupmode' => 'get_effective_groupmode',
1456 'extra' => false,
1457 'groupingid' => false,
1458 'groupmembersonly' => 'get_deprecated_group_members_only',
1459 'groupmode' => false,
1460 'icon' => false,
1461 'iconcomponent' => false,
1462 'idnumber' => false,
1463 'indent' => false,
1464 'instance' => false,
1465 'modname' => false,
1466 'module' => false,
1467 'name' => 'get_name',
1468 'score' => false,
1469 'section' => false,
1470 'sectionnum' => false,
1471 'showdescription' => false,
1472 'uservisible' => 'get_user_visible',
1473 'visible' => false,
1474 'visibleoncoursepage' => false,
1475 'visibleold' => false,
1476 'deletioninprogress' => false,
1477 'downloadcontent' => false,
1478 'lang' => false,
1482 * List of methods with no arguments that were public prior to Moodle 2.6.
1484 * They can still be accessed publicly via magic __call() function with no warnings
1485 * but are not listed in the class methods list.
1486 * For the consistency of the code it is better to use corresponding properties.
1488 * These methods be deprecated completely in later versions.
1490 * @var array $standardmethods
1492 private static $standardmethods = array(
1493 // Following methods are not recommended to use because there have associated read-only properties.
1494 'get_url',
1495 'get_content',
1496 'get_extra_classes',
1497 'get_on_click',
1498 'get_custom_data',
1499 'get_after_link',
1500 'get_after_edit_icons',
1501 // Method obtain_dynamic_data() should not be called from outside of this class but it was public before Moodle 2.6.
1502 'obtain_dynamic_data',
1506 * Magic method to call functions that are now declared as private but were public in Moodle before 2.6.
1507 * These private methods can not be used anymore.
1509 * @param string $name
1510 * @param array $arguments
1511 * @return mixed
1512 * @throws coding_exception
1514 public function __call($name, $arguments) {
1515 if (in_array($name, self::$standardmethods)) {
1516 $message = "cm_info::$name() can not be used anymore.";
1517 if ($alternative = array_search($name, self::$standardproperties)) {
1518 $message .= " Please use the property cm_info->$alternative instead.";
1520 throw new coding_exception($message);
1522 throw new coding_exception("Method cm_info::{$name}() does not exist");
1526 * Magic method getter
1528 * @param string $name
1529 * @return mixed
1531 public function __get($name) {
1532 if (isset(self::$standardproperties[$name])) {
1533 if ($method = self::$standardproperties[$name]) {
1534 return $this->$method();
1535 } else {
1536 return $this->$name;
1538 } else {
1539 debugging('Invalid cm_info property accessed: '.$name);
1540 return null;
1545 * Implementation of IteratorAggregate::getIterator(), allows to cycle through properties
1546 * and use {@link convert_to_array()}
1548 * @return ArrayIterator
1550 public function getIterator(): Traversable {
1551 // Make sure dynamic properties are retrieved prior to view properties.
1552 $this->obtain_dynamic_data();
1553 $ret = array();
1555 // Do not iterate over deprecated properties.
1556 $props = self::$standardproperties;
1557 unset($props['groupmembersonly']);
1559 foreach ($props as $key => $unused) {
1560 $ret[$key] = $this->__get($key);
1562 return new ArrayIterator($ret);
1566 * Magic method for function isset()
1568 * @param string $name
1569 * @return bool
1571 public function __isset($name) {
1572 if (isset(self::$standardproperties[$name])) {
1573 $value = $this->__get($name);
1574 return isset($value);
1576 return false;
1580 * Magic method for function empty()
1582 * @param string $name
1583 * @return bool
1585 public function __empty($name) {
1586 if (isset(self::$standardproperties[$name])) {
1587 $value = $this->__get($name);
1588 return empty($value);
1590 return true;
1594 * Magic method setter
1596 * Will display the developer warning when trying to set/overwrite property.
1598 * @param string $name
1599 * @param mixed $value
1601 public function __set($name, $value) {
1602 debugging("It is not allowed to set the property cm_info::\${$name}", DEBUG_DEVELOPER);
1606 * @return bool True if this module has a 'view' page that should be linked to in navigation
1607 * etc (note: modules may still have a view.php file, but return false if this is not
1608 * intended to be linked to from 'normal' parts of the interface; this is what label does).
1610 public function has_view() {
1611 return !is_null($this->url);
1615 * Gets the URL to link to for this module.
1617 * This method is normally called by the property ->url, but can be called directly if
1618 * there is a case when it might be called recursively (you can't call property values
1619 * recursively).
1621 * @return moodle_url URL to link to for this module, or null if it doesn't have a view page
1623 public function get_url() {
1624 $this->obtain_dynamic_data();
1625 return $this->url;
1629 * Obtains content to display on main (view) page.
1630 * Note: Will collect view data, if not already obtained.
1631 * @return string Content to display on main page below link, or empty string if none
1633 private function get_content() {
1634 $this->obtain_view_data();
1635 return $this->content;
1639 * Returns the content to display on course/overview page, formatted and passed through filters
1641 * if $options['context'] is not specified, the module context is used
1643 * @param array|stdClass $options formatting options, see {@link format_text()}
1644 * @return string
1646 public function get_formatted_content($options = array()) {
1647 $this->obtain_view_data();
1648 if (empty($this->content)) {
1649 return '';
1651 if ($this->contentisformatted) {
1652 return $this->content;
1655 // Improve filter performance by preloading filter setttings for all
1656 // activities on the course (this does nothing if called multiple
1657 // times)
1658 filter_preload_activities($this->get_modinfo());
1660 $options = (array)$options;
1661 if (!isset($options['context'])) {
1662 $options['context'] = $this->get_context();
1664 return format_text($this->content, FORMAT_HTML, $options);
1668 * Return the module custom cmlist item flag.
1670 * Activities like label uses this flag to indicate that it should be
1671 * displayed as a custom course item instead of a tipical activity card.
1673 * @return bool
1675 public function has_custom_cmlist_item(): bool {
1676 $this->obtain_view_data();
1677 return $this->customcmlistitem ?? false;
1681 * Getter method for property $name, ensures that dynamic data is obtained.
1683 * This method is normally called by the property ->name, but can be called directly if there
1684 * is a case when it might be called recursively (you can't call property values recursively).
1686 * @return string
1688 public function get_name() {
1689 $this->obtain_dynamic_data();
1690 return $this->name;
1694 * Returns the name to display on course/overview page, formatted and passed through filters
1696 * if $options['context'] is not specified, the module context is used
1698 * @param array|stdClass $options formatting options, see {@link format_string()}
1699 * @return string
1701 public function get_formatted_name($options = array()) {
1702 global $CFG;
1703 $options = (array)$options;
1704 if (!isset($options['context'])) {
1705 $options['context'] = $this->get_context();
1707 // Improve filter performance by preloading filter setttings for all
1708 // activities on the course (this does nothing if called multiple
1709 // times).
1710 if (!empty($CFG->filterall)) {
1711 filter_preload_activities($this->get_modinfo());
1713 return format_string($this->get_name(), true, $options);
1717 * Note: Will collect view data, if not already obtained.
1718 * @return string Extra CSS classes to add to html output for this activity on main page
1720 private function get_extra_classes() {
1721 $this->obtain_view_data();
1722 return $this->extraclasses;
1726 * @return string Content of HTML on-click attribute. This string will be used literally
1727 * as a string so should be pre-escaped.
1729 private function get_on_click() {
1730 // Does not need view data; may be used by navigation
1731 $this->obtain_dynamic_data();
1732 return $this->onclick;
1735 * Getter method for property $customdata, ensures that dynamic data is retrieved.
1737 * This method is normally called by the property ->customdata, but can be called directly if there
1738 * is a case when it might be called recursively (you can't call property values recursively).
1740 * @return mixed Optional custom data stored in modinfo cache for this activity, or null if none
1742 public function get_custom_data() {
1743 $this->obtain_dynamic_data();
1744 return $this->customdata;
1748 * Note: Will collect view data, if not already obtained.
1749 * @return string Extra HTML code to display after link
1751 private function get_after_link() {
1752 $this->obtain_view_data();
1753 return $this->afterlink;
1757 * Note: Will collect view data, if not already obtained.
1758 * @return string Extra HTML code to display after editing icons (e.g. more icons)
1760 private function get_after_edit_icons() {
1761 $this->obtain_view_data();
1762 return $this->afterediticons;
1766 * @param moodle_core_renderer $output Output render to use, or null for default (global)
1767 * @return moodle_url Icon URL for a suitable icon to put beside this cm
1769 public function get_icon_url($output = null) {
1770 global $OUTPUT;
1771 $this->obtain_dynamic_data();
1772 if (!$output) {
1773 $output = $OUTPUT;
1776 if (!empty($this->iconurl)) {
1777 // Support modules setting their own, external, icon image.
1778 $icon = $this->iconurl;
1779 } else if (!empty($this->icon)) {
1780 // Fallback to normal local icon + component processing.
1781 if (substr($this->icon, 0, 4) === 'mod/') {
1782 list($modname, $iconname) = explode('/', substr($this->icon, 4), 2);
1783 $icon = $output->image_url($iconname, $modname);
1784 } else {
1785 if (!empty($this->iconcomponent)) {
1786 // Icon has specified component.
1787 $icon = $output->image_url($this->icon, $this->iconcomponent);
1788 } else {
1789 // Icon does not have specified component, use default.
1790 $icon = $output->image_url($this->icon);
1793 } else {
1794 $icon = $output->image_url('monologo', $this->modname);
1796 return $icon;
1800 * @param string $textclasses additionnal classes for grouping label
1801 * @return string An empty string or HTML grouping label span tag
1803 public function get_grouping_label($textclasses = '') {
1804 $groupinglabel = '';
1805 if ($this->effectivegroupmode != NOGROUPS && !empty($this->groupingid) &&
1806 has_capability('moodle/course:managegroups', context_course::instance($this->course))) {
1807 $groupings = groups_get_all_groupings($this->course);
1808 $groupinglabel = html_writer::tag('span', '('.format_string($groupings[$this->groupingid]->name).')',
1809 array('class' => 'groupinglabel '.$textclasses));
1811 return $groupinglabel;
1815 * Returns a localised human-readable name of the module type.
1817 * @param bool $plural If true, the function returns the plural form of the name.
1818 * @return lang_string
1820 public function get_module_type_name($plural = false) {
1821 $modnames = get_module_types_names($plural);
1822 if (isset($modnames[$this->modname])) {
1823 return $modnames[$this->modname];
1824 } else {
1825 return null;
1830 * Returns a localised human-readable name of the module type in plural form - calculated on request
1832 * @return string
1834 private function get_module_type_name_plural() {
1835 return $this->get_module_type_name(true);
1839 * @return course_modinfo Modinfo object that this came from
1841 public function get_modinfo() {
1842 return $this->modinfo;
1846 * Returns the section this module belongs to
1848 * @return section_info
1850 public function get_section_info() {
1851 return $this->modinfo->get_section_info($this->sectionnum);
1855 * Returns course object that was used in the first {@link get_fast_modinfo()} call.
1857 * It may not contain all fields from DB table {course} but always has at least the following:
1858 * id,shortname,fullname,format,enablecompletion,groupmode,groupmodeforce,cacherev
1860 * If the course object lacks the field you need you can use the global
1861 * function {@link get_course()} that will save extra query if you access
1862 * current course or frontpage course.
1864 * @return stdClass
1866 public function get_course() {
1867 return $this->modinfo->get_course();
1871 * Returns course id for which the modinfo was generated.
1873 * @return int
1875 private function get_course_id() {
1876 return $this->modinfo->get_course_id();
1880 * Returns group mode used for the course containing the module
1882 * @return int one of constants NOGROUPS, SEPARATEGROUPS, VISIBLEGROUPS
1884 private function get_course_groupmode() {
1885 return $this->modinfo->get_course()->groupmode;
1889 * Returns whether group mode is forced for the course containing the module
1891 * @return bool
1893 private function get_course_groupmodeforce() {
1894 return $this->modinfo->get_course()->groupmodeforce;
1898 * Returns effective groupmode of the module that may be overwritten by forced course groupmode.
1900 * @return int one of constants NOGROUPS, SEPARATEGROUPS, VISIBLEGROUPS
1902 private function get_effective_groupmode() {
1903 $groupmode = $this->groupmode;
1904 if ($this->modinfo->get_course()->groupmodeforce) {
1905 $groupmode = $this->modinfo->get_course()->groupmode;
1906 if ($groupmode != NOGROUPS && !plugin_supports('mod', $this->modname, FEATURE_GROUPS, false)) {
1907 $groupmode = NOGROUPS;
1910 return $groupmode;
1914 * @return context_module Current module context
1916 private function get_context() {
1917 return context_module::instance($this->id);
1921 * Returns itself in the form of stdClass.
1923 * The object includes all fields that table course_modules has and additionally
1924 * fields 'name', 'modname', 'sectionnum' (if requested).
1926 * This can be used as a faster alternative to {@link get_coursemodule_from_id()}
1928 * @param bool $additionalfields include additional fields 'name', 'modname', 'sectionnum'
1929 * @return stdClass
1931 public function get_course_module_record($additionalfields = false) {
1932 $cmrecord = new stdClass();
1934 // Standard fields from table course_modules.
1935 static $cmfields = array('id', 'course', 'module', 'instance', 'section', 'idnumber', 'added',
1936 'score', 'indent', 'visible', 'visibleoncoursepage', 'visibleold', 'groupmode', 'groupingid',
1937 'completion', 'completiongradeitemnumber', 'completionview', 'completionexpected', 'completionpassgrade',
1938 'showdescription', 'availability', 'deletioninprogress', 'downloadcontent', 'lang');
1940 foreach ($cmfields as $key) {
1941 $cmrecord->$key = $this->$key;
1944 // Additional fields that function get_coursemodule_from_id() adds.
1945 if ($additionalfields) {
1946 $cmrecord->name = $this->name;
1947 $cmrecord->modname = $this->modname;
1948 $cmrecord->sectionnum = $this->sectionnum;
1951 return $cmrecord;
1954 // Set functions
1955 ////////////////
1958 * Sets content to display on course view page below link (if present).
1959 * @param string $content New content as HTML string (empty string if none)
1960 * @param bool $isformatted Whether user content is already passed through format_text/format_string and should not
1961 * be formatted again. This can be useful when module adds interactive elements on top of formatted user text.
1962 * @return void
1964 public function set_content($content, $isformatted = false) {
1965 $this->content = $content;
1966 $this->contentisformatted = $isformatted;
1970 * Sets extra classes to include in CSS.
1971 * @param string $extraclasses Extra classes (empty string if none)
1972 * @return void
1974 public function set_extra_classes($extraclasses) {
1975 $this->extraclasses = $extraclasses;
1979 * Sets the external full url that points to the icon being used
1980 * by the activity. Useful for external-tool modules (lti...)
1981 * If set, takes precedence over $icon and $iconcomponent
1983 * @param moodle_url $iconurl full external url pointing to icon image for activity
1984 * @return void
1986 public function set_icon_url(moodle_url $iconurl) {
1987 $this->iconurl = $iconurl;
1991 * Sets value of on-click attribute for JavaScript.
1992 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1993 * @param string $onclick New onclick attribute which should be HTML-escaped
1994 * (empty string if none)
1995 * @return void
1997 public function set_on_click($onclick) {
1998 $this->check_not_view_only();
1999 $this->onclick = $onclick;
2003 * Overrides the value of an element in the customdata array.
2005 * @param string $name The key in the customdata array
2006 * @param mixed $value The value
2008 public function override_customdata($name, $value) {
2009 if (!is_array($this->customdata)) {
2010 $this->customdata = [];
2012 $this->customdata[$name] = $value;
2016 * Sets HTML that displays after link on course view page.
2017 * @param string $afterlink HTML string (empty string if none)
2018 * @return void
2020 public function set_after_link($afterlink) {
2021 $this->afterlink = $afterlink;
2025 * Sets HTML that displays after edit icons on course view page.
2026 * @param string $afterediticons HTML string (empty string if none)
2027 * @return void
2029 public function set_after_edit_icons($afterediticons) {
2030 $this->afterediticons = $afterediticons;
2034 * Changes the name (text of link) for this module instance.
2035 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
2036 * @param string $name Name of activity / link text
2037 * @return void
2039 public function set_name($name) {
2040 if ($this->state < self::STATE_BUILDING_DYNAMIC) {
2041 $this->update_user_visible();
2043 $this->name = $name;
2047 * Turns off the view link for this module instance.
2048 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
2049 * @return void
2051 public function set_no_view_link() {
2052 $this->check_not_view_only();
2053 $this->url = null;
2057 * Sets the 'uservisible' flag. This can be used (by setting false) to prevent access and
2058 * display of this module link for the current user.
2059 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
2060 * @param bool $uservisible
2061 * @return void
2063 public function set_user_visible($uservisible) {
2064 $this->check_not_view_only();
2065 $this->uservisible = $uservisible;
2069 * Sets the 'customcmlistitem' flag
2071 * This can be used (by setting true) to prevent the course from rendering the
2072 * activity item as a regular activity card. This is applied to activities like labels.
2074 * @param bool $customcmlistitem if the cmlist item of that activity has a special dysplay other than a card.
2076 public function set_custom_cmlist_item(bool $customcmlistitem) {
2077 $this->customcmlistitem = $customcmlistitem;
2081 * Sets the 'available' flag and related details. This flag is normally used to make
2082 * course modules unavailable until a certain date or condition is met. (When a course
2083 * module is unavailable, it is still visible to users who have viewhiddenactivities
2084 * permission.)
2086 * When this is function is called, user-visible status is recalculated automatically.
2088 * The $showavailability flag does not really do anything any more, but is retained
2089 * for backward compatibility. Setting this to false will cause $availableinfo to
2090 * be ignored.
2092 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
2093 * @param bool $available False if this item is not 'available'
2094 * @param int $showavailability 0 = do not show this item at all if it's not available,
2095 * 1 = show this item greyed out with the following message
2096 * @param string $availableinfo Information about why this is not available, or
2097 * empty string if not displaying
2098 * @return void
2100 public function set_available($available, $showavailability=0, $availableinfo='') {
2101 $this->check_not_view_only();
2102 $this->available = $available;
2103 if (!$showavailability) {
2104 $availableinfo = '';
2106 $this->availableinfo = $availableinfo;
2107 $this->update_user_visible();
2111 * Some set functions can only be called from _cm_info_dynamic and not _cm_info_view.
2112 * This is because they may affect parts of this object which are used on pages other
2113 * than the view page (e.g. in the navigation block, or when checking access on
2114 * module pages).
2115 * @return void
2117 private function check_not_view_only() {
2118 if ($this->state >= self::STATE_DYNAMIC) {
2119 throw new coding_exception('Cannot set this data from _cm_info_view because it may ' .
2120 'affect other pages as well as view');
2125 * Constructor should not be called directly; use {@link get_fast_modinfo()}
2127 * @param course_modinfo $modinfo Parent object
2128 * @param stdClass $notused1 Argument not used
2129 * @param stdClass $mod Module object from the modinfo field of course table
2130 * @param stdClass $notused2 Argument not used
2132 public function __construct(course_modinfo $modinfo, $notused1, $mod, $notused2) {
2133 $this->modinfo = $modinfo;
2135 $this->id = $mod->cm;
2136 $this->instance = $mod->id;
2137 $this->modname = $mod->mod;
2138 $this->idnumber = isset($mod->idnumber) ? $mod->idnumber : '';
2139 $this->name = $mod->name;
2140 $this->visible = $mod->visible;
2141 $this->visibleoncoursepage = $mod->visibleoncoursepage;
2142 $this->sectionnum = $mod->section; // Note weirdness with name here
2143 $this->groupmode = isset($mod->groupmode) ? $mod->groupmode : 0;
2144 $this->groupingid = isset($mod->groupingid) ? $mod->groupingid : 0;
2145 $this->indent = isset($mod->indent) ? $mod->indent : 0;
2146 $this->extra = isset($mod->extra) ? $mod->extra : '';
2147 $this->extraclasses = isset($mod->extraclasses) ? $mod->extraclasses : '';
2148 // iconurl may be stored as either string or instance of moodle_url.
2149 $this->iconurl = isset($mod->iconurl) ? new moodle_url($mod->iconurl) : '';
2150 $this->onclick = isset($mod->onclick) ? $mod->onclick : '';
2151 $this->content = isset($mod->content) ? $mod->content : '';
2152 $this->icon = isset($mod->icon) ? $mod->icon : '';
2153 $this->iconcomponent = isset($mod->iconcomponent) ? $mod->iconcomponent : '';
2154 $this->customdata = isset($mod->customdata) ? $mod->customdata : '';
2155 $this->showdescription = isset($mod->showdescription) ? $mod->showdescription : 0;
2156 $this->state = self::STATE_BASIC;
2158 $this->section = isset($mod->sectionid) ? $mod->sectionid : 0;
2159 $this->module = isset($mod->module) ? $mod->module : 0;
2160 $this->added = isset($mod->added) ? $mod->added : 0;
2161 $this->score = isset($mod->score) ? $mod->score : 0;
2162 $this->visibleold = isset($mod->visibleold) ? $mod->visibleold : 0;
2163 $this->deletioninprogress = isset($mod->deletioninprogress) ? $mod->deletioninprogress : 0;
2164 $this->downloadcontent = $mod->downloadcontent ?? null;
2165 $this->lang = $mod->lang ?? null;
2167 // Note: it saves effort and database space to always include the
2168 // availability and completion fields, even if availability or completion
2169 // are actually disabled
2170 $this->completion = isset($mod->completion) ? $mod->completion : 0;
2171 $this->completionpassgrade = isset($mod->completionpassgrade) ? $mod->completionpassgrade : 0;
2172 $this->completiongradeitemnumber = isset($mod->completiongradeitemnumber)
2173 ? $mod->completiongradeitemnumber : null;
2174 $this->completionview = isset($mod->completionview)
2175 ? $mod->completionview : 0;
2176 $this->completionexpected = isset($mod->completionexpected)
2177 ? $mod->completionexpected : 0;
2178 $this->availability = isset($mod->availability) ? $mod->availability : null;
2179 $this->conditionscompletion = isset($mod->conditionscompletion)
2180 ? $mod->conditionscompletion : array();
2181 $this->conditionsgrade = isset($mod->conditionsgrade)
2182 ? $mod->conditionsgrade : array();
2183 $this->conditionsfield = isset($mod->conditionsfield)
2184 ? $mod->conditionsfield : array();
2186 static $modviews = array();
2187 if (!isset($modviews[$this->modname])) {
2188 $modviews[$this->modname] = !plugin_supports('mod', $this->modname,
2189 FEATURE_NO_VIEW_LINK);
2191 $this->url = $modviews[$this->modname]
2192 ? new moodle_url('/mod/' . $this->modname . '/view.php', array('id'=>$this->id))
2193 : null;
2197 * Creates a cm_info object from a database record (also accepts cm_info
2198 * in which case it is just returned unchanged).
2200 * @param stdClass|cm_info|null|bool $cm Stdclass or cm_info (or null or false)
2201 * @param int $userid Optional userid (default to current)
2202 * @return cm_info|null Object as cm_info, or null if input was null/false
2204 public static function create($cm, $userid = 0) {
2205 // Null, false, etc. gets passed through as null.
2206 if (!$cm) {
2207 return null;
2209 // If it is already a cm_info object, just return it.
2210 if ($cm instanceof cm_info) {
2211 return $cm;
2213 // Otherwise load modinfo.
2214 if (empty($cm->id) || empty($cm->course)) {
2215 throw new coding_exception('$cm must contain ->id and ->course');
2217 $modinfo = get_fast_modinfo($cm->course, $userid);
2218 return $modinfo->get_cm($cm->id);
2222 * If dynamic data for this course-module is not yet available, gets it.
2224 * This function is automatically called when requesting any course_modinfo property
2225 * that can be modified by modules (have a set_xxx method).
2227 * Dynamic data is data which does not come directly from the cache but is calculated at
2228 * runtime based on the current user. Primarily this concerns whether the user can access
2229 * the module or not.
2231 * As part of this function, the module's _cm_info_dynamic function from its lib.php will
2232 * be called (if it exists). Make sure that the functions that are called here do not use
2233 * any getter magic method from cm_info.
2234 * @return void
2236 private function obtain_dynamic_data() {
2237 global $CFG;
2238 $userid = $this->modinfo->get_user_id();
2239 if ($this->state >= self::STATE_BUILDING_DYNAMIC || $userid == -1) {
2240 return;
2242 $this->state = self::STATE_BUILDING_DYNAMIC;
2244 if (!empty($CFG->enableavailability)) {
2245 // Get availability information.
2246 $ci = new \core_availability\info_module($this);
2248 // Note that the modinfo currently available only includes minimal details (basic data)
2249 // but we know that this function does not need anything more than basic data.
2250 $this->available = $ci->is_available($this->availableinfo, true,
2251 $userid, $this->modinfo);
2252 } else {
2253 $this->available = true;
2256 // Check parent section.
2257 if ($this->available) {
2258 $parentsection = $this->modinfo->get_section_info($this->sectionnum);
2259 if (!$parentsection->get_available()) {
2260 // Do not store info from section here, as that is already
2261 // presented from the section (if appropriate) - just change
2262 // the flag
2263 $this->available = false;
2267 // Update visible state for current user.
2268 $this->update_user_visible();
2270 // Let module make dynamic changes at this point
2271 $this->call_mod_function('cm_info_dynamic');
2272 $this->state = self::STATE_DYNAMIC;
2276 * Getter method for property $uservisible, ensures that dynamic data is retrieved.
2278 * This method is normally called by the property ->uservisible, but can be called directly if
2279 * there is a case when it might be called recursively (you can't call property values
2280 * recursively).
2282 * @return bool
2284 public function get_user_visible() {
2285 $this->obtain_dynamic_data();
2286 return $this->uservisible;
2290 * Returns whether this module is visible to the current user on course page
2292 * Activity may be visible on the course page but not available, for example
2293 * when it is hidden conditionally but the condition information is displayed.
2295 * @return bool
2297 public function is_visible_on_course_page() {
2298 $this->obtain_dynamic_data();
2299 return $this->uservisibleoncoursepage;
2303 * Whether this module is available but hidden from course page
2305 * "Stealth" modules are the ones that are not shown on course page but available by following url.
2306 * They are normally also displayed in grade reports and other reports.
2307 * Module will be stealth either if visibleoncoursepage=0 or it is a visible module inside the hidden
2308 * section.
2310 * @return bool
2312 public function is_stealth() {
2313 return !$this->visibleoncoursepage ||
2314 ($this->visible && ($section = $this->get_section_info()) && !$section->visible);
2318 * Getter method for property $available, ensures that dynamic data is retrieved
2319 * @return bool
2321 private function get_available() {
2322 $this->obtain_dynamic_data();
2323 return $this->available;
2327 * This method can not be used anymore.
2329 * @see \core_availability\info_module::filter_user_list()
2330 * @deprecated Since Moodle 2.8
2332 private function get_deprecated_group_members_only() {
2333 throw new coding_exception('$cm->groupmembersonly can not be used anymore. ' .
2334 'If used to restrict a list of enrolled users to only those who can ' .
2335 'access the module, consider \core_availability\info_module::filter_user_list.');
2339 * Getter method for property $availableinfo, ensures that dynamic data is retrieved
2341 * @return string Available info (HTML)
2343 private function get_available_info() {
2344 $this->obtain_dynamic_data();
2345 return $this->availableinfo;
2349 * Works out whether activity is available to the current user
2351 * If the activity is unavailable, additional checks are required to determine if its hidden or greyed out
2353 * @return void
2355 private function update_user_visible() {
2356 $userid = $this->modinfo->get_user_id();
2357 if ($userid == -1) {
2358 return null;
2360 $this->uservisible = true;
2362 // If the module is being deleted, set the uservisible state to false and return.
2363 if ($this->deletioninprogress) {
2364 $this->uservisible = false;
2365 return null;
2368 // If the user cannot access the activity set the uservisible flag to false.
2369 // Additional checks are required to determine whether the activity is entirely hidden or just greyed out.
2370 if ((!$this->visible && !has_capability('moodle/course:viewhiddenactivities', $this->get_context(), $userid)) ||
2371 (!$this->get_available() &&
2372 !has_capability('moodle/course:ignoreavailabilityrestrictions', $this->get_context(), $userid))) {
2374 $this->uservisible = false;
2377 // Check group membership.
2378 if ($this->is_user_access_restricted_by_capability()) {
2380 $this->uservisible = false;
2381 // Ensure activity is completely hidden from the user.
2382 $this->availableinfo = '';
2385 $this->uservisibleoncoursepage = $this->uservisible &&
2386 ($this->visibleoncoursepage ||
2387 has_capability('moodle/course:manageactivities', $this->get_context(), $userid) ||
2388 has_capability('moodle/course:activityvisibility', $this->get_context(), $userid));
2389 // Activity that is not available, not hidden from course page and has availability
2390 // info is actually visible on the course page (with availability info and without a link).
2391 if (!$this->uservisible && $this->visibleoncoursepage && $this->availableinfo) {
2392 $this->uservisibleoncoursepage = true;
2397 * This method has been deprecated and should not be used.
2399 * @see $uservisible
2400 * @deprecated Since Moodle 2.8
2402 public function is_user_access_restricted_by_group() {
2403 throw new coding_exception('cm_info::is_user_access_restricted_by_group() can not be used any more.' .
2404 ' Use $cm->uservisible to decide whether the current user can access an activity.');
2408 * Checks whether mod/...:view capability restricts the current user's access.
2410 * @return bool True if the user access is restricted.
2412 public function is_user_access_restricted_by_capability() {
2413 $userid = $this->modinfo->get_user_id();
2414 if ($userid == -1) {
2415 return null;
2417 $capability = 'mod/' . $this->modname . ':view';
2418 $capabilityinfo = get_capability_info($capability);
2419 if (!$capabilityinfo) {
2420 // Capability does not exist, no one is prevented from seeing the activity.
2421 return false;
2424 // You are blocked if you don't have the capability.
2425 return !has_capability($capability, $this->get_context(), $userid);
2429 * Checks whether the module's conditional access settings mean that the
2430 * user cannot see the activity at all
2432 * @deprecated since 2.7 MDL-44070
2434 public function is_user_access_restricted_by_conditional_access() {
2435 throw new coding_exception('cm_info::is_user_access_restricted_by_conditional_access() ' .
2436 'can not be used any more; this function is not needed (use $cm->uservisible ' .
2437 'and $cm->availableinfo to decide whether it should be available ' .
2438 'or appear)');
2442 * Calls a module function (if exists), passing in one parameter: this object.
2443 * @param string $type Name of function e.g. if this is 'grooblezorb' and the modname is
2444 * 'forum' then it will try to call 'mod_forum_grooblezorb' or 'forum_grooblezorb'
2445 * @return void
2447 private function call_mod_function($type) {
2448 global $CFG;
2449 $libfile = $CFG->dirroot . '/mod/' . $this->modname . '/lib.php';
2450 if (file_exists($libfile)) {
2451 include_once($libfile);
2452 $function = 'mod_' . $this->modname . '_' . $type;
2453 if (function_exists($function)) {
2454 $function($this);
2455 } else {
2456 $function = $this->modname . '_' . $type;
2457 if (function_exists($function)) {
2458 $function($this);
2465 * If view data for this course-module is not yet available, obtains it.
2467 * This function is automatically called if any of the functions (marked) which require
2468 * view data are called.
2470 * View data is data which is needed only for displaying the course main page (& any similar
2471 * functionality on other pages) but is not needed in general. Obtaining view data may have
2472 * a performance cost.
2474 * As part of this function, the module's _cm_info_view function from its lib.php will
2475 * be called (if it exists).
2476 * @return void
2478 private function obtain_view_data() {
2479 if ($this->state >= self::STATE_BUILDING_VIEW || $this->modinfo->get_user_id() == -1) {
2480 return;
2482 $this->obtain_dynamic_data();
2483 $this->state = self::STATE_BUILDING_VIEW;
2485 // Let module make changes at this point
2486 $this->call_mod_function('cm_info_view');
2487 $this->state = self::STATE_VIEW;
2493 * Returns reference to full info about modules in course (including visibility).
2494 * Cached and as fast as possible (0 or 1 db query).
2496 * use get_fast_modinfo($courseid, 0, true) to reset the static cache for particular course
2497 * use get_fast_modinfo(0, 0, true) to reset the static cache for all courses
2499 * use rebuild_course_cache($courseid, true) to reset the application AND static cache
2500 * for particular course when it's contents has changed
2502 * @param int|stdClass $courseorid object from DB table 'course' (must have field 'id'
2503 * and recommended to have field 'cacherev') or just a course id. Just course id
2504 * is enough when calling get_fast_modinfo() for current course or site or when
2505 * calling for any other course for the second time.
2506 * @param int $userid User id to populate 'availble' and 'uservisible' attributes of modules and sections.
2507 * Set to 0 for current user (default). Set to -1 to avoid calculation of dynamic user-depended data.
2508 * @param bool $resetonly whether we want to get modinfo or just reset the cache
2509 * @return course_modinfo|null Module information for course, or null if resetting
2510 * @throws moodle_exception when course is not found (nothing is thrown if resetting)
2512 function get_fast_modinfo($courseorid, $userid = 0, $resetonly = false) {
2513 // compartibility with syntax prior to 2.4:
2514 if ($courseorid === 'reset') {
2515 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);
2516 $courseorid = 0;
2517 $resetonly = true;
2520 // Function get_fast_modinfo() can never be called during upgrade unless it is used for clearing cache only.
2521 if (!$resetonly) {
2522 upgrade_ensure_not_running();
2525 // Function is called with $reset = true
2526 if ($resetonly) {
2527 course_modinfo::clear_instance_cache($courseorid);
2528 return null;
2531 // Function is called with $reset = false, retrieve modinfo
2532 return course_modinfo::instance($courseorid, $userid);
2536 * Efficiently retrieves the $course (stdclass) and $cm (cm_info) objects, given
2537 * a cmid. If module name is also provided, it will ensure the cm is of that type.
2539 * Usage:
2540 * list($course, $cm) = get_course_and_cm_from_cmid($cmid, 'forum');
2542 * Using this method has a performance advantage because it works by loading
2543 * modinfo for the course - which will then be cached and it is needed later
2544 * in most requests. It also guarantees that the $cm object is a cm_info and
2545 * not a stdclass.
2547 * The $course object can be supplied if already known and will speed
2548 * up this function - although it is more efficient to use this function to
2549 * get the course if you are starting from a cmid.
2551 * To avoid security problems and obscure bugs, you should always specify
2552 * $modulename if the cmid value came from user input.
2554 * By default this obtains information (for example, whether user can access
2555 * the activity) for current user, but you can specify a userid if required.
2557 * @param stdClass|int $cmorid Id of course-module, or database object
2558 * @param string $modulename Optional modulename (improves security)
2559 * @param stdClass|int $courseorid Optional course object if already loaded
2560 * @param int $userid Optional userid (default = current)
2561 * @return array Array with 2 elements $course and $cm
2562 * @throws moodle_exception If the item doesn't exist or is of wrong module name
2564 function get_course_and_cm_from_cmid($cmorid, $modulename = '', $courseorid = 0, $userid = 0) {
2565 global $DB;
2566 if (is_object($cmorid)) {
2567 $cmid = $cmorid->id;
2568 if (isset($cmorid->course)) {
2569 $courseid = (int)$cmorid->course;
2570 } else {
2571 $courseid = 0;
2573 } else {
2574 $cmid = (int)$cmorid;
2575 $courseid = 0;
2578 // Validate module name if supplied.
2579 if ($modulename && !core_component::is_valid_plugin_name('mod', $modulename)) {
2580 throw new coding_exception('Invalid modulename parameter');
2583 // Get course from last parameter if supplied.
2584 $course = null;
2585 if (is_object($courseorid)) {
2586 $course = $courseorid;
2587 } else if ($courseorid) {
2588 $courseid = (int)$courseorid;
2591 if (!$course) {
2592 if ($courseid) {
2593 // If course ID is known, get it using normal function.
2594 $course = get_course($courseid);
2595 } else {
2596 // Get course record in a single query based on cmid.
2597 $course = $DB->get_record_sql("
2598 SELECT c.*
2599 FROM {course_modules} cm
2600 JOIN {course} c ON c.id = cm.course
2601 WHERE cm.id = ?", array($cmid), MUST_EXIST);
2605 // Get cm from get_fast_modinfo.
2606 $modinfo = get_fast_modinfo($course, $userid);
2607 $cm = $modinfo->get_cm($cmid);
2608 if ($modulename && $cm->modname !== $modulename) {
2609 throw new moodle_exception('invalidcoursemoduleid', 'error', '', $cmid);
2611 return array($course, $cm);
2615 * Efficiently retrieves the $course (stdclass) and $cm (cm_info) objects, given
2616 * an instance id or record and module name.
2618 * Usage:
2619 * list($course, $cm) = get_course_and_cm_from_instance($forum, 'forum');
2621 * Using this method has a performance advantage because it works by loading
2622 * modinfo for the course - which will then be cached and it is needed later
2623 * in most requests. It also guarantees that the $cm object is a cm_info and
2624 * not a stdclass.
2626 * The $course object can be supplied if already known and will speed
2627 * up this function - although it is more efficient to use this function to
2628 * get the course if you are starting from an instance id.
2630 * By default this obtains information (for example, whether user can access
2631 * the activity) for current user, but you can specify a userid if required.
2633 * @param stdclass|int $instanceorid Id of module instance, or database object
2634 * @param string $modulename Modulename (required)
2635 * @param stdClass|int $courseorid Optional course object if already loaded
2636 * @param int $userid Optional userid (default = current)
2637 * @return array Array with 2 elements $course and $cm
2638 * @throws moodle_exception If the item doesn't exist or is of wrong module name
2640 function get_course_and_cm_from_instance($instanceorid, $modulename, $courseorid = 0, $userid = 0) {
2641 global $DB;
2643 // Get data from parameter.
2644 if (is_object($instanceorid)) {
2645 $instanceid = $instanceorid->id;
2646 if (isset($instanceorid->course)) {
2647 $courseid = (int)$instanceorid->course;
2648 } else {
2649 $courseid = 0;
2651 } else {
2652 $instanceid = (int)$instanceorid;
2653 $courseid = 0;
2656 // Get course from last parameter if supplied.
2657 $course = null;
2658 if (is_object($courseorid)) {
2659 $course = $courseorid;
2660 } else if ($courseorid) {
2661 $courseid = (int)$courseorid;
2664 // Validate module name if supplied.
2665 if (!core_component::is_valid_plugin_name('mod', $modulename)) {
2666 throw new coding_exception('Invalid modulename parameter');
2669 if (!$course) {
2670 if ($courseid) {
2671 // If course ID is known, get it using normal function.
2672 $course = get_course($courseid);
2673 } else {
2674 // Get course record in a single query based on instance id.
2675 $pagetable = '{' . $modulename . '}';
2676 $course = $DB->get_record_sql("
2677 SELECT c.*
2678 FROM $pagetable instance
2679 JOIN {course} c ON c.id = instance.course
2680 WHERE instance.id = ?", array($instanceid), MUST_EXIST);
2684 // Get cm from get_fast_modinfo.
2685 $modinfo = get_fast_modinfo($course, $userid);
2686 $instances = $modinfo->get_instances_of($modulename);
2687 if (!array_key_exists($instanceid, $instances)) {
2688 throw new moodle_exception('invalidmoduleid', 'error', $instanceid);
2690 return array($course, $instances[$instanceid]);
2695 * Rebuilds or resets the cached list of course activities stored in MUC.
2697 * rebuild_course_cache() must NEVER be called from lib/db/upgrade.php.
2698 * At the same time course cache may ONLY be cleared using this function in
2699 * upgrade scripts of plugins.
2701 * During the bulk operations if it is necessary to reset cache of multiple
2702 * courses it is enough to call {@link increment_revision_number()} for the
2703 * table 'course' and field 'cacherev' specifying affected courses in select.
2705 * Cached course information is stored in MUC core/coursemodinfo and is
2706 * validated with the DB field {course}.cacherev
2708 * @global moodle_database $DB
2709 * @param int $courseid id of course to rebuild, empty means all
2710 * @param boolean $clearonly only clear the cache, gets rebuild automatically on the fly.
2711 * Recommended to set to true to avoid unnecessary multiple rebuilding.
2712 * @param boolean $partialrebuild will not delete the whole cache when it's true.
2713 * use purge_module_cache() or purge_section_cache() must be
2714 * called before when partialrebuild is true.
2715 * use purge_module_cache() to invalidate mod cache.
2716 * use purge_section_cache() to invalidate section cache.
2718 * @return void
2719 * @throws coding_exception
2721 function rebuild_course_cache(int $courseid = 0, bool $clearonly = false, bool $partialrebuild = false): void {
2722 global $COURSE, $SITE, $DB;
2724 if ($courseid == 0 and $partialrebuild) {
2725 throw new coding_exception('partialrebuild only works when a valid course id is provided.');
2728 // Function rebuild_course_cache() can not be called during upgrade unless it's clear only.
2729 if (!$clearonly && !upgrade_ensure_not_running(true)) {
2730 $clearonly = true;
2733 // Destroy navigation caches
2734 navigation_cache::destroy_volatile_caches();
2736 core_courseformat\base::reset_course_cache($courseid);
2738 $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
2739 if (empty($courseid)) {
2740 // Clearing caches for all courses.
2741 increment_revision_number('course', 'cacherev', '');
2742 if (!$partialrebuild) {
2743 $cachecoursemodinfo->purge();
2745 // Clear memory static cache.
2746 course_modinfo::clear_instance_cache();
2747 // Update global values too.
2748 $sitecacherev = $DB->get_field('course', 'cacherev', array('id' => SITEID));
2749 $SITE->cachrev = $sitecacherev;
2750 if ($COURSE->id == SITEID) {
2751 $COURSE->cacherev = $sitecacherev;
2752 } else {
2753 $COURSE->cacherev = $DB->get_field('course', 'cacherev', array('id' => $COURSE->id));
2755 } else {
2756 // Clearing cache for one course, make sure it is deleted from user request cache as well.
2757 increment_revision_number('course', 'cacherev', 'id = :id', array('id' => $courseid));
2758 if (!$partialrebuild) {
2759 // Purge all course modinfo.
2760 $cachecoursemodinfo->delete($courseid);
2762 // Clear memory static cache.
2763 course_modinfo::clear_instance_cache($courseid);
2764 // Update global values too.
2765 if ($courseid == $COURSE->id || $courseid == $SITE->id) {
2766 $cacherev = $DB->get_field('course', 'cacherev', array('id' => $courseid));
2767 if ($courseid == $COURSE->id) {
2768 $COURSE->cacherev = $cacherev;
2770 if ($courseid == $SITE->id) {
2771 $SITE->cachrev = $cacherev;
2776 if ($clearonly) {
2777 return;
2780 if ($courseid) {
2781 $select = array('id'=>$courseid);
2782 } else {
2783 $select = array();
2784 core_php_time_limit::raise(); // this could take a while! MDL-10954
2787 $fields = 'id,' . join(',', course_modinfo::$cachedfields);
2788 $sort = '';
2789 $rs = $DB->get_recordset("course", $select, $sort, $fields);
2791 // Rebuild cache for each course.
2792 foreach ($rs as $course) {
2793 course_modinfo::build_course_cache($course, $partialrebuild);
2795 $rs->close();
2800 * Class that is the return value for the _get_coursemodule_info module API function.
2802 * Note: For backward compatibility, you can also return a stdclass object from that function.
2803 * The difference is that the stdclass object may contain an 'extra' field (deprecated,
2804 * use extraclasses and onclick instead). The stdclass object may not contain
2805 * the new fields defined here (content, extraclasses, customdata).
2807 class cached_cm_info {
2809 * Name (text of link) for this activity; Leave unset to accept default name
2810 * @var string
2812 public $name;
2815 * Name of icon for this activity. Normally, this should be used together with $iconcomponent
2816 * to define the icon, as per image_url function.
2817 * For backward compatibility, if this value is of the form 'mod/forum/icon' then an icon
2818 * within that module will be used.
2819 * @see cm_info::get_icon_url()
2820 * @see renderer_base::image_url()
2821 * @var string
2823 public $icon;
2826 * Component for icon for this activity, as per image_url; leave blank to use default 'moodle'
2827 * component
2828 * @see renderer_base::image_url()
2829 * @var string
2831 public $iconcomponent;
2834 * HTML content to be displayed on the main page below the link (if any) for this course-module
2835 * @var string
2837 public $content;
2840 * Custom data to be stored in modinfo for this activity; useful if there are cases when
2841 * internal information for this activity type needs to be accessible from elsewhere on the
2842 * course without making database queries. May be of any type but should be short.
2843 * @var mixed
2845 public $customdata;
2848 * Extra CSS class or classes to be added when this activity is displayed on the main page;
2849 * space-separated string
2850 * @var string
2852 public $extraclasses;
2855 * External URL image to be used by activity as icon, useful for some external-tool modules
2856 * like lti. If set, takes precedence over $icon and $iconcomponent
2857 * @var $moodle_url
2859 public $iconurl;
2862 * Content of onclick JavaScript; escaped HTML to be inserted as attribute value
2863 * @var string
2865 public $onclick;
2870 * Data about a single section on a course. This contains the fields from the
2871 * course_sections table, plus additional data when required.
2873 * @property-read int $id Section ID - from course_sections table
2874 * @property-read int $course Course ID - from course_sections table
2875 * @property-read int $section Section number - from course_sections table
2876 * @property-read string $name Section name if specified - from course_sections table
2877 * @property-read int $visible Section visibility (1 = visible) - from course_sections table
2878 * @property-read string $summary Section summary text if specified - from course_sections table
2879 * @property-read int $summaryformat Section summary text format (FORMAT_xx constant) - from course_sections table
2880 * @property-read string $availability Availability information as JSON string -
2881 * from course_sections table
2882 * @property-read array $conditionscompletion Availability conditions for this section based on the completion of
2883 * course-modules (array from course-module id to required completion state
2884 * for that module) - from cached data in sectioncache field
2885 * @property-read array $conditionsgrade Availability conditions for this section based on course grades (array from
2886 * grade item id to object with ->min, ->max fields) - from cached data in
2887 * sectioncache field
2888 * @property-read array $conditionsfield Availability conditions for this section based on user fields
2889 * @property-read bool $available True if this section is available to the given user i.e. if all availability conditions
2890 * are met - obtained dynamically
2891 * @property-read string $availableinfo If section is not available to some users, this string gives information about
2892 * availability which can be displayed to students and/or staff (e.g. 'Available from 3 January 2010')
2893 * for display on main page - obtained dynamically
2894 * @property-read bool $uservisible True if this section is available to the given user (for example, if current user
2895 * has viewhiddensections capability, they can access the section even if it is not
2896 * visible or not available, so this would be true in that case) - obtained dynamically
2897 * @property-read string $sequence Comma-separated list of all modules in the section. Note, this field may not exactly
2898 * match course_sections.sequence if later has references to non-existing modules or not modules of not available module types.
2899 * @property-read course_modinfo $modinfo
2901 class section_info implements IteratorAggregate {
2903 * Section ID - from course_sections table
2904 * @var int
2906 private $_id;
2909 * Section number - from course_sections table
2910 * @var int
2912 private $_section;
2915 * Section name if specified - from course_sections table
2916 * @var string
2918 private $_name;
2921 * Section visibility (1 = visible) - from course_sections table
2922 * @var int
2924 private $_visible;
2927 * Section summary text if specified - from course_sections table
2928 * @var string
2930 private $_summary;
2933 * Section summary text format (FORMAT_xx constant) - from course_sections table
2934 * @var int
2936 private $_summaryformat;
2939 * Availability information as JSON string - from course_sections table
2940 * @var string
2942 private $_availability;
2945 * Availability conditions for this section based on the completion of
2946 * course-modules (array from course-module id to required completion state
2947 * for that module) - from cached data in sectioncache field
2948 * @var array
2950 private $_conditionscompletion;
2953 * Availability conditions for this section based on course grades (array from
2954 * grade item id to object with ->min, ->max fields) - from cached data in
2955 * sectioncache field
2956 * @var array
2958 private $_conditionsgrade;
2961 * Availability conditions for this section based on user fields
2962 * @var array
2964 private $_conditionsfield;
2967 * True if this section is available to students i.e. if all availability conditions
2968 * are met - obtained dynamically on request, see function {@link section_info::get_available()}
2969 * @var bool|null
2971 private $_available;
2974 * If section is not available to some users, this string gives information about
2975 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
2976 * January 2010') for display on main page - obtained dynamically on request, see
2977 * function {@link section_info::get_availableinfo()}
2978 * @var string
2980 private $_availableinfo;
2983 * True if this section is available to the CURRENT user (for example, if current user
2984 * has viewhiddensections capability, they can access the section even if it is not
2985 * visible or not available, so this would be true in that case) - obtained dynamically
2986 * on request, see function {@link section_info::get_uservisible()}
2987 * @var bool|null
2989 private $_uservisible;
2992 * Default values for sectioncache fields; if a field has this value, it won't
2993 * be stored in the sectioncache cache, to save space. Checks are done by ===
2994 * which means values must all be strings.
2995 * @var array
2997 private static $sectioncachedefaults = array(
2998 'name' => null,
2999 'summary' => '',
3000 'summaryformat' => '1', // FORMAT_HTML, but must be a string
3001 'visible' => '1',
3002 'availability' => null
3006 * Stores format options that have been cached when building 'coursecache'
3007 * When the format option is requested we look first if it has been cached
3008 * @var array
3010 private $cachedformatoptions = array();
3013 * Stores the list of all possible section options defined in each used course format.
3014 * @var array
3016 static private $sectionformatoptions = array();
3019 * Stores the modinfo object passed in constructor, may be used when requesting
3020 * dynamically obtained attributes such as available, availableinfo, uservisible.
3021 * Also used to retrun information about current course or user.
3022 * @var course_modinfo
3024 private $modinfo;
3027 * Constructs object from database information plus extra required data.
3028 * @param object $data Array entry from cached sectioncache
3029 * @param int $number Section number (array key)
3030 * @param int $notused1 argument not used (informaion is available in $modinfo)
3031 * @param int $notused2 argument not used (informaion is available in $modinfo)
3032 * @param course_modinfo $modinfo Owner (needed for checking availability)
3033 * @param int $notused3 argument not used (informaion is available in $modinfo)
3035 public function __construct($data, $number, $notused1, $notused2, $modinfo, $notused3) {
3036 global $CFG;
3037 require_once($CFG->dirroot.'/course/lib.php');
3039 // Data that is always present
3040 $this->_id = $data->id;
3042 $defaults = self::$sectioncachedefaults +
3043 array('conditionscompletion' => array(),
3044 'conditionsgrade' => array(),
3045 'conditionsfield' => array());
3047 // Data that may use default values to save cache size
3048 foreach ($defaults as $field => $value) {
3049 if (isset($data->{$field})) {
3050 $this->{'_'.$field} = $data->{$field};
3051 } else {
3052 $this->{'_'.$field} = $value;
3056 // Other data from constructor arguments.
3057 $this->_section = $number;
3058 $this->modinfo = $modinfo;
3060 // Cached course format data.
3061 $course = $modinfo->get_course();
3062 if (!isset(self::$sectionformatoptions[$course->format])) {
3063 // Store list of section format options defined in each used course format.
3064 // They do not depend on particular course but only on its format.
3065 self::$sectionformatoptions[$course->format] =
3066 course_get_format($course)->section_format_options();
3068 foreach (self::$sectionformatoptions[$course->format] as $field => $option) {
3069 if (!empty($option['cache'])) {
3070 if (isset($data->{$field})) {
3071 $this->cachedformatoptions[$field] = $data->{$field};
3072 } else if (array_key_exists('cachedefault', $option)) {
3073 $this->cachedformatoptions[$field] = $option['cachedefault'];
3080 * Magic method to check if the property is set
3082 * @param string $name name of the property
3083 * @return bool
3085 public function __isset($name) {
3086 if (method_exists($this, 'get_'.$name) ||
3087 property_exists($this, '_'.$name) ||
3088 array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
3089 $value = $this->__get($name);
3090 return isset($value);
3092 return false;
3096 * Magic method to check if the property is empty
3098 * @param string $name name of the property
3099 * @return bool
3101 public function __empty($name) {
3102 if (method_exists($this, 'get_'.$name) ||
3103 property_exists($this, '_'.$name) ||
3104 array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
3105 $value = $this->__get($name);
3106 return empty($value);
3108 return true;
3112 * Magic method to retrieve the property, this is either basic section property
3113 * or availability information or additional properties added by course format
3115 * @param string $name name of the property
3116 * @return bool
3118 public function __get($name) {
3119 if (method_exists($this, 'get_'.$name)) {
3120 return $this->{'get_'.$name}();
3122 if (property_exists($this, '_'.$name)) {
3123 return $this->{'_'.$name};
3125 if (array_key_exists($name, $this->cachedformatoptions)) {
3126 return $this->cachedformatoptions[$name];
3128 // precheck if the option is defined in format to avoid unnecessary DB queries in get_format_options()
3129 if (array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
3130 $formatoptions = course_get_format($this->modinfo->get_course())->get_format_options($this);
3131 return $formatoptions[$name];
3133 debugging('Invalid section_info property accessed! '.$name);
3134 return null;
3138 * Finds whether this section is available at the moment for the current user.
3140 * The value can be accessed publicly as $sectioninfo->available, but can be called directly if there
3141 * is a case when it might be called recursively (you can't call property values recursively).
3143 * @return bool
3145 public function get_available() {
3146 global $CFG;
3147 $userid = $this->modinfo->get_user_id();
3148 if ($this->_available !== null || $userid == -1) {
3149 // Has already been calculated or does not need calculation.
3150 return $this->_available;
3152 $this->_available = true;
3153 $this->_availableinfo = '';
3154 if (!empty($CFG->enableavailability)) {
3155 // Get availability information.
3156 $ci = new \core_availability\info_section($this);
3157 $this->_available = $ci->is_available($this->_availableinfo, true,
3158 $userid, $this->modinfo);
3160 // Execute the hook from the course format that may override the available/availableinfo properties.
3161 $currentavailable = $this->_available;
3162 course_get_format($this->modinfo->get_course())->
3163 section_get_available_hook($this, $this->_available, $this->_availableinfo);
3164 if (!$currentavailable && $this->_available) {
3165 debugging('section_get_available_hook() can not make unavailable section available', DEBUG_DEVELOPER);
3166 $this->_available = $currentavailable;
3168 return $this->_available;
3172 * Returns the availability text shown next to the section on course page.
3174 * @return string
3176 private function get_availableinfo() {
3177 // Calling get_available() will also fill the availableinfo property
3178 // (or leave it null if there is no userid).
3179 $this->get_available();
3180 return $this->_availableinfo;
3184 * Implementation of IteratorAggregate::getIterator(), allows to cycle through properties
3185 * and use {@link convert_to_array()}
3187 * @return ArrayIterator
3189 public function getIterator(): Traversable {
3190 $ret = array();
3191 foreach (get_object_vars($this) as $key => $value) {
3192 if (substr($key, 0, 1) == '_') {
3193 if (method_exists($this, 'get'.$key)) {
3194 $ret[substr($key, 1)] = $this->{'get'.$key}();
3195 } else {
3196 $ret[substr($key, 1)] = $this->$key;
3200 $ret['sequence'] = $this->get_sequence();
3201 $ret['course'] = $this->get_course();
3202 $ret = array_merge($ret, course_get_format($this->modinfo->get_course())->get_format_options($this->_section));
3203 return new ArrayIterator($ret);
3207 * Works out whether activity is visible *for current user* - if this is false, they
3208 * aren't allowed to access it.
3210 * @return bool
3212 private function get_uservisible() {
3213 $userid = $this->modinfo->get_user_id();
3214 if ($this->_uservisible !== null || $userid == -1) {
3215 // Has already been calculated or does not need calculation.
3216 return $this->_uservisible;
3218 $this->_uservisible = true;
3219 if (!$this->_visible || !$this->get_available()) {
3220 $coursecontext = context_course::instance($this->get_course());
3221 if (!$this->_visible && !has_capability('moodle/course:viewhiddensections', $coursecontext, $userid) ||
3222 (!$this->get_available() &&
3223 !has_capability('moodle/course:ignoreavailabilityrestrictions', $coursecontext, $userid))) {
3225 $this->_uservisible = false;
3228 return $this->_uservisible;
3232 * Restores the course_sections.sequence value
3234 * @return string
3236 private function get_sequence() {
3237 if (!empty($this->modinfo->sections[$this->_section])) {
3238 return implode(',', $this->modinfo->sections[$this->_section]);
3239 } else {
3240 return '';
3245 * Returns course ID - from course_sections table
3247 * @return int
3249 private function get_course() {
3250 return $this->modinfo->get_course_id();
3254 * Modinfo object
3256 * @return course_modinfo
3258 private function get_modinfo() {
3259 return $this->modinfo;
3263 * Prepares section data for inclusion in sectioncache cache, removing items
3264 * that are set to defaults, and adding availability data if required.
3266 * Called by build_section_cache in course_modinfo only; do not use otherwise.
3267 * @param object $section Raw section data object
3269 public static function convert_for_section_cache($section) {
3270 global $CFG;
3272 // Course id stored in course table
3273 unset($section->course);
3274 // Section number stored in array key
3275 unset($section->section);
3276 // Sequence stored implicity in modinfo $sections array
3277 unset($section->sequence);
3279 // Remove default data
3280 foreach (self::$sectioncachedefaults as $field => $value) {
3281 // Exact compare as strings to avoid problems if some strings are set
3282 // to "0" etc.
3283 if (isset($section->{$field}) && $section->{$field} === $value) {
3284 unset($section->{$field});