Merge branch 'MDL-73996-master-fix' of https://github.com/junpataleta/moodle
[moodle.git] / lib / modinfolib.php
blob4ce1d7c46ca4285a7bd4259cfa14b113799116d9
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * modinfolib.php - Functions/classes relating to cached information about module instances on
19 * a course.
20 * @package core
21 * @subpackage lib
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 * @author sam marshall
27 // Maximum number of modinfo items to keep in memory cache. Do not increase this to a large
28 // number because:
29 // a) modinfo can be big (megabyte range) for some courses
30 // b) performance of cache will deteriorate if there are very many items in it
31 if (!defined('MAX_MODINFO_CACHE_SIZE')) {
32 define('MAX_MODINFO_CACHE_SIZE', 10);
36 /**
37 * Information about a course that is cached in the course table 'modinfo' field (and then in
38 * memory) in order to reduce the need for other database queries.
40 * This includes information about the course-modules and the sections on the course. It can also
41 * include dynamic data that has been updated for the current user.
43 * Use {@link get_fast_modinfo()} to retrieve the instance of the object for particular course
44 * and particular user.
46 * @property-read int $courseid Course ID
47 * @property-read int $userid User ID
48 * @property-read array $sections Array from section number (e.g. 0) to array of course-module IDs in that
49 * section; this only includes sections that contain at least one course-module
50 * @property-read cm_info[] $cms Array from course-module instance to cm_info object within this course, in
51 * order of appearance
52 * @property-read cm_info[][] $instances Array from string (modname) => int (instance id) => cm_info object
53 * @property-read array $groups Groups that the current user belongs to. Calculated on the first request.
54 * Is an array of grouping id => array of group id => group id. Includes grouping id 0 for 'all groups'
56 class course_modinfo {
57 /** @var int Maximum time the course cache building lock can be held */
58 const COURSE_CACHE_LOCK_EXPIRY = 180;
60 /** @var int Time to wait for the course cache building lock before throwing an exception */
61 const COURSE_CACHE_LOCK_WAIT = 60;
63 /**
64 * List of fields from DB table 'course' that are cached in MUC and are always present in course_modinfo::$course
65 * @var array
67 public static $cachedfields = array('shortname', 'fullname', 'format',
68 'enablecompletion', 'groupmode', 'groupmodeforce', 'cacherev');
70 /**
71 * For convenience we store the course object here as it is needed in other parts of code
72 * @var stdClass
74 private $course;
76 /**
77 * Array of section data from cache
78 * @var section_info[]
80 private $sectioninfo;
82 /**
83 * User ID
84 * @var int
86 private $userid;
88 /**
89 * Array from int (section num, e.g. 0) => array of int (course-module id); this list only
90 * includes sections that actually contain at least one course-module
91 * @var array
93 private $sections;
95 /**
96 * Array from section id => section num.
97 * @var array
99 private $sectionids;
102 * Array from int (cm id) => cm_info object
103 * @var cm_info[]
105 private $cms;
108 * Array from string (modname) => int (instance id) => cm_info object
109 * @var cm_info[][]
111 private $instances;
114 * Groups that the current user belongs to. This value is calculated on first
115 * request to the property or function.
116 * When set, it is an array of grouping id => array of group id => group id.
117 * Includes grouping id 0 for 'all groups'.
118 * @var int[][]
120 private $groups;
123 * List of class read-only properties and their getter methods.
124 * Used by magic functions __get(), __isset(), __empty()
125 * @var array
127 private static $standardproperties = array(
128 'courseid' => 'get_course_id',
129 'userid' => 'get_user_id',
130 'sections' => 'get_sections',
131 'cms' => 'get_cms',
132 'instances' => 'get_instances',
133 'groups' => 'get_groups_all',
137 * Magic method getter
139 * @param string $name
140 * @return mixed
142 public function __get($name) {
143 if (isset(self::$standardproperties[$name])) {
144 $method = self::$standardproperties[$name];
145 return $this->$method();
146 } else {
147 debugging('Invalid course_modinfo property accessed: '.$name);
148 return null;
153 * Magic method for function isset()
155 * @param string $name
156 * @return bool
158 public function __isset($name) {
159 if (isset(self::$standardproperties[$name])) {
160 $value = $this->__get($name);
161 return isset($value);
163 return false;
167 * Magic method for function empty()
169 * @param string $name
170 * @return bool
172 public function __empty($name) {
173 if (isset(self::$standardproperties[$name])) {
174 $value = $this->__get($name);
175 return empty($value);
177 return true;
181 * Magic method setter
183 * Will display the developer warning when trying to set/overwrite existing property.
185 * @param string $name
186 * @param mixed $value
188 public function __set($name, $value) {
189 debugging("It is not allowed to set the property course_modinfo::\${$name}", DEBUG_DEVELOPER);
193 * Returns course object that was used in the first {@link get_fast_modinfo()} call.
195 * It may not contain all fields from DB table {course} but always has at least the following:
196 * id,shortname,fullname,format,enablecompletion,groupmode,groupmodeforce,cacherev
198 * @return stdClass
200 public function get_course() {
201 return $this->course;
205 * @return int Course ID
207 public function get_course_id() {
208 return $this->course->id;
212 * @return int User ID
214 public function get_user_id() {
215 return $this->userid;
219 * @return array Array from section number (e.g. 0) to array of course-module IDs in that
220 * section; this only includes sections that contain at least one course-module
222 public function get_sections() {
223 return $this->sections;
227 * @return cm_info[] Array from course-module instance to cm_info object within this course, in
228 * order of appearance
230 public function get_cms() {
231 return $this->cms;
235 * Obtains a single course-module object (for a course-module that is on this course).
236 * @param int $cmid Course-module ID
237 * @return cm_info Information about that course-module
238 * @throws moodle_exception If the course-module does not exist
240 public function get_cm($cmid) {
241 if (empty($this->cms[$cmid])) {
242 throw new moodle_exception('invalidcoursemodule', 'error');
244 return $this->cms[$cmid];
248 * Obtains all module instances on this course.
249 * @return cm_info[][] Array from module name => array from instance id => cm_info
251 public function get_instances() {
252 return $this->instances;
256 * Returns array of localised human-readable module names used in this course
258 * @param bool $plural if true returns the plural form of modules names
259 * @return array
261 public function get_used_module_names($plural = false) {
262 $modnames = get_module_types_names($plural);
263 $modnamesused = array();
264 foreach ($this->get_cms() as $cmid => $mod) {
265 if (!isset($modnamesused[$mod->modname]) && isset($modnames[$mod->modname]) && $mod->uservisible) {
266 $modnamesused[$mod->modname] = $modnames[$mod->modname];
269 return $modnamesused;
273 * Obtains all instances of a particular module on this course.
274 * @param $modname Name of module (not full frankenstyle) e.g. 'label'
275 * @return cm_info[] Array from instance id => cm_info for modules on this course; empty if none
277 public function get_instances_of($modname) {
278 if (empty($this->instances[$modname])) {
279 return array();
281 return $this->instances[$modname];
285 * Groups that the current user belongs to organised by grouping id. Calculated on the first request.
286 * @return int[][] array of grouping id => array of group id => group id. Includes grouping id 0 for 'all groups'
288 private function get_groups_all() {
289 if (is_null($this->groups)) {
290 // NOTE: Performance could be improved here. The system caches user groups
291 // in $USER->groupmember[$courseid] => array of groupid=>groupid. Unfortunately this
292 // structure does not include grouping information. It probably could be changed to
293 // do so, without a significant performance hit on login, thus saving this one query
294 // each request.
295 $this->groups = groups_get_user_groups($this->course->id, $this->userid);
297 return $this->groups;
301 * Returns groups that the current user belongs to on the course. Note: If not already
302 * available, this may make a database query.
303 * @param int $groupingid Grouping ID or 0 (default) for all groups
304 * @return int[] Array of int (group id) => int (same group id again); empty array if none
306 public function get_groups($groupingid = 0) {
307 $allgroups = $this->get_groups_all();
308 if (!isset($allgroups[$groupingid])) {
309 return array();
311 return $allgroups[$groupingid];
315 * Gets all sections as array from section number => data about section.
316 * @return section_info[] Array of section_info objects organised by section number
318 public function get_section_info_all() {
319 return $this->sectioninfo;
323 * Gets data about specific numbered section.
324 * @param int $sectionnumber Number (not id) of section
325 * @param int $strictness Use MUST_EXIST to throw exception if it doesn't
326 * @return section_info Information for numbered section or null if not found
328 public function get_section_info($sectionnumber, $strictness = IGNORE_MISSING) {
329 if (!array_key_exists($sectionnumber, $this->sectioninfo)) {
330 if ($strictness === MUST_EXIST) {
331 throw new moodle_exception('sectionnotexist');
332 } else {
333 return null;
336 return $this->sectioninfo[$sectionnumber];
340 * Gets data about specific section ID.
341 * @param int $sectionid ID (not number) of section
342 * @param int $strictness Use MUST_EXIST to throw exception if it doesn't
343 * @return section_info|null Information for numbered section or null if not found
345 public function get_section_info_by_id(int $sectionid, int $strictness = IGNORE_MISSING): ?section_info {
347 if (!isset($this->sectionids[$sectionid])) {
348 if ($strictness === MUST_EXIST) {
349 throw new moodle_exception('sectionnotexist');
350 } else {
351 return null;
354 return $this->get_section_info($this->sectionids[$sectionid], $strictness);
358 * Static cache for generated course_modinfo instances
360 * @see course_modinfo::instance()
361 * @see course_modinfo::clear_instance_cache()
362 * @var course_modinfo[]
364 protected static $instancecache = array();
367 * Timestamps (microtime) when the course_modinfo instances were last accessed
369 * It is used to remove the least recent accessed instances when static cache is full
371 * @var float[]
373 protected static $cacheaccessed = array();
376 * Clears the cache used in course_modinfo::instance()
378 * Used in {@link get_fast_modinfo()} when called with argument $reset = true
379 * and in {@link rebuild_course_cache()}
381 * @param null|int|stdClass $courseorid if specified removes only cached value for this course
383 public static function clear_instance_cache($courseorid = null) {
384 if (empty($courseorid)) {
385 self::$instancecache = array();
386 self::$cacheaccessed = array();
387 return;
389 if (is_object($courseorid)) {
390 $courseorid = $courseorid->id;
392 if (isset(self::$instancecache[$courseorid])) {
393 // Unsetting static variable in PHP is peculiar, it removes the reference,
394 // but data remain in memory. Prior to unsetting, the varable needs to be
395 // set to empty to remove its remains from memory.
396 self::$instancecache[$courseorid] = '';
397 unset(self::$instancecache[$courseorid]);
398 unset(self::$cacheaccessed[$courseorid]);
403 * Returns the instance of course_modinfo for the specified course and specified user
405 * This function uses static cache for the retrieved instances. The cache
406 * size is limited by MAX_MODINFO_CACHE_SIZE. If instance is not found in
407 * the static cache or it was created for another user or the cacherev validation
408 * failed - a new instance is constructed and returned.
410 * Used in {@link get_fast_modinfo()}
412 * @param int|stdClass $courseorid object from DB table 'course' (must have field 'id'
413 * and recommended to have field 'cacherev') or just a course id
414 * @param int $userid User id to populate 'availble' and 'uservisible' attributes of modules and sections.
415 * Set to 0 for current user (default). Set to -1 to avoid calculation of dynamic user-depended data.
416 * @return course_modinfo
418 public static function instance($courseorid, $userid = 0) {
419 global $USER;
420 if (is_object($courseorid)) {
421 $course = $courseorid;
422 } else {
423 $course = (object)array('id' => $courseorid);
425 if (empty($userid)) {
426 $userid = $USER->id;
429 if (!empty(self::$instancecache[$course->id])) {
430 if (self::$instancecache[$course->id]->userid == $userid &&
431 (!isset($course->cacherev) ||
432 $course->cacherev == self::$instancecache[$course->id]->get_course()->cacherev)) {
433 // This course's modinfo for the same user was recently retrieved, return cached.
434 self::$cacheaccessed[$course->id] = microtime(true);
435 return self::$instancecache[$course->id];
436 } else {
437 // Prevent potential reference problems when switching users.
438 self::clear_instance_cache($course->id);
441 $modinfo = new course_modinfo($course, $userid);
443 // We have a limit of MAX_MODINFO_CACHE_SIZE entries to store in static variable.
444 if (count(self::$instancecache) >= MAX_MODINFO_CACHE_SIZE) {
445 // Find the course that was the least recently accessed.
446 asort(self::$cacheaccessed, SORT_NUMERIC);
447 $courseidtoremove = key(array_reverse(self::$cacheaccessed, true));
448 self::clear_instance_cache($courseidtoremove);
451 // Add modinfo to the static cache.
452 self::$instancecache[$course->id] = $modinfo;
453 self::$cacheaccessed[$course->id] = microtime(true);
455 return $modinfo;
459 * Constructs based on course.
460 * Note: This constructor should not usually be called directly.
461 * Use get_fast_modinfo($course) instead as this maintains a cache.
462 * @param stdClass $course course object, only property id is required.
463 * @param int $userid User ID
464 * @throws moodle_exception if course is not found
466 public function __construct($course, $userid) {
467 global $CFG, $COURSE, $SITE, $DB;
469 if (!isset($course->cacherev)) {
470 // We require presence of property cacherev to validate the course cache.
471 // No need to clone the $COURSE or $SITE object here because we clone it below anyway.
472 $course = get_course($course->id, false);
475 $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
477 // Retrieve modinfo from cache. If not present or cacherev mismatches, call rebuild and retrieve again.
478 $coursemodinfo = $cachecoursemodinfo->get_versioned($course->id, $course->cacherev);
479 if (!$coursemodinfo) {
480 $lock = self::get_course_cache_lock($course->id);
481 try {
482 // Only actually do the build if it's still needed after getting the lock (not if
483 // somebody else, who might have been holding the lock, built it already).
484 $coursemodinfo = $cachecoursemodinfo->get_versioned($course->id, $course->cacherev);
485 if (!$coursemodinfo) {
486 $coursemodinfo = self::inner_build_course_cache($course, $lock);
488 } finally {
489 $lock->release();
493 // Set initial values
494 $this->userid = $userid;
495 $this->sections = array();
496 $this->sectionids = [];
497 $this->cms = array();
498 $this->instances = array();
499 $this->groups = null;
501 // If we haven't already preloaded contexts for the course, do it now
502 // Modules are also cached here as long as it's the first time this course has been preloaded.
503 context_helper::preload_course($course->id);
505 // Quick integrity check: as a result of race conditions modinfo may not be regenerated after the change.
506 // It is especially dangerous if modinfo contains the deleted course module, as it results in fatal error.
507 // We can check it very cheap by validating the existence of module context.
508 if ($course->id == $COURSE->id || $course->id == $SITE->id) {
509 // Only verify current course (or frontpage) as pages with many courses may not have module contexts cached.
510 // (Uncached modules will result in a very slow verification).
511 foreach ($coursemodinfo->modinfo as $mod) {
512 if (!context_module::instance($mod->cm, IGNORE_MISSING)) {
513 debugging('Course cache integrity check failed: course module with id '. $mod->cm.
514 ' does not have context. Rebuilding cache for course '. $course->id);
515 // Re-request the course record from DB as well, don't use get_course() here.
516 $course = $DB->get_record('course', array('id' => $course->id), '*', MUST_EXIST);
517 $coursemodinfo = self::build_course_cache($course);
518 break;
523 // Overwrite unset fields in $course object with cached values, store the course object.
524 $this->course = fullclone($course);
525 foreach ($coursemodinfo as $key => $value) {
526 if ($key !== 'modinfo' && $key !== 'sectioncache' &&
527 (!isset($this->course->$key) || $key === 'cacherev')) {
528 $this->course->$key = $value;
532 // Loop through each piece of module data, constructing it
533 static $modexists = array();
534 foreach ($coursemodinfo->modinfo as $mod) {
535 if (!isset($mod->name) || strval($mod->name) === '') {
536 // something is wrong here
537 continue;
540 // Skip modules which don't exist
541 if (!array_key_exists($mod->mod, $modexists)) {
542 $modexists[$mod->mod] = file_exists("$CFG->dirroot/mod/$mod->mod/lib.php");
544 if (!$modexists[$mod->mod]) {
545 continue;
548 // Construct info for this module
549 $cm = new cm_info($this, null, $mod, null);
551 // Store module in instances and cms array
552 if (!isset($this->instances[$cm->modname])) {
553 $this->instances[$cm->modname] = array();
555 $this->instances[$cm->modname][$cm->instance] = $cm;
556 $this->cms[$cm->id] = $cm;
558 // Reconstruct sections. This works because modules are stored in order
559 if (!isset($this->sections[$cm->sectionnum])) {
560 $this->sections[$cm->sectionnum] = array();
562 $this->sections[$cm->sectionnum][] = $cm->id;
565 // Expand section objects
566 $this->sectioninfo = array();
567 foreach ($coursemodinfo->sectioncache as $number => $data) {
568 $this->sectionids[$data->id] = $number;
569 $this->sectioninfo[$number] = new section_info($data, $number, null, null,
570 $this, null);
575 * This method can not be used anymore.
577 * @see course_modinfo::build_course_cache()
578 * @deprecated since 2.6
580 public static function build_section_cache($courseid) {
581 throw new coding_exception('Function course_modinfo::build_section_cache() can not be used anymore.' .
582 ' Please use course_modinfo::build_course_cache() whenever applicable.');
586 * Builds a list of information about sections on a course to be stored in
587 * the course cache. (Does not include information that is already cached
588 * in some other way.)
590 * @param stdClass $course Course object (must contain fields
591 * @return array Information about sections, indexed by section number (not id)
593 protected static function build_course_section_cache($course) {
594 global $DB;
596 // Get section data
597 $sections = $DB->get_records('course_sections', array('course' => $course->id), 'section',
598 'section, id, course, name, summary, summaryformat, sequence, visible, availability');
599 $compressedsections = array();
601 $formatoptionsdef = course_get_format($course)->section_format_options();
602 // Remove unnecessary data and add availability
603 foreach ($sections as $number => $section) {
604 // Add cached options from course format to $section object
605 foreach ($formatoptionsdef as $key => $option) {
606 if (!empty($option['cache'])) {
607 $formatoptions = course_get_format($course)->get_format_options($section);
608 if (!array_key_exists('cachedefault', $option) || $option['cachedefault'] !== $formatoptions[$key]) {
609 $section->$key = $formatoptions[$key];
613 // Clone just in case it is reused elsewhere
614 $compressedsections[$number] = clone($section);
615 section_info::convert_for_section_cache($compressedsections[$number]);
618 return $compressedsections;
622 * Gets a lock for rebuilding the cache of a single course.
624 * Caller must release the returned lock.
626 * This is used to ensure that the cache rebuild doesn't happen multiple times in parallel.
627 * This function will wait up to 1 minute for the lock to be obtained. If the lock cannot
628 * be obtained, it throws an exception.
630 * @param int $courseid Course id
631 * @return \core\lock\lock Lock (must be released!)
632 * @throws moodle_exception If the lock cannot be obtained
634 protected static function get_course_cache_lock($courseid) {
635 // Get database lock to ensure this doesn't happen multiple times in parallel. Wait a
636 // reasonable time for the lock to be released, so we can give a suitable error message.
637 // In case the system crashes while building the course cache, the lock will automatically
638 // expire after a (slightly longer) period.
639 $lockfactory = \core\lock\lock_config::get_lock_factory('core_modinfo');
640 $lock = $lockfactory->get_lock('build_course_cache_' . $courseid,
641 self::COURSE_CACHE_LOCK_WAIT, self::COURSE_CACHE_LOCK_EXPIRY);
642 if (!$lock) {
643 throw new moodle_exception('locktimeout', '', '', null,
644 'core_modinfo/build_course_cache_' . $courseid);
646 return $lock;
650 * Builds and stores in MUC object containing information about course
651 * modules and sections together with cached fields from table course.
653 * @param stdClass $course object from DB table course. Must have property 'id'
654 * but preferably should have all cached fields.
655 * @return stdClass object with all cached keys of the course plus fields modinfo and sectioncache.
656 * The same object is stored in MUC
657 * @throws moodle_exception if course is not found (if $course object misses some of the
658 * necessary fields it is re-requested from database)
660 public static function build_course_cache($course) {
661 if (empty($course->id)) {
662 throw new coding_exception('Object $course is missing required property \id\'');
665 $lock = self::get_course_cache_lock($course->id);
666 try {
667 return self::inner_build_course_cache($course, $lock);
668 } finally {
669 $lock->release();
674 * Called to build course cache when there is already a lock obtained.
676 * @param stdClass $course object from DB table course
677 * @param \core\lock\lock $lock Lock object - not actually used, just there to indicate you have a lock
678 * @return stdClass Course object that has been stored in MUC
680 protected static function inner_build_course_cache($course, \core\lock\lock $lock) {
681 global $DB, $CFG;
682 require_once("{$CFG->dirroot}/course/lib.php");
684 // Always reload the course object from database to ensure we have the latest possible
685 // value for cacherev.
686 $course = $DB->get_record('course', ['id' => $course->id],
687 implode(',', array_merge(['id'], self::$cachedfields)), MUST_EXIST);
689 // Retrieve all information about activities and sections.
690 $coursemodinfo = new stdClass();
691 $coursemodinfo->modinfo = get_array_of_activities($course->id);
692 $coursemodinfo->sectioncache = self::build_course_section_cache($course);
693 foreach (self::$cachedfields as $key) {
694 $coursemodinfo->$key = $course->$key;
696 // Set the accumulated activities and sections information in cache, together with cacherev.
697 $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
698 $cachecoursemodinfo->set_versioned($course->id, $course->cacherev, $coursemodinfo);
699 return $coursemodinfo;
705 * Data about a single module on a course. This contains most of the fields in the course_modules
706 * table, plus additional data when required.
708 * The object can be accessed by core or any plugin (i.e. course format, block, filter, etc.) as
709 * get_fast_modinfo($courseorid)->cms[$coursemoduleid]
710 * or
711 * get_fast_modinfo($courseorid)->instances[$moduletype][$instanceid]
713 * There are three stages when activity module can add/modify data in this object:
715 * <b>Stage 1 - during building the cache.</b>
716 * Allows to add to the course cache static user-independent information about the module.
717 * Modules should try to include only absolutely necessary information that may be required
718 * when displaying course view page. The information is stored in application-level cache
719 * and reset when {@link rebuild_course_cache()} is called or cache is purged by admin.
721 * Modules can implement callback XXX_get_coursemodule_info() returning instance of object
722 * {@link cached_cm_info}
724 * <b>Stage 2 - dynamic data.</b>
725 * Dynamic data is user-dependent, it is stored in request-level cache. To reset this cache
726 * {@link get_fast_modinfo()} with $reset argument may be called.
728 * Dynamic data is obtained when any of the following properties/methods is requested:
729 * - {@link cm_info::$url}
730 * - {@link cm_info::$name}
731 * - {@link cm_info::$onclick}
732 * - {@link cm_info::get_icon_url()}
733 * - {@link cm_info::$uservisible}
734 * - {@link cm_info::$available}
735 * - {@link cm_info::$availableinfo}
736 * - plus any of the properties listed in Stage 3.
738 * Modules can implement callback <b>XXX_cm_info_dynamic()</b> and inside this callback they
739 * are allowed to use any of the following set methods:
740 * - {@link cm_info::set_available()}
741 * - {@link cm_info::set_name()}
742 * - {@link cm_info::set_no_view_link()}
743 * - {@link cm_info::set_user_visible()}
744 * - {@link cm_info::set_on_click()}
745 * - {@link cm_info::set_icon_url()}
746 * - {@link cm_info::override_customdata()}
747 * Any methods affecting view elements can also be set in this callback.
749 * <b>Stage 3 (view data).</b>
750 * Also user-dependend data stored in request-level cache. Second stage is created
751 * because populating the view data can be expensive as it may access much more
752 * Moodle APIs such as filters, user information, output renderers and we
753 * don't want to request it until necessary.
754 * View data is obtained when any of the following properties/methods is requested:
755 * - {@link cm_info::$afterediticons}
756 * - {@link cm_info::$content}
757 * - {@link cm_info::get_formatted_content()}
758 * - {@link cm_info::$extraclasses}
759 * - {@link cm_info::$afterlink}
761 * Modules can implement callback <b>XXX_cm_info_view()</b> and inside this callback they
762 * are allowed to use any of the following set methods:
763 * - {@link cm_info::set_after_edit_icons()}
764 * - {@link cm_info::set_after_link()}
765 * - {@link cm_info::set_content()}
766 * - {@link cm_info::set_extra_classes()}
768 * @property-read int $id Course-module ID - from course_modules table
769 * @property-read int $instance Module instance (ID within module table) - from course_modules table
770 * @property-read int $course Course ID - from course_modules table
771 * @property-read string $idnumber 'ID number' from course-modules table (arbitrary text set by user) - from
772 * course_modules table
773 * @property-read int $added Time that this course-module was added (unix time) - from course_modules table
774 * @property-read int $visible Visible setting (0 or 1; if this is 0, students cannot see/access the activity) - from
775 * course_modules table
776 * @property-read int $visibleoncoursepage Visible on course page setting - from course_modules table, adjusted to
777 * whether course format allows this module to have the "stealth" mode
778 * @property-read int $visibleold Old visible setting (if the entire section is hidden, the previous value for
779 * visible is stored in this field) - from course_modules table
780 * @property-read int $groupmode Group mode (one of the constants NOGROUPS, SEPARATEGROUPS, or VISIBLEGROUPS) - from
781 * course_modules table. Use {@link cm_info::$effectivegroupmode} to find the actual group mode that may be forced by course.
782 * @property-read int $groupingid Grouping ID (0 = all groupings)
783 * @property-read bool $coursegroupmodeforce Indicates whether the course containing the module has forced the groupmode
784 * This means that cm_info::$groupmode should be ignored and cm_info::$coursegroupmode be used instead
785 * @property-read int $coursegroupmode Group mode (one of the constants NOGROUPS, SEPARATEGROUPS, or VISIBLEGROUPS) - from
786 * course table - as specified for the course containing the module
787 * Effective only if {@link cm_info::$coursegroupmodeforce} is set
788 * @property-read int $effectivegroupmode Effective group mode for this module (one of the constants NOGROUPS, SEPARATEGROUPS,
789 * or VISIBLEGROUPS). This can be different from groupmode set for the module if the groupmode is forced for the course.
790 * This value will always be NOGROUPS if module type does not support group mode.
791 * @property-read int $indent Indent level on course page (0 = no indent) - from course_modules table
792 * @property-read int $completion Activity completion setting for this activity, COMPLETION_TRACKING_xx constant - from
793 * course_modules table
794 * @property-read mixed $completiongradeitemnumber Set to the item number (usually 0) if completion depends on a particular
795 * grade of this activity, or null if completion does not depend on a grade - from course_modules table
796 * @property-read int $completionview 1 if 'on view' completion is enabled, 0 otherwise - from course_modules table
797 * @property-read int $completionexpected Set to a unix time if completion of this activity is expected at a
798 * particular time, 0 if no time set - from course_modules table
799 * @property-read string $availability Availability information as JSON string or null if none -
800 * from course_modules table
801 * @property-read int $showdescription Controls whether the description of the activity displays on the course main page (in
802 * addition to anywhere it might display within the activity itself). 0 = do not show
803 * on main page, 1 = show on main page.
804 * @property-read string $extra (deprecated) Extra HTML that is put in an unhelpful part of the HTML when displaying this module in
805 * course page - from cached data in modinfo field. Deprecated, replaced by ->extraclasses and ->onclick
806 * @property-read string $icon Name of icon to use - from cached data in modinfo field
807 * @property-read string $iconcomponent Component that contains icon - from cached data in modinfo field
808 * @property-read string $modname Name of module e.g. 'forum' (this is the same name as the module's main database
809 * table) - from cached data in modinfo field
810 * @property-read int $module ID of module type - from course_modules table
811 * @property-read string $name Name of module instance for display on page e.g. 'General discussion forum' - from cached
812 * data in modinfo field
813 * @property-read int $sectionnum Section number that this course-module is in (section 0 = above the calendar, section 1
814 * = week/topic 1, etc) - from cached data in modinfo field
815 * @property-read int $section Section id - from course_modules table
816 * @property-read array $conditionscompletion Availability conditions for this course-module based on the completion of other
817 * course-modules (array from other course-module id to required completion state for that
818 * module) - from cached data in modinfo field
819 * @property-read array $conditionsgrade Availability conditions for this course-module based on course grades (array from
820 * grade item id to object with ->min, ->max fields) - from cached data in modinfo field
821 * @property-read array $conditionsfield Availability conditions for this course-module based on user fields
822 * @property-read bool $available True if this course-module is available to students i.e. if all availability conditions
823 * are met - obtained dynamically
824 * @property-read string $availableinfo If course-module is not available to students, this string gives information about
825 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
826 * January 2010') for display on main page - obtained dynamically
827 * @property-read bool $uservisible True if this course-module is available to the CURRENT user (for example, if current user
828 * has viewhiddenactivities capability, they can access the course-module even if it is not
829 * visible or not available, so this would be true in that case)
830 * @property-read context_module $context Module context
831 * @property-read string $modfullname Returns a localised human-readable name of the module type - calculated on request
832 * @property-read string $modplural Returns a localised human-readable name of the module type in plural form - calculated on request
833 * @property-read string $content Content to display on main (view) page - calculated on request
834 * @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
835 * @property-read string $extraclasses Extra CSS classes to add to html output for this activity on main page - calculated on request
836 * @property-read string $onclick Content of HTML on-click attribute already escaped - calculated on request
837 * @property-read mixed $customdata Optional custom data stored in modinfo cache for this activity, or null if none
838 * @property-read string $afterlink Extra HTML code to display after link - calculated on request
839 * @property-read string $afterediticons Extra HTML code to display after editing icons (e.g. more icons) - calculated on request
840 * @property-read bool $deletioninprogress True if this course module is scheduled for deletion, false otherwise.
841 * @property-read bool $downloadcontent True if content download is enabled for this course module, false otherwise.
843 class cm_info implements IteratorAggregate {
845 * State: Only basic data from modinfo cache is available.
847 const STATE_BASIC = 0;
850 * State: In the process of building dynamic data (to avoid recursive calls to obtain_dynamic_data())
852 const STATE_BUILDING_DYNAMIC = 1;
855 * State: Dynamic data is available too.
857 const STATE_DYNAMIC = 2;
860 * State: In the process of building view data (to avoid recursive calls to obtain_view_data())
862 const STATE_BUILDING_VIEW = 3;
865 * State: View data (for course page) is available.
867 const STATE_VIEW = 4;
870 * Parent object
871 * @var course_modinfo
873 private $modinfo;
876 * Level of information stored inside this object (STATE_xx constant)
877 * @var int
879 private $state;
882 * Course-module ID - from course_modules table
883 * @var int
885 private $id;
888 * Module instance (ID within module table) - from course_modules table
889 * @var int
891 private $instance;
894 * 'ID number' from course-modules table (arbitrary text set by user) - from
895 * course_modules table
896 * @var string
898 private $idnumber;
901 * Time that this course-module was added (unix time) - from course_modules table
902 * @var int
904 private $added;
907 * This variable is not used and is included here only so it can be documented.
908 * Once the database entry is removed from course_modules, it should be deleted
909 * here too.
910 * @var int
911 * @deprecated Do not use this variable
913 private $score;
916 * Visible setting (0 or 1; if this is 0, students cannot see/access the activity) - from
917 * course_modules table
918 * @var int
920 private $visible;
923 * Visible on course page setting - from course_modules table
924 * @var int
926 private $visibleoncoursepage;
929 * Old visible setting (if the entire section is hidden, the previous value for
930 * visible is stored in this field) - from course_modules table
931 * @var int
933 private $visibleold;
936 * Group mode (one of the constants NONE, SEPARATEGROUPS, or VISIBLEGROUPS) - from
937 * course_modules table
938 * @var int
940 private $groupmode;
943 * Grouping ID (0 = all groupings)
944 * @var int
946 private $groupingid;
949 * Indent level on course page (0 = no indent) - from course_modules table
950 * @var int
952 private $indent;
955 * Activity completion setting for this activity, COMPLETION_TRACKING_xx constant - from
956 * course_modules table
957 * @var int
959 private $completion;
962 * Set to the item number (usually 0) if completion depends on a particular
963 * grade of this activity, or null if completion does not depend on a grade - from
964 * course_modules table
965 * @var mixed
967 private $completiongradeitemnumber;
970 * 1 if pass grade completion is enabled, 0 otherwise - from course_modules table
971 * @var int
973 private $completionpassgrade;
976 * 1 if 'on view' completion is enabled, 0 otherwise - from course_modules table
977 * @var int
979 private $completionview;
982 * Set to a unix time if completion of this activity is expected at a
983 * particular time, 0 if no time set - from course_modules table
984 * @var int
986 private $completionexpected;
989 * Availability information as JSON string or null if none - from course_modules table
990 * @var string
992 private $availability;
995 * Controls whether the description of the activity displays on the course main page (in
996 * addition to anywhere it might display within the activity itself). 0 = do not show
997 * on main page, 1 = show on main page.
998 * @var int
1000 private $showdescription;
1003 * Extra HTML that is put in an unhelpful part of the HTML when displaying this module in
1004 * course page - from cached data in modinfo field
1005 * @deprecated This is crazy, don't use it. Replaced by ->extraclasses and ->onclick
1006 * @var string
1008 private $extra;
1011 * Name of icon to use - from cached data in modinfo field
1012 * @var string
1014 private $icon;
1017 * Component that contains icon - from cached data in modinfo field
1018 * @var string
1020 private $iconcomponent;
1023 * Name of module e.g. 'forum' (this is the same name as the module's main database
1024 * table) - from cached data in modinfo field
1025 * @var string
1027 private $modname;
1030 * ID of module - from course_modules table
1031 * @var int
1033 private $module;
1036 * Name of module instance for display on page e.g. 'General discussion forum' - from cached
1037 * data in modinfo field
1038 * @var string
1040 private $name;
1043 * Section number that this course-module is in (section 0 = above the calendar, section 1
1044 * = week/topic 1, etc) - from cached data in modinfo field
1045 * @var int
1047 private $sectionnum;
1050 * Section id - from course_modules table
1051 * @var int
1053 private $section;
1056 * Availability conditions for this course-module based on the completion of other
1057 * course-modules (array from other course-module id to required completion state for that
1058 * module) - from cached data in modinfo field
1059 * @var array
1061 private $conditionscompletion;
1064 * Availability conditions for this course-module based on course grades (array from
1065 * grade item id to object with ->min, ->max fields) - from cached data in modinfo field
1066 * @var array
1068 private $conditionsgrade;
1071 * Availability conditions for this course-module based on user fields
1072 * @var array
1074 private $conditionsfield;
1077 * True if this course-module is available to students i.e. if all availability conditions
1078 * are met - obtained dynamically
1079 * @var bool
1081 private $available;
1084 * If course-module is not available to students, this string gives information about
1085 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
1086 * January 2010') for display on main page - obtained dynamically
1087 * @var string
1089 private $availableinfo;
1092 * True if this course-module is available to the CURRENT user (for example, if current user
1093 * has viewhiddenactivities capability, they can access the course-module even if it is not
1094 * visible or not available, so this would be true in that case)
1095 * @var bool
1097 private $uservisible;
1100 * True if this course-module is visible to the CURRENT user on the course page
1101 * @var bool
1103 private $uservisibleoncoursepage;
1106 * @var moodle_url
1108 private $url;
1111 * @var string
1113 private $content;
1116 * @var bool
1118 private $contentisformatted;
1121 * @var bool True if the content has a special course item display like labels.
1123 private $customcmlistitem;
1126 * @var string
1128 private $extraclasses;
1131 * @var moodle_url full external url pointing to icon image for activity
1133 private $iconurl;
1136 * @var string
1138 private $onclick;
1141 * @var mixed
1143 private $customdata;
1146 * @var string
1148 private $afterlink;
1151 * @var string
1153 private $afterediticons;
1156 * @var bool representing the deletion state of the module. True if the mod is scheduled for deletion.
1158 private $deletioninprogress;
1161 * @var int enable/disable download content for this course module
1163 private $downloadcontent;
1166 * List of class read-only properties and their getter methods.
1167 * Used by magic functions __get(), __isset(), __empty()
1168 * @var array
1170 private static $standardproperties = array(
1171 'url' => 'get_url',
1172 'content' => 'get_content',
1173 'extraclasses' => 'get_extra_classes',
1174 'onclick' => 'get_on_click',
1175 'customdata' => 'get_custom_data',
1176 'afterlink' => 'get_after_link',
1177 'afterediticons' => 'get_after_edit_icons',
1178 'modfullname' => 'get_module_type_name',
1179 'modplural' => 'get_module_type_name_plural',
1180 'id' => false,
1181 'added' => false,
1182 'availability' => false,
1183 'available' => 'get_available',
1184 'availableinfo' => 'get_available_info',
1185 'completion' => false,
1186 'completionexpected' => false,
1187 'completiongradeitemnumber' => false,
1188 'completionpassgrade' => false,
1189 'completionview' => false,
1190 'conditionscompletion' => false,
1191 'conditionsfield' => false,
1192 'conditionsgrade' => false,
1193 'context' => 'get_context',
1194 'course' => 'get_course_id',
1195 'coursegroupmode' => 'get_course_groupmode',
1196 'coursegroupmodeforce' => 'get_course_groupmodeforce',
1197 'customcmlistitem' => 'has_custom_cmlist_item',
1198 'effectivegroupmode' => 'get_effective_groupmode',
1199 'extra' => false,
1200 'groupingid' => false,
1201 'groupmembersonly' => 'get_deprecated_group_members_only',
1202 'groupmode' => false,
1203 'icon' => false,
1204 'iconcomponent' => false,
1205 'idnumber' => false,
1206 'indent' => false,
1207 'instance' => false,
1208 'modname' => false,
1209 'module' => false,
1210 'name' => 'get_name',
1211 'score' => false,
1212 'section' => false,
1213 'sectionnum' => false,
1214 'showdescription' => false,
1215 'uservisible' => 'get_user_visible',
1216 'visible' => false,
1217 'visibleoncoursepage' => false,
1218 'visibleold' => false,
1219 'deletioninprogress' => false,
1220 'downloadcontent' => false
1224 * List of methods with no arguments that were public prior to Moodle 2.6.
1226 * They can still be accessed publicly via magic __call() function with no warnings
1227 * but are not listed in the class methods list.
1228 * For the consistency of the code it is better to use corresponding properties.
1230 * These methods be deprecated completely in later versions.
1232 * @var array $standardmethods
1234 private static $standardmethods = array(
1235 // Following methods are not recommended to use because there have associated read-only properties.
1236 'get_url',
1237 'get_content',
1238 'get_extra_classes',
1239 'get_on_click',
1240 'get_custom_data',
1241 'get_after_link',
1242 'get_after_edit_icons',
1243 // Method obtain_dynamic_data() should not be called from outside of this class but it was public before Moodle 2.6.
1244 'obtain_dynamic_data',
1248 * Magic method to call functions that are now declared as private but were public in Moodle before 2.6.
1249 * These private methods can not be used anymore.
1251 * @param string $name
1252 * @param array $arguments
1253 * @return mixed
1254 * @throws coding_exception
1256 public function __call($name, $arguments) {
1257 if (in_array($name, self::$standardmethods)) {
1258 $message = "cm_info::$name() can not be used anymore.";
1259 if ($alternative = array_search($name, self::$standardproperties)) {
1260 $message .= " Please use the property cm_info->$alternative instead.";
1262 throw new coding_exception($message);
1264 throw new coding_exception("Method cm_info::{$name}() does not exist");
1268 * Magic method getter
1270 * @param string $name
1271 * @return mixed
1273 public function __get($name) {
1274 if (isset(self::$standardproperties[$name])) {
1275 if ($method = self::$standardproperties[$name]) {
1276 return $this->$method();
1277 } else {
1278 return $this->$name;
1280 } else {
1281 debugging('Invalid cm_info property accessed: '.$name);
1282 return null;
1287 * Implementation of IteratorAggregate::getIterator(), allows to cycle through properties
1288 * and use {@link convert_to_array()}
1290 * @return ArrayIterator
1292 public function getIterator() {
1293 // Make sure dynamic properties are retrieved prior to view properties.
1294 $this->obtain_dynamic_data();
1295 $ret = array();
1297 // Do not iterate over deprecated properties.
1298 $props = self::$standardproperties;
1299 unset($props['groupmembersonly']);
1301 foreach ($props as $key => $unused) {
1302 $ret[$key] = $this->__get($key);
1304 return new ArrayIterator($ret);
1308 * Magic method for function isset()
1310 * @param string $name
1311 * @return bool
1313 public function __isset($name) {
1314 if (isset(self::$standardproperties[$name])) {
1315 $value = $this->__get($name);
1316 return isset($value);
1318 return false;
1322 * Magic method for function empty()
1324 * @param string $name
1325 * @return bool
1327 public function __empty($name) {
1328 if (isset(self::$standardproperties[$name])) {
1329 $value = $this->__get($name);
1330 return empty($value);
1332 return true;
1336 * Magic method setter
1338 * Will display the developer warning when trying to set/overwrite property.
1340 * @param string $name
1341 * @param mixed $value
1343 public function __set($name, $value) {
1344 debugging("It is not allowed to set the property cm_info::\${$name}", DEBUG_DEVELOPER);
1348 * @return bool True if this module has a 'view' page that should be linked to in navigation
1349 * etc (note: modules may still have a view.php file, but return false if this is not
1350 * intended to be linked to from 'normal' parts of the interface; this is what label does).
1352 public function has_view() {
1353 return !is_null($this->url);
1357 * Gets the URL to link to for this module.
1359 * This method is normally called by the property ->url, but can be called directly if
1360 * there is a case when it might be called recursively (you can't call property values
1361 * recursively).
1363 * @return moodle_url URL to link to for this module, or null if it doesn't have a view page
1365 public function get_url() {
1366 $this->obtain_dynamic_data();
1367 return $this->url;
1371 * Obtains content to display on main (view) page.
1372 * Note: Will collect view data, if not already obtained.
1373 * @return string Content to display on main page below link, or empty string if none
1375 private function get_content() {
1376 $this->obtain_view_data();
1377 return $this->content;
1381 * Returns the content to display on course/overview page, formatted and passed through filters
1383 * if $options['context'] is not specified, the module context is used
1385 * @param array|stdClass $options formatting options, see {@link format_text()}
1386 * @return string
1388 public function get_formatted_content($options = array()) {
1389 $this->obtain_view_data();
1390 if (empty($this->content)) {
1391 return '';
1393 if ($this->contentisformatted) {
1394 return $this->content;
1397 // Improve filter performance by preloading filter setttings for all
1398 // activities on the course (this does nothing if called multiple
1399 // times)
1400 filter_preload_activities($this->get_modinfo());
1402 $options = (array)$options;
1403 if (!isset($options['context'])) {
1404 $options['context'] = $this->get_context();
1406 return format_text($this->content, FORMAT_HTML, $options);
1410 * Return the module custom cmlist item flag.
1412 * Activities like label uses this flag to indicate that it should be
1413 * displayed as a custom course item instead of a tipical activity card.
1415 * @return bool
1417 public function has_custom_cmlist_item(): bool {
1418 $this->obtain_view_data();
1419 return $this->customcmlistitem ?? false;
1423 * Getter method for property $name, ensures that dynamic data is obtained.
1425 * This method is normally called by the property ->name, but can be called directly if there
1426 * is a case when it might be called recursively (you can't call property values recursively).
1428 * @return string
1430 public function get_name() {
1431 $this->obtain_dynamic_data();
1432 return $this->name;
1436 * Returns the name to display on course/overview page, formatted and passed through filters
1438 * if $options['context'] is not specified, the module context is used
1440 * @param array|stdClass $options formatting options, see {@link format_string()}
1441 * @return string
1443 public function get_formatted_name($options = array()) {
1444 global $CFG;
1445 $options = (array)$options;
1446 if (!isset($options['context'])) {
1447 $options['context'] = $this->get_context();
1449 // Improve filter performance by preloading filter setttings for all
1450 // activities on the course (this does nothing if called multiple
1451 // times).
1452 if (!empty($CFG->filterall)) {
1453 filter_preload_activities($this->get_modinfo());
1455 return format_string($this->get_name(), true, $options);
1459 * Note: Will collect view data, if not already obtained.
1460 * @return string Extra CSS classes to add to html output for this activity on main page
1462 private function get_extra_classes() {
1463 $this->obtain_view_data();
1464 return $this->extraclasses;
1468 * @return string Content of HTML on-click attribute. This string will be used literally
1469 * as a string so should be pre-escaped.
1471 private function get_on_click() {
1472 // Does not need view data; may be used by navigation
1473 $this->obtain_dynamic_data();
1474 return $this->onclick;
1477 * Getter method for property $customdata, ensures that dynamic data is retrieved.
1479 * This method is normally called by the property ->customdata, but can be called directly if there
1480 * is a case when it might be called recursively (you can't call property values recursively).
1482 * @return mixed Optional custom data stored in modinfo cache for this activity, or null if none
1484 public function get_custom_data() {
1485 $this->obtain_dynamic_data();
1486 return $this->customdata;
1490 * Note: Will collect view data, if not already obtained.
1491 * @return string Extra HTML code to display after link
1493 private function get_after_link() {
1494 $this->obtain_view_data();
1495 return $this->afterlink;
1499 * Note: Will collect view data, if not already obtained.
1500 * @return string Extra HTML code to display after editing icons (e.g. more icons)
1502 private function get_after_edit_icons() {
1503 $this->obtain_view_data();
1504 return $this->afterediticons;
1508 * @param moodle_core_renderer $output Output render to use, or null for default (global)
1509 * @return moodle_url Icon URL for a suitable icon to put beside this cm
1511 public function get_icon_url($output = null) {
1512 global $OUTPUT;
1513 $this->obtain_dynamic_data();
1514 if (!$output) {
1515 $output = $OUTPUT;
1517 // Support modules setting their own, external, icon image
1518 if (!empty($this->iconurl)) {
1519 $icon = $this->iconurl;
1521 // Fallback to normal local icon + component procesing
1522 } else if (!empty($this->icon)) {
1523 if (substr($this->icon, 0, 4) === 'mod/') {
1524 list($modname, $iconname) = explode('/', substr($this->icon, 4), 2);
1525 $icon = $output->image_url($iconname, $modname);
1526 } else {
1527 if (!empty($this->iconcomponent)) {
1528 // Icon has specified component
1529 $icon = $output->image_url($this->icon, $this->iconcomponent);
1530 } else {
1531 // Icon does not have specified component, use default
1532 $icon = $output->image_url($this->icon);
1535 } else {
1536 $icon = $output->image_url('icon', $this->modname);
1538 return $icon;
1542 * @param string $textclasses additionnal classes for grouping label
1543 * @return string An empty string or HTML grouping label span tag
1545 public function get_grouping_label($textclasses = '') {
1546 $groupinglabel = '';
1547 if ($this->effectivegroupmode != NOGROUPS && !empty($this->groupingid) &&
1548 has_capability('moodle/course:managegroups', context_course::instance($this->course))) {
1549 $groupings = groups_get_all_groupings($this->course);
1550 $groupinglabel = html_writer::tag('span', '('.format_string($groupings[$this->groupingid]->name).')',
1551 array('class' => 'groupinglabel '.$textclasses));
1553 return $groupinglabel;
1557 * Returns a localised human-readable name of the module type
1559 * @param bool $plural return plural form
1560 * @return string
1562 public function get_module_type_name($plural = false) {
1563 $modnames = get_module_types_names($plural);
1564 if (isset($modnames[$this->modname])) {
1565 return $modnames[$this->modname];
1566 } else {
1567 return null;
1572 * Returns a localised human-readable name of the module type in plural form - calculated on request
1574 * @return string
1576 private function get_module_type_name_plural() {
1577 return $this->get_module_type_name(true);
1581 * @return course_modinfo Modinfo object that this came from
1583 public function get_modinfo() {
1584 return $this->modinfo;
1588 * Returns the section this module belongs to
1590 * @return section_info
1592 public function get_section_info() {
1593 return $this->modinfo->get_section_info($this->sectionnum);
1597 * Returns course object that was used in the first {@link get_fast_modinfo()} call.
1599 * It may not contain all fields from DB table {course} but always has at least the following:
1600 * id,shortname,fullname,format,enablecompletion,groupmode,groupmodeforce,cacherev
1602 * If the course object lacks the field you need you can use the global
1603 * function {@link get_course()} that will save extra query if you access
1604 * current course or frontpage course.
1606 * @return stdClass
1608 public function get_course() {
1609 return $this->modinfo->get_course();
1613 * Returns course id for which the modinfo was generated.
1615 * @return int
1617 private function get_course_id() {
1618 return $this->modinfo->get_course_id();
1622 * Returns group mode used for the course containing the module
1624 * @return int one of constants NOGROUPS, SEPARATEGROUPS, VISIBLEGROUPS
1626 private function get_course_groupmode() {
1627 return $this->modinfo->get_course()->groupmode;
1631 * Returns whether group mode is forced for the course containing the module
1633 * @return bool
1635 private function get_course_groupmodeforce() {
1636 return $this->modinfo->get_course()->groupmodeforce;
1640 * Returns effective groupmode of the module that may be overwritten by forced course groupmode.
1642 * @return int one of constants NOGROUPS, SEPARATEGROUPS, VISIBLEGROUPS
1644 private function get_effective_groupmode() {
1645 $groupmode = $this->groupmode;
1646 if ($this->modinfo->get_course()->groupmodeforce) {
1647 $groupmode = $this->modinfo->get_course()->groupmode;
1648 if ($groupmode != NOGROUPS && !plugin_supports('mod', $this->modname, FEATURE_GROUPS, false)) {
1649 $groupmode = NOGROUPS;
1652 return $groupmode;
1656 * @return context_module Current module context
1658 private function get_context() {
1659 return context_module::instance($this->id);
1663 * Returns itself in the form of stdClass.
1665 * The object includes all fields that table course_modules has and additionally
1666 * fields 'name', 'modname', 'sectionnum' (if requested).
1668 * This can be used as a faster alternative to {@link get_coursemodule_from_id()}
1670 * @param bool $additionalfields include additional fields 'name', 'modname', 'sectionnum'
1671 * @return stdClass
1673 public function get_course_module_record($additionalfields = false) {
1674 $cmrecord = new stdClass();
1676 // Standard fields from table course_modules.
1677 static $cmfields = array('id', 'course', 'module', 'instance', 'section', 'idnumber', 'added',
1678 'score', 'indent', 'visible', 'visibleoncoursepage', 'visibleold', 'groupmode', 'groupingid',
1679 'completion', 'completiongradeitemnumber', 'completionview', 'completionexpected', 'completionpassgrade',
1680 'showdescription', 'availability', 'deletioninprogress', 'downloadcontent');
1682 foreach ($cmfields as $key) {
1683 $cmrecord->$key = $this->$key;
1686 // Additional fields that function get_coursemodule_from_id() adds.
1687 if ($additionalfields) {
1688 $cmrecord->name = $this->name;
1689 $cmrecord->modname = $this->modname;
1690 $cmrecord->sectionnum = $this->sectionnum;
1693 return $cmrecord;
1696 // Set functions
1697 ////////////////
1700 * Sets content to display on course view page below link (if present).
1701 * @param string $content New content as HTML string (empty string if none)
1702 * @param bool $isformatted Whether user content is already passed through format_text/format_string and should not
1703 * be formatted again. This can be useful when module adds interactive elements on top of formatted user text.
1704 * @return void
1706 public function set_content($content, $isformatted = false) {
1707 $this->content = $content;
1708 $this->contentisformatted = $isformatted;
1712 * Sets extra classes to include in CSS.
1713 * @param string $extraclasses Extra classes (empty string if none)
1714 * @return void
1716 public function set_extra_classes($extraclasses) {
1717 $this->extraclasses = $extraclasses;
1721 * Sets the external full url that points to the icon being used
1722 * by the activity. Useful for external-tool modules (lti...)
1723 * If set, takes precedence over $icon and $iconcomponent
1725 * @param moodle_url $iconurl full external url pointing to icon image for activity
1726 * @return void
1728 public function set_icon_url(moodle_url $iconurl) {
1729 $this->iconurl = $iconurl;
1733 * Sets value of on-click attribute for JavaScript.
1734 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1735 * @param string $onclick New onclick attribute which should be HTML-escaped
1736 * (empty string if none)
1737 * @return void
1739 public function set_on_click($onclick) {
1740 $this->check_not_view_only();
1741 $this->onclick = $onclick;
1745 * Overrides the value of an element in the customdata array.
1747 * @param string $name The key in the customdata array
1748 * @param mixed $value The value
1750 public function override_customdata($name, $value) {
1751 if (!is_array($this->customdata)) {
1752 $this->customdata = [];
1754 $this->customdata[$name] = $value;
1758 * Sets HTML that displays after link on course view page.
1759 * @param string $afterlink HTML string (empty string if none)
1760 * @return void
1762 public function set_after_link($afterlink) {
1763 $this->afterlink = $afterlink;
1767 * Sets HTML that displays after edit icons on course view page.
1768 * @param string $afterediticons HTML string (empty string if none)
1769 * @return void
1771 public function set_after_edit_icons($afterediticons) {
1772 $this->afterediticons = $afterediticons;
1776 * Changes the name (text of link) for this module instance.
1777 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1778 * @param string $name Name of activity / link text
1779 * @return void
1781 public function set_name($name) {
1782 if ($this->state < self::STATE_BUILDING_DYNAMIC) {
1783 $this->update_user_visible();
1785 $this->name = $name;
1789 * Turns off the view link for this module instance.
1790 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1791 * @return void
1793 public function set_no_view_link() {
1794 $this->check_not_view_only();
1795 $this->url = null;
1799 * Sets the 'uservisible' flag. This can be used (by setting false) to prevent access and
1800 * display of this module link for the current user.
1801 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1802 * @param bool $uservisible
1803 * @return void
1805 public function set_user_visible($uservisible) {
1806 $this->check_not_view_only();
1807 $this->uservisible = $uservisible;
1811 * Sets the 'customcmlistitem' flag
1813 * This can be used (by setting true) to prevent the course from rendering the
1814 * activity item as a regular activity card. This is applied to activities like labels.
1816 * @param bool $customcmlistitem if the cmlist item of that activity has a special dysplay other than a card.
1818 public function set_custom_cmlist_item(bool $customcmlistitem) {
1819 $this->customcmlistitem = $customcmlistitem;
1823 * Sets the 'available' flag and related details. This flag is normally used to make
1824 * course modules unavailable until a certain date or condition is met. (When a course
1825 * module is unavailable, it is still visible to users who have viewhiddenactivities
1826 * permission.)
1828 * When this is function is called, user-visible status is recalculated automatically.
1830 * The $showavailability flag does not really do anything any more, but is retained
1831 * for backward compatibility. Setting this to false will cause $availableinfo to
1832 * be ignored.
1834 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1835 * @param bool $available False if this item is not 'available'
1836 * @param int $showavailability 0 = do not show this item at all if it's not available,
1837 * 1 = show this item greyed out with the following message
1838 * @param string $availableinfo Information about why this is not available, or
1839 * empty string if not displaying
1840 * @return void
1842 public function set_available($available, $showavailability=0, $availableinfo='') {
1843 $this->check_not_view_only();
1844 $this->available = $available;
1845 if (!$showavailability) {
1846 $availableinfo = '';
1848 $this->availableinfo = $availableinfo;
1849 $this->update_user_visible();
1853 * Some set functions can only be called from _cm_info_dynamic and not _cm_info_view.
1854 * This is because they may affect parts of this object which are used on pages other
1855 * than the view page (e.g. in the navigation block, or when checking access on
1856 * module pages).
1857 * @return void
1859 private function check_not_view_only() {
1860 if ($this->state >= self::STATE_DYNAMIC) {
1861 throw new coding_exception('Cannot set this data from _cm_info_view because it may ' .
1862 'affect other pages as well as view');
1867 * Constructor should not be called directly; use {@link get_fast_modinfo()}
1869 * @param course_modinfo $modinfo Parent object
1870 * @param stdClass $notused1 Argument not used
1871 * @param stdClass $mod Module object from the modinfo field of course table
1872 * @param stdClass $notused2 Argument not used
1874 public function __construct(course_modinfo $modinfo, $notused1, $mod, $notused2) {
1875 $this->modinfo = $modinfo;
1877 $this->id = $mod->cm;
1878 $this->instance = $mod->id;
1879 $this->modname = $mod->mod;
1880 $this->idnumber = isset($mod->idnumber) ? $mod->idnumber : '';
1881 $this->name = $mod->name;
1882 $this->visible = $mod->visible;
1883 $this->visibleoncoursepage = $mod->visibleoncoursepage;
1884 $this->sectionnum = $mod->section; // Note weirdness with name here
1885 $this->groupmode = isset($mod->groupmode) ? $mod->groupmode : 0;
1886 $this->groupingid = isset($mod->groupingid) ? $mod->groupingid : 0;
1887 $this->indent = isset($mod->indent) ? $mod->indent : 0;
1888 $this->extra = isset($mod->extra) ? $mod->extra : '';
1889 $this->extraclasses = isset($mod->extraclasses) ? $mod->extraclasses : '';
1890 // iconurl may be stored as either string or instance of moodle_url.
1891 $this->iconurl = isset($mod->iconurl) ? new moodle_url($mod->iconurl) : '';
1892 $this->onclick = isset($mod->onclick) ? $mod->onclick : '';
1893 $this->content = isset($mod->content) ? $mod->content : '';
1894 $this->icon = isset($mod->icon) ? $mod->icon : '';
1895 $this->iconcomponent = isset($mod->iconcomponent) ? $mod->iconcomponent : '';
1896 $this->customdata = isset($mod->customdata) ? $mod->customdata : '';
1897 $this->showdescription = isset($mod->showdescription) ? $mod->showdescription : 0;
1898 $this->state = self::STATE_BASIC;
1900 $this->section = isset($mod->sectionid) ? $mod->sectionid : 0;
1901 $this->module = isset($mod->module) ? $mod->module : 0;
1902 $this->added = isset($mod->added) ? $mod->added : 0;
1903 $this->score = isset($mod->score) ? $mod->score : 0;
1904 $this->visibleold = isset($mod->visibleold) ? $mod->visibleold : 0;
1905 $this->deletioninprogress = isset($mod->deletioninprogress) ? $mod->deletioninprogress : 0;
1906 $this->downloadcontent = $mod->downloadcontent ?? null;
1908 // Note: it saves effort and database space to always include the
1909 // availability and completion fields, even if availability or completion
1910 // are actually disabled
1911 $this->completion = isset($mod->completion) ? $mod->completion : 0;
1912 $this->completionpassgrade = isset($mod->completionpassgrade) ? $mod->completionpassgrade : 0;
1913 $this->completiongradeitemnumber = isset($mod->completiongradeitemnumber)
1914 ? $mod->completiongradeitemnumber : null;
1915 $this->completionview = isset($mod->completionview)
1916 ? $mod->completionview : 0;
1917 $this->completionexpected = isset($mod->completionexpected)
1918 ? $mod->completionexpected : 0;
1919 $this->availability = isset($mod->availability) ? $mod->availability : null;
1920 $this->conditionscompletion = isset($mod->conditionscompletion)
1921 ? $mod->conditionscompletion : array();
1922 $this->conditionsgrade = isset($mod->conditionsgrade)
1923 ? $mod->conditionsgrade : array();
1924 $this->conditionsfield = isset($mod->conditionsfield)
1925 ? $mod->conditionsfield : array();
1927 static $modviews = array();
1928 if (!isset($modviews[$this->modname])) {
1929 $modviews[$this->modname] = !plugin_supports('mod', $this->modname,
1930 FEATURE_NO_VIEW_LINK);
1932 $this->url = $modviews[$this->modname]
1933 ? new moodle_url('/mod/' . $this->modname . '/view.php', array('id'=>$this->id))
1934 : null;
1938 * Creates a cm_info object from a database record (also accepts cm_info
1939 * in which case it is just returned unchanged).
1941 * @param stdClass|cm_info|null|bool $cm Stdclass or cm_info (or null or false)
1942 * @param int $userid Optional userid (default to current)
1943 * @return cm_info|null Object as cm_info, or null if input was null/false
1945 public static function create($cm, $userid = 0) {
1946 // Null, false, etc. gets passed through as null.
1947 if (!$cm) {
1948 return null;
1950 // If it is already a cm_info object, just return it.
1951 if ($cm instanceof cm_info) {
1952 return $cm;
1954 // Otherwise load modinfo.
1955 if (empty($cm->id) || empty($cm->course)) {
1956 throw new coding_exception('$cm must contain ->id and ->course');
1958 $modinfo = get_fast_modinfo($cm->course, $userid);
1959 return $modinfo->get_cm($cm->id);
1963 * If dynamic data for this course-module is not yet available, gets it.
1965 * This function is automatically called when requesting any course_modinfo property
1966 * that can be modified by modules (have a set_xxx method).
1968 * Dynamic data is data which does not come directly from the cache but is calculated at
1969 * runtime based on the current user. Primarily this concerns whether the user can access
1970 * the module or not.
1972 * As part of this function, the module's _cm_info_dynamic function from its lib.php will
1973 * be called (if it exists). Make sure that the functions that are called here do not use
1974 * any getter magic method from cm_info.
1975 * @return void
1977 private function obtain_dynamic_data() {
1978 global $CFG;
1979 $userid = $this->modinfo->get_user_id();
1980 if ($this->state >= self::STATE_BUILDING_DYNAMIC || $userid == -1) {
1981 return;
1983 $this->state = self::STATE_BUILDING_DYNAMIC;
1985 if (!empty($CFG->enableavailability)) {
1986 // Get availability information.
1987 $ci = new \core_availability\info_module($this);
1989 // Note that the modinfo currently available only includes minimal details (basic data)
1990 // but we know that this function does not need anything more than basic data.
1991 $this->available = $ci->is_available($this->availableinfo, true,
1992 $userid, $this->modinfo);
1993 } else {
1994 $this->available = true;
1997 // Check parent section.
1998 if ($this->available) {
1999 $parentsection = $this->modinfo->get_section_info($this->sectionnum);
2000 if (!$parentsection->get_available()) {
2001 // Do not store info from section here, as that is already
2002 // presented from the section (if appropriate) - just change
2003 // the flag
2004 $this->available = false;
2008 // Update visible state for current user.
2009 $this->update_user_visible();
2011 // Let module make dynamic changes at this point
2012 $this->call_mod_function('cm_info_dynamic');
2013 $this->state = self::STATE_DYNAMIC;
2017 * Getter method for property $uservisible, ensures that dynamic data is retrieved.
2019 * This method is normally called by the property ->uservisible, but can be called directly if
2020 * there is a case when it might be called recursively (you can't call property values
2021 * recursively).
2023 * @return bool
2025 public function get_user_visible() {
2026 $this->obtain_dynamic_data();
2027 return $this->uservisible;
2031 * Returns whether this module is visible to the current user on course page
2033 * Activity may be visible on the course page but not available, for example
2034 * when it is hidden conditionally but the condition information is displayed.
2036 * @return bool
2038 public function is_visible_on_course_page() {
2039 $this->obtain_dynamic_data();
2040 return $this->uservisibleoncoursepage;
2044 * Whether this module is available but hidden from course page
2046 * "Stealth" modules are the ones that are not shown on course page but available by following url.
2047 * They are normally also displayed in grade reports and other reports.
2048 * Module will be stealth either if visibleoncoursepage=0 or it is a visible module inside the hidden
2049 * section.
2051 * @return bool
2053 public function is_stealth() {
2054 return !$this->visibleoncoursepage ||
2055 ($this->visible && ($section = $this->get_section_info()) && !$section->visible);
2059 * Getter method for property $available, ensures that dynamic data is retrieved
2060 * @return bool
2062 private function get_available() {
2063 $this->obtain_dynamic_data();
2064 return $this->available;
2068 * This method can not be used anymore.
2070 * @see \core_availability\info_module::filter_user_list()
2071 * @deprecated Since Moodle 2.8
2073 private function get_deprecated_group_members_only() {
2074 throw new coding_exception('$cm->groupmembersonly can not be used anymore. ' .
2075 'If used to restrict a list of enrolled users to only those who can ' .
2076 'access the module, consider \core_availability\info_module::filter_user_list.');
2080 * Getter method for property $availableinfo, ensures that dynamic data is retrieved
2082 * @return string Available info (HTML)
2084 private function get_available_info() {
2085 $this->obtain_dynamic_data();
2086 return $this->availableinfo;
2090 * Works out whether activity is available to the current user
2092 * If the activity is unavailable, additional checks are required to determine if its hidden or greyed out
2094 * @return void
2096 private function update_user_visible() {
2097 $userid = $this->modinfo->get_user_id();
2098 if ($userid == -1) {
2099 return null;
2101 $this->uservisible = true;
2103 // If the module is being deleted, set the uservisible state to false and return.
2104 if ($this->deletioninprogress) {
2105 $this->uservisible = false;
2106 return null;
2109 // If the user cannot access the activity set the uservisible flag to false.
2110 // Additional checks are required to determine whether the activity is entirely hidden or just greyed out.
2111 if ((!$this->visible && !has_capability('moodle/course:viewhiddenactivities', $this->get_context(), $userid)) ||
2112 (!$this->get_available() &&
2113 !has_capability('moodle/course:ignoreavailabilityrestrictions', $this->get_context(), $userid))) {
2115 $this->uservisible = false;
2118 // Check group membership.
2119 if ($this->is_user_access_restricted_by_capability()) {
2121 $this->uservisible = false;
2122 // Ensure activity is completely hidden from the user.
2123 $this->availableinfo = '';
2126 $this->uservisibleoncoursepage = $this->uservisible &&
2127 ($this->visibleoncoursepage ||
2128 has_capability('moodle/course:manageactivities', $this->get_context(), $userid) ||
2129 has_capability('moodle/course:activityvisibility', $this->get_context(), $userid));
2130 // Activity that is not available, not hidden from course page and has availability
2131 // info is actually visible on the course page (with availability info and without a link).
2132 if (!$this->uservisible && $this->visibleoncoursepage && $this->availableinfo) {
2133 $this->uservisibleoncoursepage = true;
2138 * This method has been deprecated and should not be used.
2140 * @see $uservisible
2141 * @deprecated Since Moodle 2.8
2143 public function is_user_access_restricted_by_group() {
2144 throw new coding_exception('cm_info::is_user_access_restricted_by_group() can not be used any more.' .
2145 ' Use $cm->uservisible to decide whether the current user can access an activity.');
2149 * Checks whether mod/...:view capability restricts the current user's access.
2151 * @return bool True if the user access is restricted.
2153 public function is_user_access_restricted_by_capability() {
2154 $userid = $this->modinfo->get_user_id();
2155 if ($userid == -1) {
2156 return null;
2158 $capability = 'mod/' . $this->modname . ':view';
2159 $capabilityinfo = get_capability_info($capability);
2160 if (!$capabilityinfo) {
2161 // Capability does not exist, no one is prevented from seeing the activity.
2162 return false;
2165 // You are blocked if you don't have the capability.
2166 return !has_capability($capability, $this->get_context(), $userid);
2170 * Checks whether the module's conditional access settings mean that the
2171 * user cannot see the activity at all
2173 * @deprecated since 2.7 MDL-44070
2175 public function is_user_access_restricted_by_conditional_access() {
2176 throw new coding_exception('cm_info::is_user_access_restricted_by_conditional_access() ' .
2177 'can not be used any more; this function is not needed (use $cm->uservisible ' .
2178 'and $cm->availableinfo to decide whether it should be available ' .
2179 'or appear)');
2183 * Calls a module function (if exists), passing in one parameter: this object.
2184 * @param string $type Name of function e.g. if this is 'grooblezorb' and the modname is
2185 * 'forum' then it will try to call 'mod_forum_grooblezorb' or 'forum_grooblezorb'
2186 * @return void
2188 private function call_mod_function($type) {
2189 global $CFG;
2190 $libfile = $CFG->dirroot . '/mod/' . $this->modname . '/lib.php';
2191 if (file_exists($libfile)) {
2192 include_once($libfile);
2193 $function = 'mod_' . $this->modname . '_' . $type;
2194 if (function_exists($function)) {
2195 $function($this);
2196 } else {
2197 $function = $this->modname . '_' . $type;
2198 if (function_exists($function)) {
2199 $function($this);
2206 * If view data for this course-module is not yet available, obtains it.
2208 * This function is automatically called if any of the functions (marked) which require
2209 * view data are called.
2211 * View data is data which is needed only for displaying the course main page (& any similar
2212 * functionality on other pages) but is not needed in general. Obtaining view data may have
2213 * a performance cost.
2215 * As part of this function, the module's _cm_info_view function from its lib.php will
2216 * be called (if it exists).
2217 * @return void
2219 private function obtain_view_data() {
2220 if ($this->state >= self::STATE_BUILDING_VIEW || $this->modinfo->get_user_id() == -1) {
2221 return;
2223 $this->obtain_dynamic_data();
2224 $this->state = self::STATE_BUILDING_VIEW;
2226 // Let module make changes at this point
2227 $this->call_mod_function('cm_info_view');
2228 $this->state = self::STATE_VIEW;
2234 * Returns reference to full info about modules in course (including visibility).
2235 * Cached and as fast as possible (0 or 1 db query).
2237 * use get_fast_modinfo($courseid, 0, true) to reset the static cache for particular course
2238 * use get_fast_modinfo(0, 0, true) to reset the static cache for all courses
2240 * use rebuild_course_cache($courseid, true) to reset the application AND static cache
2241 * for particular course when it's contents has changed
2243 * @param int|stdClass $courseorid object from DB table 'course' (must have field 'id'
2244 * and recommended to have field 'cacherev') or just a course id. Just course id
2245 * is enough when calling get_fast_modinfo() for current course or site or when
2246 * calling for any other course for the second time.
2247 * @param int $userid User id to populate 'availble' and 'uservisible' attributes of modules and sections.
2248 * Set to 0 for current user (default). Set to -1 to avoid calculation of dynamic user-depended data.
2249 * @param bool $resetonly whether we want to get modinfo or just reset the cache
2250 * @return course_modinfo|null Module information for course, or null if resetting
2251 * @throws moodle_exception when course is not found (nothing is thrown if resetting)
2253 function get_fast_modinfo($courseorid, $userid = 0, $resetonly = false) {
2254 // compartibility with syntax prior to 2.4:
2255 if ($courseorid === 'reset') {
2256 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);
2257 $courseorid = 0;
2258 $resetonly = true;
2261 // Function get_fast_modinfo() can never be called during upgrade unless it is used for clearing cache only.
2262 if (!$resetonly) {
2263 upgrade_ensure_not_running();
2266 // Function is called with $reset = true
2267 if ($resetonly) {
2268 course_modinfo::clear_instance_cache($courseorid);
2269 return null;
2272 // Function is called with $reset = false, retrieve modinfo
2273 return course_modinfo::instance($courseorid, $userid);
2277 * Efficiently retrieves the $course (stdclass) and $cm (cm_info) objects, given
2278 * a cmid. If module name is also provided, it will ensure the cm is of that type.
2280 * Usage:
2281 * list($course, $cm) = get_course_and_cm_from_cmid($cmid, 'forum');
2283 * Using this method has a performance advantage because it works by loading
2284 * modinfo for the course - which will then be cached and it is needed later
2285 * in most requests. It also guarantees that the $cm object is a cm_info and
2286 * not a stdclass.
2288 * The $course object can be supplied if already known and will speed
2289 * up this function - although it is more efficient to use this function to
2290 * get the course if you are starting from a cmid.
2292 * To avoid security problems and obscure bugs, you should always specify
2293 * $modulename if the cmid value came from user input.
2295 * By default this obtains information (for example, whether user can access
2296 * the activity) for current user, but you can specify a userid if required.
2298 * @param stdClass|int $cmorid Id of course-module, or database object
2299 * @param string $modulename Optional modulename (improves security)
2300 * @param stdClass|int $courseorid Optional course object if already loaded
2301 * @param int $userid Optional userid (default = current)
2302 * @return array Array with 2 elements $course and $cm
2303 * @throws moodle_exception If the item doesn't exist or is of wrong module name
2305 function get_course_and_cm_from_cmid($cmorid, $modulename = '', $courseorid = 0, $userid = 0) {
2306 global $DB;
2307 if (is_object($cmorid)) {
2308 $cmid = $cmorid->id;
2309 if (isset($cmorid->course)) {
2310 $courseid = (int)$cmorid->course;
2311 } else {
2312 $courseid = 0;
2314 } else {
2315 $cmid = (int)$cmorid;
2316 $courseid = 0;
2319 // Validate module name if supplied.
2320 if ($modulename && !core_component::is_valid_plugin_name('mod', $modulename)) {
2321 throw new coding_exception('Invalid modulename parameter');
2324 // Get course from last parameter if supplied.
2325 $course = null;
2326 if (is_object($courseorid)) {
2327 $course = $courseorid;
2328 } else if ($courseorid) {
2329 $courseid = (int)$courseorid;
2332 if (!$course) {
2333 if ($courseid) {
2334 // If course ID is known, get it using normal function.
2335 $course = get_course($courseid);
2336 } else {
2337 // Get course record in a single query based on cmid.
2338 $course = $DB->get_record_sql("
2339 SELECT c.*
2340 FROM {course_modules} cm
2341 JOIN {course} c ON c.id = cm.course
2342 WHERE cm.id = ?", array($cmid), MUST_EXIST);
2346 // Get cm from get_fast_modinfo.
2347 $modinfo = get_fast_modinfo($course, $userid);
2348 $cm = $modinfo->get_cm($cmid);
2349 if ($modulename && $cm->modname !== $modulename) {
2350 throw new moodle_exception('invalidcoursemodule', 'error');
2352 return array($course, $cm);
2356 * Efficiently retrieves the $course (stdclass) and $cm (cm_info) objects, given
2357 * an instance id or record and module name.
2359 * Usage:
2360 * list($course, $cm) = get_course_and_cm_from_instance($forum, 'forum');
2362 * Using this method has a performance advantage because it works by loading
2363 * modinfo for the course - which will then be cached and it is needed later
2364 * in most requests. It also guarantees that the $cm object is a cm_info and
2365 * not a stdclass.
2367 * The $course object can be supplied if already known and will speed
2368 * up this function - although it is more efficient to use this function to
2369 * get the course if you are starting from an instance id.
2371 * By default this obtains information (for example, whether user can access
2372 * the activity) for current user, but you can specify a userid if required.
2374 * @param stdclass|int $instanceorid Id of module instance, or database object
2375 * @param string $modulename Modulename (required)
2376 * @param stdClass|int $courseorid Optional course object if already loaded
2377 * @param int $userid Optional userid (default = current)
2378 * @return array Array with 2 elements $course and $cm
2379 * @throws moodle_exception If the item doesn't exist or is of wrong module name
2381 function get_course_and_cm_from_instance($instanceorid, $modulename, $courseorid = 0, $userid = 0) {
2382 global $DB;
2384 // Get data from parameter.
2385 if (is_object($instanceorid)) {
2386 $instanceid = $instanceorid->id;
2387 if (isset($instanceorid->course)) {
2388 $courseid = (int)$instanceorid->course;
2389 } else {
2390 $courseid = 0;
2392 } else {
2393 $instanceid = (int)$instanceorid;
2394 $courseid = 0;
2397 // Get course from last parameter if supplied.
2398 $course = null;
2399 if (is_object($courseorid)) {
2400 $course = $courseorid;
2401 } else if ($courseorid) {
2402 $courseid = (int)$courseorid;
2405 // Validate module name if supplied.
2406 if (!core_component::is_valid_plugin_name('mod', $modulename)) {
2407 throw new coding_exception('Invalid modulename parameter');
2410 if (!$course) {
2411 if ($courseid) {
2412 // If course ID is known, get it using normal function.
2413 $course = get_course($courseid);
2414 } else {
2415 // Get course record in a single query based on instance id.
2416 $pagetable = '{' . $modulename . '}';
2417 $course = $DB->get_record_sql("
2418 SELECT c.*
2419 FROM $pagetable instance
2420 JOIN {course} c ON c.id = instance.course
2421 WHERE instance.id = ?", array($instanceid), MUST_EXIST);
2425 // Get cm from get_fast_modinfo.
2426 $modinfo = get_fast_modinfo($course, $userid);
2427 $instances = $modinfo->get_instances_of($modulename);
2428 if (!array_key_exists($instanceid, $instances)) {
2429 throw new moodle_exception('invalidmoduleid', 'error', $instanceid);
2431 return array($course, $instances[$instanceid]);
2436 * Rebuilds or resets the cached list of course activities stored in MUC.
2438 * rebuild_course_cache() must NEVER be called from lib/db/upgrade.php.
2439 * At the same time course cache may ONLY be cleared using this function in
2440 * upgrade scripts of plugins.
2442 * During the bulk operations if it is necessary to reset cache of multiple
2443 * courses it is enough to call {@link increment_revision_number()} for the
2444 * table 'course' and field 'cacherev' specifying affected courses in select.
2446 * Cached course information is stored in MUC core/coursemodinfo and is
2447 * validated with the DB field {course}.cacherev
2449 * @global moodle_database $DB
2450 * @param int $courseid id of course to rebuild, empty means all
2451 * @param boolean $clearonly only clear the cache, gets rebuild automatically on the fly.
2452 * Recommended to set to true to avoid unnecessary multiple rebuilding.
2454 function rebuild_course_cache($courseid=0, $clearonly=false) {
2455 global $COURSE, $SITE, $DB, $CFG;
2457 // Function rebuild_course_cache() can not be called during upgrade unless it's clear only.
2458 if (!$clearonly && !upgrade_ensure_not_running(true)) {
2459 $clearonly = true;
2462 // Destroy navigation caches
2463 navigation_cache::destroy_volatile_caches();
2465 core_courseformat\base::reset_course_cache($courseid);
2467 $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
2468 if (empty($courseid)) {
2469 // Clearing caches for all courses.
2470 increment_revision_number('course', 'cacherev', '');
2471 $cachecoursemodinfo->purge();
2472 course_modinfo::clear_instance_cache();
2473 // Update global values too.
2474 $sitecacherev = $DB->get_field('course', 'cacherev', array('id' => SITEID));
2475 $SITE->cachrev = $sitecacherev;
2476 if ($COURSE->id == SITEID) {
2477 $COURSE->cacherev = $sitecacherev;
2478 } else {
2479 $COURSE->cacherev = $DB->get_field('course', 'cacherev', array('id' => $COURSE->id));
2481 } else {
2482 // Clearing cache for one course, make sure it is deleted from user request cache as well.
2483 increment_revision_number('course', 'cacherev', 'id = :id', array('id' => $courseid));
2484 $cachecoursemodinfo->delete($courseid);
2485 course_modinfo::clear_instance_cache($courseid);
2486 // Update global values too.
2487 if ($courseid == $COURSE->id || $courseid == $SITE->id) {
2488 $cacherev = $DB->get_field('course', 'cacherev', array('id' => $courseid));
2489 if ($courseid == $COURSE->id) {
2490 $COURSE->cacherev = $cacherev;
2492 if ($courseid == $SITE->id) {
2493 $SITE->cachrev = $cacherev;
2498 if ($clearonly) {
2499 return;
2502 if ($courseid) {
2503 $select = array('id'=>$courseid);
2504 } else {
2505 $select = array();
2506 core_php_time_limit::raise(); // this could take a while! MDL-10954
2509 $rs = $DB->get_recordset("course", $select,'','id,'.join(',', course_modinfo::$cachedfields));
2510 // Rebuild cache for each course.
2511 foreach ($rs as $course) {
2512 course_modinfo::build_course_cache($course);
2514 $rs->close();
2519 * Class that is the return value for the _get_coursemodule_info module API function.
2521 * Note: For backward compatibility, you can also return a stdclass object from that function.
2522 * The difference is that the stdclass object may contain an 'extra' field (deprecated,
2523 * use extraclasses and onclick instead). The stdclass object may not contain
2524 * the new fields defined here (content, extraclasses, customdata).
2526 class cached_cm_info {
2528 * Name (text of link) for this activity; Leave unset to accept default name
2529 * @var string
2531 public $name;
2534 * Name of icon for this activity. Normally, this should be used together with $iconcomponent
2535 * to define the icon, as per image_url function.
2536 * For backward compatibility, if this value is of the form 'mod/forum/icon' then an icon
2537 * within that module will be used.
2538 * @see cm_info::get_icon_url()
2539 * @see renderer_base::image_url()
2540 * @var string
2542 public $icon;
2545 * Component for icon for this activity, as per image_url; leave blank to use default 'moodle'
2546 * component
2547 * @see renderer_base::image_url()
2548 * @var string
2550 public $iconcomponent;
2553 * HTML content to be displayed on the main page below the link (if any) for this course-module
2554 * @var string
2556 public $content;
2559 * Custom data to be stored in modinfo for this activity; useful if there are cases when
2560 * internal information for this activity type needs to be accessible from elsewhere on the
2561 * course without making database queries. May be of any type but should be short.
2562 * @var mixed
2564 public $customdata;
2567 * Extra CSS class or classes to be added when this activity is displayed on the main page;
2568 * space-separated string
2569 * @var string
2571 public $extraclasses;
2574 * External URL image to be used by activity as icon, useful for some external-tool modules
2575 * like lti. If set, takes precedence over $icon and $iconcomponent
2576 * @var $moodle_url
2578 public $iconurl;
2581 * Content of onclick JavaScript; escaped HTML to be inserted as attribute value
2582 * @var string
2584 public $onclick;
2589 * Data about a single section on a course. This contains the fields from the
2590 * course_sections table, plus additional data when required.
2592 * @property-read int $id Section ID - from course_sections table
2593 * @property-read int $course Course ID - from course_sections table
2594 * @property-read int $section Section number - from course_sections table
2595 * @property-read string $name Section name if specified - from course_sections table
2596 * @property-read int $visible Section visibility (1 = visible) - from course_sections table
2597 * @property-read string $summary Section summary text if specified - from course_sections table
2598 * @property-read int $summaryformat Section summary text format (FORMAT_xx constant) - from course_sections table
2599 * @property-read string $availability Availability information as JSON string -
2600 * from course_sections table
2601 * @property-read array $conditionscompletion Availability conditions for this section based on the completion of
2602 * course-modules (array from course-module id to required completion state
2603 * for that module) - from cached data in sectioncache field
2604 * @property-read array $conditionsgrade Availability conditions for this section based on course grades (array from
2605 * grade item id to object with ->min, ->max fields) - from cached data in
2606 * sectioncache field
2607 * @property-read array $conditionsfield Availability conditions for this section based on user fields
2608 * @property-read bool $available True if this section is available to the given user i.e. if all availability conditions
2609 * are met - obtained dynamically
2610 * @property-read string $availableinfo If section is not available to some users, this string gives information about
2611 * availability which can be displayed to students and/or staff (e.g. 'Available from 3 January 2010')
2612 * for display on main page - obtained dynamically
2613 * @property-read bool $uservisible True if this section is available to the given user (for example, if current user
2614 * has viewhiddensections capability, they can access the section even if it is not
2615 * visible or not available, so this would be true in that case) - obtained dynamically
2616 * @property-read string $sequence Comma-separated list of all modules in the section. Note, this field may not exactly
2617 * match course_sections.sequence if later has references to non-existing modules or not modules of not available module types.
2618 * @property-read course_modinfo $modinfo
2620 class section_info implements IteratorAggregate {
2622 * Section ID - from course_sections table
2623 * @var int
2625 private $_id;
2628 * Section number - from course_sections table
2629 * @var int
2631 private $_section;
2634 * Section name if specified - from course_sections table
2635 * @var string
2637 private $_name;
2640 * Section visibility (1 = visible) - from course_sections table
2641 * @var int
2643 private $_visible;
2646 * Section summary text if specified - from course_sections table
2647 * @var string
2649 private $_summary;
2652 * Section summary text format (FORMAT_xx constant) - from course_sections table
2653 * @var int
2655 private $_summaryformat;
2658 * Availability information as JSON string - from course_sections table
2659 * @var string
2661 private $_availability;
2664 * Availability conditions for this section based on the completion of
2665 * course-modules (array from course-module id to required completion state
2666 * for that module) - from cached data in sectioncache field
2667 * @var array
2669 private $_conditionscompletion;
2672 * Availability conditions for this section based on course grades (array from
2673 * grade item id to object with ->min, ->max fields) - from cached data in
2674 * sectioncache field
2675 * @var array
2677 private $_conditionsgrade;
2680 * Availability conditions for this section based on user fields
2681 * @var array
2683 private $_conditionsfield;
2686 * True if this section is available to students i.e. if all availability conditions
2687 * are met - obtained dynamically on request, see function {@link section_info::get_available()}
2688 * @var bool|null
2690 private $_available;
2693 * If section is not available to some users, this string gives information about
2694 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
2695 * January 2010') for display on main page - obtained dynamically on request, see
2696 * function {@link section_info::get_availableinfo()}
2697 * @var string
2699 private $_availableinfo;
2702 * True if this section is available to the CURRENT user (for example, if current user
2703 * has viewhiddensections capability, they can access the section even if it is not
2704 * visible or not available, so this would be true in that case) - obtained dynamically
2705 * on request, see function {@link section_info::get_uservisible()}
2706 * @var bool|null
2708 private $_uservisible;
2711 * Default values for sectioncache fields; if a field has this value, it won't
2712 * be stored in the sectioncache cache, to save space. Checks are done by ===
2713 * which means values must all be strings.
2714 * @var array
2716 private static $sectioncachedefaults = array(
2717 'name' => null,
2718 'summary' => '',
2719 'summaryformat' => '1', // FORMAT_HTML, but must be a string
2720 'visible' => '1',
2721 'availability' => null
2725 * Stores format options that have been cached when building 'coursecache'
2726 * When the format option is requested we look first if it has been cached
2727 * @var array
2729 private $cachedformatoptions = array();
2732 * Stores the list of all possible section options defined in each used course format.
2733 * @var array
2735 static private $sectionformatoptions = array();
2738 * Stores the modinfo object passed in constructor, may be used when requesting
2739 * dynamically obtained attributes such as available, availableinfo, uservisible.
2740 * Also used to retrun information about current course or user.
2741 * @var course_modinfo
2743 private $modinfo;
2746 * Constructs object from database information plus extra required data.
2747 * @param object $data Array entry from cached sectioncache
2748 * @param int $number Section number (array key)
2749 * @param int $notused1 argument not used (informaion is available in $modinfo)
2750 * @param int $notused2 argument not used (informaion is available in $modinfo)
2751 * @param course_modinfo $modinfo Owner (needed for checking availability)
2752 * @param int $notused3 argument not used (informaion is available in $modinfo)
2754 public function __construct($data, $number, $notused1, $notused2, $modinfo, $notused3) {
2755 global $CFG;
2756 require_once($CFG->dirroot.'/course/lib.php');
2758 // Data that is always present
2759 $this->_id = $data->id;
2761 $defaults = self::$sectioncachedefaults +
2762 array('conditionscompletion' => array(),
2763 'conditionsgrade' => array(),
2764 'conditionsfield' => array());
2766 // Data that may use default values to save cache size
2767 foreach ($defaults as $field => $value) {
2768 if (isset($data->{$field})) {
2769 $this->{'_'.$field} = $data->{$field};
2770 } else {
2771 $this->{'_'.$field} = $value;
2775 // Other data from constructor arguments.
2776 $this->_section = $number;
2777 $this->modinfo = $modinfo;
2779 // Cached course format data.
2780 $course = $modinfo->get_course();
2781 if (!isset(self::$sectionformatoptions[$course->format])) {
2782 // Store list of section format options defined in each used course format.
2783 // They do not depend on particular course but only on its format.
2784 self::$sectionformatoptions[$course->format] =
2785 course_get_format($course)->section_format_options();
2787 foreach (self::$sectionformatoptions[$course->format] as $field => $option) {
2788 if (!empty($option['cache'])) {
2789 if (isset($data->{$field})) {
2790 $this->cachedformatoptions[$field] = $data->{$field};
2791 } else if (array_key_exists('cachedefault', $option)) {
2792 $this->cachedformatoptions[$field] = $option['cachedefault'];
2799 * Magic method to check if the property is set
2801 * @param string $name name of the property
2802 * @return bool
2804 public function __isset($name) {
2805 if (method_exists($this, 'get_'.$name) ||
2806 property_exists($this, '_'.$name) ||
2807 array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
2808 $value = $this->__get($name);
2809 return isset($value);
2811 return false;
2815 * Magic method to check if the property is empty
2817 * @param string $name name of the property
2818 * @return bool
2820 public function __empty($name) {
2821 if (method_exists($this, 'get_'.$name) ||
2822 property_exists($this, '_'.$name) ||
2823 array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
2824 $value = $this->__get($name);
2825 return empty($value);
2827 return true;
2831 * Magic method to retrieve the property, this is either basic section property
2832 * or availability information or additional properties added by course format
2834 * @param string $name name of the property
2835 * @return bool
2837 public function __get($name) {
2838 if (method_exists($this, 'get_'.$name)) {
2839 return $this->{'get_'.$name}();
2841 if (property_exists($this, '_'.$name)) {
2842 return $this->{'_'.$name};
2844 if (array_key_exists($name, $this->cachedformatoptions)) {
2845 return $this->cachedformatoptions[$name];
2847 // precheck if the option is defined in format to avoid unnecessary DB queries in get_format_options()
2848 if (array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
2849 $formatoptions = course_get_format($this->modinfo->get_course())->get_format_options($this);
2850 return $formatoptions[$name];
2852 debugging('Invalid section_info property accessed! '.$name);
2853 return null;
2857 * Finds whether this section is available at the moment for the current user.
2859 * The value can be accessed publicly as $sectioninfo->available, but can be called directly if there
2860 * is a case when it might be called recursively (you can't call property values recursively).
2862 * @return bool
2864 public function get_available() {
2865 global $CFG;
2866 $userid = $this->modinfo->get_user_id();
2867 if ($this->_available !== null || $userid == -1) {
2868 // Has already been calculated or does not need calculation.
2869 return $this->_available;
2871 $this->_available = true;
2872 $this->_availableinfo = '';
2873 if (!empty($CFG->enableavailability)) {
2874 // Get availability information.
2875 $ci = new \core_availability\info_section($this);
2876 $this->_available = $ci->is_available($this->_availableinfo, true,
2877 $userid, $this->modinfo);
2879 // Execute the hook from the course format that may override the available/availableinfo properties.
2880 $currentavailable = $this->_available;
2881 course_get_format($this->modinfo->get_course())->
2882 section_get_available_hook($this, $this->_available, $this->_availableinfo);
2883 if (!$currentavailable && $this->_available) {
2884 debugging('section_get_available_hook() can not make unavailable section available', DEBUG_DEVELOPER);
2885 $this->_available = $currentavailable;
2887 return $this->_available;
2891 * Returns the availability text shown next to the section on course page.
2893 * @return string
2895 private function get_availableinfo() {
2896 // Calling get_available() will also fill the availableinfo property
2897 // (or leave it null if there is no userid).
2898 $this->get_available();
2899 return $this->_availableinfo;
2903 * Implementation of IteratorAggregate::getIterator(), allows to cycle through properties
2904 * and use {@link convert_to_array()}
2906 * @return ArrayIterator
2908 public function getIterator() {
2909 $ret = array();
2910 foreach (get_object_vars($this) as $key => $value) {
2911 if (substr($key, 0, 1) == '_') {
2912 if (method_exists($this, 'get'.$key)) {
2913 $ret[substr($key, 1)] = $this->{'get'.$key}();
2914 } else {
2915 $ret[substr($key, 1)] = $this->$key;
2919 $ret['sequence'] = $this->get_sequence();
2920 $ret['course'] = $this->get_course();
2921 $ret = array_merge($ret, course_get_format($this->modinfo->get_course())->get_format_options($this->_section));
2922 return new ArrayIterator($ret);
2926 * Works out whether activity is visible *for current user* - if this is false, they
2927 * aren't allowed to access it.
2929 * @return bool
2931 private function get_uservisible() {
2932 $userid = $this->modinfo->get_user_id();
2933 if ($this->_uservisible !== null || $userid == -1) {
2934 // Has already been calculated or does not need calculation.
2935 return $this->_uservisible;
2937 $this->_uservisible = true;
2938 if (!$this->_visible || !$this->get_available()) {
2939 $coursecontext = context_course::instance($this->get_course());
2940 if (!$this->_visible && !has_capability('moodle/course:viewhiddensections', $coursecontext, $userid) ||
2941 (!$this->get_available() &&
2942 !has_capability('moodle/course:ignoreavailabilityrestrictions', $coursecontext, $userid))) {
2944 $this->_uservisible = false;
2947 return $this->_uservisible;
2951 * Restores the course_sections.sequence value
2953 * @return string
2955 private function get_sequence() {
2956 if (!empty($this->modinfo->sections[$this->_section])) {
2957 return implode(',', $this->modinfo->sections[$this->_section]);
2958 } else {
2959 return '';
2964 * Returns course ID - from course_sections table
2966 * @return int
2968 private function get_course() {
2969 return $this->modinfo->get_course_id();
2973 * Modinfo object
2975 * @return course_modinfo
2977 private function get_modinfo() {
2978 return $this->modinfo;
2982 * Prepares section data for inclusion in sectioncache cache, removing items
2983 * that are set to defaults, and adding availability data if required.
2985 * Called by build_section_cache in course_modinfo only; do not use otherwise.
2986 * @param object $section Raw section data object
2988 public static function convert_for_section_cache($section) {
2989 global $CFG;
2991 // Course id stored in course table
2992 unset($section->course);
2993 // Section number stored in array key
2994 unset($section->section);
2995 // Sequence stored implicity in modinfo $sections array
2996 unset($section->sequence);
2998 // Remove default data
2999 foreach (self::$sectioncachedefaults as $field => $value) {
3000 // Exact compare as strings to avoid problems if some strings are set
3001 // to "0" etc.
3002 if (isset($section->{$field}) && $section->{$field} === $value) {
3003 unset($section->{$field});