2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
18 * modinfolib.php - Functions/classes relating to cached information about module instances on
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
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);
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
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;
64 * List of fields from DB table 'course' that are cached in MUC and are always present in course_modinfo::$course
67 public static $cachedfields = array('shortname', 'fullname', 'format',
68 'enablecompletion', 'groupmode', 'groupmodeforce', 'cacherev');
71 * For convenience we store the course object here as it is needed in other parts of code
77 * Array of section data from cache
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
96 * Array from section id => section num.
102 * Array from int (cm id) => cm_info object
108 * Array from string (modname) => int (instance id) => cm_info object
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'.
123 * List of class read-only properties and their getter methods.
124 * Used by magic functions __get(), __isset(), __empty()
127 private static $standardproperties = array(
128 'courseid' => 'get_course_id',
129 'userid' => 'get_user_id',
130 'sections' => 'get_sections',
132 'instances' => 'get_instances',
133 'groups' => 'get_groups_all',
137 * Magic method getter
139 * @param string $name
142 public function __get($name) {
143 if (isset(self
::$standardproperties[$name])) {
144 $method = self
::$standardproperties[$name];
145 return $this->$method();
147 debugging('Invalid course_modinfo property accessed: '.$name);
153 * Magic method for function isset()
155 * @param string $name
158 public function __isset($name) {
159 if (isset(self
::$standardproperties[$name])) {
160 $value = $this->__get($name);
161 return isset($value);
167 * Magic method for function empty()
169 * @param string $name
172 public function __empty($name) {
173 if (isset(self
::$standardproperties[$name])) {
174 $value = $this->__get($name);
175 return empty($value);
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
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() {
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
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])) {
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])) {
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');
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');
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
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();
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) {
415 if (is_object($courseorid)) {
416 $course = $courseorid;
418 $course = (object)array('id' => $courseorid);
420 if (empty($userid)) {
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
];
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);
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);
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
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
]) {
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,
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 {
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);
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) {
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 if (!$cachecoursemodinfo->acquire_lock($cachekey)) {
644 throw new moodle_exception('ex_unabletolock', 'cache', '', null,
645 'Unable to lock modinfo cache for course ' . $cachekey);
648 // Only actually do the build if it's still needed after getting the lock (not if
649 // somebody else, who might have been holding the lock, built it already).
650 $coursemodinfo = $cachecoursemodinfo->get_versioned($course->id
, $course->cacherev
);
651 if ($coursemodinfo === false ||
($course->cacherev
> $coursemodinfo->cacherev
)) {
652 $coursemodinfo = self
::inner_build_course_cache($course);
655 $cachecoursemodinfo->release_lock($cachekey);
657 return $coursemodinfo;
661 * Called to build course cache when there is already a lock obtained.
663 * @param stdClass $course object from DB table course
664 * @param bool $partialrebuild Indicate if it's partial course cache rebuild or not
665 * @return stdClass Course object that has been stored in MUC
667 protected static function inner_build_course_cache(\stdClass
$course, bool $partialrebuild = false): \stdClass
{
669 require_once("{$CFG->dirroot}/course/lib.php");
671 $cachekey = $course->id
;
672 $cachecoursemodinfo = cache
::make('core', 'coursemodinfo');
673 if (!$cachecoursemodinfo->check_lock_state($cachekey)) {
674 throw new coding_exception('You must acquire a lock on the course ID before calling inner_build_course_cache');
677 // Always reload the course object from database to ensure we have the latest possible
678 // value for cacherev.
679 $course = $DB->get_record('course', ['id' => $course->id
],
680 implode(',', array_merge(['id'], self
::$cachedfields)), MUST_EXIST
);
681 // Retrieve all information about activities and sections.
682 $coursemodinfo = new stdClass();
683 $coursemodinfo->modinfo
= self
::get_array_of_activities($course, $partialrebuild);
684 $coursemodinfo->sectioncache
= self
::build_course_section_cache($course, $partialrebuild);
685 foreach (self
::$cachedfields as $key) {
686 $coursemodinfo->$key = $course->$key;
688 // Set the accumulated activities and sections information in cache, together with cacherev.
689 $cachecoursemodinfo->set_versioned($cachekey, $course->cacherev
, $coursemodinfo);
690 return $coursemodinfo;
694 * Purge the cache of a course section by its id.
696 * @param int $courseid The course to purge cache in
697 * @param int $sectionid The section _id_ to purge
699 public static function purge_course_section_cache_by_id(int $courseid, int $sectionid): void
{
700 $course = get_course($courseid);
701 $cache = cache
::make('core', 'coursemodinfo');
702 $cachekey = $course->id
;
703 $cache->acquire_lock($cachekey);
704 $coursemodinfo = $cache->get_versioned($cachekey, $course->cacherev
);
705 if ($coursemodinfo !== false) {
706 foreach ($coursemodinfo->sectioncache
as $sectionno => $sectioncache) {
707 if ($sectioncache->id
== $sectionid) {
708 $coursemodinfo->cacherev
= -1;
709 unset($coursemodinfo->sectioncache
[$sectionno]);
710 $cache->set_versioned($cachekey, $course->cacherev
, $coursemodinfo);
715 $cache->release_lock($cachekey);
719 * Purge the cache of a course section by its number.
721 * @param int $courseid The course to purge cache in
722 * @param int $sectionno The section number to purge
724 public static function purge_course_section_cache_by_number(int $courseid, int $sectionno): void
{
725 $course = get_course($courseid);
726 $cache = cache
::make('core', 'coursemodinfo');
727 $cachekey = $course->id
;
728 $cache->acquire_lock($cachekey);
729 $coursemodinfo = $cache->get_versioned($cachekey, $course->cacherev
);
730 if ($coursemodinfo !== false && array_key_exists($sectionno, $coursemodinfo->sectioncache
)) {
731 $coursemodinfo->cacherev
= -1;
732 unset($coursemodinfo->sectioncache
[$sectionno]);
733 $cache->set_versioned($cachekey, $course->cacherev
, $coursemodinfo);
735 $cache->release_lock($cachekey);
739 * Purge the cache of a course module.
741 * @param int $courseid Course id
742 * @param int $cmid Course module id
744 public static function purge_course_module_cache(int $courseid, int $cmid): void
{
745 $course = get_course($courseid);
746 $cache = cache
::make('core', 'coursemodinfo');
747 $cachekey = $course->id
;
748 $cache->acquire_lock($cachekey);
749 $coursemodinfo = $cache->get_versioned($cachekey, $course->cacherev
);
750 $hascache = ($coursemodinfo !== false) && array_key_exists($cmid, $coursemodinfo->modinfo
);
752 $coursemodinfo->cacherev
= -1;
753 unset($coursemodinfo->modinfo
[$cmid]);
754 $cache->set_versioned($cachekey, $course->cacherev
, $coursemodinfo);
755 $coursemodinfo = $cache->get_versioned($cachekey, $course->cacherev
);
757 $cache->release_lock($cachekey);
761 * For a given course, returns an array of course activity objects
763 * @param stdClass $course Course object
764 * @param bool $usecache get activities from cache if modinfo exists when $usecache is true
765 * @return array list of activities
767 public static function get_array_of_activities(stdClass
$course, bool $usecache = false): array {
770 if (empty($course)) {
771 throw new moodle_exception('courseidnotfound');
774 $rawmods = get_course_mods($course->id
);
775 if (empty($rawmods)) {
781 // Get existing cache.
782 $cachecoursemodinfo = cache
::make('core', 'coursemodinfo');
783 $coursemodinfo = $cachecoursemodinfo->get_versioned($course->id
, $course->cacherev
);
784 if ($coursemodinfo !== false) {
785 $mods = $coursemodinfo->modinfo
;
789 $courseformat = course_get_format($course);
791 if ($sections = $DB->get_records('course_sections', ['course' => $course->id
],
792 'section ASC', 'id,section,sequence,visible')) {
793 // First check and correct obvious mismatches between course_sections.sequence and course_modules.section.
794 if ($errormessages = course_integrity_check($course->id
, $rawmods, $sections)) {
795 debugging(join('<br>', $errormessages));
796 $rawmods = get_course_mods($course->id
);
797 $sections = $DB->get_records('course_sections', ['course' => $course->id
],
798 'section ASC', 'id,section,sequence,visible');
800 // Build array of activities.
801 foreach ($sections as $section) {
802 if (!empty($section->sequence
)) {
803 $cmids = explode(",", $section->sequence
);
804 $numberofmods = count($cmids);
805 foreach ($cmids as $cmid) {
806 // Activity does not exist in the database.
807 $notexistindb = empty($rawmods[$cmid]);
808 $activitycached = isset($mods[$cmid]);
809 if ($activitycached ||
$notexistindb) {
813 // Adjust visibleoncoursepage, value in DB may not respect format availability.
814 $rawmods[$cmid]->visibleoncoursepage
= (!$rawmods[$cmid]->visible
815 ||
$rawmods[$cmid]->visibleoncoursepage
816 ||
empty($CFG->allowstealth
)
817 ||
!$courseformat->allow_stealth_module_visibility($rawmods[$cmid], $section)) ?
1 : 0;
819 $mods[$cmid] = new stdClass();
820 $mods[$cmid]->id
= $rawmods[$cmid]->instance
;
821 $mods[$cmid]->cm
= $rawmods[$cmid]->id
;
822 $mods[$cmid]->mod
= $rawmods[$cmid]->modname
;
824 // Oh dear. Inconsistent names left here for backward compatibility.
825 $mods[$cmid]->section
= $section->section
;
826 $mods[$cmid]->sectionid
= $rawmods[$cmid]->section
;
828 $mods[$cmid]->module
= $rawmods[$cmid]->module
;
829 $mods[$cmid]->added
= $rawmods[$cmid]->added
;
830 $mods[$cmid]->score
= $rawmods[$cmid]->score
;
831 $mods[$cmid]->idnumber
= $rawmods[$cmid]->idnumber
;
832 $mods[$cmid]->visible
= $rawmods[$cmid]->visible
;
833 $mods[$cmid]->visibleoncoursepage
= $rawmods[$cmid]->visibleoncoursepage
;
834 $mods[$cmid]->visibleold
= $rawmods[$cmid]->visibleold
;
835 $mods[$cmid]->groupmode
= $rawmods[$cmid]->groupmode
;
836 $mods[$cmid]->groupingid
= $rawmods[$cmid]->groupingid
;
837 $mods[$cmid]->indent
= $rawmods[$cmid]->indent
;
838 $mods[$cmid]->completion
= $rawmods[$cmid]->completion
;
839 $mods[$cmid]->extra
= "";
840 $mods[$cmid]->completiongradeitemnumber
=
841 $rawmods[$cmid]->completiongradeitemnumber
;
842 $mods[$cmid]->completionpassgrade
= $rawmods[$cmid]->completionpassgrade
;
843 $mods[$cmid]->completionview
= $rawmods[$cmid]->completionview
;
844 $mods[$cmid]->completionexpected
= $rawmods[$cmid]->completionexpected
;
845 $mods[$cmid]->showdescription
= $rawmods[$cmid]->showdescription
;
846 $mods[$cmid]->availability
= $rawmods[$cmid]->availability
;
847 $mods[$cmid]->deletioninprogress
= $rawmods[$cmid]->deletioninprogress
;
848 $mods[$cmid]->downloadcontent
= $rawmods[$cmid]->downloadcontent
;
849 $mods[$cmid]->lang
= $rawmods[$cmid]->lang
;
851 $modname = $mods[$cmid]->mod
;
852 $functionname = $modname . "_get_coursemodule_info";
854 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
858 include_once("$CFG->dirroot/mod/$modname/lib.php");
860 if ($hasfunction = function_exists($functionname)) {
861 if ($info = $functionname($rawmods[$cmid])) {
862 if (!empty($info->icon
)) {
863 $mods[$cmid]->icon
= $info->icon
;
865 if (!empty($info->iconcomponent
)) {
866 $mods[$cmid]->iconcomponent
= $info->iconcomponent
;
868 if (!empty($info->name
)) {
869 $mods[$cmid]->name
= $info->name
;
871 if ($info instanceof cached_cm_info
) {
872 // When using cached_cm_info you can include three new fields.
873 // That aren't available for legacy code.
874 if (!empty($info->content
)) {
875 $mods[$cmid]->content
= $info->content
;
877 if (!empty($info->extraclasses
)) {
878 $mods[$cmid]->extraclasses
= $info->extraclasses
;
880 if (!empty($info->iconurl
)) {
881 // Convert URL to string as it's easier to store.
882 // Also serialized object contains \0 byte,
883 // ... and can not be written to Postgres DB.
884 $url = new moodle_url($info->iconurl
);
885 $mods[$cmid]->iconurl
= $url->out(false);
887 if (!empty($info->onclick
)) {
888 $mods[$cmid]->onclick
= $info->onclick
;
890 if (!empty($info->customdata
)) {
891 $mods[$cmid]->customdata
= $info->customdata
;
894 // When using a stdclass, the (horrible) deprecated ->extra field,
895 // ... that is available for BC.
896 if (!empty($info->extra
)) {
897 $mods[$cmid]->extra
= $info->extra
;
902 // When there is no modname_get_coursemodule_info function,
903 // ... but showdescriptions is enabled, then we use the 'intro',
904 // ... and 'introformat' fields in the module table.
905 if (!$hasfunction && $rawmods[$cmid]->showdescription
) {
906 if ($modvalues = $DB->get_record($rawmods[$cmid]->modname
,
907 ['id' => $rawmods[$cmid]->instance
], 'name, intro, introformat')) {
908 // Set content from intro and introformat. Filters are disabled.
909 // Because we filter it with format_text at display time.
910 $mods[$cmid]->content
= format_module_intro($rawmods[$cmid]->modname
,
911 $modvalues, $rawmods[$cmid]->id
, false);
913 // To save making another query just below, put name in here.
914 $mods[$cmid]->name
= $modvalues->name
;
917 if (!isset($mods[$cmid]->name
)) {
918 $mods[$cmid]->name
= $DB->get_field($rawmods[$cmid]->modname
, "name",
919 ["id" => $rawmods[$cmid]->instance
]);
922 // Minimise the database size by unsetting default options when they are 'empty'.
923 // This list corresponds to code in the cm_info constructor.
924 foreach (['idnumber', 'groupmode', 'groupingid',
925 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
926 'icon', 'iconcomponent', 'customdata', 'availability', 'completionview',
927 'completionexpected', 'score', 'showdescription', 'deletioninprogress'] as $property) {
928 if (property_exists($mods[$cmid], $property) &&
929 empty($mods[$cmid]->{$property})) {
930 unset($mods[$cmid]->{$property});
933 // Special case: this value is usually set to null, but may be 0.
934 if (property_exists($mods[$cmid], 'completiongradeitemnumber') &&
935 is_null($mods[$cmid]->completiongradeitemnumber
)) {
936 unset($mods[$cmid]->completiongradeitemnumber
);
946 * Purge the cache of a given course
948 * @param int $courseid Course id
950 public static function purge_course_cache(int $courseid): void
{
951 increment_revision_number('course', 'cacherev', 'id = :id', array('id' => $courseid));
952 $cachemodinfo = cache
::make('core', 'coursemodinfo');
953 $cachemodinfo->delete($courseid);
959 * Data about a single module on a course. This contains most of the fields in the course_modules
960 * table, plus additional data when required.
962 * The object can be accessed by core or any plugin (i.e. course format, block, filter, etc.) as
963 * get_fast_modinfo($courseorid)->cms[$coursemoduleid]
965 * get_fast_modinfo($courseorid)->instances[$moduletype][$instanceid]
967 * There are three stages when activity module can add/modify data in this object:
969 * <b>Stage 1 - during building the cache.</b>
970 * Allows to add to the course cache static user-independent information about the module.
971 * Modules should try to include only absolutely necessary information that may be required
972 * when displaying course view page. The information is stored in application-level cache
973 * and reset when {@link rebuild_course_cache()} is called or cache is purged by admin.
975 * Modules can implement callback XXX_get_coursemodule_info() returning instance of object
976 * {@link cached_cm_info}
978 * <b>Stage 2 - dynamic data.</b>
979 * Dynamic data is user-dependent, it is stored in request-level cache. To reset this cache
980 * {@link get_fast_modinfo()} with $reset argument may be called.
982 * Dynamic data is obtained when any of the following properties/methods is requested:
983 * - {@link cm_info::$url}
984 * - {@link cm_info::$name}
985 * - {@link cm_info::$onclick}
986 * - {@link cm_info::get_icon_url()}
987 * - {@link cm_info::$uservisible}
988 * - {@link cm_info::$available}
989 * - {@link cm_info::$availableinfo}
990 * - plus any of the properties listed in Stage 3.
992 * Modules can implement callback <b>XXX_cm_info_dynamic()</b> and inside this callback they
993 * are allowed to use any of the following set methods:
994 * - {@link cm_info::set_available()}
995 * - {@link cm_info::set_name()}
996 * - {@link cm_info::set_no_view_link()}
997 * - {@link cm_info::set_user_visible()}
998 * - {@link cm_info::set_on_click()}
999 * - {@link cm_info::set_icon_url()}
1000 * - {@link cm_info::override_customdata()}
1001 * Any methods affecting view elements can also be set in this callback.
1003 * <b>Stage 3 (view data).</b>
1004 * Also user-dependend data stored in request-level cache. Second stage is created
1005 * because populating the view data can be expensive as it may access much more
1006 * Moodle APIs such as filters, user information, output renderers and we
1007 * don't want to request it until necessary.
1008 * View data is obtained when any of the following properties/methods is requested:
1009 * - {@link cm_info::$afterediticons}
1010 * - {@link cm_info::$content}
1011 * - {@link cm_info::get_formatted_content()}
1012 * - {@link cm_info::$extraclasses}
1013 * - {@link cm_info::$afterlink}
1015 * Modules can implement callback <b>XXX_cm_info_view()</b> and inside this callback they
1016 * are allowed to use any of the following set methods:
1017 * - {@link cm_info::set_after_edit_icons()}
1018 * - {@link cm_info::set_after_link()}
1019 * - {@link cm_info::set_content()}
1020 * - {@link cm_info::set_extra_classes()}
1022 * @property-read int $id Course-module ID - from course_modules table
1023 * @property-read int $instance Module instance (ID within module table) - from course_modules table
1024 * @property-read int $course Course ID - from course_modules table
1025 * @property-read string $idnumber 'ID number' from course-modules table (arbitrary text set by user) - from
1026 * course_modules table
1027 * @property-read int $added Time that this course-module was added (unix time) - from course_modules table
1028 * @property-read int $visible Visible setting (0 or 1; if this is 0, students cannot see/access the activity) - from
1029 * course_modules table
1030 * @property-read int $visibleoncoursepage Visible on course page setting - from course_modules table, adjusted to
1031 * whether course format allows this module to have the "stealth" mode
1032 * @property-read int $visibleold Old visible setting (if the entire section is hidden, the previous value for
1033 * visible is stored in this field) - from course_modules table
1034 * @property-read int $groupmode Group mode (one of the constants NOGROUPS, SEPARATEGROUPS, or VISIBLEGROUPS) - from
1035 * course_modules table. Use {@link cm_info::$effectivegroupmode} to find the actual group mode that may be forced by course.
1036 * @property-read int $groupingid Grouping ID (0 = all groupings)
1037 * @property-read bool $coursegroupmodeforce Indicates whether the course containing the module has forced the groupmode
1038 * This means that cm_info::$groupmode should be ignored and cm_info::$coursegroupmode be used instead
1039 * @property-read int $coursegroupmode Group mode (one of the constants NOGROUPS, SEPARATEGROUPS, or VISIBLEGROUPS) - from
1040 * course table - as specified for the course containing the module
1041 * Effective only if {@link cm_info::$coursegroupmodeforce} is set
1042 * @property-read int $effectivegroupmode Effective group mode for this module (one of the constants NOGROUPS, SEPARATEGROUPS,
1043 * or VISIBLEGROUPS). This can be different from groupmode set for the module if the groupmode is forced for the course.
1044 * This value will always be NOGROUPS if module type does not support group mode.
1045 * @property-read int $indent Indent level on course page (0 = no indent) - from course_modules table
1046 * @property-read int $completion Activity completion setting for this activity, COMPLETION_TRACKING_xx constant - from
1047 * course_modules table
1048 * @property-read mixed $completiongradeitemnumber Set to the item number (usually 0) if completion depends on a particular
1049 * grade of this activity, or null if completion does not depend on a grade - from course_modules table
1050 * @property-read int $completionview 1 if 'on view' completion is enabled, 0 otherwise - from course_modules table
1051 * @property-read int $completionexpected Set to a unix time if completion of this activity is expected at a
1052 * particular time, 0 if no time set - from course_modules table
1053 * @property-read string $availability Availability information as JSON string or null if none -
1054 * from course_modules table
1055 * @property-read int $showdescription Controls whether the description of the activity displays on the course main page (in
1056 * addition to anywhere it might display within the activity itself). 0 = do not show
1057 * on main page, 1 = show on main page.
1058 * @property-read string $extra (deprecated) Extra HTML that is put in an unhelpful part of the HTML when displaying this module in
1059 * course page - from cached data in modinfo field. Deprecated, replaced by ->extraclasses and ->onclick
1060 * @property-read string $icon Name of icon to use - from cached data in modinfo field
1061 * @property-read string $iconcomponent Component that contains icon - from cached data in modinfo field
1062 * @property-read string $modname Name of module e.g. 'forum' (this is the same name as the module's main database
1063 * table) - from cached data in modinfo field
1064 * @property-read int $module ID of module type - from course_modules table
1065 * @property-read string $name Name of module instance for display on page e.g. 'General discussion forum' - from cached
1066 * data in modinfo field
1067 * @property-read int $sectionnum Section number that this course-module is in (section 0 = above the calendar, section 1
1068 * = week/topic 1, etc) - from cached data in modinfo field
1069 * @property-read int $section Section id - from course_modules table
1070 * @property-read array $conditionscompletion Availability conditions for this course-module based on the completion of other
1071 * course-modules (array from other course-module id to required completion state for that
1072 * module) - from cached data in modinfo field
1073 * @property-read array $conditionsgrade Availability conditions for this course-module based on course grades (array from
1074 * grade item id to object with ->min, ->max fields) - from cached data in modinfo field
1075 * @property-read array $conditionsfield Availability conditions for this course-module based on user fields
1076 * @property-read bool $available True if this course-module is available to students i.e. if all availability conditions
1077 * are met - obtained dynamically
1078 * @property-read string $availableinfo If course-module is not available to students, this string gives information about
1079 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
1080 * January 2010') for display on main page - obtained dynamically
1081 * @property-read bool $uservisible True if this course-module is available to the CURRENT user (for example, if current user
1082 * has viewhiddenactivities capability, they can access the course-module even if it is not
1083 * visible or not available, so this would be true in that case)
1084 * @property-read context_module $context Module context
1085 * @property-read string $modfullname Returns a localised human-readable name of the module type - calculated on request
1086 * @property-read string $modplural Returns a localised human-readable name of the module type in plural form - calculated on request
1087 * @property-read string $content Content to display on main (view) page - calculated on request
1088 * @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
1089 * @property-read string $extraclasses Extra CSS classes to add to html output for this activity on main page - calculated on request
1090 * @property-read string $onclick Content of HTML on-click attribute already escaped - calculated on request
1091 * @property-read mixed $customdata Optional custom data stored in modinfo cache for this activity, or null if none
1092 * @property-read string $afterlink Extra HTML code to display after link - calculated on request
1093 * @property-read string $afterediticons Extra HTML code to display after editing icons (e.g. more icons) - calculated on request
1094 * @property-read bool $deletioninprogress True if this course module is scheduled for deletion, false otherwise.
1095 * @property-read bool $downloadcontent True if content download is enabled for this course module, false otherwise.
1096 * @property-read bool $lang the forced language for this activity (language pack name). Null means not forced.
1098 class cm_info
implements IteratorAggregate
{
1100 * State: Only basic data from modinfo cache is available.
1102 const STATE_BASIC
= 0;
1105 * State: In the process of building dynamic data (to avoid recursive calls to obtain_dynamic_data())
1107 const STATE_BUILDING_DYNAMIC
= 1;
1110 * State: Dynamic data is available too.
1112 const STATE_DYNAMIC
= 2;
1115 * State: In the process of building view data (to avoid recursive calls to obtain_view_data())
1117 const STATE_BUILDING_VIEW
= 3;
1120 * State: View data (for course page) is available.
1122 const STATE_VIEW
= 4;
1126 * @var course_modinfo
1131 * Level of information stored inside this object (STATE_xx constant)
1137 * Course-module ID - from course_modules table
1143 * Module instance (ID within module table) - from course_modules table
1149 * 'ID number' from course-modules table (arbitrary text set by user) - from
1150 * course_modules table
1156 * Time that this course-module was added (unix time) - from course_modules table
1162 * This variable is not used and is included here only so it can be documented.
1163 * Once the database entry is removed from course_modules, it should be deleted
1166 * @deprecated Do not use this variable
1171 * Visible setting (0 or 1; if this is 0, students cannot see/access the activity) - from
1172 * course_modules table
1178 * Visible on course page setting - from course_modules table
1181 private $visibleoncoursepage;
1184 * Old visible setting (if the entire section is hidden, the previous value for
1185 * visible is stored in this field) - from course_modules table
1188 private $visibleold;
1191 * Group mode (one of the constants NONE, SEPARATEGROUPS, or VISIBLEGROUPS) - from
1192 * course_modules table
1198 * Grouping ID (0 = all groupings)
1201 private $groupingid;
1204 * Indent level on course page (0 = no indent) - from course_modules table
1210 * Activity completion setting for this activity, COMPLETION_TRACKING_xx constant - from
1211 * course_modules table
1214 private $completion;
1217 * Set to the item number (usually 0) if completion depends on a particular
1218 * grade of this activity, or null if completion does not depend on a grade - from
1219 * course_modules table
1222 private $completiongradeitemnumber;
1225 * 1 if pass grade completion is enabled, 0 otherwise - from course_modules table
1228 private $completionpassgrade;
1231 * 1 if 'on view' completion is enabled, 0 otherwise - from course_modules table
1234 private $completionview;
1237 * Set to a unix time if completion of this activity is expected at a
1238 * particular time, 0 if no time set - from course_modules table
1241 private $completionexpected;
1244 * Availability information as JSON string or null if none - from course_modules table
1247 private $availability;
1250 * Controls whether the description of the activity displays on the course main page (in
1251 * addition to anywhere it might display within the activity itself). 0 = do not show
1252 * on main page, 1 = show on main page.
1255 private $showdescription;
1258 * Extra HTML that is put in an unhelpful part of the HTML when displaying this module in
1259 * course page - from cached data in modinfo field
1260 * @deprecated This is crazy, don't use it. Replaced by ->extraclasses and ->onclick
1266 * Name of icon to use - from cached data in modinfo field
1272 * Component that contains icon - from cached data in modinfo field
1275 private $iconcomponent;
1278 * Name of module e.g. 'forum' (this is the same name as the module's main database
1279 * table) - from cached data in modinfo field
1285 * ID of module - from course_modules table
1291 * Name of module instance for display on page e.g. 'General discussion forum' - from cached
1292 * data in modinfo field
1298 * Section number that this course-module is in (section 0 = above the calendar, section 1
1299 * = week/topic 1, etc) - from cached data in modinfo field
1302 private $sectionnum;
1305 * Section id - from course_modules table
1311 * Availability conditions for this course-module based on the completion of other
1312 * course-modules (array from other course-module id to required completion state for that
1313 * module) - from cached data in modinfo field
1316 private $conditionscompletion;
1319 * Availability conditions for this course-module based on course grades (array from
1320 * grade item id to object with ->min, ->max fields) - from cached data in modinfo field
1323 private $conditionsgrade;
1326 * Availability conditions for this course-module based on user fields
1329 private $conditionsfield;
1332 * True if this course-module is available to students i.e. if all availability conditions
1333 * are met - obtained dynamically
1339 * If course-module is not available to students, this string gives information about
1340 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
1341 * January 2010') for display on main page - obtained dynamically
1344 private $availableinfo;
1347 * True if this course-module is available to the CURRENT user (for example, if current user
1348 * has viewhiddenactivities capability, they can access the course-module even if it is not
1349 * visible or not available, so this would be true in that case)
1352 private $uservisible;
1355 * True if this course-module is visible to the CURRENT user on the course page
1358 private $uservisibleoncoursepage;
1373 private $contentisformatted;
1376 * @var bool True if the content has a special course item display like labels.
1378 private $customcmlistitem;
1383 private $extraclasses;
1386 * @var moodle_url full external url pointing to icon image for activity
1398 private $customdata;
1408 private $afterediticons;
1411 * @var bool representing the deletion state of the module. True if the mod is scheduled for deletion.
1413 private $deletioninprogress;
1416 * @var int enable/disable download content for this course module
1418 private $downloadcontent;
1421 * @var string|null the forced language for this activity (language pack name). Null means not forced.
1426 * List of class read-only properties and their getter methods.
1427 * Used by magic functions __get(), __isset(), __empty()
1430 private static $standardproperties = [
1432 'content' => 'get_content',
1433 'extraclasses' => 'get_extra_classes',
1434 'onclick' => 'get_on_click',
1435 'customdata' => 'get_custom_data',
1436 'afterlink' => 'get_after_link',
1437 'afterediticons' => 'get_after_edit_icons',
1438 'modfullname' => 'get_module_type_name',
1439 'modplural' => 'get_module_type_name_plural',
1442 'availability' => false,
1443 'available' => 'get_available',
1444 'availableinfo' => 'get_available_info',
1445 'completion' => false,
1446 'completionexpected' => false,
1447 'completiongradeitemnumber' => false,
1448 'completionpassgrade' => false,
1449 'completionview' => false,
1450 'conditionscompletion' => false,
1451 'conditionsfield' => false,
1452 'conditionsgrade' => false,
1453 'context' => 'get_context',
1454 'course' => 'get_course_id',
1455 'coursegroupmode' => 'get_course_groupmode',
1456 'coursegroupmodeforce' => 'get_course_groupmodeforce',
1457 'customcmlistitem' => 'has_custom_cmlist_item',
1458 'effectivegroupmode' => 'get_effective_groupmode',
1460 'groupingid' => false,
1461 'groupmembersonly' => 'get_deprecated_group_members_only',
1462 'groupmode' => false,
1464 'iconcomponent' => false,
1465 'idnumber' => false,
1467 'instance' => false,
1470 'name' => 'get_name',
1473 'sectionnum' => false,
1474 'showdescription' => false,
1475 'uservisible' => 'get_user_visible',
1477 'visibleoncoursepage' => false,
1478 'visibleold' => false,
1479 'deletioninprogress' => false,
1480 'downloadcontent' => false,
1485 * List of methods with no arguments that were public prior to Moodle 2.6.
1487 * They can still be accessed publicly via magic __call() function with no warnings
1488 * but are not listed in the class methods list.
1489 * For the consistency of the code it is better to use corresponding properties.
1491 * These methods be deprecated completely in later versions.
1493 * @var array $standardmethods
1495 private static $standardmethods = array(
1496 // Following methods are not recommended to use because there have associated read-only properties.
1499 'get_extra_classes',
1503 'get_after_edit_icons',
1504 // Method obtain_dynamic_data() should not be called from outside of this class but it was public before Moodle 2.6.
1505 'obtain_dynamic_data',
1509 * Magic method to call functions that are now declared as private but were public in Moodle before 2.6.
1510 * These private methods can not be used anymore.
1512 * @param string $name
1513 * @param array $arguments
1515 * @throws coding_exception
1517 public function __call($name, $arguments) {
1518 if (in_array($name, self
::$standardmethods)) {
1519 $message = "cm_info::$name() can not be used anymore.";
1520 if ($alternative = array_search($name, self
::$standardproperties)) {
1521 $message .= " Please use the property cm_info->$alternative instead.";
1523 throw new coding_exception($message);
1525 throw new coding_exception("Method cm_info::{$name}() does not exist");
1529 * Magic method getter
1531 * @param string $name
1534 public function __get($name) {
1535 if (isset(self
::$standardproperties[$name])) {
1536 if ($method = self
::$standardproperties[$name]) {
1537 return $this->$method();
1539 return $this->$name;
1542 debugging('Invalid cm_info property accessed: '.$name);
1548 * Implementation of IteratorAggregate::getIterator(), allows to cycle through properties
1549 * and use {@link convert_to_array()}
1551 * @return ArrayIterator
1553 public function getIterator(): Traversable
{
1554 // Make sure dynamic properties are retrieved prior to view properties.
1555 $this->obtain_dynamic_data();
1558 // Do not iterate over deprecated properties.
1559 $props = self
::$standardproperties;
1560 unset($props['groupmembersonly']);
1562 foreach ($props as $key => $unused) {
1563 $ret[$key] = $this->__get($key);
1565 return new ArrayIterator($ret);
1569 * Magic method for function isset()
1571 * @param string $name
1574 public function __isset($name) {
1575 if (isset(self
::$standardproperties[$name])) {
1576 $value = $this->__get($name);
1577 return isset($value);
1583 * Magic method for function empty()
1585 * @param string $name
1588 public function __empty($name) {
1589 if (isset(self
::$standardproperties[$name])) {
1590 $value = $this->__get($name);
1591 return empty($value);
1597 * Magic method setter
1599 * Will display the developer warning when trying to set/overwrite property.
1601 * @param string $name
1602 * @param mixed $value
1604 public function __set($name, $value) {
1605 debugging("It is not allowed to set the property cm_info::\${$name}", DEBUG_DEVELOPER
);
1609 * @return bool True if this module has a 'view' page that should be linked to in navigation
1610 * etc (note: modules may still have a view.php file, but return false if this is not
1611 * intended to be linked to from 'normal' parts of the interface; this is what label does).
1613 public function has_view() {
1614 return !is_null($this->url
);
1618 * Gets the URL to link to for this module.
1620 * This method is normally called by the property ->url, but can be called directly if
1621 * there is a case when it might be called recursively (you can't call property values
1624 * @return moodle_url URL to link to for this module, or null if it doesn't have a view page
1626 public function get_url() {
1627 $this->obtain_dynamic_data();
1632 * Obtains content to display on main (view) page.
1633 * Note: Will collect view data, if not already obtained.
1634 * @return string Content to display on main page below link, or empty string if none
1636 private function get_content() {
1637 $this->obtain_view_data();
1638 return $this->content
;
1642 * Returns the content to display on course/overview page, formatted and passed through filters
1644 * if $options['context'] is not specified, the module context is used
1646 * @param array|stdClass $options formatting options, see {@link format_text()}
1649 public function get_formatted_content($options = array()) {
1650 $this->obtain_view_data();
1651 if (empty($this->content
)) {
1654 if ($this->contentisformatted
) {
1655 return $this->content
;
1658 // Improve filter performance by preloading filter setttings for all
1659 // activities on the course (this does nothing if called multiple
1661 filter_preload_activities($this->get_modinfo());
1663 $options = (array)$options;
1664 if (!isset($options['context'])) {
1665 $options['context'] = $this->get_context();
1667 return format_text($this->content
, FORMAT_HTML
, $options);
1671 * Return the module custom cmlist item flag.
1673 * Activities like label uses this flag to indicate that it should be
1674 * displayed as a custom course item instead of a tipical activity card.
1678 public function has_custom_cmlist_item(): bool {
1679 $this->obtain_view_data();
1680 return $this->customcmlistitem ??
false;
1684 * Getter method for property $name, ensures that dynamic data is obtained.
1686 * This method is normally called by the property ->name, but can be called directly if there
1687 * is a case when it might be called recursively (you can't call property values recursively).
1691 public function get_name() {
1692 $this->obtain_dynamic_data();
1697 * Returns the name to display on course/overview page, formatted and passed through filters
1699 * if $options['context'] is not specified, the module context is used
1701 * @param array|stdClass $options formatting options, see {@link format_string()}
1704 public function get_formatted_name($options = array()) {
1706 $options = (array)$options;
1707 if (!isset($options['context'])) {
1708 $options['context'] = $this->get_context();
1710 // Improve filter performance by preloading filter setttings for all
1711 // activities on the course (this does nothing if called multiple
1713 if (!empty($CFG->filterall
)) {
1714 filter_preload_activities($this->get_modinfo());
1716 return format_string($this->get_name(), true, $options);
1720 * Note: Will collect view data, if not already obtained.
1721 * @return string Extra CSS classes to add to html output for this activity on main page
1723 private function get_extra_classes() {
1724 $this->obtain_view_data();
1725 return $this->extraclasses
;
1729 * @return string Content of HTML on-click attribute. This string will be used literally
1730 * as a string so should be pre-escaped.
1732 private function get_on_click() {
1733 // Does not need view data; may be used by navigation
1734 $this->obtain_dynamic_data();
1735 return $this->onclick
;
1738 * Getter method for property $customdata, ensures that dynamic data is retrieved.
1740 * This method is normally called by the property ->customdata, but can be called directly if there
1741 * is a case when it might be called recursively (you can't call property values recursively).
1743 * @return mixed Optional custom data stored in modinfo cache for this activity, or null if none
1745 public function get_custom_data() {
1746 $this->obtain_dynamic_data();
1747 return $this->customdata
;
1751 * Note: Will collect view data, if not already obtained.
1752 * @return string Extra HTML code to display after link
1754 private function get_after_link() {
1755 $this->obtain_view_data();
1756 return $this->afterlink
;
1760 * Note: Will collect view data, if not already obtained.
1761 * @return string Extra HTML code to display after editing icons (e.g. more icons)
1763 private function get_after_edit_icons() {
1764 $this->obtain_view_data();
1765 return $this->afterediticons
;
1769 * Fetch the module's icon URL.
1771 * This function fetches the course module instance's icon URL.
1772 * This method adds a `filtericon` parameter in the URL when rendering the monologo version of the course module icon or when
1773 * the plugin declares, via its `filtericon` custom data, that the icon needs to be filtered.
1774 * This additional information can be used by plugins when rendering the module icon to determine whether to apply
1775 * CSS filtering to the icon.
1777 * @param core_renderer $output Output render to use, or null for default (global)
1778 * @return moodle_url Icon URL for a suitable icon to put beside this cm
1780 public function get_icon_url($output = null) {
1782 $this->obtain_dynamic_data();
1787 $ismonologo = false;
1788 if (!empty($this->iconurl
)) {
1789 // Support modules setting their own, external, icon image.
1790 $icon = $this->iconurl
;
1791 } else if (!empty($this->icon
)) {
1792 // Fallback to normal local icon + component processing.
1793 if (substr($this->icon
, 0, 4) === 'mod/') {
1794 list($modname, $iconname) = explode('/', substr($this->icon
, 4), 2);
1795 $icon = $output->image_url($iconname, $modname);
1797 if (!empty($this->iconcomponent
)) {
1798 // Icon has specified component.
1799 $icon = $output->image_url($this->icon
, $this->iconcomponent
);
1801 // Icon does not have specified component, use default.
1802 $icon = $output->image_url($this->icon
);
1806 $icon = $output->image_url('monologo', $this->modname
);
1807 // Activity modules may only have an `icon` icon instead of a `monologo` icon.
1808 // So we need to determine if the module really has a `monologo` icon.
1809 $ismonologo = core_component
::has_monologo_icon('mod', $this->modname
);
1812 // Determine whether the icon will be filtered in the CSS.
1813 // This can be controlled by the module by declaring a 'filtericon' custom data.
1814 // If the 'filtericon' custom data is not set, icon filtering will be determined whether the module has a `monologo` icon.
1815 // Additionally, we need to cast custom data to array as some modules may treat it as an object.
1816 $filtericon = ((array)$this->customdata
)['filtericon'] ??
$ismonologo;
1818 $icon->param('filtericon', 1);
1824 * @param string $textclasses additionnal classes for grouping label
1825 * @return string An empty string or HTML grouping label span tag
1827 public function get_grouping_label($textclasses = '') {
1828 $groupinglabel = '';
1829 if ($this->effectivegroupmode
!= NOGROUPS
&& !empty($this->groupingid
) &&
1830 has_capability('moodle/course:managegroups', context_course
::instance($this->course
))) {
1831 $groupings = groups_get_all_groupings($this->course
);
1832 $groupinglabel = html_writer
::tag('span', '('.format_string($groupings[$this->groupingid
]->name
).')',
1833 array('class' => 'groupinglabel '.$textclasses));
1835 return $groupinglabel;
1839 * Returns a localised human-readable name of the module type.
1841 * @param bool $plural If true, the function returns the plural form of the name.
1842 * @return lang_string
1844 public function get_module_type_name($plural = false) {
1845 $modnames = get_module_types_names($plural);
1846 if (isset($modnames[$this->modname
])) {
1847 return $modnames[$this->modname
];
1854 * Returns a localised human-readable name of the module type in plural form - calculated on request
1858 private function get_module_type_name_plural() {
1859 return $this->get_module_type_name(true);
1863 * @return course_modinfo Modinfo object that this came from
1865 public function get_modinfo() {
1866 return $this->modinfo
;
1870 * Returns the section this module belongs to
1872 * @return section_info
1874 public function get_section_info() {
1875 return $this->modinfo
->get_section_info($this->sectionnum
);
1879 * Returns course object that was used in the first {@link get_fast_modinfo()} call.
1881 * It may not contain all fields from DB table {course} but always has at least the following:
1882 * id,shortname,fullname,format,enablecompletion,groupmode,groupmodeforce,cacherev
1884 * If the course object lacks the field you need you can use the global
1885 * function {@link get_course()} that will save extra query if you access
1886 * current course or frontpage course.
1890 public function get_course() {
1891 return $this->modinfo
->get_course();
1895 * Returns course id for which the modinfo was generated.
1899 private function get_course_id() {
1900 return $this->modinfo
->get_course_id();
1904 * Returns group mode used for the course containing the module
1906 * @return int one of constants NOGROUPS, SEPARATEGROUPS, VISIBLEGROUPS
1908 private function get_course_groupmode() {
1909 return $this->modinfo
->get_course()->groupmode
;
1913 * Returns whether group mode is forced for the course containing the module
1917 private function get_course_groupmodeforce() {
1918 return $this->modinfo
->get_course()->groupmodeforce
;
1922 * Returns effective groupmode of the module that may be overwritten by forced course groupmode.
1924 * @return int one of constants NOGROUPS, SEPARATEGROUPS, VISIBLEGROUPS
1926 private function get_effective_groupmode() {
1927 $groupmode = $this->groupmode
;
1928 if ($this->modinfo
->get_course()->groupmodeforce
) {
1929 $groupmode = $this->modinfo
->get_course()->groupmode
;
1930 if ($groupmode != NOGROUPS
&& !plugin_supports('mod', $this->modname
, FEATURE_GROUPS
, false)) {
1931 $groupmode = NOGROUPS
;
1938 * @return context_module Current module context
1940 private function get_context() {
1941 return context_module
::instance($this->id
);
1945 * Returns itself in the form of stdClass.
1947 * The object includes all fields that table course_modules has and additionally
1948 * fields 'name', 'modname', 'sectionnum' (if requested).
1950 * This can be used as a faster alternative to {@link get_coursemodule_from_id()}
1952 * @param bool $additionalfields include additional fields 'name', 'modname', 'sectionnum'
1955 public function get_course_module_record($additionalfields = false) {
1956 $cmrecord = new stdClass();
1958 // Standard fields from table course_modules.
1959 static $cmfields = array('id', 'course', 'module', 'instance', 'section', 'idnumber', 'added',
1960 'score', 'indent', 'visible', 'visibleoncoursepage', 'visibleold', 'groupmode', 'groupingid',
1961 'completion', 'completiongradeitemnumber', 'completionview', 'completionexpected', 'completionpassgrade',
1962 'showdescription', 'availability', 'deletioninprogress', 'downloadcontent', 'lang');
1964 foreach ($cmfields as $key) {
1965 $cmrecord->$key = $this->$key;
1968 // Additional fields that function get_coursemodule_from_id() adds.
1969 if ($additionalfields) {
1970 $cmrecord->name
= $this->name
;
1971 $cmrecord->modname
= $this->modname
;
1972 $cmrecord->sectionnum
= $this->sectionnum
;
1982 * Sets content to display on course view page below link (if present).
1983 * @param string $content New content as HTML string (empty string if none)
1984 * @param bool $isformatted Whether user content is already passed through format_text/format_string and should not
1985 * be formatted again. This can be useful when module adds interactive elements on top of formatted user text.
1988 public function set_content($content, $isformatted = false) {
1989 $this->content
= $content;
1990 $this->contentisformatted
= $isformatted;
1994 * Sets extra classes to include in CSS.
1995 * @param string $extraclasses Extra classes (empty string if none)
1998 public function set_extra_classes($extraclasses) {
1999 $this->extraclasses
= $extraclasses;
2003 * Sets the external full url that points to the icon being used
2004 * by the activity. Useful for external-tool modules (lti...)
2005 * If set, takes precedence over $icon and $iconcomponent
2007 * @param moodle_url $iconurl full external url pointing to icon image for activity
2010 public function set_icon_url(moodle_url
$iconurl) {
2011 $this->iconurl
= $iconurl;
2015 * Sets value of on-click attribute for JavaScript.
2016 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
2017 * @param string $onclick New onclick attribute which should be HTML-escaped
2018 * (empty string if none)
2021 public function set_on_click($onclick) {
2022 $this->check_not_view_only();
2023 $this->onclick
= $onclick;
2027 * Overrides the value of an element in the customdata array.
2029 * @param string $name The key in the customdata array
2030 * @param mixed $value The value
2032 public function override_customdata($name, $value) {
2033 if (!is_array($this->customdata
)) {
2034 $this->customdata
= [];
2036 $this->customdata
[$name] = $value;
2040 * Sets HTML that displays after link on course view page.
2041 * @param string $afterlink HTML string (empty string if none)
2044 public function set_after_link($afterlink) {
2045 $this->afterlink
= $afterlink;
2049 * Sets HTML that displays after edit icons on course view page.
2050 * @param string $afterediticons HTML string (empty string if none)
2053 public function set_after_edit_icons($afterediticons) {
2054 $this->afterediticons
= $afterediticons;
2058 * Changes the name (text of link) for this module instance.
2059 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
2060 * @param string $name Name of activity / link text
2063 public function set_name($name) {
2064 if ($this->state
< self
::STATE_BUILDING_DYNAMIC
) {
2065 $this->update_user_visible();
2067 $this->name
= $name;
2071 * Turns off the view link for this module instance.
2072 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
2075 public function set_no_view_link() {
2076 $this->check_not_view_only();
2081 * Sets the 'uservisible' flag. This can be used (by setting false) to prevent access and
2082 * display of this module link for the current user.
2083 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
2084 * @param bool $uservisible
2087 public function set_user_visible($uservisible) {
2088 $this->check_not_view_only();
2089 $this->uservisible
= $uservisible;
2093 * Sets the 'customcmlistitem' flag
2095 * This can be used (by setting true) to prevent the course from rendering the
2096 * activity item as a regular activity card. This is applied to activities like labels.
2098 * @param bool $customcmlistitem if the cmlist item of that activity has a special dysplay other than a card.
2100 public function set_custom_cmlist_item(bool $customcmlistitem) {
2101 $this->customcmlistitem
= $customcmlistitem;
2105 * Sets the 'available' flag and related details. This flag is normally used to make
2106 * course modules unavailable until a certain date or condition is met. (When a course
2107 * module is unavailable, it is still visible to users who have viewhiddenactivities
2110 * When this is function is called, user-visible status is recalculated automatically.
2112 * The $showavailability flag does not really do anything any more, but is retained
2113 * for backward compatibility. Setting this to false will cause $availableinfo to
2116 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
2117 * @param bool $available False if this item is not 'available'
2118 * @param int $showavailability 0 = do not show this item at all if it's not available,
2119 * 1 = show this item greyed out with the following message
2120 * @param string $availableinfo Information about why this is not available, or
2121 * empty string if not displaying
2124 public function set_available($available, $showavailability=0, $availableinfo='') {
2125 $this->check_not_view_only();
2126 $this->available
= $available;
2127 if (!$showavailability) {
2128 $availableinfo = '';
2130 $this->availableinfo
= $availableinfo;
2131 $this->update_user_visible();
2135 * Some set functions can only be called from _cm_info_dynamic and not _cm_info_view.
2136 * This is because they may affect parts of this object which are used on pages other
2137 * than the view page (e.g. in the navigation block, or when checking access on
2141 private function check_not_view_only() {
2142 if ($this->state
>= self
::STATE_DYNAMIC
) {
2143 throw new coding_exception('Cannot set this data from _cm_info_view because it may ' .
2144 'affect other pages as well as view');
2149 * Constructor should not be called directly; use {@link get_fast_modinfo()}
2151 * @param course_modinfo $modinfo Parent object
2152 * @param stdClass $notused1 Argument not used
2153 * @param stdClass $mod Module object from the modinfo field of course table
2154 * @param stdClass $notused2 Argument not used
2156 public function __construct(course_modinfo
$modinfo, $notused1, $mod, $notused2) {
2157 $this->modinfo
= $modinfo;
2159 $this->id
= $mod->cm
;
2160 $this->instance
= $mod->id
;
2161 $this->modname
= $mod->mod
;
2162 $this->idnumber
= isset($mod->idnumber
) ?
$mod->idnumber
: '';
2163 $this->name
= $mod->name
;
2164 $this->visible
= $mod->visible
;
2165 $this->visibleoncoursepage
= $mod->visibleoncoursepage
;
2166 $this->sectionnum
= $mod->section
; // Note weirdness with name here
2167 $this->groupmode
= isset($mod->groupmode
) ?
$mod->groupmode
: 0;
2168 $this->groupingid
= isset($mod->groupingid
) ?
$mod->groupingid
: 0;
2169 $this->indent
= isset($mod->indent
) ?
$mod->indent
: 0;
2170 $this->extra
= isset($mod->extra
) ?
$mod->extra
: '';
2171 $this->extraclasses
= isset($mod->extraclasses
) ?
$mod->extraclasses
: '';
2172 // iconurl may be stored as either string or instance of moodle_url.
2173 $this->iconurl
= isset($mod->iconurl
) ?
new moodle_url($mod->iconurl
) : '';
2174 $this->onclick
= isset($mod->onclick
) ?
$mod->onclick
: '';
2175 $this->content
= isset($mod->content
) ?
$mod->content
: '';
2176 $this->icon
= isset($mod->icon
) ?
$mod->icon
: '';
2177 $this->iconcomponent
= isset($mod->iconcomponent
) ?
$mod->iconcomponent
: '';
2178 $this->customdata
= isset($mod->customdata
) ?
$mod->customdata
: '';
2179 $this->showdescription
= isset($mod->showdescription
) ?
$mod->showdescription
: 0;
2180 $this->state
= self
::STATE_BASIC
;
2182 $this->section
= isset($mod->sectionid
) ?
$mod->sectionid
: 0;
2183 $this->module
= isset($mod->module
) ?
$mod->module
: 0;
2184 $this->added
= isset($mod->added
) ?
$mod->added
: 0;
2185 $this->score
= isset($mod->score
) ?
$mod->score
: 0;
2186 $this->visibleold
= isset($mod->visibleold
) ?
$mod->visibleold
: 0;
2187 $this->deletioninprogress
= isset($mod->deletioninprogress
) ?
$mod->deletioninprogress
: 0;
2188 $this->downloadcontent
= $mod->downloadcontent ??
null;
2189 $this->lang
= $mod->lang ??
null;
2191 // Note: it saves effort and database space to always include the
2192 // availability and completion fields, even if availability or completion
2193 // are actually disabled
2194 $this->completion
= isset($mod->completion
) ?
$mod->completion
: 0;
2195 $this->completionpassgrade
= isset($mod->completionpassgrade
) ?
$mod->completionpassgrade
: 0;
2196 $this->completiongradeitemnumber
= isset($mod->completiongradeitemnumber
)
2197 ?
$mod->completiongradeitemnumber
: null;
2198 $this->completionview
= isset($mod->completionview
)
2199 ?
$mod->completionview
: 0;
2200 $this->completionexpected
= isset($mod->completionexpected
)
2201 ?
$mod->completionexpected
: 0;
2202 $this->availability
= isset($mod->availability
) ?
$mod->availability
: null;
2203 $this->conditionscompletion
= isset($mod->conditionscompletion
)
2204 ?
$mod->conditionscompletion
: array();
2205 $this->conditionsgrade
= isset($mod->conditionsgrade
)
2206 ?
$mod->conditionsgrade
: array();
2207 $this->conditionsfield
= isset($mod->conditionsfield
)
2208 ?
$mod->conditionsfield
: array();
2210 static $modviews = array();
2211 if (!isset($modviews[$this->modname
])) {
2212 $modviews[$this->modname
] = !plugin_supports('mod', $this->modname
,
2213 FEATURE_NO_VIEW_LINK
);
2215 $this->url
= $modviews[$this->modname
]
2216 ?
new moodle_url('/mod/' . $this->modname
. '/view.php', array('id'=>$this->id
))
2221 * Creates a cm_info object from a database record (also accepts cm_info
2222 * in which case it is just returned unchanged).
2224 * @param stdClass|cm_info|null|bool $cm Stdclass or cm_info (or null or false)
2225 * @param int $userid Optional userid (default to current)
2226 * @return cm_info|null Object as cm_info, or null if input was null/false
2228 public static function create($cm, $userid = 0) {
2229 // Null, false, etc. gets passed through as null.
2233 // If it is already a cm_info object, just return it.
2234 if ($cm instanceof cm_info
) {
2237 // Otherwise load modinfo.
2238 if (empty($cm->id
) ||
empty($cm->course
)) {
2239 throw new coding_exception('$cm must contain ->id and ->course');
2241 $modinfo = get_fast_modinfo($cm->course
, $userid);
2242 return $modinfo->get_cm($cm->id
);
2246 * If dynamic data for this course-module is not yet available, gets it.
2248 * This function is automatically called when requesting any course_modinfo property
2249 * that can be modified by modules (have a set_xxx method).
2251 * Dynamic data is data which does not come directly from the cache but is calculated at
2252 * runtime based on the current user. Primarily this concerns whether the user can access
2253 * the module or not.
2255 * As part of this function, the module's _cm_info_dynamic function from its lib.php will
2256 * be called (if it exists). Make sure that the functions that are called here do not use
2257 * any getter magic method from cm_info.
2260 private function obtain_dynamic_data() {
2262 $userid = $this->modinfo
->get_user_id();
2263 if ($this->state
>= self
::STATE_BUILDING_DYNAMIC ||
$userid == -1) {
2266 $this->state
= self
::STATE_BUILDING_DYNAMIC
;
2268 if (!empty($CFG->enableavailability
)) {
2269 // Get availability information.
2270 $ci = new \core_availability\
info_module($this);
2272 // Note that the modinfo currently available only includes minimal details (basic data)
2273 // but we know that this function does not need anything more than basic data.
2274 $this->available
= $ci->is_available($this->availableinfo
, true,
2275 $userid, $this->modinfo
);
2277 $this->available
= true;
2280 // Check parent section.
2281 if ($this->available
) {
2282 $parentsection = $this->modinfo
->get_section_info($this->sectionnum
);
2283 if (!$parentsection->get_available()) {
2284 // Do not store info from section here, as that is already
2285 // presented from the section (if appropriate) - just change
2287 $this->available
= false;
2291 // Update visible state for current user.
2292 $this->update_user_visible();
2294 // Let module make dynamic changes at this point
2295 $this->call_mod_function('cm_info_dynamic');
2296 $this->state
= self
::STATE_DYNAMIC
;
2300 * Getter method for property $uservisible, ensures that dynamic data is retrieved.
2302 * This method is normally called by the property ->uservisible, but can be called directly if
2303 * there is a case when it might be called recursively (you can't call property values
2308 public function get_user_visible() {
2309 $this->obtain_dynamic_data();
2310 return $this->uservisible
;
2314 * Returns whether this module is visible to the current user on course page
2316 * Activity may be visible on the course page but not available, for example
2317 * when it is hidden conditionally but the condition information is displayed.
2321 public function is_visible_on_course_page() {
2322 $this->obtain_dynamic_data();
2323 return $this->uservisibleoncoursepage
;
2327 * Whether this module is available but hidden from course page
2329 * "Stealth" modules are the ones that are not shown on course page but available by following url.
2330 * They are normally also displayed in grade reports and other reports.
2331 * Module will be stealth either if visibleoncoursepage=0 or it is a visible module inside the hidden
2336 public function is_stealth() {
2337 return !$this->visibleoncoursepage ||
2338 ($this->visible
&& ($section = $this->get_section_info()) && !$section->visible
);
2342 * Getter method for property $available, ensures that dynamic data is retrieved
2345 private function get_available() {
2346 $this->obtain_dynamic_data();
2347 return $this->available
;
2351 * This method can not be used anymore.
2353 * @see \core_availability\info_module::filter_user_list()
2354 * @deprecated Since Moodle 2.8
2356 private function get_deprecated_group_members_only() {
2357 throw new coding_exception('$cm->groupmembersonly can not be used anymore. ' .
2358 'If used to restrict a list of enrolled users to only those who can ' .
2359 'access the module, consider \core_availability\info_module::filter_user_list.');
2363 * Getter method for property $availableinfo, ensures that dynamic data is retrieved
2365 * @return string Available info (HTML)
2367 private function get_available_info() {
2368 $this->obtain_dynamic_data();
2369 return $this->availableinfo
;
2373 * Works out whether activity is available to the current user
2375 * If the activity is unavailable, additional checks are required to determine if its hidden or greyed out
2379 private function update_user_visible() {
2380 $userid = $this->modinfo
->get_user_id();
2381 if ($userid == -1) {
2384 $this->uservisible
= true;
2386 // If the module is being deleted, set the uservisible state to false and return.
2387 if ($this->deletioninprogress
) {
2388 $this->uservisible
= false;
2392 // If the user cannot access the activity set the uservisible flag to false.
2393 // Additional checks are required to determine whether the activity is entirely hidden or just greyed out.
2394 if ((!$this->visible
&& !has_capability('moodle/course:viewhiddenactivities', $this->get_context(), $userid)) ||
2395 (!$this->get_available() &&
2396 !has_capability('moodle/course:ignoreavailabilityrestrictions', $this->get_context(), $userid))) {
2398 $this->uservisible
= false;
2401 // Check group membership.
2402 if ($this->is_user_access_restricted_by_capability()) {
2404 $this->uservisible
= false;
2405 // Ensure activity is completely hidden from the user.
2406 $this->availableinfo
= '';
2409 $this->uservisibleoncoursepage
= $this->uservisible
&&
2410 ($this->visibleoncoursepage ||
2411 has_capability('moodle/course:manageactivities', $this->get_context(), $userid) ||
2412 has_capability('moodle/course:activityvisibility', $this->get_context(), $userid));
2413 // Activity that is not available, not hidden from course page and has availability
2414 // info is actually visible on the course page (with availability info and without a link).
2415 if (!$this->uservisible
&& $this->visibleoncoursepage
&& $this->availableinfo
) {
2416 $this->uservisibleoncoursepage
= true;
2421 * This method has been deprecated and should not be used.
2424 * @deprecated Since Moodle 2.8
2426 public function is_user_access_restricted_by_group() {
2427 throw new coding_exception('cm_info::is_user_access_restricted_by_group() can not be used any more.' .
2428 ' Use $cm->uservisible to decide whether the current user can access an activity.');
2432 * Checks whether mod/...:view capability restricts the current user's access.
2434 * @return bool True if the user access is restricted.
2436 public function is_user_access_restricted_by_capability() {
2437 $userid = $this->modinfo
->get_user_id();
2438 if ($userid == -1) {
2441 $capability = 'mod/' . $this->modname
. ':view';
2442 $capabilityinfo = get_capability_info($capability);
2443 if (!$capabilityinfo) {
2444 // Capability does not exist, no one is prevented from seeing the activity.
2448 // You are blocked if you don't have the capability.
2449 return !has_capability($capability, $this->get_context(), $userid);
2453 * Checks whether the module's conditional access settings mean that the
2454 * user cannot see the activity at all
2456 * @deprecated since 2.7 MDL-44070
2458 public function is_user_access_restricted_by_conditional_access() {
2459 throw new coding_exception('cm_info::is_user_access_restricted_by_conditional_access() ' .
2460 'can not be used any more; this function is not needed (use $cm->uservisible ' .
2461 'and $cm->availableinfo to decide whether it should be available ' .
2466 * Calls a module function (if exists), passing in one parameter: this object.
2467 * @param string $type Name of function e.g. if this is 'grooblezorb' and the modname is
2468 * 'forum' then it will try to call 'mod_forum_grooblezorb' or 'forum_grooblezorb'
2471 private function call_mod_function($type) {
2473 $libfile = $CFG->dirroot
. '/mod/' . $this->modname
. '/lib.php';
2474 if (file_exists($libfile)) {
2475 include_once($libfile);
2476 $function = 'mod_' . $this->modname
. '_' . $type;
2477 if (function_exists($function)) {
2480 $function = $this->modname
. '_' . $type;
2481 if (function_exists($function)) {
2489 * If view data for this course-module is not yet available, obtains it.
2491 * This function is automatically called if any of the functions (marked) which require
2492 * view data are called.
2494 * View data is data which is needed only for displaying the course main page (& any similar
2495 * functionality on other pages) but is not needed in general. Obtaining view data may have
2496 * a performance cost.
2498 * As part of this function, the module's _cm_info_view function from its lib.php will
2499 * be called (if it exists).
2502 private function obtain_view_data() {
2503 if ($this->state
>= self
::STATE_BUILDING_VIEW ||
$this->modinfo
->get_user_id() == -1) {
2506 $this->obtain_dynamic_data();
2507 $this->state
= self
::STATE_BUILDING_VIEW
;
2509 // Let module make changes at this point
2510 $this->call_mod_function('cm_info_view');
2511 $this->state
= self
::STATE_VIEW
;
2517 * Returns reference to full info about modules in course (including visibility).
2518 * Cached and as fast as possible (0 or 1 db query).
2520 * use get_fast_modinfo($courseid, 0, true) to reset the static cache for particular course
2521 * use get_fast_modinfo(0, 0, true) to reset the static cache for all courses
2523 * use rebuild_course_cache($courseid, true) to reset the application AND static cache
2524 * for particular course when it's contents has changed
2526 * @param int|stdClass $courseorid object from DB table 'course' (must have field 'id'
2527 * and recommended to have field 'cacherev') or just a course id. Just course id
2528 * is enough when calling get_fast_modinfo() for current course or site or when
2529 * calling for any other course for the second time.
2530 * @param int $userid User id to populate 'availble' and 'uservisible' attributes of modules and sections.
2531 * Set to 0 for current user (default). Set to -1 to avoid calculation of dynamic user-depended data.
2532 * @param bool $resetonly whether we want to get modinfo or just reset the cache
2533 * @return course_modinfo|null Module information for course, or null if resetting
2534 * @throws moodle_exception when course is not found (nothing is thrown if resetting)
2536 function get_fast_modinfo($courseorid, $userid = 0, $resetonly = false) {
2537 // compartibility with syntax prior to 2.4:
2538 if ($courseorid === 'reset') {
2539 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
);
2544 // Function get_fast_modinfo() can never be called during upgrade unless it is used for clearing cache only.
2546 upgrade_ensure_not_running();
2549 // Function is called with $reset = true
2551 course_modinfo
::clear_instance_cache($courseorid);
2555 // Function is called with $reset = false, retrieve modinfo
2556 return course_modinfo
::instance($courseorid, $userid);
2560 * Efficiently retrieves the $course (stdclass) and $cm (cm_info) objects, given
2561 * a cmid. If module name is also provided, it will ensure the cm is of that type.
2564 * list($course, $cm) = get_course_and_cm_from_cmid($cmid, 'forum');
2566 * Using this method has a performance advantage because it works by loading
2567 * modinfo for the course - which will then be cached and it is needed later
2568 * in most requests. It also guarantees that the $cm object is a cm_info and
2571 * The $course object can be supplied if already known and will speed
2572 * up this function - although it is more efficient to use this function to
2573 * get the course if you are starting from a cmid.
2575 * To avoid security problems and obscure bugs, you should always specify
2576 * $modulename if the cmid value came from user input.
2578 * By default this obtains information (for example, whether user can access
2579 * the activity) for current user, but you can specify a userid if required.
2581 * @param stdClass|int $cmorid Id of course-module, or database object
2582 * @param string $modulename Optional modulename (improves security)
2583 * @param stdClass|int $courseorid Optional course object if already loaded
2584 * @param int $userid Optional userid (default = current)
2585 * @return array Array with 2 elements $course and $cm
2586 * @throws moodle_exception If the item doesn't exist or is of wrong module name
2588 function get_course_and_cm_from_cmid($cmorid, $modulename = '', $courseorid = 0, $userid = 0) {
2590 if (is_object($cmorid)) {
2591 $cmid = $cmorid->id
;
2592 if (isset($cmorid->course
)) {
2593 $courseid = (int)$cmorid->course
;
2598 $cmid = (int)$cmorid;
2602 // Validate module name if supplied.
2603 if ($modulename && !core_component
::is_valid_plugin_name('mod', $modulename)) {
2604 throw new coding_exception('Invalid modulename parameter');
2607 // Get course from last parameter if supplied.
2609 if (is_object($courseorid)) {
2610 $course = $courseorid;
2611 } else if ($courseorid) {
2612 $courseid = (int)$courseorid;
2617 // If course ID is known, get it using normal function.
2618 $course = get_course($courseid);
2620 // Get course record in a single query based on cmid.
2621 $course = $DB->get_record_sql("
2623 FROM {course_modules} cm
2624 JOIN {course} c ON c.id = cm.course
2625 WHERE cm.id = ?", array($cmid), MUST_EXIST
);
2629 // Get cm from get_fast_modinfo.
2630 $modinfo = get_fast_modinfo($course, $userid);
2631 $cm = $modinfo->get_cm($cmid);
2632 if ($modulename && $cm->modname
!== $modulename) {
2633 throw new moodle_exception('invalidcoursemoduleid', 'error', '', $cmid);
2635 return array($course, $cm);
2639 * Efficiently retrieves the $course (stdclass) and $cm (cm_info) objects, given
2640 * an instance id or record and module name.
2643 * list($course, $cm) = get_course_and_cm_from_instance($forum, 'forum');
2645 * Using this method has a performance advantage because it works by loading
2646 * modinfo for the course - which will then be cached and it is needed later
2647 * in most requests. It also guarantees that the $cm object is a cm_info and
2650 * The $course object can be supplied if already known and will speed
2651 * up this function - although it is more efficient to use this function to
2652 * get the course if you are starting from an instance id.
2654 * By default this obtains information (for example, whether user can access
2655 * the activity) for current user, but you can specify a userid if required.
2657 * @param stdclass|int $instanceorid Id of module instance, or database object
2658 * @param string $modulename Modulename (required)
2659 * @param stdClass|int $courseorid Optional course object if already loaded
2660 * @param int $userid Optional userid (default = current)
2661 * @return array Array with 2 elements $course and $cm
2662 * @throws moodle_exception If the item doesn't exist or is of wrong module name
2664 function get_course_and_cm_from_instance($instanceorid, $modulename, $courseorid = 0, $userid = 0) {
2667 // Get data from parameter.
2668 if (is_object($instanceorid)) {
2669 $instanceid = $instanceorid->id
;
2670 if (isset($instanceorid->course
)) {
2671 $courseid = (int)$instanceorid->course
;
2676 $instanceid = (int)$instanceorid;
2680 // Get course from last parameter if supplied.
2682 if (is_object($courseorid)) {
2683 $course = $courseorid;
2684 } else if ($courseorid) {
2685 $courseid = (int)$courseorid;
2688 // Validate module name if supplied.
2689 if (!core_component
::is_valid_plugin_name('mod', $modulename)) {
2690 throw new coding_exception('Invalid modulename parameter');
2695 // If course ID is known, get it using normal function.
2696 $course = get_course($courseid);
2698 // Get course record in a single query based on instance id.
2699 $pagetable = '{' . $modulename . '}';
2700 $course = $DB->get_record_sql("
2702 FROM $pagetable instance
2703 JOIN {course} c ON c.id = instance.course
2704 WHERE instance.id = ?", array($instanceid), MUST_EXIST
);
2708 // Get cm from get_fast_modinfo.
2709 $modinfo = get_fast_modinfo($course, $userid);
2710 $instances = $modinfo->get_instances_of($modulename);
2711 if (!array_key_exists($instanceid, $instances)) {
2712 throw new moodle_exception('invalidmoduleid', 'error', $instanceid);
2714 return array($course, $instances[$instanceid]);
2719 * Rebuilds or resets the cached list of course activities stored in MUC.
2721 * rebuild_course_cache() must NEVER be called from lib/db/upgrade.php.
2722 * At the same time course cache may ONLY be cleared using this function in
2723 * upgrade scripts of plugins.
2725 * During the bulk operations if it is necessary to reset cache of multiple
2726 * courses it is enough to call {@link increment_revision_number()} for the
2727 * table 'course' and field 'cacherev' specifying affected courses in select.
2729 * Cached course information is stored in MUC core/coursemodinfo and is
2730 * validated with the DB field {course}.cacherev
2732 * @global moodle_database $DB
2733 * @param int $courseid id of course to rebuild, empty means all
2734 * @param boolean $clearonly only clear the cache, gets rebuild automatically on the fly.
2735 * Recommended to set to true to avoid unnecessary multiple rebuilding.
2736 * @param boolean $partialrebuild will not delete the whole cache when it's true.
2737 * use purge_module_cache() or purge_section_cache() must be
2738 * called before when partialrebuild is true.
2739 * use purge_module_cache() to invalidate mod cache.
2740 * use purge_section_cache() to invalidate section cache.
2743 * @throws coding_exception
2745 function rebuild_course_cache(int $courseid = 0, bool $clearonly = false, bool $partialrebuild = false): void
{
2746 global $COURSE, $SITE, $DB;
2748 if ($courseid == 0 and $partialrebuild) {
2749 throw new coding_exception('partialrebuild only works when a valid course id is provided.');
2752 // Function rebuild_course_cache() can not be called during upgrade unless it's clear only.
2753 if (!$clearonly && !upgrade_ensure_not_running(true)) {
2757 // Destroy navigation caches
2758 navigation_cache
::destroy_volatile_caches();
2760 core_courseformat\base
::reset_course_cache($courseid);
2762 $cachecoursemodinfo = cache
::make('core', 'coursemodinfo');
2763 if (empty($courseid)) {
2764 // Clearing caches for all courses.
2765 increment_revision_number('course', 'cacherev', '');
2766 if (!$partialrebuild) {
2767 $cachecoursemodinfo->purge();
2769 // Clear memory static cache.
2770 course_modinfo
::clear_instance_cache();
2771 // Update global values too.
2772 $sitecacherev = $DB->get_field('course', 'cacherev', array('id' => SITEID
));
2773 $SITE->cachrev
= $sitecacherev;
2774 if ($COURSE->id
== SITEID
) {
2775 $COURSE->cacherev
= $sitecacherev;
2777 $COURSE->cacherev
= $DB->get_field('course', 'cacherev', array('id' => $COURSE->id
));
2780 // Clearing cache for one course, make sure it is deleted from user request cache as well.
2781 increment_revision_number('course', 'cacherev', 'id = :id', array('id' => $courseid));
2782 if (!$partialrebuild) {
2783 // Purge all course modinfo.
2784 $cachecoursemodinfo->delete($courseid);
2786 // Clear memory static cache.
2787 course_modinfo
::clear_instance_cache($courseid);
2788 // Update global values too.
2789 if ($courseid == $COURSE->id ||
$courseid == $SITE->id
) {
2790 $cacherev = $DB->get_field('course', 'cacherev', array('id' => $courseid));
2791 if ($courseid == $COURSE->id
) {
2792 $COURSE->cacherev
= $cacherev;
2794 if ($courseid == $SITE->id
) {
2795 $SITE->cachrev
= $cacherev;
2805 $select = array('id'=>$courseid);
2808 core_php_time_limit
::raise(); // this could take a while! MDL-10954
2811 $fields = 'id,' . join(',', course_modinfo
::$cachedfields);
2813 $rs = $DB->get_recordset("course", $select, $sort, $fields);
2815 // Rebuild cache for each course.
2816 foreach ($rs as $course) {
2817 course_modinfo
::build_course_cache($course, $partialrebuild);
2824 * Class that is the return value for the _get_coursemodule_info module API function.
2826 * Note: For backward compatibility, you can also return a stdclass object from that function.
2827 * The difference is that the stdclass object may contain an 'extra' field (deprecated,
2828 * use extraclasses and onclick instead). The stdclass object may not contain
2829 * the new fields defined here (content, extraclasses, customdata).
2831 class cached_cm_info
{
2833 * Name (text of link) for this activity; Leave unset to accept default name
2839 * Name of icon for this activity. Normally, this should be used together with $iconcomponent
2840 * to define the icon, as per image_url function.
2841 * For backward compatibility, if this value is of the form 'mod/forum/icon' then an icon
2842 * within that module will be used.
2843 * @see cm_info::get_icon_url()
2844 * @see renderer_base::image_url()
2850 * Component for icon for this activity, as per image_url; leave blank to use default 'moodle'
2852 * @see renderer_base::image_url()
2855 public $iconcomponent;
2858 * HTML content to be displayed on the main page below the link (if any) for this course-module
2864 * Custom data to be stored in modinfo for this activity; useful if there are cases when
2865 * internal information for this activity type needs to be accessible from elsewhere on the
2866 * course without making database queries. May be of any type but should be short.
2872 * Extra CSS class or classes to be added when this activity is displayed on the main page;
2873 * space-separated string
2876 public $extraclasses;
2879 * External URL image to be used by activity as icon, useful for some external-tool modules
2880 * like lti. If set, takes precedence over $icon and $iconcomponent
2886 * Content of onclick JavaScript; escaped HTML to be inserted as attribute value
2894 * Data about a single section on a course. This contains the fields from the
2895 * course_sections table, plus additional data when required.
2897 * @property-read int $id Section ID - from course_sections table
2898 * @property-read int $course Course ID - from course_sections table
2899 * @property-read int $section Section number - from course_sections table
2900 * @property-read string $name Section name if specified - from course_sections table
2901 * @property-read int $visible Section visibility (1 = visible) - from course_sections table
2902 * @property-read string $summary Section summary text if specified - from course_sections table
2903 * @property-read int $summaryformat Section summary text format (FORMAT_xx constant) - from course_sections table
2904 * @property-read string $availability Availability information as JSON string -
2905 * from course_sections table
2906 * @property-read array $conditionscompletion Availability conditions for this section based on the completion of
2907 * course-modules (array from course-module id to required completion state
2908 * for that module) - from cached data in sectioncache field
2909 * @property-read array $conditionsgrade Availability conditions for this section based on course grades (array from
2910 * grade item id to object with ->min, ->max fields) - from cached data in
2911 * sectioncache field
2912 * @property-read array $conditionsfield Availability conditions for this section based on user fields
2913 * @property-read bool $available True if this section is available to the given user i.e. if all availability conditions
2914 * are met - obtained dynamically
2915 * @property-read string $availableinfo If section is not available to some users, this string gives information about
2916 * availability which can be displayed to students and/or staff (e.g. 'Available from 3 January 2010')
2917 * for display on main page - obtained dynamically
2918 * @property-read bool $uservisible True if this section is available to the given user (for example, if current user
2919 * has viewhiddensections capability, they can access the section even if it is not
2920 * visible or not available, so this would be true in that case) - obtained dynamically
2921 * @property-read string $sequence Comma-separated list of all modules in the section. Note, this field may not exactly
2922 * match course_sections.sequence if later has references to non-existing modules or not modules of not available module types.
2923 * @property-read course_modinfo $modinfo
2925 class section_info
implements IteratorAggregate
{
2927 * Section ID - from course_sections table
2933 * Section number - from course_sections table
2939 * Section name if specified - from course_sections table
2945 * Section visibility (1 = visible) - from course_sections table
2951 * Section summary text if specified - from course_sections table
2957 * Section summary text format (FORMAT_xx constant) - from course_sections table
2960 private $_summaryformat;
2963 * Availability information as JSON string - from course_sections table
2966 private $_availability;
2969 * Availability conditions for this section based on the completion of
2970 * course-modules (array from course-module id to required completion state
2971 * for that module) - from cached data in sectioncache field
2974 private $_conditionscompletion;
2977 * Availability conditions for this section based on course grades (array from
2978 * grade item id to object with ->min, ->max fields) - from cached data in
2979 * sectioncache field
2982 private $_conditionsgrade;
2985 * Availability conditions for this section based on user fields
2988 private $_conditionsfield;
2991 * True if this section is available to students i.e. if all availability conditions
2992 * are met - obtained dynamically on request, see function {@link section_info::get_available()}
2995 private $_available;
2998 * If section is not available to some users, this string gives information about
2999 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
3000 * January 2010') for display on main page - obtained dynamically on request, see
3001 * function {@link section_info::get_availableinfo()}
3004 private $_availableinfo;
3007 * True if this section is available to the CURRENT user (for example, if current user
3008 * has viewhiddensections capability, they can access the section even if it is not
3009 * visible or not available, so this would be true in that case) - obtained dynamically
3010 * on request, see function {@link section_info::get_uservisible()}
3013 private $_uservisible;
3016 * Default values for sectioncache fields; if a field has this value, it won't
3017 * be stored in the sectioncache cache, to save space. Checks are done by ===
3018 * which means values must all be strings.
3021 private static $sectioncachedefaults = array(
3024 'summaryformat' => '1', // FORMAT_HTML, but must be a string
3026 'availability' => null
3030 * Stores format options that have been cached when building 'coursecache'
3031 * When the format option is requested we look first if it has been cached
3034 private $cachedformatoptions = array();
3037 * Stores the list of all possible section options defined in each used course format.
3040 static private $sectionformatoptions = array();
3043 * Stores the modinfo object passed in constructor, may be used when requesting
3044 * dynamically obtained attributes such as available, availableinfo, uservisible.
3045 * Also used to retrun information about current course or user.
3046 * @var course_modinfo
3051 * Constructs object from database information plus extra required data.
3052 * @param object $data Array entry from cached sectioncache
3053 * @param int $number Section number (array key)
3054 * @param int $notused1 argument not used (informaion is available in $modinfo)
3055 * @param int $notused2 argument not used (informaion is available in $modinfo)
3056 * @param course_modinfo $modinfo Owner (needed for checking availability)
3057 * @param int $notused3 argument not used (informaion is available in $modinfo)
3059 public function __construct($data, $number, $notused1, $notused2, $modinfo, $notused3) {
3061 require_once($CFG->dirroot
.'/course/lib.php');
3063 // Data that is always present
3064 $this->_id
= $data->id
;
3066 $defaults = self
::$sectioncachedefaults +
3067 array('conditionscompletion' => array(),
3068 'conditionsgrade' => array(),
3069 'conditionsfield' => array());
3071 // Data that may use default values to save cache size
3072 foreach ($defaults as $field => $value) {
3073 if (isset($data->{$field})) {
3074 $this->{'_'.$field} = $data->{$field};
3076 $this->{'_'.$field} = $value;
3080 // Other data from constructor arguments.
3081 $this->_section
= $number;
3082 $this->modinfo
= $modinfo;
3084 // Cached course format data.
3085 $course = $modinfo->get_course();
3086 if (!isset(self
::$sectionformatoptions[$course->format
])) {
3087 // Store list of section format options defined in each used course format.
3088 // They do not depend on particular course but only on its format.
3089 self
::$sectionformatoptions[$course->format
] =
3090 course_get_format($course)->section_format_options();
3092 foreach (self
::$sectionformatoptions[$course->format
] as $field => $option) {
3093 if (!empty($option['cache'])) {
3094 if (isset($data->{$field})) {
3095 $this->cachedformatoptions
[$field] = $data->{$field};
3096 } else if (array_key_exists('cachedefault', $option)) {
3097 $this->cachedformatoptions
[$field] = $option['cachedefault'];
3104 * Magic method to check if the property is set
3106 * @param string $name name of the property
3109 public function __isset($name) {
3110 if (method_exists($this, 'get_'.$name) ||
3111 property_exists($this, '_'.$name) ||
3112 array_key_exists($name, self
::$sectionformatoptions[$this->modinfo
->get_course()->format
])) {
3113 $value = $this->__get($name);
3114 return isset($value);
3120 * Magic method to check if the property is empty
3122 * @param string $name name of the property
3125 public function __empty($name) {
3126 if (method_exists($this, 'get_'.$name) ||
3127 property_exists($this, '_'.$name) ||
3128 array_key_exists($name, self
::$sectionformatoptions[$this->modinfo
->get_course()->format
])) {
3129 $value = $this->__get($name);
3130 return empty($value);
3136 * Magic method to retrieve the property, this is either basic section property
3137 * or availability information or additional properties added by course format
3139 * @param string $name name of the property
3142 public function __get($name) {
3143 if (method_exists($this, 'get_'.$name)) {
3144 return $this->{'get_'.$name}();
3146 if (property_exists($this, '_'.$name)) {
3147 return $this->{'_'.$name};
3149 if (array_key_exists($name, $this->cachedformatoptions
)) {
3150 return $this->cachedformatoptions
[$name];
3152 // precheck if the option is defined in format to avoid unnecessary DB queries in get_format_options()
3153 if (array_key_exists($name, self
::$sectionformatoptions[$this->modinfo
->get_course()->format
])) {
3154 $formatoptions = course_get_format($this->modinfo
->get_course())->get_format_options($this);
3155 return $formatoptions[$name];
3157 debugging('Invalid section_info property accessed! '.$name);
3162 * Finds whether this section is available at the moment for the current user.
3164 * The value can be accessed publicly as $sectioninfo->available, but can be called directly if there
3165 * is a case when it might be called recursively (you can't call property values recursively).
3169 public function get_available() {
3171 $userid = $this->modinfo
->get_user_id();
3172 if ($this->_available
!== null ||
$userid == -1) {
3173 // Has already been calculated or does not need calculation.
3174 return $this->_available
;
3176 $this->_available
= true;
3177 $this->_availableinfo
= '';
3178 if (!empty($CFG->enableavailability
)) {
3179 // Get availability information.
3180 $ci = new \core_availability\
info_section($this);
3181 $this->_available
= $ci->is_available($this->_availableinfo
, true,
3182 $userid, $this->modinfo
);
3184 // Execute the hook from the course format that may override the available/availableinfo properties.
3185 $currentavailable = $this->_available
;
3186 course_get_format($this->modinfo
->get_course())->
3187 section_get_available_hook($this, $this->_available
, $this->_availableinfo
);
3188 if (!$currentavailable && $this->_available
) {
3189 debugging('section_get_available_hook() can not make unavailable section available', DEBUG_DEVELOPER
);
3190 $this->_available
= $currentavailable;
3192 return $this->_available
;
3196 * Returns the availability text shown next to the section on course page.
3200 private function get_availableinfo() {
3201 // Calling get_available() will also fill the availableinfo property
3202 // (or leave it null if there is no userid).
3203 $this->get_available();
3204 return $this->_availableinfo
;
3208 * Implementation of IteratorAggregate::getIterator(), allows to cycle through properties
3209 * and use {@link convert_to_array()}
3211 * @return ArrayIterator
3213 public function getIterator(): Traversable
{
3215 foreach (get_object_vars($this) as $key => $value) {
3216 if (substr($key, 0, 1) == '_') {
3217 if (method_exists($this, 'get'.$key)) {
3218 $ret[substr($key, 1)] = $this->{'get'.$key}();
3220 $ret[substr($key, 1)] = $this->$key;
3224 $ret['sequence'] = $this->get_sequence();
3225 $ret['course'] = $this->get_course();
3226 $ret = array_merge($ret, course_get_format($this->modinfo
->get_course())->get_format_options($this->_section
));
3227 return new ArrayIterator($ret);
3231 * Works out whether activity is visible *for current user* - if this is false, they
3232 * aren't allowed to access it.
3236 private function get_uservisible() {
3237 $userid = $this->modinfo
->get_user_id();
3238 if ($this->_uservisible
!== null ||
$userid == -1) {
3239 // Has already been calculated or does not need calculation.
3240 return $this->_uservisible
;
3242 $this->_uservisible
= true;
3243 if (!$this->_visible ||
!$this->get_available()) {
3244 $coursecontext = context_course
::instance($this->get_course());
3245 if (!$this->_visible
&& !has_capability('moodle/course:viewhiddensections', $coursecontext, $userid) ||
3246 (!$this->get_available() &&
3247 !has_capability('moodle/course:ignoreavailabilityrestrictions', $coursecontext, $userid))) {
3249 $this->_uservisible
= false;
3252 return $this->_uservisible
;
3256 * Restores the course_sections.sequence value
3260 private function get_sequence() {
3261 if (!empty($this->modinfo
->sections
[$this->_section
])) {
3262 return implode(',', $this->modinfo
->sections
[$this->_section
]);
3269 * Returns course ID - from course_sections table
3273 private function get_course() {
3274 return $this->modinfo
->get_course_id();
3280 * @return course_modinfo
3282 private function get_modinfo() {
3283 return $this->modinfo
;
3287 * Prepares section data for inclusion in sectioncache cache, removing items
3288 * that are set to defaults, and adding availability data if required.
3290 * Called by build_section_cache in course_modinfo only; do not use otherwise.
3291 * @param object $section Raw section data object
3293 public static function convert_for_section_cache($section) {
3296 // Course id stored in course table
3297 unset($section->course
);
3298 // Section number stored in array key
3299 unset($section->section
);
3300 // Sequence stored implicity in modinfo $sections array
3301 unset($section->sequence
);
3303 // Remove default data
3304 foreach (self
::$sectioncachedefaults as $field => $value) {
3305 // Exact compare as strings to avoid problems if some strings are set
3307 if (isset($section->{$field}) && $section->{$field} === $value) {
3308 unset($section->{$field});