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);
35 use core_courseformat\output\activitybadge
;
36 use core_courseformat\sectiondelegate
;
39 * Information about a course that is cached in the course table 'modinfo' field (and then in
40 * memory) in order to reduce the need for other database queries.
42 * This includes information about the course-modules and the sections on the course. It can also
43 * include dynamic data that has been updated for the current user.
45 * Use {@link get_fast_modinfo()} to retrieve the instance of the object for particular course
46 * and particular user.
48 * @property-read int $courseid Course ID
49 * @property-read int $userid User ID
50 * @property-read array $sections Array from section number (e.g. 0) to array of course-module IDs in that
51 * section; this only includes sections that contain at least one course-module
52 * @property-read cm_info[] $cms Array from course-module instance to cm_info object within this course, in
54 * @property-read cm_info[][] $instances Array from string (modname) => int (instance id) => cm_info object
55 * @property-read array $groups Groups that the current user belongs to. Calculated on the first request.
56 * Is an array of grouping id => array of group id => group id. Includes grouping id 0 for 'all groups'
58 class course_modinfo
{
59 /** @var int Maximum time the course cache building lock can be held */
60 const COURSE_CACHE_LOCK_EXPIRY
= 180;
62 /** @var int Time to wait for the course cache building lock before throwing an exception */
63 const COURSE_CACHE_LOCK_WAIT
= 60;
66 * List of fields from DB table 'course' that are cached in MUC and are always present in course_modinfo::$course
69 public static $cachedfields = array('shortname', 'fullname', 'format',
70 'enablecompletion', 'groupmode', 'groupmodeforce', 'cacherev');
73 * For convenience we store the course object here as it is needed in other parts of code
79 * Array of section data from cache indexed by section number.
82 private $sectioninfobynum;
85 * Array of section data from cache indexed by id.
88 private $sectioninfobyid;
91 * Index of delegated sections (indexed by component and itemid)
94 private $delegatedsections;
103 * Array indexed by section num (e.g. 0) => array of course-module ids
104 * This list only includes sections that actually contain at least one course-module
107 private $sectionmodules;
110 * Array from int (cm id) => cm_info object
116 * Array from string (modname) => int (instance id) => cm_info object
122 * Groups that the current user belongs to. This value is calculated on first
123 * request to the property or function.
124 * When set, it is an array of grouping id => array of group id => group id.
125 * Includes grouping id 0 for 'all groups'.
131 * List of class read-only properties and their getter methods.
132 * Used by magic functions __get(), __isset(), __empty()
135 private static $standardproperties = array(
136 'courseid' => 'get_course_id',
137 'userid' => 'get_user_id',
138 'sections' => 'get_sections',
140 'instances' => 'get_instances',
141 'groups' => 'get_groups_all',
145 * Magic method getter
147 * @param string $name
150 public function __get($name) {
151 if (isset(self
::$standardproperties[$name])) {
152 $method = self
::$standardproperties[$name];
153 return $this->$method();
155 debugging('Invalid course_modinfo property accessed: '.$name);
161 * Magic method for function isset()
163 * @param string $name
166 public function __isset($name) {
167 if (isset(self
::$standardproperties[$name])) {
168 $value = $this->__get($name);
169 return isset($value);
175 * Magic method for function empty()
177 * @param string $name
180 public function __empty($name) {
181 if (isset(self
::$standardproperties[$name])) {
182 $value = $this->__get($name);
183 return empty($value);
189 * Magic method setter
191 * Will display the developer warning when trying to set/overwrite existing property.
193 * @param string $name
194 * @param mixed $value
196 public function __set($name, $value) {
197 debugging("It is not allowed to set the property course_modinfo::\${$name}", DEBUG_DEVELOPER
);
201 * Returns course object that was used in the first {@link get_fast_modinfo()} call.
203 * It may not contain all fields from DB table {course} but always has at least the following:
204 * id,shortname,fullname,format,enablecompletion,groupmode,groupmodeforce,cacherev
208 public function get_course() {
209 return $this->course
;
213 * @return int Course ID
215 public function get_course_id() {
216 return $this->course
->id
;
220 * @return int User ID
222 public function get_user_id() {
223 return $this->userid
;
227 * @return array Array from section number (e.g. 0) to array of course-module IDs in that
228 * section; this only includes sections that contain at least one course-module
230 public function get_sections() {
231 return $this->sectionmodules
;
235 * @return cm_info[] Array from course-module instance to cm_info object within this course, in
236 * order of appearance
238 public function get_cms() {
243 * Obtains a single course-module object (for a course-module that is on this course).
244 * @param int $cmid Course-module ID
245 * @return cm_info Information about that course-module
246 * @throws moodle_exception If the course-module does not exist
248 public function get_cm($cmid) {
249 if (empty($this->cms
[$cmid])) {
250 throw new moodle_exception('invalidcoursemoduleid', 'error', '', $cmid);
252 return $this->cms
[$cmid];
256 * Obtains all module instances on this course.
257 * @return cm_info[][] Array from module name => array from instance id => cm_info
259 public function get_instances() {
260 return $this->instances
;
264 * Returns array of localised human-readable module names used in this course
266 * @param bool $plural if true returns the plural form of modules names
269 public function get_used_module_names($plural = false) {
270 $modnames = get_module_types_names($plural);
271 $modnamesused = array();
272 foreach ($this->get_cms() as $cmid => $mod) {
273 if (!isset($modnamesused[$mod->modname
]) && isset($modnames[$mod->modname
]) && $mod->uservisible
) {
274 $modnamesused[$mod->modname
] = $modnames[$mod->modname
];
277 return $modnamesused;
281 * Obtains all instances of a particular module on this course.
282 * @param string $modname Name of module (not full frankenstyle) e.g. 'label'
283 * @return cm_info[] Array from instance id => cm_info for modules on this course; empty if none
285 public function get_instances_of($modname) {
286 if (empty($this->instances
[$modname])) {
289 return $this->instances
[$modname];
293 * Groups that the current user belongs to organised by grouping id. Calculated on the first request.
294 * @return int[][] array of grouping id => array of group id => group id. Includes grouping id 0 for 'all groups'
296 private function get_groups_all() {
297 if (is_null($this->groups
)) {
298 $this->groups
= groups_get_user_groups($this->course
->id
, $this->userid
);
300 return $this->groups
;
304 * Returns groups that the current user belongs to on the course. Note: If not already
305 * available, this may make a database query.
306 * @param int $groupingid Grouping ID or 0 (default) for all groups
307 * @return int[] Array of int (group id) => int (same group id again); empty array if none
309 public function get_groups($groupingid = 0) {
310 $allgroups = $this->get_groups_all();
311 if (!isset($allgroups[$groupingid])) {
314 return $allgroups[$groupingid];
318 * Gets all sections as array from section number => data about section.
319 * @return section_info[] Array of section_info objects organised by section number
321 public function get_section_info_all() {
322 return $this->sectioninfobynum
;
326 * Gets data about specific numbered section.
327 * @param int $sectionnumber Number (not id) of section
328 * @param int $strictness Use MUST_EXIST to throw exception if it doesn't
329 * @return section_info Information for numbered section or null if not found
331 public function get_section_info($sectionnumber, $strictness = IGNORE_MISSING
) {
332 if (!array_key_exists($sectionnumber, $this->sectioninfobynum
)) {
333 if ($strictness === MUST_EXIST
) {
334 throw new moodle_exception('sectionnotexist');
339 return $this->sectioninfobynum
[$sectionnumber];
343 * Gets data about specific section ID.
344 * @param int $sectionid ID (not number) of section
345 * @param int $strictness Use MUST_EXIST to throw exception if it doesn't
346 * @return section_info|null Information for numbered section or null if not found
348 public function get_section_info_by_id(int $sectionid, int $strictness = IGNORE_MISSING
): ?section_info
{
349 if (!array_key_exists($sectionid, $this->sectioninfobyid
)) {
350 if ($strictness === MUST_EXIST
) {
351 throw new moodle_exception('sectionnotexist');
356 return $this->sectioninfobyid
[$sectionid];
360 * Gets data about specific delegated section.
361 * @param string $component Component name
362 * @param int $itemid Item id
363 * @param int $strictness Use MUST_EXIST to throw exception if it doesn't
364 * @return section_info|null Information for numbered section or null if not found
366 public function get_section_info_by_component(
369 int $strictness = IGNORE_MISSING
371 if (!isset($this->delegatedsections
[$component][$itemid])) {
372 if ($strictness === MUST_EXIST
) {
373 throw new moodle_exception('sectionnotexist');
378 return $this->delegatedsections
[$component][$itemid];
382 * Check if the course has delegated sections.
385 public function has_delegated_sections(): bool {
386 return !empty($this->delegatedsections
);
390 * Static cache for generated course_modinfo instances
392 * @see course_modinfo::instance()
393 * @see course_modinfo::clear_instance_cache()
394 * @var course_modinfo[]
396 protected static $instancecache = array();
399 * Timestamps (microtime) when the course_modinfo instances were last accessed
401 * It is used to remove the least recent accessed instances when static cache is full
405 protected static $cacheaccessed = array();
408 * Store a list of known course cacherev values. This is in case people reuse a course object
409 * (with an old cacherev value) within the same request when calling things like
410 * get_fast_modinfo, after rebuild_course_cache.
414 protected static $mincacherevs = [];
417 * Clears the cache used in course_modinfo::instance()
419 * Used in {@link get_fast_modinfo()} when called with argument $reset = true
420 * and in {@link rebuild_course_cache()}
422 * If the cacherev for the course is known to have updated (i.e. when doing
423 * rebuild_course_cache), it should be specified here.
425 * @param null|int|stdClass $courseorid if specified removes only cached value for this course
426 * @param int $newcacherev If specified, the known cache rev for this course id will be updated
428 public static function clear_instance_cache($courseorid = null, int $newcacherev = 0) {
429 if (empty($courseorid)) {
430 self
::$instancecache = array();
431 self
::$cacheaccessed = array();
432 // This is called e.g. in phpunit when we just want to reset the caches, so also
433 // reset the mincacherevs static cache.
434 self
::$mincacherevs = [];
437 if (is_object($courseorid)) {
438 $courseorid = $courseorid->id
;
440 if (isset(self
::$instancecache[$courseorid])) {
441 // Unsetting static variable in PHP is peculiar, it removes the reference,
442 // but data remain in memory. Prior to unsetting, the varable needs to be
443 // set to empty to remove its remains from memory.
444 self
::$instancecache[$courseorid] = '';
445 unset(self
::$instancecache[$courseorid]);
446 unset(self
::$cacheaccessed[$courseorid]);
448 // When clearing cache for a course, we record the new cacherev version, to make
449 // sure that any future requests for the cache use at least this version.
451 self
::$mincacherevs[(int)$courseorid] = $newcacherev;
456 * Returns the instance of course_modinfo for the specified course and specified user
458 * This function uses static cache for the retrieved instances. The cache
459 * size is limited by MAX_MODINFO_CACHE_SIZE. If instance is not found in
460 * the static cache or it was created for another user or the cacherev validation
461 * failed - a new instance is constructed and returned.
463 * Used in {@link get_fast_modinfo()}
465 * @param int|stdClass $courseorid object from DB table 'course' (must have field 'id'
466 * and recommended to have field 'cacherev') or just a course id
467 * @param int $userid User id to populate 'availble' and 'uservisible' attributes of modules and sections.
468 * Set to 0 for current user (default). Set to -1 to avoid calculation of dynamic user-depended data.
469 * @return course_modinfo
471 public static function instance($courseorid, $userid = 0) {
473 if (is_object($courseorid)) {
474 $course = $courseorid;
476 $course = (object)array('id' => $courseorid);
478 if (empty($userid)) {
482 if (!empty(self
::$instancecache[$course->id
])) {
483 if (self
::$instancecache[$course->id
]->userid
== $userid &&
484 (!isset($course->cacherev
) ||
485 $course->cacherev
== self
::$instancecache[$course->id
]->get_course()->cacherev
)) {
486 // This course's modinfo for the same user was recently retrieved, return cached.
487 self
::$cacheaccessed[$course->id
] = microtime(true);
488 return self
::$instancecache[$course->id
];
490 // Prevent potential reference problems when switching users.
491 self
::clear_instance_cache($course->id
);
494 $modinfo = new course_modinfo($course, $userid);
496 // We have a limit of MAX_MODINFO_CACHE_SIZE entries to store in static variable.
497 if (count(self
::$instancecache) >= MAX_MODINFO_CACHE_SIZE
) {
498 // Find the course that was the least recently accessed.
499 asort(self
::$cacheaccessed, SORT_NUMERIC
);
500 $courseidtoremove = key(array_reverse(self
::$cacheaccessed, true));
501 self
::clear_instance_cache($courseidtoremove);
504 // Add modinfo to the static cache.
505 self
::$instancecache[$course->id
] = $modinfo;
506 self
::$cacheaccessed[$course->id
] = microtime(true);
512 * Constructs based on course.
513 * Note: This constructor should not usually be called directly.
514 * Use get_fast_modinfo($course) instead as this maintains a cache.
515 * @param stdClass $course course object, only property id is required.
516 * @param int $userid User ID
517 * @throws moodle_exception if course is not found
519 public function __construct($course, $userid) {
520 global $CFG, $COURSE, $SITE, $DB;
522 if (!isset($course->cacherev
)) {
523 // We require presence of property cacherev to validate the course cache.
524 // No need to clone the $COURSE or $SITE object here because we clone it below anyway.
525 $course = get_course($course->id
, false);
528 // If we have rebuilt the course cache in this request, ensure that requested cacherev is
529 // at least that value. This ensures that we're not reusing a course object with old
530 // cacherev, which could result in using old cached data.
531 if (array_key_exists($course->id
, self
::$mincacherevs) &&
532 $course->cacherev
< self
::$mincacherevs[$course->id
]) {
533 $course->cacherev
= self
::$mincacherevs[$course->id
];
536 $cachecoursemodinfo = cache
::make('core', 'coursemodinfo');
538 // Retrieve modinfo from cache. If not present or cacherev mismatches, call rebuild and retrieve again.
539 $coursemodinfo = $cachecoursemodinfo->get_versioned($course->id
, $course->cacherev
);
540 // Note the version comparison using the data in the cache should not be necessary, but the
541 // partial rebuild logic sometimes sets the $coursemodinfo->cacherev to -1 which is an
542 // indicator that it needs rebuilding.
543 if ($coursemodinfo === false ||
($course->cacherev
> $coursemodinfo->cacherev
)) {
544 $coursemodinfo = self
::build_course_cache($course);
547 // Set initial values
548 $this->userid
= $userid;
549 $this->sectionmodules
= [];
551 $this->instances
= [];
552 $this->groups
= null;
554 // If we haven't already preloaded contexts for the course, do it now
555 // Modules are also cached here as long as it's the first time this course has been preloaded.
556 context_helper
::preload_course($course->id
);
558 // Quick integrity check: as a result of race conditions modinfo may not be regenerated after the change.
559 // It is especially dangerous if modinfo contains the deleted course module, as it results in fatal error.
560 // We can check it very cheap by validating the existence of module context.
561 if ($course->id
== $COURSE->id ||
$course->id
== $SITE->id
) {
562 // Only verify current course (or frontpage) as pages with many courses may not have module contexts cached.
563 // (Uncached modules will result in a very slow verification).
564 foreach ($coursemodinfo->modinfo
as $mod) {
565 if (!context_module
::instance($mod->cm
, IGNORE_MISSING
)) {
566 debugging('Course cache integrity check failed: course module with id '. $mod->cm
.
567 ' does not have context. Rebuilding cache for course '. $course->id
);
568 // Re-request the course record from DB as well, don't use get_course() here.
569 $course = $DB->get_record('course', array('id' => $course->id
), '*', MUST_EXIST
);
570 $coursemodinfo = self
::build_course_cache($course, true);
576 // Overwrite unset fields in $course object with cached values, store the course object.
577 $this->course
= fullclone($course);
578 foreach ($coursemodinfo as $key => $value) {
579 if ($key !== 'modinfo' && $key !== 'sectioncache' &&
580 (!isset($this->course
->$key) ||
$key === 'cacherev')) {
581 $this->course
->$key = $value;
585 // Loop through each piece of module data, constructing it
586 static $modexists = array();
587 foreach ($coursemodinfo->modinfo
as $mod) {
588 if (!isset($mod->name
) ||
strval($mod->name
) === '') {
589 // something is wrong here
593 // Skip modules which don't exist
594 if (!array_key_exists($mod->mod
, $modexists)) {
595 $modexists[$mod->mod
] = file_exists("$CFG->dirroot/mod/$mod->mod/lib.php");
597 if (!$modexists[$mod->mod
]) {
601 // Construct info for this module
602 $cm = new cm_info($this, null, $mod, null);
604 // Store module in instances and cms array
605 if (!isset($this->instances
[$cm->modname
])) {
606 $this->instances
[$cm->modname
] = array();
608 $this->instances
[$cm->modname
][$cm->instance
] = $cm;
609 $this->cms
[$cm->id
] = $cm;
611 // Reconstruct sections. This works because modules are stored in order
612 if (!isset($this->sectionmodules
[$cm->sectionnum
])) {
613 $this->sectionmodules
[$cm->sectionnum
] = [];
615 $this->sectionmodules
[$cm->sectionnum
][] = $cm->id
;
618 // Expand section objects
619 $this->sectioninfobynum
= [];
620 $this->sectioninfobyid
= [];
621 $this->delegatedsections
= [];
622 foreach ($coursemodinfo->sectioncache
as $data) {
623 $sectioninfo = new section_info($data, $data->section
, null, null,
625 $this->sectioninfobynum
[$data->section
] = $sectioninfo;
626 $this->sectioninfobyid
[$data->id
] = $sectioninfo;
627 if (!empty($sectioninfo->component
)) {
628 if (!isset($this->delegatedsections
[$sectioninfo->component
])) {
629 $this->delegatedsections
[$sectioninfo->component
] = [];
631 $this->delegatedsections
[$sectioninfo->component
][$sectioninfo->itemid
] = $sectioninfo;
634 ksort($this->sectioninfobynum
);
638 * This method can not be used anymore.
640 * @see course_modinfo::build_course_cache()
641 * @deprecated since 2.6
643 public static function build_section_cache($courseid) {
644 throw new coding_exception('Function course_modinfo::build_section_cache() can not be used anymore.' .
645 ' Please use course_modinfo::build_course_cache() whenever applicable.');
649 * Builds a list of information about sections on a course to be stored in
650 * the course cache. (Does not include information that is already cached
651 * in some other way.)
653 * @param stdClass $course Course object (must contain fields id and cacherev)
654 * @param boolean $usecache use cached section info if exists, use true for partial course rebuild
655 * @return array Information about sections, indexed by section id (not number)
657 protected static function build_course_section_cache(\stdClass
$course, bool $usecache = false): array {
661 $sections = $DB->get_records(
663 ['course' => $course->id
],
665 'id, section, course, name, summary, summaryformat, sequence, visible, availability, component, itemid'
667 $compressedsections = [];
668 $courseformat = course_get_format($course);
671 $cachecoursemodinfo = cache
::make('core', 'coursemodinfo');
672 $coursemodinfo = $cachecoursemodinfo->get_versioned($course->id
, $course->cacherev
);
673 if ($coursemodinfo !== false) {
674 $compressedsections = $coursemodinfo->sectioncache
;
678 $formatoptionsdef = course_get_format($course)->section_format_options();
679 // Remove unnecessary data and add availability.
680 foreach ($sections as $section) {
681 $sectionid = $section->id
;
682 $sectioninfocached = isset($compressedsections[$sectionid]);
683 if ($sectioninfocached) {
686 // Add cached options from course format to $section object.
687 foreach ($formatoptionsdef as $key => $option) {
688 if (!empty($option['cache'])) {
689 $formatoptions = $courseformat->get_format_options($section);
690 if (!array_key_exists('cachedefault', $option) ||
$option['cachedefault'] !== $formatoptions[$key]) {
691 $section->$key = $formatoptions[$key];
695 // Clone just in case it is reused elsewhere.
696 $compressedsections[$sectionid] = clone($section);
697 section_info
::convert_for_section_cache($compressedsections[$sectionid]);
699 return $compressedsections;
703 * Builds and stores in MUC object containing information about course
704 * modules and sections together with cached fields from table course.
706 * @param stdClass $course object from DB table course. Must have property 'id'
707 * but preferably should have all cached fields.
708 * @param boolean $partialrebuild Indicate if it's partial course cache rebuild or not
709 * @return stdClass object with all cached keys of the course plus fields modinfo and sectioncache.
710 * The same object is stored in MUC
711 * @throws moodle_exception if course is not found (if $course object misses some of the
712 * necessary fields it is re-requested from database)
714 public static function build_course_cache(\stdClass
$course, bool $partialrebuild = false): \stdClass
{
715 if (empty($course->id
)) {
716 throw new coding_exception('Object $course is missing required property \id\'');
719 $cachecoursemodinfo = cache
::make('core', 'coursemodinfo');
720 $cachekey = $course->id
;
721 $cachecoursemodinfo->acquire_lock($cachekey);
723 // Only actually do the build if it's still needed after getting the lock (not if
724 // somebody else, who might have been holding the lock, built it already).
725 $coursemodinfo = $cachecoursemodinfo->get_versioned($course->id
, $course->cacherev
);
726 if ($coursemodinfo === false ||
($course->cacherev
> $coursemodinfo->cacherev
)) {
727 $coursemodinfo = self
::inner_build_course_cache($course);
730 $cachecoursemodinfo->release_lock($cachekey);
732 return $coursemodinfo;
736 * Called to build course cache when there is already a lock obtained.
738 * @param stdClass $course object from DB table course
739 * @param bool $partialrebuild Indicate if it's partial course cache rebuild or not
740 * @return stdClass Course object that has been stored in MUC
742 protected static function inner_build_course_cache(\stdClass
$course, bool $partialrebuild = false): \stdClass
{
744 require_once("{$CFG->dirroot}/course/lib.php");
746 $cachekey = $course->id
;
747 $cachecoursemodinfo = cache
::make('core', 'coursemodinfo');
748 if (!$cachecoursemodinfo->check_lock_state($cachekey)) {
749 throw new coding_exception('You must acquire a lock on the course ID before calling inner_build_course_cache');
752 // Always reload the course object from database to ensure we have the latest possible
753 // value for cacherev.
754 $course = $DB->get_record('course', ['id' => $course->id
],
755 implode(',', array_merge(['id'], self
::$cachedfields)), MUST_EXIST
);
756 // Retrieve all information about activities and sections.
757 $coursemodinfo = new stdClass();
758 $coursemodinfo->modinfo
= self
::get_array_of_activities($course, $partialrebuild);
759 $coursemodinfo->sectioncache
= self
::build_course_section_cache($course, $partialrebuild);
760 foreach (self
::$cachedfields as $key) {
761 $coursemodinfo->$key = $course->$key;
763 // Set the accumulated activities and sections information in cache, together with cacherev.
764 $cachecoursemodinfo->set_versioned($cachekey, $course->cacherev
, $coursemodinfo);
765 return $coursemodinfo;
769 * Purge the cache of a course section by its id.
771 * @param int $courseid The course to purge cache in
772 * @param int $sectionid The section _id_ to purge
774 public static function purge_course_section_cache_by_id(int $courseid, int $sectionid): void
{
775 $course = get_course($courseid);
776 $cache = cache
::make('core', 'coursemodinfo');
777 $cachekey = $course->id
;
778 $cache->acquire_lock($cachekey);
780 $coursemodinfo = $cache->get_versioned($cachekey, $course->cacherev
);
781 if ($coursemodinfo !== false && array_key_exists($sectionid, $coursemodinfo->sectioncache
)) {
782 $coursemodinfo->cacherev
= -1;
783 unset($coursemodinfo->sectioncache
[$sectionid]);
784 $cache->set_versioned($cachekey, $course->cacherev
, $coursemodinfo);
787 $cache->release_lock($cachekey);
792 * Purge the cache of a course section by its number.
794 * @param int $courseid The course to purge cache in
795 * @param int $sectionno The section number to purge
797 public static function purge_course_section_cache_by_number(int $courseid, int $sectionno): void
{
798 $course = get_course($courseid);
799 $cache = cache
::make('core', 'coursemodinfo');
800 $cachekey = $course->id
;
801 $cache->acquire_lock($cachekey);
803 $coursemodinfo = $cache->get_versioned($cachekey, $course->cacherev
);
804 if ($coursemodinfo !== false) {
805 foreach ($coursemodinfo->sectioncache
as $sectionid => $sectioncache) {
806 if ($sectioncache->section
== $sectionno) {
807 $coursemodinfo->cacherev
= -1;
808 unset($coursemodinfo->sectioncache
[$sectionid]);
809 $cache->set_versioned($cachekey, $course->cacherev
, $coursemodinfo);
815 $cache->release_lock($cachekey);
820 * Purge the cache of a course module.
822 * @param int $courseid Course id
823 * @param int $cmid Course module id
825 public static function purge_course_module_cache(int $courseid, int $cmid): void
{
826 self
::purge_course_modules_cache($courseid, [$cmid]);
830 * Purge the cache of multiple course modules.
832 * @param int $courseid Course id
833 * @param int[] $cmids List of course module ids
836 public static function purge_course_modules_cache(int $courseid, array $cmids): void
{
837 $course = get_course($courseid);
838 $cache = cache
::make('core', 'coursemodinfo');
839 $cachekey = $course->id
;
840 $cache->acquire_lock($cachekey);
842 $coursemodinfo = $cache->get_versioned($cachekey, $course->cacherev
);
843 $hascache = ($coursemodinfo !== false);
844 $updatedcache = false;
846 foreach ($cmids as $cmid) {
847 if (array_key_exists($cmid, $coursemodinfo->modinfo
)) {
848 unset($coursemodinfo->modinfo
[$cmid]);
849 $updatedcache = true;
853 $coursemodinfo->cacherev
= -1;
854 $cache->set_versioned($cachekey, $course->cacherev
, $coursemodinfo);
855 $cache->get_versioned($cachekey, $course->cacherev
);
859 $cache->release_lock($cachekey);
864 * For a given course, returns an array of course activity objects
866 * @param stdClass $course Course object
867 * @param bool $usecache get activities from cache if modinfo exists when $usecache is true
868 * @return array list of activities
870 public static function get_array_of_activities(stdClass
$course, bool $usecache = false): array {
873 if (empty($course)) {
874 throw new moodle_exception('courseidnotfound');
877 $rawmods = get_course_mods($course->id
);
878 if (empty($rawmods)) {
884 // Get existing cache.
885 $cachecoursemodinfo = cache
::make('core', 'coursemodinfo');
886 $coursemodinfo = $cachecoursemodinfo->get_versioned($course->id
, $course->cacherev
);
887 if ($coursemodinfo !== false) {
888 $mods = $coursemodinfo->modinfo
;
892 $courseformat = course_get_format($course);
894 if ($sections = $DB->get_records('course_sections', ['course' => $course->id
],
895 'section ASC', 'id,section,sequence,visible')) {
896 // First check and correct obvious mismatches between course_sections.sequence and course_modules.section.
897 if ($errormessages = course_integrity_check($course->id
, $rawmods, $sections)) {
898 debugging(join('<br>', $errormessages));
899 $rawmods = get_course_mods($course->id
);
900 $sections = $DB->get_records('course_sections', ['course' => $course->id
],
901 'section ASC', 'id,section,sequence,visible');
903 // Build array of activities.
904 foreach ($sections as $section) {
905 if (!empty($section->sequence
)) {
906 $cmids = explode(",", $section->sequence
);
907 $numberofmods = count($cmids);
908 foreach ($cmids as $cmid) {
909 // Activity does not exist in the database.
910 $notexistindb = empty($rawmods[$cmid]);
911 $activitycached = isset($mods[$cmid]);
912 if ($activitycached ||
$notexistindb) {
916 // Adjust visibleoncoursepage, value in DB may not respect format availability.
917 $rawmods[$cmid]->visibleoncoursepage
= (!$rawmods[$cmid]->visible
918 ||
$rawmods[$cmid]->visibleoncoursepage
919 ||
empty($CFG->allowstealth
)
920 ||
!$courseformat->allow_stealth_module_visibility($rawmods[$cmid], $section)) ?
1 : 0;
922 $mods[$cmid] = new stdClass();
923 $mods[$cmid]->id
= $rawmods[$cmid]->instance
;
924 $mods[$cmid]->cm
= $rawmods[$cmid]->id
;
925 $mods[$cmid]->mod
= $rawmods[$cmid]->modname
;
927 // Oh dear. Inconsistent names left 'section' here for backward compatibility,
928 // but also save sectionid and sectionnumber.
929 $mods[$cmid]->section
= $section->section
;
930 $mods[$cmid]->sectionnumber
= $section->section
;
931 $mods[$cmid]->sectionid
= $rawmods[$cmid]->section
;
933 $mods[$cmid]->module
= $rawmods[$cmid]->module
;
934 $mods[$cmid]->added
= $rawmods[$cmid]->added
;
935 $mods[$cmid]->score
= $rawmods[$cmid]->score
;
936 $mods[$cmid]->idnumber
= $rawmods[$cmid]->idnumber
;
937 $mods[$cmid]->visible
= $rawmods[$cmid]->visible
;
938 $mods[$cmid]->visibleoncoursepage
= $rawmods[$cmid]->visibleoncoursepage
;
939 $mods[$cmid]->visibleold
= $rawmods[$cmid]->visibleold
;
940 $mods[$cmid]->groupmode
= $rawmods[$cmid]->groupmode
;
941 $mods[$cmid]->groupingid
= $rawmods[$cmid]->groupingid
;
942 $mods[$cmid]->indent
= $rawmods[$cmid]->indent
;
943 $mods[$cmid]->completion
= $rawmods[$cmid]->completion
;
944 $mods[$cmid]->extra
= "";
945 $mods[$cmid]->completiongradeitemnumber
=
946 $rawmods[$cmid]->completiongradeitemnumber
;
947 $mods[$cmid]->completionpassgrade
= $rawmods[$cmid]->completionpassgrade
;
948 $mods[$cmid]->completionview
= $rawmods[$cmid]->completionview
;
949 $mods[$cmid]->completionexpected
= $rawmods[$cmid]->completionexpected
;
950 $mods[$cmid]->showdescription
= $rawmods[$cmid]->showdescription
;
951 $mods[$cmid]->availability
= $rawmods[$cmid]->availability
;
952 $mods[$cmid]->deletioninprogress
= $rawmods[$cmid]->deletioninprogress
;
953 $mods[$cmid]->downloadcontent
= $rawmods[$cmid]->downloadcontent
;
954 $mods[$cmid]->lang
= $rawmods[$cmid]->lang
;
956 $modname = $mods[$cmid]->mod
;
957 $functionname = $modname . "_get_coursemodule_info";
959 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
963 include_once("$CFG->dirroot/mod/$modname/lib.php");
965 if ($hasfunction = function_exists($functionname)) {
966 if ($info = $functionname($rawmods[$cmid])) {
967 if (!empty($info->icon
)) {
968 $mods[$cmid]->icon
= $info->icon
;
970 if (!empty($info->iconcomponent
)) {
971 $mods[$cmid]->iconcomponent
= $info->iconcomponent
;
973 if (!empty($info->name
)) {
974 $mods[$cmid]->name
= $info->name
;
976 if ($info instanceof cached_cm_info
) {
977 // When using cached_cm_info you can include three new fields.
978 // That aren't available for legacy code.
979 if (!empty($info->content
)) {
980 $mods[$cmid]->content
= $info->content
;
982 if (!empty($info->extraclasses
)) {
983 $mods[$cmid]->extraclasses
= $info->extraclasses
;
985 if (!empty($info->iconurl
)) {
986 // Convert URL to string as it's easier to store.
987 // Also serialized object contains \0 byte,
988 // ... and can not be written to Postgres DB.
989 $url = new moodle_url($info->iconurl
);
990 $mods[$cmid]->iconurl
= $url->out(false);
992 if (!empty($info->onclick
)) {
993 $mods[$cmid]->onclick
= $info->onclick
;
995 if (!empty($info->customdata
)) {
996 $mods[$cmid]->customdata
= $info->customdata
;
999 // When using a stdclass, the (horrible) deprecated ->extra field,
1000 // ... that is available for BC.
1001 if (!empty($info->extra
)) {
1002 $mods[$cmid]->extra
= $info->extra
;
1007 // When there is no modname_get_coursemodule_info function,
1008 // ... but showdescriptions is enabled, then we use the 'intro',
1009 // ... and 'introformat' fields in the module table.
1010 if (!$hasfunction && $rawmods[$cmid]->showdescription
) {
1011 if ($modvalues = $DB->get_record($rawmods[$cmid]->modname
,
1012 ['id' => $rawmods[$cmid]->instance
], 'name, intro, introformat')) {
1013 // Set content from intro and introformat. Filters are disabled.
1014 // Because we filter it with format_text at display time.
1015 $mods[$cmid]->content
= format_module_intro($rawmods[$cmid]->modname
,
1016 $modvalues, $rawmods[$cmid]->id
, false);
1018 // To save making another query just below, put name in here.
1019 $mods[$cmid]->name
= $modvalues->name
;
1022 if (!isset($mods[$cmid]->name
)) {
1023 $mods[$cmid]->name
= $DB->get_field($rawmods[$cmid]->modname
, "name",
1024 ["id" => $rawmods[$cmid]->instance
]);
1027 // Minimise the database size by unsetting default options when they are 'empty'.
1028 // This list corresponds to code in the cm_info constructor.
1029 foreach (['idnumber', 'groupmode', 'groupingid',
1030 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
1031 'icon', 'iconcomponent', 'customdata', 'availability', 'completionview',
1032 'completionexpected', 'score', 'showdescription', 'deletioninprogress'] as $property) {
1033 if (property_exists($mods[$cmid], $property) &&
1034 empty($mods[$cmid]->{$property})) {
1035 unset($mods[$cmid]->{$property});
1038 // Special case: this value is usually set to null, but may be 0.
1039 if (property_exists($mods[$cmid], 'completiongradeitemnumber') &&
1040 is_null($mods[$cmid]->completiongradeitemnumber
)) {
1041 unset($mods[$cmid]->completiongradeitemnumber
);
1051 * Purge the cache of a given course
1053 * @param int $courseid Course id
1055 public static function purge_course_cache(int $courseid): void
{
1056 increment_revision_number('course', 'cacherev', 'id = :id', array('id' => $courseid));
1057 // Because this is a versioned cache, there is no need to actually delete the cache item,
1058 // only increase the required version number.
1064 * Data about a single module on a course. This contains most of the fields in the course_modules
1065 * table, plus additional data when required.
1067 * The object can be accessed by core or any plugin (i.e. course format, block, filter, etc.) as
1068 * get_fast_modinfo($courseorid)->cms[$coursemoduleid]
1070 * get_fast_modinfo($courseorid)->instances[$moduletype][$instanceid]
1072 * There are three stages when activity module can add/modify data in this object:
1074 * <b>Stage 1 - during building the cache.</b>
1075 * Allows to add to the course cache static user-independent information about the module.
1076 * Modules should try to include only absolutely necessary information that may be required
1077 * when displaying course view page. The information is stored in application-level cache
1078 * and reset when {@link rebuild_course_cache()} is called or cache is purged by admin.
1080 * Modules can implement callback XXX_get_coursemodule_info() returning instance of object
1081 * {@link cached_cm_info}
1083 * <b>Stage 2 - dynamic data.</b>
1084 * Dynamic data is user-dependent, it is stored in request-level cache. To reset this cache
1085 * {@link get_fast_modinfo()} with $reset argument may be called.
1087 * Dynamic data is obtained when any of the following properties/methods is requested:
1088 * - {@link cm_info::$url}
1089 * - {@link cm_info::$name}
1090 * - {@link cm_info::$onclick}
1091 * - {@link cm_info::get_icon_url()}
1092 * - {@link cm_info::$uservisible}
1093 * - {@link cm_info::$available}
1094 * - {@link cm_info::$availableinfo}
1095 * - plus any of the properties listed in Stage 3.
1097 * Modules can implement callback <b>XXX_cm_info_dynamic()</b> and inside this callback they
1098 * are allowed to use any of the following set methods:
1099 * - {@link cm_info::set_available()}
1100 * - {@link cm_info::set_name()}
1101 * - {@link cm_info::set_no_view_link()}
1102 * - {@link cm_info::set_user_visible()}
1103 * - {@link cm_info::set_on_click()}
1104 * - {@link cm_info::set_icon_url()}
1105 * - {@link cm_info::override_customdata()}
1106 * Any methods affecting view elements can also be set in this callback.
1108 * <b>Stage 3 (view data).</b>
1109 * Also user-dependend data stored in request-level cache. Second stage is created
1110 * because populating the view data can be expensive as it may access much more
1111 * Moodle APIs such as filters, user information, output renderers and we
1112 * don't want to request it until necessary.
1113 * View data is obtained when any of the following properties/methods is requested:
1114 * - {@link cm_info::$afterediticons}
1115 * - {@link cm_info::$content}
1116 * - {@link cm_info::get_formatted_content()}
1117 * - {@link cm_info::$extraclasses}
1118 * - {@link cm_info::$afterlink}
1120 * Modules can implement callback <b>XXX_cm_info_view()</b> and inside this callback they
1121 * are allowed to use any of the following set methods:
1122 * - {@link cm_info::set_after_edit_icons()}
1123 * - {@link cm_info::set_after_link()}
1124 * - {@link cm_info::set_content()}
1125 * - {@link cm_info::set_extra_classes()}
1127 * @property-read int $id Course-module ID - from course_modules table
1128 * @property-read int $instance Module instance (ID within module table) - from course_modules table
1129 * @property-read int $course Course ID - from course_modules table
1130 * @property-read string $idnumber 'ID number' from course-modules table (arbitrary text set by user) - from
1131 * course_modules table
1132 * @property-read int $added Time that this course-module was added (unix time) - from course_modules table
1133 * @property-read int $visible Visible setting (0 or 1; if this is 0, students cannot see/access the activity) - from
1134 * course_modules table
1135 * @property-read int $visibleoncoursepage Visible on course page setting - from course_modules table, adjusted to
1136 * whether course format allows this module to have the "stealth" mode
1137 * @property-read int $visibleold Old visible setting (if the entire section is hidden, the previous value for
1138 * visible is stored in this field) - from course_modules table
1139 * @property-read int $groupmode Group mode (one of the constants NOGROUPS, SEPARATEGROUPS, or VISIBLEGROUPS) - from
1140 * course_modules table. Use {@link cm_info::$effectivegroupmode} to find the actual group mode that may be forced by course.
1141 * @property-read int $groupingid Grouping ID (0 = all groupings)
1142 * @property-read bool $coursegroupmodeforce Indicates whether the course containing the module has forced the groupmode
1143 * This means that cm_info::$groupmode should be ignored and cm_info::$coursegroupmode be used instead
1144 * @property-read int $coursegroupmode Group mode (one of the constants NOGROUPS, SEPARATEGROUPS, or VISIBLEGROUPS) - from
1145 * course table - as specified for the course containing the module
1146 * Effective only if {@link cm_info::$coursegroupmodeforce} is set
1147 * @property-read int $effectivegroupmode Effective group mode for this module (one of the constants NOGROUPS, SEPARATEGROUPS,
1148 * or VISIBLEGROUPS). This can be different from groupmode set for the module if the groupmode is forced for the course.
1149 * This value will always be NOGROUPS if module type does not support group mode.
1150 * @property-read int $indent Indent level on course page (0 = no indent) - from course_modules table
1151 * @property-read int $completion Activity completion setting for this activity, COMPLETION_TRACKING_xx constant - from
1152 * course_modules table
1153 * @property-read mixed $completiongradeitemnumber Set to the item number (usually 0) if completion depends on a particular
1154 * grade of this activity, or null if completion does not depend on a grade - from course_modules table
1155 * @property-read int $completionview 1 if 'on view' completion is enabled, 0 otherwise - from course_modules table
1156 * @property-read int $completionexpected Set to a unix time if completion of this activity is expected at a
1157 * particular time, 0 if no time set - from course_modules table
1158 * @property-read string $availability Availability information as JSON string or null if none -
1159 * from course_modules table
1160 * @property-read int $showdescription Controls whether the description of the activity displays on the course main page (in
1161 * addition to anywhere it might display within the activity itself). 0 = do not show
1162 * on main page, 1 = show on main page.
1163 * @property-read string $extra (deprecated) Extra HTML that is put in an unhelpful part of the HTML when displaying this module in
1164 * course page - from cached data in modinfo field. Deprecated, replaced by ->extraclasses and ->onclick
1165 * @property-read string $icon Name of icon to use - from cached data in modinfo field
1166 * @property-read string $iconcomponent Component that contains icon - from cached data in modinfo field
1167 * @property-read string $modname Name of module e.g. 'forum' (this is the same name as the module's main database
1168 * table) - from cached data in modinfo field
1169 * @property-read int $module ID of module type - from course_modules table
1170 * @property-read string $name Name of module instance for display on page e.g. 'General discussion forum' - from cached
1171 * data in modinfo field
1172 * @property-read int $sectionnum Section number that this course-module is in (section 0 = above the calendar, section 1
1173 * = week/topic 1, etc) - from cached data in modinfo field
1174 * @property-read int $sectionid Section id - from course_modules table
1175 * @property-read array $conditionscompletion Availability conditions for this course-module based on the completion of other
1176 * course-modules (array from other course-module id to required completion state for that
1177 * module) - from cached data in modinfo field
1178 * @property-read array $conditionsgrade Availability conditions for this course-module based on course grades (array from
1179 * grade item id to object with ->min, ->max fields) - from cached data in modinfo field
1180 * @property-read array $conditionsfield Availability conditions for this course-module based on user fields
1181 * @property-read bool $available True if this course-module is available to students i.e. if all availability conditions
1182 * are met - obtained dynamically
1183 * @property-read string $availableinfo If course-module is not available to students, this string gives information about
1184 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
1185 * January 2010') for display on main page - obtained dynamically
1186 * @property-read bool $uservisible True if this course-module is available to the CURRENT user (for example, if current user
1187 * has viewhiddenactivities capability, they can access the course-module even if it is not
1188 * visible or not available, so this would be true in that case)
1189 * @property-read context_module $context Module context
1190 * @property-read string $modfullname Returns a localised human-readable name of the module type - calculated on request
1191 * @property-read string $modplural Returns a localised human-readable name of the module type in plural form - calculated on request
1192 * @property-read string $content Content to display on main (view) page - calculated on request
1193 * @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
1194 * @property-read string $extraclasses Extra CSS classes to add to html output for this activity on main page - calculated on request
1195 * @property-read string $onclick Content of HTML on-click attribute already escaped - calculated on request
1196 * @property-read mixed $customdata Optional custom data stored in modinfo cache for this activity, or null if none
1197 * @property-read string $afterlink Extra HTML code to display after link - calculated on request
1198 * @property-read string $afterediticons Extra HTML code to display after editing icons (e.g. more icons) - calculated on request
1199 * @property-read bool $deletioninprogress True if this course module is scheduled for deletion, false otherwise.
1200 * @property-read bool $downloadcontent True if content download is enabled for this course module, false otherwise.
1201 * @property-read bool $lang the forced language for this activity (language pack name). Null means not forced.
1203 class cm_info
implements IteratorAggregate
{
1205 * State: Only basic data from modinfo cache is available.
1207 const STATE_BASIC
= 0;
1210 * State: In the process of building dynamic data (to avoid recursive calls to obtain_dynamic_data())
1212 const STATE_BUILDING_DYNAMIC
= 1;
1215 * State: Dynamic data is available too.
1217 const STATE_DYNAMIC
= 2;
1220 * State: In the process of building view data (to avoid recursive calls to obtain_view_data())
1222 const STATE_BUILDING_VIEW
= 3;
1225 * State: View data (for course page) is available.
1227 const STATE_VIEW
= 4;
1231 * @var course_modinfo
1236 * Level of information stored inside this object (STATE_xx constant)
1242 * Course-module ID - from course_modules table
1248 * Module instance (ID within module table) - from course_modules table
1254 * 'ID number' from course-modules table (arbitrary text set by user) - from
1255 * course_modules table
1261 * Time that this course-module was added (unix time) - from course_modules table
1267 * This variable is not used and is included here only so it can be documented.
1268 * Once the database entry is removed from course_modules, it should be deleted
1271 * @deprecated Do not use this variable
1276 * Visible setting (0 or 1; if this is 0, students cannot see/access the activity) - from
1277 * course_modules table
1283 * Visible on course page setting - from course_modules table
1286 private $visibleoncoursepage;
1289 * Old visible setting (if the entire section is hidden, the previous value for
1290 * visible is stored in this field) - from course_modules table
1293 private $visibleold;
1296 * Group mode (one of the constants NONE, SEPARATEGROUPS, or VISIBLEGROUPS) - from
1297 * course_modules table
1303 * Grouping ID (0 = all groupings)
1306 private $groupingid;
1309 * Indent level on course page (0 = no indent) - from course_modules table
1315 * Activity completion setting for this activity, COMPLETION_TRACKING_xx constant - from
1316 * course_modules table
1319 private $completion;
1322 * Set to the item number (usually 0) if completion depends on a particular
1323 * grade of this activity, or null if completion does not depend on a grade - from
1324 * course_modules table
1327 private $completiongradeitemnumber;
1330 * 1 if pass grade completion is enabled, 0 otherwise - from course_modules table
1333 private $completionpassgrade;
1336 * 1 if 'on view' completion is enabled, 0 otherwise - from course_modules table
1339 private $completionview;
1342 * Set to a unix time if completion of this activity is expected at a
1343 * particular time, 0 if no time set - from course_modules table
1346 private $completionexpected;
1349 * Availability information as JSON string or null if none - from course_modules table
1352 private $availability;
1355 * Controls whether the description of the activity displays on the course main page (in
1356 * addition to anywhere it might display within the activity itself). 0 = do not show
1357 * on main page, 1 = show on main page.
1360 private $showdescription;
1363 * Extra HTML that is put in an unhelpful part of the HTML when displaying this module in
1364 * course page - from cached data in modinfo field
1365 * @deprecated This is crazy, don't use it. Replaced by ->extraclasses and ->onclick
1371 * Name of icon to use - from cached data in modinfo field
1377 * Component that contains icon - from cached data in modinfo field
1380 private $iconcomponent;
1383 * Name of module e.g. 'forum' (this is the same name as the module's main database
1384 * table) - from cached data in modinfo field
1390 * ID of module - from course_modules table
1396 * Name of module instance for display on page e.g. 'General discussion forum' - from cached
1397 * data in modinfo field
1403 * Section number that this course-module is in (section 0 = above the calendar, section 1
1404 * = week/topic 1, etc) - from cached data in modinfo field
1407 private $sectionnum;
1410 * Section id - from course_modules table
1416 * Availability conditions for this course-module based on the completion of other
1417 * course-modules (array from other course-module id to required completion state for that
1418 * module) - from cached data in modinfo field
1421 private $conditionscompletion;
1424 * Availability conditions for this course-module based on course grades (array from
1425 * grade item id to object with ->min, ->max fields) - from cached data in modinfo field
1428 private $conditionsgrade;
1431 * Availability conditions for this course-module based on user fields
1434 private $conditionsfield;
1437 * True if this course-module is available to students i.e. if all availability conditions
1438 * are met - obtained dynamically
1444 * If course-module is not available to students, this string gives information about
1445 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
1446 * January 2010') for display on main page - obtained dynamically
1449 private $availableinfo;
1452 * True if this course-module is available to the CURRENT user (for example, if current user
1453 * has viewhiddenactivities capability, they can access the course-module even if it is not
1454 * visible or not available, so this would be true in that case)
1457 private $uservisible;
1460 * True if this course-module is visible to the CURRENT user on the course page
1463 private $uservisibleoncoursepage;
1478 private $contentisformatted;
1481 * @var bool True if the content has a special course item display like labels.
1483 private $customcmlistitem;
1488 private $extraclasses;
1491 * @var moodle_url full external url pointing to icon image for activity
1503 private $customdata;
1513 private $afterediticons;
1516 * @var bool representing the deletion state of the module. True if the mod is scheduled for deletion.
1518 private $deletioninprogress;
1521 * @var int enable/disable download content for this course module
1523 private $downloadcontent;
1526 * @var string|null the forced language for this activity (language pack name). Null means not forced.
1531 * List of class read-only properties and their getter methods.
1532 * Used by magic functions __get(), __isset(), __empty()
1535 private static $standardproperties = [
1537 'content' => 'get_content',
1538 'extraclasses' => 'get_extra_classes',
1539 'onclick' => 'get_on_click',
1540 'customdata' => 'get_custom_data',
1541 'afterlink' => 'get_after_link',
1542 'afterediticons' => 'get_after_edit_icons',
1543 'modfullname' => 'get_module_type_name',
1544 'modplural' => 'get_module_type_name_plural',
1547 'availability' => false,
1548 'available' => 'get_available',
1549 'availableinfo' => 'get_available_info',
1550 'completion' => false,
1551 'completionexpected' => false,
1552 'completiongradeitemnumber' => false,
1553 'completionpassgrade' => false,
1554 'completionview' => false,
1555 'conditionscompletion' => false,
1556 'conditionsfield' => false,
1557 'conditionsgrade' => false,
1558 'context' => 'get_context',
1559 'course' => 'get_course_id',
1560 'coursegroupmode' => 'get_course_groupmode',
1561 'coursegroupmodeforce' => 'get_course_groupmodeforce',
1562 'customcmlistitem' => 'has_custom_cmlist_item',
1563 'effectivegroupmode' => 'get_effective_groupmode',
1565 'groupingid' => false,
1566 'groupmembersonly' => 'get_deprecated_group_members_only',
1567 'groupmode' => false,
1569 'iconcomponent' => false,
1570 'idnumber' => false,
1572 'instance' => false,
1575 'name' => 'get_name',
1577 'section' => 'get_section_id',
1578 'sectionid' => false,
1579 'sectionnum' => false,
1580 'showdescription' => false,
1581 'uservisible' => 'get_user_visible',
1583 'visibleoncoursepage' => false,
1584 'visibleold' => false,
1585 'deletioninprogress' => false,
1586 'downloadcontent' => false,
1591 * List of methods with no arguments that were public prior to Moodle 2.6.
1593 * They can still be accessed publicly via magic __call() function with no warnings
1594 * but are not listed in the class methods list.
1595 * For the consistency of the code it is better to use corresponding properties.
1597 * These methods be deprecated completely in later versions.
1599 * @var array $standardmethods
1601 private static $standardmethods = array(
1602 // Following methods are not recommended to use because there have associated read-only properties.
1605 'get_extra_classes',
1609 'get_after_edit_icons',
1610 // Method obtain_dynamic_data() should not be called from outside of this class but it was public before Moodle 2.6.
1611 'obtain_dynamic_data',
1615 * Magic method to call functions that are now declared as private but were public in Moodle before 2.6.
1616 * These private methods can not be used anymore.
1618 * @param string $name
1619 * @param array $arguments
1621 * @throws coding_exception
1623 public function __call($name, $arguments) {
1624 if (in_array($name, self
::$standardmethods)) {
1625 $message = "cm_info::$name() can not be used anymore.";
1626 if ($alternative = array_search($name, self
::$standardproperties)) {
1627 $message .= " Please use the property cm_info->$alternative instead.";
1629 throw new coding_exception($message);
1631 throw new coding_exception("Method cm_info::{$name}() does not exist");
1635 * Magic method getter
1637 * @param string $name
1640 public function __get($name) {
1641 if (isset(self
::$standardproperties[$name])) {
1642 if ($method = self
::$standardproperties[$name]) {
1643 return $this->$method();
1645 return $this->$name;
1648 debugging('Invalid cm_info property accessed: '.$name);
1654 * Implementation of IteratorAggregate::getIterator(), allows to cycle through properties
1655 * and use {@link convert_to_array()}
1657 * @return ArrayIterator
1659 public function getIterator(): Traversable
{
1660 // Make sure dynamic properties are retrieved prior to view properties.
1661 $this->obtain_dynamic_data();
1664 // Do not iterate over deprecated properties.
1665 $props = self
::$standardproperties;
1666 unset($props['groupmembersonly']);
1668 foreach ($props as $key => $unused) {
1669 $ret[$key] = $this->__get($key);
1671 return new ArrayIterator($ret);
1675 * Magic method for function isset()
1677 * @param string $name
1680 public function __isset($name) {
1681 if (isset(self
::$standardproperties[$name])) {
1682 $value = $this->__get($name);
1683 return isset($value);
1689 * Magic method for function empty()
1691 * @param string $name
1694 public function __empty($name) {
1695 if (isset(self
::$standardproperties[$name])) {
1696 $value = $this->__get($name);
1697 return empty($value);
1703 * Magic method setter
1705 * Will display the developer warning when trying to set/overwrite property.
1707 * @param string $name
1708 * @param mixed $value
1710 public function __set($name, $value) {
1711 debugging("It is not allowed to set the property cm_info::\${$name}", DEBUG_DEVELOPER
);
1715 * @return bool True if this module has a 'view' page that should be linked to in navigation
1716 * etc (note: modules may still have a view.php file, but return false if this is not
1717 * intended to be linked to from 'normal' parts of the interface; this is what label does).
1719 public function has_view() {
1720 return !is_null($this->url
);
1724 * Gets the URL to link to for this module.
1726 * This method is normally called by the property ->url, but can be called directly if
1727 * there is a case when it might be called recursively (you can't call property values
1730 * @return moodle_url URL to link to for this module, or null if it doesn't have a view page
1732 public function get_url() {
1733 $this->obtain_dynamic_data();
1738 * Obtains content to display on main (view) page.
1739 * Note: Will collect view data, if not already obtained.
1740 * @return string Content to display on main page below link, or empty string if none
1742 private function get_content() {
1743 $this->obtain_view_data();
1744 return $this->content
;
1748 * Returns the content to display on course/overview page, formatted and passed through filters
1750 * if $options['context'] is not specified, the module context is used
1752 * @param array|stdClass $options formatting options, see {@link format_text()}
1755 public function get_formatted_content($options = array()) {
1756 $this->obtain_view_data();
1757 if (empty($this->content
)) {
1760 if ($this->contentisformatted
) {
1761 return $this->content
;
1764 // Improve filter performance by preloading filter setttings for all
1765 // activities on the course (this does nothing if called multiple
1767 filter_preload_activities($this->get_modinfo());
1769 $options = (array)$options;
1770 if (!isset($options['context'])) {
1771 $options['context'] = $this->get_context();
1773 return format_text($this->content
, FORMAT_HTML
, $options);
1777 * Return the module custom cmlist item flag.
1779 * Activities like label uses this flag to indicate that it should be
1780 * displayed as a custom course item instead of a tipical activity card.
1784 public function has_custom_cmlist_item(): bool {
1785 $this->obtain_view_data();
1786 return $this->customcmlistitem ??
false;
1790 * Getter method for property $name, ensures that dynamic data is obtained.
1792 * This method is normally called by the property ->name, but can be called directly if there
1793 * is a case when it might be called recursively (you can't call property values recursively).
1797 public function get_name() {
1798 $this->obtain_dynamic_data();
1803 * Returns the name to display on course/overview page, formatted and passed through filters
1805 * if $options['context'] is not specified, the module context is used
1807 * @param array|stdClass $options formatting options, see {@link format_string()}
1810 public function get_formatted_name($options = array()) {
1812 $options = (array)$options;
1813 if (!isset($options['context'])) {
1814 $options['context'] = $this->get_context();
1816 // Improve filter performance by preloading filter setttings for all
1817 // activities on the course (this does nothing if called multiple
1819 if (!empty($CFG->filterall
)) {
1820 filter_preload_activities($this->get_modinfo());
1822 return format_string($this->get_name(), true, $options);
1826 * Note: Will collect view data, if not already obtained.
1827 * @return string Extra CSS classes to add to html output for this activity on main page
1829 private function get_extra_classes() {
1830 $this->obtain_view_data();
1831 return $this->extraclasses
;
1835 * @return string Content of HTML on-click attribute. This string will be used literally
1836 * as a string so should be pre-escaped.
1838 private function get_on_click() {
1839 // Does not need view data; may be used by navigation
1840 $this->obtain_dynamic_data();
1841 return $this->onclick
;
1844 * Getter method for property $customdata, ensures that dynamic data is retrieved.
1846 * This method is normally called by the property ->customdata, but can be called directly if there
1847 * is a case when it might be called recursively (you can't call property values recursively).
1849 * @return mixed Optional custom data stored in modinfo cache for this activity, or null if none
1851 public function get_custom_data() {
1852 $this->obtain_dynamic_data();
1853 return $this->customdata
;
1857 * Note: Will collect view data, if not already obtained.
1858 * @return string Extra HTML code to display after link
1860 private function get_after_link() {
1861 $this->obtain_view_data();
1862 return $this->afterlink
;
1866 * Get the activity badge data associated to this course module (if the module supports it).
1867 * Modules can use this method to provide additional data to be displayed in the activity badge.
1869 * @param renderer_base $output Output render to use, or null for default (global)
1870 * @return stdClass|null The activitybadge data (badgecontent, badgestyle...) or null if the module doesn't implement it.
1872 public function get_activitybadge(?renderer_base
$output = null): ?stdClass
{
1875 $activibybadgeclass = activitybadge
::create_instance($this);
1876 if (empty($activibybadgeclass)) {
1880 if (!isset($output)) {
1884 return $activibybadgeclass->export_for_template($output);
1888 * Note: Will collect view data, if not already obtained.
1889 * @return string Extra HTML code to display after editing icons (e.g. more icons)
1891 private function get_after_edit_icons() {
1892 $this->obtain_view_data();
1893 return $this->afterediticons
;
1897 * Fetch the module's icon URL.
1899 * This function fetches the course module instance's icon URL.
1900 * This method adds a `filtericon` parameter in the URL when rendering the monologo version of the course module icon or when
1901 * the plugin declares, via its `filtericon` custom data, that the icon needs to be filtered.
1902 * This additional information can be used by plugins when rendering the module icon to determine whether to apply
1903 * CSS filtering to the icon.
1905 * @param core_renderer $output Output render to use, or null for default (global)
1906 * @return moodle_url Icon URL for a suitable icon to put beside this cm
1908 public function get_icon_url($output = null) {
1910 $this->obtain_dynamic_data();
1915 $ismonologo = false;
1916 if (!empty($this->iconurl
)) {
1917 // Support modules setting their own, external, icon image.
1918 $icon = $this->iconurl
;
1919 } else if (!empty($this->icon
)) {
1920 // Fallback to normal local icon + component processing.
1921 if (substr($this->icon
, 0, 4) === 'mod/') {
1922 list($modname, $iconname) = explode('/', substr($this->icon
, 4), 2);
1923 $icon = $output->image_url($iconname, $modname);
1925 if (!empty($this->iconcomponent
)) {
1926 // Icon has specified component.
1927 $icon = $output->image_url($this->icon
, $this->iconcomponent
);
1929 // Icon does not have specified component, use default.
1930 $icon = $output->image_url($this->icon
);
1934 $icon = $output->image_url('monologo', $this->modname
);
1935 // Activity modules may only have an `icon` icon instead of a `monologo` icon.
1936 // So we need to determine if the module really has a `monologo` icon.
1937 $ismonologo = core_component
::has_monologo_icon('mod', $this->modname
);
1940 // Determine whether the icon will be filtered in the CSS.
1941 // This can be controlled by the module by declaring a 'filtericon' custom data.
1942 // If the 'filtericon' custom data is not set, icon filtering will be determined whether the module has a `monologo` icon.
1943 // Additionally, we need to cast custom data to array as some modules may treat it as an object.
1944 $filtericon = ((array)$this->customdata
)['filtericon'] ??
$ismonologo;
1946 $icon->param('filtericon', 1);
1952 * @param string $textclasses additionnal classes for grouping label
1953 * @return string An empty string or HTML grouping label span tag
1955 public function get_grouping_label($textclasses = '') {
1956 $groupinglabel = '';
1957 if ($this->effectivegroupmode
!= NOGROUPS
&& !empty($this->groupingid
) &&
1958 has_capability('moodle/course:managegroups', context_course
::instance($this->course
))) {
1959 $groupings = groups_get_all_groupings($this->course
);
1960 $groupinglabel = html_writer
::tag('span', '('.format_string($groupings[$this->groupingid
]->name
).')',
1961 array('class' => 'groupinglabel '.$textclasses));
1963 return $groupinglabel;
1967 * Returns a localised human-readable name of the module type.
1969 * @param bool $plural If true, the function returns the plural form of the name.
1970 * @return lang_string
1972 public function get_module_type_name($plural = false) {
1973 $modnames = get_module_types_names($plural);
1974 if (isset($modnames[$this->modname
])) {
1975 return $modnames[$this->modname
];
1982 * Returns a localised human-readable name of the module type in plural form - calculated on request
1986 private function get_module_type_name_plural() {
1987 return $this->get_module_type_name(true);
1991 * @return course_modinfo Modinfo object that this came from
1993 public function get_modinfo() {
1994 return $this->modinfo
;
1998 * Returns the section this module belongs to
2000 * @return section_info
2002 public function get_section_info() {
2003 return $this->modinfo
->get_section_info_by_id($this->sectionid
);
2007 * Getter method for property $section that returns section id.
2009 * This method is called by the property ->section.
2013 private function get_section_id(): int {
2014 return $this->sectionid
;
2018 * Returns course object that was used in the first {@link get_fast_modinfo()} call.
2020 * It may not contain all fields from DB table {course} but always has at least the following:
2021 * id,shortname,fullname,format,enablecompletion,groupmode,groupmodeforce,cacherev
2023 * If the course object lacks the field you need you can use the global
2024 * function {@link get_course()} that will save extra query if you access
2025 * current course or frontpage course.
2029 public function get_course() {
2030 return $this->modinfo
->get_course();
2034 * Returns course id for which the modinfo was generated.
2038 private function get_course_id() {
2039 return $this->modinfo
->get_course_id();
2043 * Returns group mode used for the course containing the module
2045 * @return int one of constants NOGROUPS, SEPARATEGROUPS, VISIBLEGROUPS
2047 private function get_course_groupmode() {
2048 return $this->modinfo
->get_course()->groupmode
;
2052 * Returns whether group mode is forced for the course containing the module
2056 private function get_course_groupmodeforce() {
2057 return $this->modinfo
->get_course()->groupmodeforce
;
2061 * Returns effective groupmode of the module that may be overwritten by forced course groupmode.
2063 * @return int one of constants NOGROUPS, SEPARATEGROUPS, VISIBLEGROUPS
2065 private function get_effective_groupmode() {
2066 $groupmode = $this->groupmode
;
2067 if ($this->modinfo
->get_course()->groupmodeforce
) {
2068 $groupmode = $this->modinfo
->get_course()->groupmode
;
2069 if ($groupmode != NOGROUPS
&& !plugin_supports('mod', $this->modname
, FEATURE_GROUPS
, false)) {
2070 $groupmode = NOGROUPS
;
2077 * @return context_module Current module context
2079 private function get_context() {
2080 return context_module
::instance($this->id
);
2084 * Returns itself in the form of stdClass.
2086 * The object includes all fields that table course_modules has and additionally
2087 * fields 'name', 'modname', 'sectionnum' (if requested).
2089 * This can be used as a faster alternative to {@link get_coursemodule_from_id()}
2091 * @param bool $additionalfields include additional fields 'name', 'modname', 'sectionnum'
2094 public function get_course_module_record($additionalfields = false) {
2095 $cmrecord = new stdClass();
2097 // Standard fields from table course_modules.
2098 static $cmfields = array('id', 'course', 'module', 'instance', 'section', 'idnumber', 'added',
2099 'score', 'indent', 'visible', 'visibleoncoursepage', 'visibleold', 'groupmode', 'groupingid',
2100 'completion', 'completiongradeitemnumber', 'completionview', 'completionexpected', 'completionpassgrade',
2101 'showdescription', 'availability', 'deletioninprogress', 'downloadcontent', 'lang');
2103 foreach ($cmfields as $key) {
2104 $cmrecord->$key = $this->$key;
2107 // Additional fields that function get_coursemodule_from_id() adds.
2108 if ($additionalfields) {
2109 $cmrecord->name
= $this->name
;
2110 $cmrecord->modname
= $this->modname
;
2111 $cmrecord->sectionnum
= $this->sectionnum
;
2121 * Sets content to display on course view page below link (if present).
2122 * @param string $content New content as HTML string (empty string if none)
2123 * @param bool $isformatted Whether user content is already passed through format_text/format_string and should not
2124 * be formatted again. This can be useful when module adds interactive elements on top of formatted user text.
2127 public function set_content($content, $isformatted = false) {
2128 $this->content
= $content;
2129 $this->contentisformatted
= $isformatted;
2133 * Sets extra classes to include in CSS.
2134 * @param string $extraclasses Extra classes (empty string if none)
2137 public function set_extra_classes($extraclasses) {
2138 $this->extraclasses
= $extraclasses;
2142 * Sets the external full url that points to the icon being used
2143 * by the activity. Useful for external-tool modules (lti...)
2144 * If set, takes precedence over $icon and $iconcomponent
2146 * @param moodle_url $iconurl full external url pointing to icon image for activity
2149 public function set_icon_url(moodle_url
$iconurl) {
2150 $this->iconurl
= $iconurl;
2154 * Sets value of on-click attribute for JavaScript.
2155 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
2156 * @param string $onclick New onclick attribute which should be HTML-escaped
2157 * (empty string if none)
2160 public function set_on_click($onclick) {
2161 $this->check_not_view_only();
2162 $this->onclick
= $onclick;
2166 * Overrides the value of an element in the customdata array.
2168 * @param string $name The key in the customdata array
2169 * @param mixed $value The value
2171 public function override_customdata($name, $value) {
2172 if (!is_array($this->customdata
)) {
2173 $this->customdata
= [];
2175 $this->customdata
[$name] = $value;
2179 * Sets HTML that displays after link on course view page.
2180 * @param string $afterlink HTML string (empty string if none)
2183 public function set_after_link($afterlink) {
2184 $this->afterlink
= $afterlink;
2188 * Sets HTML that displays after edit icons on course view page.
2189 * @param string $afterediticons HTML string (empty string if none)
2192 public function set_after_edit_icons($afterediticons) {
2193 $this->afterediticons
= $afterediticons;
2197 * Changes the name (text of link) for this module instance.
2198 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
2199 * @param string $name Name of activity / link text
2202 public function set_name($name) {
2203 if ($this->state
< self
::STATE_BUILDING_DYNAMIC
) {
2204 $this->update_user_visible();
2206 $this->name
= $name;
2210 * Turns off the view link for this module instance.
2211 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
2214 public function set_no_view_link() {
2215 $this->check_not_view_only();
2220 * Sets the 'uservisible' flag. This can be used (by setting false) to prevent access and
2221 * display of this module link for the current user.
2222 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
2223 * @param bool $uservisible
2226 public function set_user_visible($uservisible) {
2227 $this->check_not_view_only();
2228 $this->uservisible
= $uservisible;
2232 * Sets the 'customcmlistitem' flag
2234 * This can be used (by setting true) to prevent the course from rendering the
2235 * activity item as a regular activity card. This is applied to activities like labels.
2237 * @param bool $customcmlistitem if the cmlist item of that activity has a special dysplay other than a card.
2239 public function set_custom_cmlist_item(bool $customcmlistitem) {
2240 $this->customcmlistitem
= $customcmlistitem;
2244 * Sets the 'available' flag and related details. This flag is normally used to make
2245 * course modules unavailable until a certain date or condition is met. (When a course
2246 * module is unavailable, it is still visible to users who have viewhiddenactivities
2249 * When this is function is called, user-visible status is recalculated automatically.
2251 * The $showavailability flag does not really do anything any more, but is retained
2252 * for backward compatibility. Setting this to false will cause $availableinfo to
2255 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
2256 * @param bool $available False if this item is not 'available'
2257 * @param int $showavailability 0 = do not show this item at all if it's not available,
2258 * 1 = show this item greyed out with the following message
2259 * @param string $availableinfo Information about why this is not available, or
2260 * empty string if not displaying
2263 public function set_available($available, $showavailability=0, $availableinfo='') {
2264 $this->check_not_view_only();
2265 $this->available
= $available;
2266 if (!$showavailability) {
2267 $availableinfo = '';
2269 $this->availableinfo
= $availableinfo;
2270 $this->update_user_visible();
2274 * Some set functions can only be called from _cm_info_dynamic and not _cm_info_view.
2275 * This is because they may affect parts of this object which are used on pages other
2276 * than the view page (e.g. in the navigation block, or when checking access on
2280 private function check_not_view_only() {
2281 if ($this->state
>= self
::STATE_DYNAMIC
) {
2282 throw new coding_exception('Cannot set this data from _cm_info_view because it may ' .
2283 'affect other pages as well as view');
2288 * Constructor should not be called directly; use {@link get_fast_modinfo()}
2290 * @param course_modinfo $modinfo Parent object
2291 * @param stdClass $notused1 Argument not used
2292 * @param stdClass $mod Module object from the modinfo field of course table
2293 * @param stdClass $notused2 Argument not used
2295 public function __construct(course_modinfo
$modinfo, $notused1, $mod, $notused2) {
2296 $this->modinfo
= $modinfo;
2298 $this->id
= $mod->cm
;
2299 $this->instance
= $mod->id
;
2300 $this->modname
= $mod->mod
;
2301 $this->idnumber
= isset($mod->idnumber
) ?
$mod->idnumber
: '';
2302 $this->name
= $mod->name
;
2303 $this->visible
= $mod->visible
;
2304 $this->visibleoncoursepage
= $mod->visibleoncoursepage
;
2305 $this->sectionnum
= $mod->section
; // Note weirdness with name here. Keeping for backwards compatibility.
2306 $this->groupmode
= isset($mod->groupmode
) ?
$mod->groupmode
: 0;
2307 $this->groupingid
= isset($mod->groupingid
) ?
$mod->groupingid
: 0;
2308 $this->indent
= isset($mod->indent
) ?
$mod->indent
: 0;
2309 $this->extra
= isset($mod->extra
) ?
$mod->extra
: '';
2310 $this->extraclasses
= isset($mod->extraclasses
) ?
$mod->extraclasses
: '';
2311 // iconurl may be stored as either string or instance of moodle_url.
2312 $this->iconurl
= isset($mod->iconurl
) ?
new moodle_url($mod->iconurl
) : '';
2313 $this->onclick
= isset($mod->onclick
) ?
$mod->onclick
: '';
2314 $this->content
= isset($mod->content
) ?
$mod->content
: '';
2315 $this->icon
= isset($mod->icon
) ?
$mod->icon
: '';
2316 $this->iconcomponent
= isset($mod->iconcomponent
) ?
$mod->iconcomponent
: '';
2317 $this->customdata
= isset($mod->customdata
) ?
$mod->customdata
: '';
2318 $this->showdescription
= isset($mod->showdescription
) ?
$mod->showdescription
: 0;
2319 $this->state
= self
::STATE_BASIC
;
2321 $this->sectionid
= isset($mod->sectionid
) ?
$mod->sectionid
: 0;
2322 $this->module
= isset($mod->module
) ?
$mod->module
: 0;
2323 $this->added
= isset($mod->added
) ?
$mod->added
: 0;
2324 $this->score
= isset($mod->score
) ?
$mod->score
: 0;
2325 $this->visibleold
= isset($mod->visibleold
) ?
$mod->visibleold
: 0;
2326 $this->deletioninprogress
= isset($mod->deletioninprogress
) ?
$mod->deletioninprogress
: 0;
2327 $this->downloadcontent
= $mod->downloadcontent ??
null;
2328 $this->lang
= $mod->lang ??
null;
2330 // Note: it saves effort and database space to always include the
2331 // availability and completion fields, even if availability or completion
2332 // are actually disabled
2333 $this->completion
= isset($mod->completion
) ?
$mod->completion
: 0;
2334 $this->completionpassgrade
= isset($mod->completionpassgrade
) ?
$mod->completionpassgrade
: 0;
2335 $this->completiongradeitemnumber
= isset($mod->completiongradeitemnumber
)
2336 ?
$mod->completiongradeitemnumber
: null;
2337 $this->completionview
= isset($mod->completionview
)
2338 ?
$mod->completionview
: 0;
2339 $this->completionexpected
= isset($mod->completionexpected
)
2340 ?
$mod->completionexpected
: 0;
2341 $this->availability
= isset($mod->availability
) ?
$mod->availability
: null;
2342 $this->conditionscompletion
= isset($mod->conditionscompletion
)
2343 ?
$mod->conditionscompletion
: array();
2344 $this->conditionsgrade
= isset($mod->conditionsgrade
)
2345 ?
$mod->conditionsgrade
: array();
2346 $this->conditionsfield
= isset($mod->conditionsfield
)
2347 ?
$mod->conditionsfield
: array();
2349 static $modviews = array();
2350 if (!isset($modviews[$this->modname
])) {
2351 $modviews[$this->modname
] = !plugin_supports('mod', $this->modname
,
2352 FEATURE_NO_VIEW_LINK
);
2354 $this->url
= $modviews[$this->modname
]
2355 ?
new moodle_url('/mod/' . $this->modname
. '/view.php', array('id'=>$this->id
))
2360 * Creates a cm_info object from a database record (also accepts cm_info
2361 * in which case it is just returned unchanged).
2363 * @param stdClass|cm_info|null|bool $cm Stdclass or cm_info (or null or false)
2364 * @param int $userid Optional userid (default to current)
2365 * @return cm_info|null Object as cm_info, or null if input was null/false
2367 public static function create($cm, $userid = 0) {
2368 // Null, false, etc. gets passed through as null.
2372 // If it is already a cm_info object, just return it.
2373 if ($cm instanceof cm_info
) {
2376 // Otherwise load modinfo.
2377 if (empty($cm->id
) ||
empty($cm->course
)) {
2378 throw new coding_exception('$cm must contain ->id and ->course');
2380 $modinfo = get_fast_modinfo($cm->course
, $userid);
2381 return $modinfo->get_cm($cm->id
);
2385 * If dynamic data for this course-module is not yet available, gets it.
2387 * This function is automatically called when requesting any course_modinfo property
2388 * that can be modified by modules (have a set_xxx method).
2390 * Dynamic data is data which does not come directly from the cache but is calculated at
2391 * runtime based on the current user. Primarily this concerns whether the user can access
2392 * the module or not.
2394 * As part of this function, the module's _cm_info_dynamic function from its lib.php will
2395 * be called (if it exists). Make sure that the functions that are called here do not use
2396 * any getter magic method from cm_info.
2399 private function obtain_dynamic_data() {
2401 $userid = $this->modinfo
->get_user_id();
2402 if ($this->state
>= self
::STATE_BUILDING_DYNAMIC ||
$userid == -1) {
2405 $this->state
= self
::STATE_BUILDING_DYNAMIC
;
2407 if (!empty($CFG->enableavailability
)) {
2408 // Get availability information.
2409 $ci = new \core_availability\
info_module($this);
2411 // Note that the modinfo currently available only includes minimal details (basic data)
2412 // but we know that this function does not need anything more than basic data.
2413 $this->available
= $ci->is_available($this->availableinfo
, true,
2414 $userid, $this->modinfo
);
2416 $this->available
= true;
2419 // Check parent section.
2420 if ($this->available
) {
2421 $parentsection = $this->modinfo
->get_section_info($this->sectionnum
);
2422 if (!$parentsection->get_available()) {
2423 // Do not store info from section here, as that is already
2424 // presented from the section (if appropriate) - just change
2426 $this->available
= false;
2430 // Update visible state for current user.
2431 $this->update_user_visible();
2433 // Let module make dynamic changes at this point
2434 $this->call_mod_function('cm_info_dynamic');
2435 $this->state
= self
::STATE_DYNAMIC
;
2439 * Getter method for property $uservisible, ensures that dynamic data is retrieved.
2441 * This method is normally called by the property ->uservisible, but can be called directly if
2442 * there is a case when it might be called recursively (you can't call property values
2447 public function get_user_visible() {
2448 $this->obtain_dynamic_data();
2449 return $this->uservisible
;
2453 * Returns whether this module is visible to the current user on course page
2455 * Activity may be visible on the course page but not available, for example
2456 * when it is hidden conditionally but the condition information is displayed.
2460 public function is_visible_on_course_page() {
2461 $this->obtain_dynamic_data();
2462 return $this->uservisibleoncoursepage
;
2466 * Whether this module is available but hidden from course page
2468 * "Stealth" modules are the ones that are not shown on course page but available by following url.
2469 * They are normally also displayed in grade reports and other reports.
2470 * Module will be stealth either if visibleoncoursepage=0 or it is a visible module inside the hidden
2475 public function is_stealth() {
2476 return !$this->visibleoncoursepage ||
2477 ($this->visible
&& ($section = $this->get_section_info()) && !$section->visible
);
2481 * Getter method for property $available, ensures that dynamic data is retrieved
2484 private function get_available() {
2485 $this->obtain_dynamic_data();
2486 return $this->available
;
2490 * This method can not be used anymore.
2492 * @see \core_availability\info_module::filter_user_list()
2493 * @deprecated Since Moodle 2.8
2495 private function get_deprecated_group_members_only() {
2496 throw new coding_exception('$cm->groupmembersonly can not be used anymore. ' .
2497 'If used to restrict a list of enrolled users to only those who can ' .
2498 'access the module, consider \core_availability\info_module::filter_user_list.');
2502 * Getter method for property $availableinfo, ensures that dynamic data is retrieved
2504 * @return string Available info (HTML)
2506 private function get_available_info() {
2507 $this->obtain_dynamic_data();
2508 return $this->availableinfo
;
2512 * Works out whether activity is available to the current user
2514 * If the activity is unavailable, additional checks are required to determine if its hidden or greyed out
2518 private function update_user_visible() {
2519 $userid = $this->modinfo
->get_user_id();
2520 if ($userid == -1) {
2523 $this->uservisible
= true;
2525 // If the module is being deleted, set the uservisible state to false and return.
2526 if ($this->deletioninprogress
) {
2527 $this->uservisible
= false;
2531 // If the user cannot access the activity set the uservisible flag to false.
2532 // Additional checks are required to determine whether the activity is entirely hidden or just greyed out.
2533 if ((!$this->visible
&& !has_capability('moodle/course:viewhiddenactivities', $this->get_context(), $userid)) ||
2534 (!$this->get_available() &&
2535 !has_capability('moodle/course:ignoreavailabilityrestrictions', $this->get_context(), $userid))) {
2537 $this->uservisible
= false;
2540 // Check group membership.
2541 if ($this->is_user_access_restricted_by_capability()) {
2543 $this->uservisible
= false;
2544 // Ensure activity is completely hidden from the user.
2545 $this->availableinfo
= '';
2548 $this->uservisibleoncoursepage
= $this->uservisible
&&
2549 ($this->visibleoncoursepage ||
2550 has_capability('moodle/course:manageactivities', $this->get_context(), $userid) ||
2551 has_capability('moodle/course:activityvisibility', $this->get_context(), $userid));
2552 // Activity that is not available, not hidden from course page and has availability
2553 // info is actually visible on the course page (with availability info and without a link).
2554 if (!$this->uservisible
&& $this->visibleoncoursepage
&& $this->availableinfo
) {
2555 $this->uservisibleoncoursepage
= true;
2560 * This method has been deprecated and should not be used.
2563 * @deprecated Since Moodle 2.8
2565 public function is_user_access_restricted_by_group() {
2566 throw new coding_exception('cm_info::is_user_access_restricted_by_group() can not be used any more.' .
2567 ' Use $cm->uservisible to decide whether the current user can access an activity.');
2571 * Checks whether mod/...:view capability restricts the current user's access.
2573 * @return bool True if the user access is restricted.
2575 public function is_user_access_restricted_by_capability() {
2576 $userid = $this->modinfo
->get_user_id();
2577 if ($userid == -1) {
2580 $capability = 'mod/' . $this->modname
. ':view';
2581 $capabilityinfo = get_capability_info($capability);
2582 if (!$capabilityinfo) {
2583 // Capability does not exist, no one is prevented from seeing the activity.
2587 // You are blocked if you don't have the capability.
2588 return !has_capability($capability, $this->get_context(), $userid);
2592 * Checks whether the module's conditional access settings mean that the
2593 * user cannot see the activity at all
2595 * @deprecated since 2.7 MDL-44070
2597 public function is_user_access_restricted_by_conditional_access() {
2598 throw new coding_exception('cm_info::is_user_access_restricted_by_conditional_access() ' .
2599 'can not be used any more; this function is not needed (use $cm->uservisible ' .
2600 'and $cm->availableinfo to decide whether it should be available ' .
2605 * Calls a module function (if exists), passing in one parameter: this object.
2606 * @param string $type Name of function e.g. if this is 'grooblezorb' and the modname is
2607 * 'forum' then it will try to call 'mod_forum_grooblezorb' or 'forum_grooblezorb'
2610 private function call_mod_function($type) {
2612 $libfile = $CFG->dirroot
. '/mod/' . $this->modname
. '/lib.php';
2613 if (file_exists($libfile)) {
2614 include_once($libfile);
2615 $function = 'mod_' . $this->modname
. '_' . $type;
2616 if (function_exists($function)) {
2619 $function = $this->modname
. '_' . $type;
2620 if (function_exists($function)) {
2628 * If view data for this course-module is not yet available, obtains it.
2630 * This function is automatically called if any of the functions (marked) which require
2631 * view data are called.
2633 * View data is data which is needed only for displaying the course main page (& any similar
2634 * functionality on other pages) but is not needed in general. Obtaining view data may have
2635 * a performance cost.
2637 * As part of this function, the module's _cm_info_view function from its lib.php will
2638 * be called (if it exists).
2641 private function obtain_view_data() {
2642 if ($this->state
>= self
::STATE_BUILDING_VIEW ||
$this->modinfo
->get_user_id() == -1) {
2645 $this->obtain_dynamic_data();
2646 $this->state
= self
::STATE_BUILDING_VIEW
;
2648 // Let module make changes at this point
2649 $this->call_mod_function('cm_info_view');
2650 $this->state
= self
::STATE_VIEW
;
2656 * Returns reference to full info about modules in course (including visibility).
2657 * Cached and as fast as possible (0 or 1 db query).
2659 * use get_fast_modinfo($courseid, 0, true) to reset the static cache for particular course
2660 * use get_fast_modinfo(0, 0, true) to reset the static cache for all courses
2662 * use rebuild_course_cache($courseid, true) to reset the application AND static cache
2663 * for particular course when it's contents has changed
2665 * @param int|stdClass $courseorid object from DB table 'course' (must have field 'id'
2666 * and recommended to have field 'cacherev') or just a course id. Just course id
2667 * is enough when calling get_fast_modinfo() for current course or site or when
2668 * calling for any other course for the second time.
2669 * @param int $userid User id to populate 'availble' and 'uservisible' attributes of modules and sections.
2670 * Set to 0 for current user (default). Set to -1 to avoid calculation of dynamic user-depended data.
2671 * @param bool $resetonly whether we want to get modinfo or just reset the cache
2672 * @return course_modinfo|null Module information for course, or null if resetting
2673 * @throws moodle_exception when course is not found (nothing is thrown if resetting)
2675 function get_fast_modinfo($courseorid, $userid = 0, $resetonly = false) {
2676 // compartibility with syntax prior to 2.4:
2677 if ($courseorid === 'reset') {
2678 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
);
2683 // Function get_fast_modinfo() can never be called during upgrade unless it is used for clearing cache only.
2685 upgrade_ensure_not_running();
2688 // Function is called with $reset = true
2690 course_modinfo
::clear_instance_cache($courseorid);
2694 // Function is called with $reset = false, retrieve modinfo
2695 return course_modinfo
::instance($courseorid, $userid);
2699 * Efficiently retrieves the $course (stdclass) and $cm (cm_info) objects, given
2700 * a cmid. If module name is also provided, it will ensure the cm is of that type.
2703 * list($course, $cm) = get_course_and_cm_from_cmid($cmid, 'forum');
2705 * Using this method has a performance advantage because it works by loading
2706 * modinfo for the course - which will then be cached and it is needed later
2707 * in most requests. It also guarantees that the $cm object is a cm_info and
2710 * The $course object can be supplied if already known and will speed
2711 * up this function - although it is more efficient to use this function to
2712 * get the course if you are starting from a cmid.
2714 * To avoid security problems and obscure bugs, you should always specify
2715 * $modulename if the cmid value came from user input.
2717 * By default this obtains information (for example, whether user can access
2718 * the activity) for current user, but you can specify a userid if required.
2720 * @param stdClass|int $cmorid Id of course-module, or database object
2721 * @param string $modulename Optional modulename (improves security)
2722 * @param stdClass|int $courseorid Optional course object if already loaded
2723 * @param int $userid Optional userid (default = current)
2724 * @return array Array with 2 elements $course and $cm
2725 * @throws moodle_exception If the item doesn't exist or is of wrong module name
2727 function get_course_and_cm_from_cmid($cmorid, $modulename = '', $courseorid = 0, $userid = 0) {
2729 if (is_object($cmorid)) {
2730 $cmid = $cmorid->id
;
2731 if (isset($cmorid->course
)) {
2732 $courseid = (int)$cmorid->course
;
2737 $cmid = (int)$cmorid;
2741 // Validate module name if supplied.
2742 if ($modulename && !core_component
::is_valid_plugin_name('mod', $modulename)) {
2743 throw new coding_exception('Invalid modulename parameter');
2746 // Get course from last parameter if supplied.
2748 if (is_object($courseorid)) {
2749 $course = $courseorid;
2750 } else if ($courseorid) {
2751 $courseid = (int)$courseorid;
2756 // If course ID is known, get it using normal function.
2757 $course = get_course($courseid);
2759 // Get course record in a single query based on cmid.
2760 $course = $DB->get_record_sql("
2762 FROM {course_modules} cm
2763 JOIN {course} c ON c.id = cm.course
2764 WHERE cm.id = ?", array($cmid), MUST_EXIST
);
2768 // Get cm from get_fast_modinfo.
2769 $modinfo = get_fast_modinfo($course, $userid);
2770 $cm = $modinfo->get_cm($cmid);
2771 if ($modulename && $cm->modname
!== $modulename) {
2772 throw new moodle_exception('invalidcoursemoduleid', 'error', '', $cmid);
2774 return array($course, $cm);
2778 * Efficiently retrieves the $course (stdclass) and $cm (cm_info) objects, given
2779 * an instance id or record and module name.
2782 * list($course, $cm) = get_course_and_cm_from_instance($forum, 'forum');
2784 * Using this method has a performance advantage because it works by loading
2785 * modinfo for the course - which will then be cached and it is needed later
2786 * in most requests. It also guarantees that the $cm object is a cm_info and
2789 * The $course object can be supplied if already known and will speed
2790 * up this function - although it is more efficient to use this function to
2791 * get the course if you are starting from an instance id.
2793 * By default this obtains information (for example, whether user can access
2794 * the activity) for current user, but you can specify a userid if required.
2796 * @param stdclass|int $instanceorid Id of module instance, or database object
2797 * @param string $modulename Modulename (required)
2798 * @param stdClass|int $courseorid Optional course object if already loaded
2799 * @param int $userid Optional userid (default = current)
2800 * @return array Array with 2 elements $course and $cm
2801 * @throws moodle_exception If the item doesn't exist or is of wrong module name
2803 function get_course_and_cm_from_instance($instanceorid, $modulename, $courseorid = 0, $userid = 0) {
2806 // Get data from parameter.
2807 if (is_object($instanceorid)) {
2808 $instanceid = $instanceorid->id
;
2809 if (isset($instanceorid->course
)) {
2810 $courseid = (int)$instanceorid->course
;
2815 $instanceid = (int)$instanceorid;
2819 // Get course from last parameter if supplied.
2821 if (is_object($courseorid)) {
2822 $course = $courseorid;
2823 } else if ($courseorid) {
2824 $courseid = (int)$courseorid;
2827 // Validate module name if supplied.
2828 if (!core_component
::is_valid_plugin_name('mod', $modulename)) {
2829 throw new coding_exception('Invalid modulename parameter');
2834 // If course ID is known, get it using normal function.
2835 $course = get_course($courseid);
2837 // Get course record in a single query based on instance id.
2838 $pagetable = '{' . $modulename . '}';
2839 $course = $DB->get_record_sql("
2841 FROM $pagetable instance
2842 JOIN {course} c ON c.id = instance.course
2843 WHERE instance.id = ?", array($instanceid), MUST_EXIST
);
2847 // Get cm from get_fast_modinfo.
2848 $modinfo = get_fast_modinfo($course, $userid);
2849 $instances = $modinfo->get_instances_of($modulename);
2850 if (!array_key_exists($instanceid, $instances)) {
2851 throw new moodle_exception('invalidmoduleid', 'error', '', $instanceid);
2853 return array($course, $instances[$instanceid]);
2858 * Rebuilds or resets the cached list of course activities stored in MUC.
2860 * rebuild_course_cache() must NEVER be called from lib/db/upgrade.php.
2861 * At the same time course cache may ONLY be cleared using this function in
2862 * upgrade scripts of plugins.
2864 * During the bulk operations if it is necessary to reset cache of multiple
2865 * courses it is enough to call {@link increment_revision_number()} for the
2866 * table 'course' and field 'cacherev' specifying affected courses in select.
2868 * Cached course information is stored in MUC core/coursemodinfo and is
2869 * validated with the DB field {course}.cacherev
2871 * @global moodle_database $DB
2872 * @param int $courseid id of course to rebuild, empty means all
2873 * @param boolean $clearonly only clear the cache, gets rebuild automatically on the fly.
2874 * Recommended to set to true to avoid unnecessary multiple rebuilding.
2875 * @param boolean $partialrebuild will not delete the whole cache when it's true.
2876 * use purge_module_cache() or purge_section_cache() must be
2877 * called before when partialrebuild is true.
2878 * use purge_module_cache() to invalidate mod cache.
2879 * use purge_section_cache() to invalidate section cache.
2882 * @throws coding_exception
2884 function rebuild_course_cache(int $courseid = 0, bool $clearonly = false, bool $partialrebuild = false): void
{
2885 global $COURSE, $SITE, $DB;
2887 if ($courseid == 0 and $partialrebuild) {
2888 throw new coding_exception('partialrebuild only works when a valid course id is provided.');
2891 // Function rebuild_course_cache() can not be called during upgrade unless it's clear only.
2892 if (!$clearonly && !upgrade_ensure_not_running(true)) {
2896 // Destroy navigation caches
2897 navigation_cache
::destroy_volatile_caches();
2899 core_courseformat\base
::reset_course_cache($courseid);
2901 $cachecoursemodinfo = cache
::make('core', 'coursemodinfo');
2902 if (empty($courseid)) {
2903 // Clearing caches for all courses.
2904 increment_revision_number('course', 'cacherev', '');
2905 if (!$partialrebuild) {
2906 $cachecoursemodinfo->purge();
2908 // Clear memory static cache.
2909 course_modinfo
::clear_instance_cache();
2910 // Update global values too.
2911 $sitecacherev = $DB->get_field('course', 'cacherev', array('id' => SITEID
));
2912 $SITE->cachrev
= $sitecacherev;
2913 if ($COURSE->id
== SITEID
) {
2914 $COURSE->cacherev
= $sitecacherev;
2916 $COURSE->cacherev
= $DB->get_field('course', 'cacherev', array('id' => $COURSE->id
));
2919 // Clearing cache for one course, make sure it is deleted from user request cache as well.
2920 // Because this is a versioned cache, there is no need to actually delete the cache item,
2921 // only increase the required version number.
2922 increment_revision_number('course', 'cacherev', 'id = :id', array('id' => $courseid));
2923 $cacherev = $DB->get_field('course', 'cacherev', ['id' => $courseid]);
2924 // Clear memory static cache.
2925 course_modinfo
::clear_instance_cache($courseid, $cacherev);
2926 // Update global values too.
2927 if ($courseid == $COURSE->id ||
$courseid == $SITE->id
) {
2928 if ($courseid == $COURSE->id
) {
2929 $COURSE->cacherev
= $cacherev;
2931 if ($courseid == $SITE->id
) {
2932 $SITE->cacherev
= $cacherev;
2942 $select = array('id'=>$courseid);
2945 core_php_time_limit
::raise(); // this could take a while! MDL-10954
2948 $fields = 'id,' . join(',', course_modinfo
::$cachedfields);
2950 $rs = $DB->get_recordset("course", $select, $sort, $fields);
2952 // Rebuild cache for each course.
2953 foreach ($rs as $course) {
2954 course_modinfo
::build_course_cache($course, $partialrebuild);
2961 * Class that is the return value for the _get_coursemodule_info module API function.
2963 * Note: For backward compatibility, you can also return a stdclass object from that function.
2964 * The difference is that the stdclass object may contain an 'extra' field (deprecated,
2965 * use extraclasses and onclick instead). The stdclass object may not contain
2966 * the new fields defined here (content, extraclasses, customdata).
2968 class cached_cm_info
{
2970 * Name (text of link) for this activity; Leave unset to accept default name
2976 * Name of icon for this activity. Normally, this should be used together with $iconcomponent
2977 * to define the icon, as per image_url function.
2978 * For backward compatibility, if this value is of the form 'mod/forum/icon' then an icon
2979 * within that module will be used.
2980 * @see cm_info::get_icon_url()
2981 * @see renderer_base::image_url()
2987 * Component for icon for this activity, as per image_url; leave blank to use default 'moodle'
2989 * @see renderer_base::image_url()
2992 public $iconcomponent;
2995 * HTML content to be displayed on the main page below the link (if any) for this course-module
3001 * Custom data to be stored in modinfo for this activity; useful if there are cases when
3002 * internal information for this activity type needs to be accessible from elsewhere on the
3003 * course without making database queries. May be of any type but should be short.
3009 * Extra CSS class or classes to be added when this activity is displayed on the main page;
3010 * space-separated string
3013 public $extraclasses;
3016 * External URL image to be used by activity as icon, useful for some external-tool modules
3017 * like lti. If set, takes precedence over $icon and $iconcomponent
3023 * Content of onclick JavaScript; escaped HTML to be inserted as attribute value
3031 * Data about a single section on a course. This contains the fields from the
3032 * course_sections table, plus additional data when required.
3034 * @property-read int $id Section ID - from course_sections table
3035 * @property-read int $course Course ID - from course_sections table
3036 * @property-read int $sectionnum Section number - from course_sections table
3037 * @property-read string $name Section name if specified - from course_sections table
3038 * @property-read int $visible Section visibility (1 = visible) - from course_sections table
3039 * @property-read string $summary Section summary text if specified - from course_sections table
3040 * @property-read int $summaryformat Section summary text format (FORMAT_xx constant) - from course_sections table
3041 * @property-read string $availability Availability information as JSON string - from course_sections table
3042 * @property-read string|null $component Optional section delegate component - from course_sections table
3043 * @property-read int|null $itemid Optional section delegate item id - from course_sections table
3044 * @property-read array $conditionscompletion Availability conditions for this section based on the completion of
3045 * course-modules (array from course-module id to required completion state
3046 * for that module) - from cached data in sectioncache field
3047 * @property-read array $conditionsgrade Availability conditions for this section based on course grades (array from
3048 * grade item id to object with ->min, ->max fields) - from cached data in
3049 * sectioncache field
3050 * @property-read array $conditionsfield Availability conditions for this section based on user fields
3051 * @property-read bool $available True if this section is available to the given user i.e. if all availability conditions
3052 * are met - obtained dynamically
3053 * @property-read string $availableinfo If section is not available to some users, this string gives information about
3054 * availability which can be displayed to students and/or staff (e.g. 'Available from 3 January 2010')
3055 * for display on main page - obtained dynamically
3056 * @property-read bool $uservisible True if this section is available to the given user (for example, if current user
3057 * has viewhiddensections capability, they can access the section even if it is not
3058 * visible or not available, so this would be true in that case) - obtained dynamically
3059 * @property-read string $sequence Comma-separated list of all modules in the section. Note, this field may not exactly
3060 * match course_sections.sequence if later has references to non-existing modules or not modules of not available module types.
3061 * @property-read course_modinfo $modinfo
3063 class section_info
implements IteratorAggregate
{
3065 * Section ID - from course_sections table
3071 * Section number - from course_sections table
3074 private $_sectionnum;
3077 * Section name if specified - from course_sections table
3083 * Section visibility (1 = visible) - from course_sections table
3089 * Section summary text if specified - from course_sections table
3095 * Section summary text format (FORMAT_xx constant) - from course_sections table
3098 private $_summaryformat;
3101 * Availability information as JSON string - from course_sections table
3104 private $_availability;
3107 * @var string|null the delegated component if any.
3109 private ?
string $_component = null;
3112 * @var int|null the delegated instance item id if any.
3114 private ?
int $_itemid = null;
3117 * @var sectiondelegate|null Section delegate instance if any.
3119 private ?sectiondelegate
$_delegateinstance = null;
3122 * Availability conditions for this section based on the completion of
3123 * course-modules (array from course-module id to required completion state
3124 * for that module) - from cached data in sectioncache field
3127 private $_conditionscompletion;
3130 * Availability conditions for this section based on course grades (array from
3131 * grade item id to object with ->min, ->max fields) - from cached data in
3132 * sectioncache field
3135 private $_conditionsgrade;
3138 * Availability conditions for this section based on user fields
3141 private $_conditionsfield;
3144 * True if this section is available to students i.e. if all availability conditions
3145 * are met - obtained dynamically on request, see function {@link section_info::get_available()}
3148 private $_available;
3151 * If section is not available to some users, this string gives information about
3152 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
3153 * January 2010') for display on main page - obtained dynamically on request, see
3154 * function {@link section_info::get_availableinfo()}
3157 private $_availableinfo;
3160 * True if this section is available to the CURRENT user (for example, if current user
3161 * has viewhiddensections capability, they can access the section even if it is not
3162 * visible or not available, so this would be true in that case) - obtained dynamically
3163 * on request, see function {@link section_info::get_uservisible()}
3166 private $_uservisible;
3169 * Default values for sectioncache fields; if a field has this value, it won't
3170 * be stored in the sectioncache cache, to save space. Checks are done by ===
3171 * which means values must all be strings.
3174 private static $sectioncachedefaults = array(
3177 'summaryformat' => '1', // FORMAT_HTML, but must be a string
3179 'availability' => null,
3180 'component' => null,
3185 * Stores format options that have been cached when building 'coursecache'
3186 * When the format option is requested we look first if it has been cached
3189 private $cachedformatoptions = array();
3192 * Stores the list of all possible section options defined in each used course format.
3195 static private $sectionformatoptions = array();
3198 * Stores the modinfo object passed in constructor, may be used when requesting
3199 * dynamically obtained attributes such as available, availableinfo, uservisible.
3200 * Also used to retrun information about current course or user.
3201 * @var course_modinfo
3206 * True if has activities, otherwise false.
3209 public $hasactivites;
3212 * List of class read-only properties' getter methods.
3213 * Used by magic functions __get(), __isset(), __empty()
3216 private static $standardproperties = [
3217 'section' => 'get_section_number',
3221 * Constructs object from database information plus extra required data.
3222 * @param object $data Array entry from cached sectioncache
3223 * @param int $number Section number (array key)
3224 * @param int $notused1 argument not used (informaion is available in $modinfo)
3225 * @param int $notused2 argument not used (informaion is available in $modinfo)
3226 * @param course_modinfo $modinfo Owner (needed for checking availability)
3227 * @param int $notused3 argument not used (informaion is available in $modinfo)
3229 public function __construct($data, $number, $notused1, $notused2, $modinfo, $notused3) {
3231 require_once($CFG->dirroot
.'/course/lib.php');
3233 // Data that is always present
3234 $this->_id
= $data->id
;
3236 $defaults = self
::$sectioncachedefaults +
3237 array('conditionscompletion' => array(),
3238 'conditionsgrade' => array(),
3239 'conditionsfield' => array());
3241 // Data that may use default values to save cache size
3242 foreach ($defaults as $field => $value) {
3243 if (isset($data->{$field})) {
3244 $this->{'_'.$field} = $data->{$field};
3246 $this->{'_'.$field} = $value;
3250 // Other data from constructor arguments.
3251 $this->_sectionnum
= $number;
3252 $this->modinfo
= $modinfo;
3254 // Cached course format data.
3255 $course = $modinfo->get_course();
3256 if (!isset(self
::$sectionformatoptions[$course->format
])) {
3257 // Store list of section format options defined in each used course format.
3258 // They do not depend on particular course but only on its format.
3259 self
::$sectionformatoptions[$course->format
] =
3260 course_get_format($course)->section_format_options();
3262 foreach (self
::$sectionformatoptions[$course->format
] as $field => $option) {
3263 if (!empty($option['cache'])) {
3264 if (isset($data->{$field})) {
3265 $this->cachedformatoptions
[$field] = $data->{$field};
3266 } else if (array_key_exists('cachedefault', $option)) {
3267 $this->cachedformatoptions
[$field] = $option['cachedefault'];
3274 * Magic method to check if the property is set
3276 * @param string $name name of the property
3279 public function __isset($name) {
3280 if (isset(self
::$standardproperties[$name])) {
3281 $value = $this->__get($name);
3282 return isset($value);
3284 if (method_exists($this, 'get_'.$name) ||
3285 property_exists($this, '_'.$name) ||
3286 array_key_exists($name, self
::$sectionformatoptions[$this->modinfo
->get_course()->format
])) {
3287 $value = $this->__get($name);
3288 return isset($value);
3294 * Magic method to check if the property is empty
3296 * @param string $name name of the property
3299 public function __empty($name) {
3300 if (isset(self
::$standardproperties[$name])) {
3301 $value = $this->__get($name);
3302 return empty($value);
3304 if (method_exists($this, 'get_'.$name) ||
3305 property_exists($this, '_'.$name) ||
3306 array_key_exists($name, self
::$sectionformatoptions[$this->modinfo
->get_course()->format
])) {
3307 $value = $this->__get($name);
3308 return empty($value);
3314 * Magic method to retrieve the property, this is either basic section property
3315 * or availability information or additional properties added by course format
3317 * @param string $name name of the property
3320 public function __get($name) {
3321 if (isset(self
::$standardproperties[$name])) {
3322 if ($method = self
::$standardproperties[$name]) {
3323 return $this->$method();
3326 if (method_exists($this, 'get_'.$name)) {
3327 return $this->{'get_'.$name}();
3329 if (property_exists($this, '_'.$name)) {
3330 return $this->{'_'.$name};
3332 if (array_key_exists($name, $this->cachedformatoptions
)) {
3333 return $this->cachedformatoptions
[$name];
3335 // precheck if the option is defined in format to avoid unnecessary DB queries in get_format_options()
3336 if (array_key_exists($name, self
::$sectionformatoptions[$this->modinfo
->get_course()->format
])) {
3337 $formatoptions = course_get_format($this->modinfo
->get_course())->get_format_options($this);
3338 return $formatoptions[$name];
3340 debugging('Invalid section_info property accessed! '.$name);
3345 * Finds whether this section is available at the moment for the current user.
3347 * The value can be accessed publicly as $sectioninfo->available, but can be called directly if there
3348 * is a case when it might be called recursively (you can't call property values recursively).
3352 public function get_available() {
3354 $userid = $this->modinfo
->get_user_id();
3355 if ($this->_available
!== null ||
$userid == -1) {
3356 // Has already been calculated or does not need calculation.
3357 return $this->_available
;
3359 $this->_available
= true;
3360 $this->_availableinfo
= '';
3361 if (!empty($CFG->enableavailability
)) {
3362 // Get availability information.
3363 $ci = new \core_availability\
info_section($this);
3364 $this->_available
= $ci->is_available($this->_availableinfo
, true,
3365 $userid, $this->modinfo
);
3367 // Execute the hook from the course format that may override the available/availableinfo properties.
3368 $currentavailable = $this->_available
;
3369 course_get_format($this->modinfo
->get_course())->
3370 section_get_available_hook($this, $this->_available
, $this->_availableinfo
);
3371 if (!$currentavailable && $this->_available
) {
3372 debugging('section_get_available_hook() can not make unavailable section available', DEBUG_DEVELOPER
);
3373 $this->_available
= $currentavailable;
3375 return $this->_available
;
3379 * Returns the availability text shown next to the section on course page.
3383 private function get_availableinfo() {
3384 // Calling get_available() will also fill the availableinfo property
3385 // (or leave it null if there is no userid).
3386 $this->get_available();
3387 return $this->_availableinfo
;
3391 * Implementation of IteratorAggregate::getIterator(), allows to cycle through properties
3392 * and use {@link convert_to_array()}
3394 * @return ArrayIterator
3396 public function getIterator(): Traversable
{
3398 foreach (get_object_vars($this) as $key => $value) {
3399 if (substr($key, 0, 1) == '_') {
3400 if (method_exists($this, 'get'.$key)) {
3401 $ret[substr($key, 1)] = $this->{'get'.$key}();
3403 $ret[substr($key, 1)] = $this->$key;
3407 $ret['sequence'] = $this->get_sequence();
3408 $ret['course'] = $this->get_course();
3409 $ret = array_merge($ret, course_get_format($this->modinfo
->get_course())->get_format_options($this));
3410 return new ArrayIterator($ret);
3414 * Works out whether activity is visible *for current user* - if this is false, they
3415 * aren't allowed to access it.
3419 private function get_uservisible() {
3420 $userid = $this->modinfo
->get_user_id();
3421 if ($this->_uservisible
!== null ||
$userid == -1) {
3422 // Has already been calculated or does not need calculation.
3423 return $this->_uservisible
;
3425 $this->_uservisible
= true;
3426 if (!$this->_visible ||
!$this->get_available()) {
3427 $coursecontext = context_course
::instance($this->get_course());
3428 if (!$this->_visible
&& !has_capability('moodle/course:viewhiddensections', $coursecontext, $userid) ||
3429 (!$this->get_available() &&
3430 !has_capability('moodle/course:ignoreavailabilityrestrictions', $coursecontext, $userid))) {
3432 $this->_uservisible
= false;
3435 return $this->_uservisible
;
3439 * Restores the course_sections.sequence value
3443 private function get_sequence() {
3444 if (!empty($this->modinfo
->sections
[$this->_sectionnum
])) {
3445 return implode(',', $this->modinfo
->sections
[$this->_sectionnum
]);
3452 * Returns course ID - from course_sections table
3456 private function get_course() {
3457 return $this->modinfo
->get_course_id();
3463 * @return course_modinfo
3465 private function get_modinfo() {
3466 return $this->modinfo
;
3470 * Returns section number.
3472 * This method is called by the property ->section.
3476 private function get_section_number(): int {
3477 return $this->sectionnum
;
3481 * Get the delegate component instance.
3483 public function get_component_instance(): ?sectiondelegate
{
3484 if (empty($this->_component
)) {
3487 if ($this->_delegateinstance
!== null) {
3488 return $this->_delegateinstance
;
3490 $this->_delegateinstance
= sectiondelegate
::instance($this);
3491 return $this->_delegateinstance
;
3495 * Prepares section data for inclusion in sectioncache cache, removing items
3496 * that are set to defaults, and adding availability data if required.
3498 * Called by build_section_cache in course_modinfo only; do not use otherwise.
3499 * @param object $section Raw section data object
3501 public static function convert_for_section_cache($section) {
3504 // Course id stored in course table
3505 unset($section->course
);
3506 // Sequence stored implicity in modinfo $sections array
3507 unset($section->sequence
);
3509 // Remove default data
3510 foreach (self
::$sectioncachedefaults as $field => $value) {
3511 // Exact compare as strings to avoid problems if some strings are set
3513 if (isset($section->{$field}) && $section->{$field} === $value) {
3514 unset($section->{$field});