/lib/modinfolib.php
PHP | 2904 lines | 1177 code | 269 blank | 1458 comment | 204 complexity | 3e90787f094cc9e98544553b9a3dedf3 MD5 | raw file
Possible License(s): MIT, AGPL-3.0, MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, Apache-2.0, LGPL-2.1, BSD-3-Clause
Large files files are truncated, but you can click here to view the full file
- <?php
- // This file is part of Moodle - http://moodle.org/
- //
- // Moodle is free software: you can redistribute it and/or modify
- // it under the terms of the GNU General Public License as published by
- // the Free Software Foundation, either version 3 of the License, or
- // (at your option) any later version.
- //
- // Moodle is distributed in the hope that it will be useful,
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- // GNU General Public License for more details.
- //
- // You should have received a copy of the GNU General Public License
- // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
- /**
- * modinfolib.php - Functions/classes relating to cached information about module instances on
- * a course.
- * @package core
- * @subpackage lib
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- * @author sam marshall
- */
- // Maximum number of modinfo items to keep in memory cache. Do not increase this to a large
- // number because:
- // a) modinfo can be big (megabyte range) for some courses
- // b) performance of cache will deteriorate if there are very many items in it
- if (!defined('MAX_MODINFO_CACHE_SIZE')) {
- define('MAX_MODINFO_CACHE_SIZE', 10);
- }
- /**
- * Information about a course that is cached in the course table 'modinfo' field (and then in
- * memory) in order to reduce the need for other database queries.
- *
- * This includes information about the course-modules and the sections on the course. It can also
- * include dynamic data that has been updated for the current user.
- *
- * Use {@link get_fast_modinfo()} to retrieve the instance of the object for particular course
- * and particular user.
- *
- * @property-read int $courseid Course ID
- * @property-read int $userid User ID
- * @property-read array $sections Array from section number (e.g. 0) to array of course-module IDs in that
- * section; this only includes sections that contain at least one course-module
- * @property-read cm_info[] $cms Array from course-module instance to cm_info object within this course, in
- * order of appearance
- * @property-read cm_info[][] $instances Array from string (modname) => int (instance id) => cm_info object
- * @property-read array $groups Groups that the current user belongs to. Calculated on the first request.
- * Is an array of grouping id => array of group id => group id. Includes grouping id 0 for 'all groups'
- */
- class course_modinfo {
- /** @var int Maximum time the course cache building lock can be held */
- const COURSE_CACHE_LOCK_EXPIRY = 180;
- /** @var int Time to wait for the course cache building lock before throwing an exception */
- const COURSE_CACHE_LOCK_WAIT = 60;
- /**
- * List of fields from DB table 'course' that are cached in MUC and are always present in course_modinfo::$course
- * @var array
- */
- public static $cachedfields = array('shortname', 'fullname', 'format',
- 'enablecompletion', 'groupmode', 'groupmodeforce', 'cacherev');
- /**
- * For convenience we store the course object here as it is needed in other parts of code
- * @var stdClass
- */
- private $course;
- /**
- * Array of section data from cache
- * @var section_info[]
- */
- private $sectioninfo;
- /**
- * User ID
- * @var int
- */
- private $userid;
- /**
- * Array from int (section num, e.g. 0) => array of int (course-module id); this list only
- * includes sections that actually contain at least one course-module
- * @var array
- */
- private $sections;
- /**
- * Array from int (cm id) => cm_info object
- * @var cm_info[]
- */
- private $cms;
- /**
- * Array from string (modname) => int (instance id) => cm_info object
- * @var cm_info[][]
- */
- private $instances;
- /**
- * Groups that the current user belongs to. This value is calculated on first
- * request to the property or function.
- * When set, it is an array of grouping id => array of group id => group id.
- * Includes grouping id 0 for 'all groups'.
- * @var int[][]
- */
- private $groups;
- /**
- * List of class read-only properties and their getter methods.
- * Used by magic functions __get(), __isset(), __empty()
- * @var array
- */
- private static $standardproperties = array(
- 'courseid' => 'get_course_id',
- 'userid' => 'get_user_id',
- 'sections' => 'get_sections',
- 'cms' => 'get_cms',
- 'instances' => 'get_instances',
- 'groups' => 'get_groups_all',
- );
- /**
- * Magic method getter
- *
- * @param string $name
- * @return mixed
- */
- public function __get($name) {
- if (isset(self::$standardproperties[$name])) {
- $method = self::$standardproperties[$name];
- return $this->$method();
- } else {
- debugging('Invalid course_modinfo property accessed: '.$name);
- return null;
- }
- }
- /**
- * Magic method for function isset()
- *
- * @param string $name
- * @return bool
- */
- public function __isset($name) {
- if (isset(self::$standardproperties[$name])) {
- $value = $this->__get($name);
- return isset($value);
- }
- return false;
- }
- /**
- * Magic method for function empty()
- *
- * @param string $name
- * @return bool
- */
- public function __empty($name) {
- if (isset(self::$standardproperties[$name])) {
- $value = $this->__get($name);
- return empty($value);
- }
- return true;
- }
- /**
- * Magic method setter
- *
- * Will display the developer warning when trying to set/overwrite existing property.
- *
- * @param string $name
- * @param mixed $value
- */
- public function __set($name, $value) {
- debugging("It is not allowed to set the property course_modinfo::\${$name}", DEBUG_DEVELOPER);
- }
- /**
- * Returns course object that was used in the first {@link get_fast_modinfo()} call.
- *
- * It may not contain all fields from DB table {course} but always has at least the following:
- * id,shortname,fullname,format,enablecompletion,groupmode,groupmodeforce,cacherev
- *
- * @return stdClass
- */
- public function get_course() {
- return $this->course;
- }
- /**
- * @return int Course ID
- */
- public function get_course_id() {
- return $this->course->id;
- }
- /**
- * @return int User ID
- */
- public function get_user_id() {
- return $this->userid;
- }
- /**
- * @return array Array from section number (e.g. 0) to array of course-module IDs in that
- * section; this only includes sections that contain at least one course-module
- */
- public function get_sections() {
- return $this->sections;
- }
- /**
- * @return cm_info[] Array from course-module instance to cm_info object within this course, in
- * order of appearance
- */
- public function get_cms() {
- return $this->cms;
- }
- /**
- * Obtains a single course-module object (for a course-module that is on this course).
- * @param int $cmid Course-module ID
- * @return cm_info Information about that course-module
- * @throws moodle_exception If the course-module does not exist
- */
- public function get_cm($cmid) {
- if (empty($this->cms[$cmid])) {
- throw new moodle_exception('invalidcoursemodule', 'error');
- }
- return $this->cms[$cmid];
- }
- /**
- * Obtains all module instances on this course.
- * @return cm_info[][] Array from module name => array from instance id => cm_info
- */
- public function get_instances() {
- return $this->instances;
- }
- /**
- * Returns array of localised human-readable module names used in this course
- *
- * @param bool $plural if true returns the plural form of modules names
- * @return array
- */
- public function get_used_module_names($plural = false) {
- $modnames = get_module_types_names($plural);
- $modnamesused = array();
- foreach ($this->get_cms() as $cmid => $mod) {
- if (!isset($modnamesused[$mod->modname]) && isset($modnames[$mod->modname]) && $mod->uservisible) {
- $modnamesused[$mod->modname] = $modnames[$mod->modname];
- }
- }
- return $modnamesused;
- }
- /**
- * Obtains all instances of a particular module on this course.
- * @param $modname Name of module (not full frankenstyle) e.g. 'label'
- * @return cm_info[] Array from instance id => cm_info for modules on this course; empty if none
- */
- public function get_instances_of($modname) {
- if (empty($this->instances[$modname])) {
- return array();
- }
- return $this->instances[$modname];
- }
- /**
- * Groups that the current user belongs to organised by grouping id. Calculated on the first request.
- * @return int[][] array of grouping id => array of group id => group id. Includes grouping id 0 for 'all groups'
- */
- private function get_groups_all() {
- if (is_null($this->groups)) {
- // NOTE: Performance could be improved here. The system caches user groups
- // in $USER->groupmember[$courseid] => array of groupid=>groupid. Unfortunately this
- // structure does not include grouping information. It probably could be changed to
- // do so, without a significant performance hit on login, thus saving this one query
- // each request.
- $this->groups = groups_get_user_groups($this->course->id, $this->userid);
- }
- return $this->groups;
- }
- /**
- * Returns groups that the current user belongs to on the course. Note: If not already
- * available, this may make a database query.
- * @param int $groupingid Grouping ID or 0 (default) for all groups
- * @return int[] Array of int (group id) => int (same group id again); empty array if none
- */
- public function get_groups($groupingid = 0) {
- $allgroups = $this->get_groups_all();
- if (!isset($allgroups[$groupingid])) {
- return array();
- }
- return $allgroups[$groupingid];
- }
- /**
- * Gets all sections as array from section number => data about section.
- * @return section_info[] Array of section_info objects organised by section number
- */
- public function get_section_info_all() {
- return $this->sectioninfo;
- }
- /**
- * Gets data about specific numbered section.
- * @param int $sectionnumber Number (not id) of section
- * @param int $strictness Use MUST_EXIST to throw exception if it doesn't
- * @return section_info Information for numbered section or null if not found
- */
- public function get_section_info($sectionnumber, $strictness = IGNORE_MISSING) {
- if (!array_key_exists($sectionnumber, $this->sectioninfo)) {
- if ($strictness === MUST_EXIST) {
- throw new moodle_exception('sectionnotexist');
- } else {
- return null;
- }
- }
- return $this->sectioninfo[$sectionnumber];
- }
- /**
- * Static cache for generated course_modinfo instances
- *
- * @see course_modinfo::instance()
- * @see course_modinfo::clear_instance_cache()
- * @var course_modinfo[]
- */
- protected static $instancecache = array();
- /**
- * Timestamps (microtime) when the course_modinfo instances were last accessed
- *
- * It is used to remove the least recent accessed instances when static cache is full
- *
- * @var float[]
- */
- protected static $cacheaccessed = array();
- /**
- * Clears the cache used in course_modinfo::instance()
- *
- * Used in {@link get_fast_modinfo()} when called with argument $reset = true
- * and in {@link rebuild_course_cache()}
- *
- * @param null|int|stdClass $courseorid if specified removes only cached value for this course
- */
- public static function clear_instance_cache($courseorid = null) {
- if (empty($courseorid)) {
- self::$instancecache = array();
- self::$cacheaccessed = array();
- return;
- }
- if (is_object($courseorid)) {
- $courseorid = $courseorid->id;
- }
- if (isset(self::$instancecache[$courseorid])) {
- // Unsetting static variable in PHP is peculiar, it removes the reference,
- // but data remain in memory. Prior to unsetting, the varable needs to be
- // set to empty to remove its remains from memory.
- self::$instancecache[$courseorid] = '';
- unset(self::$instancecache[$courseorid]);
- unset(self::$cacheaccessed[$courseorid]);
- }
- }
- /**
- * Returns the instance of course_modinfo for the specified course and specified user
- *
- * This function uses static cache for the retrieved instances. The cache
- * size is limited by MAX_MODINFO_CACHE_SIZE. If instance is not found in
- * the static cache or it was created for another user or the cacherev validation
- * failed - a new instance is constructed and returned.
- *
- * Used in {@link get_fast_modinfo()}
- *
- * @param int|stdClass $courseorid object from DB table 'course' (must have field 'id'
- * and recommended to have field 'cacherev') or just a course id
- * @param int $userid User id to populate 'availble' and 'uservisible' attributes of modules and sections.
- * Set to 0 for current user (default). Set to -1 to avoid calculation of dynamic user-depended data.
- * @return course_modinfo
- */
- public static function instance($courseorid, $userid = 0) {
- global $USER;
- if (is_object($courseorid)) {
- $course = $courseorid;
- } else {
- $course = (object)array('id' => $courseorid);
- }
- if (empty($userid)) {
- $userid = $USER->id;
- }
- if (!empty(self::$instancecache[$course->id])) {
- if (self::$instancecache[$course->id]->userid == $userid &&
- (!isset($course->cacherev) ||
- $course->cacherev == self::$instancecache[$course->id]->get_course()->cacherev)) {
- // This course's modinfo for the same user was recently retrieved, return cached.
- self::$cacheaccessed[$course->id] = microtime(true);
- return self::$instancecache[$course->id];
- } else {
- // Prevent potential reference problems when switching users.
- self::clear_instance_cache($course->id);
- }
- }
- $modinfo = new course_modinfo($course, $userid);
- // We have a limit of MAX_MODINFO_CACHE_SIZE entries to store in static variable.
- if (count(self::$instancecache) >= MAX_MODINFO_CACHE_SIZE) {
- // Find the course that was the least recently accessed.
- asort(self::$cacheaccessed, SORT_NUMERIC);
- $courseidtoremove = key(array_reverse(self::$cacheaccessed, true));
- self::clear_instance_cache($courseidtoremove);
- }
- // Add modinfo to the static cache.
- self::$instancecache[$course->id] = $modinfo;
- self::$cacheaccessed[$course->id] = microtime(true);
- return $modinfo;
- }
- /**
- * Constructs based on course.
- * Note: This constructor should not usually be called directly.
- * Use get_fast_modinfo($course) instead as this maintains a cache.
- * @param stdClass $course course object, only property id is required.
- * @param int $userid User ID
- * @throws moodle_exception if course is not found
- */
- public function __construct($course, $userid) {
- global $CFG, $COURSE, $SITE, $DB;
- if (!isset($course->cacherev)) {
- // We require presence of property cacherev to validate the course cache.
- // No need to clone the $COURSE or $SITE object here because we clone it below anyway.
- $course = get_course($course->id, false);
- }
- $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
- // Retrieve modinfo from cache. If not present or cacherev mismatches, call rebuild and retrieve again.
- $coursemodinfo = $cachecoursemodinfo->get($course->id);
- if ($coursemodinfo === false || ($course->cacherev != $coursemodinfo->cacherev)) {
- $lock = self::get_course_cache_lock($course->id);
- try {
- // Only actually do the build if it's still needed after getting the lock (not if
- // somebody else, who might have been holding the lock, built it already).
- $coursemodinfo = $cachecoursemodinfo->get($course->id);
- if ($coursemodinfo === false || ($course->cacherev != $coursemodinfo->cacherev)) {
- $coursemodinfo = self::inner_build_course_cache($course, $lock);
- }
- } finally {
- $lock->release();
- }
- }
- // Set initial values
- $this->userid = $userid;
- $this->sections = array();
- $this->cms = array();
- $this->instances = array();
- $this->groups = null;
- // If we haven't already preloaded contexts for the course, do it now
- // Modules are also cached here as long as it's the first time this course has been preloaded.
- context_helper::preload_course($course->id);
- // Quick integrity check: as a result of race conditions modinfo may not be regenerated after the change.
- // It is especially dangerous if modinfo contains the deleted course module, as it results in fatal error.
- // We can check it very cheap by validating the existence of module context.
- if ($course->id == $COURSE->id || $course->id == $SITE->id) {
- // Only verify current course (or frontpage) as pages with many courses may not have module contexts cached.
- // (Uncached modules will result in a very slow verification).
- foreach ($coursemodinfo->modinfo as $mod) {
- if (!context_module::instance($mod->cm, IGNORE_MISSING)) {
- debugging('Course cache integrity check failed: course module with id '. $mod->cm.
- ' does not have context. Rebuilding cache for course '. $course->id);
- // Re-request the course record from DB as well, don't use get_course() here.
- $course = $DB->get_record('course', array('id' => $course->id), '*', MUST_EXIST);
- $coursemodinfo = self::build_course_cache($course);
- break;
- }
- }
- }
- // Overwrite unset fields in $course object with cached values, store the course object.
- $this->course = fullclone($course);
- foreach ($coursemodinfo as $key => $value) {
- if ($key !== 'modinfo' && $key !== 'sectioncache' &&
- (!isset($this->course->$key) || $key === 'cacherev')) {
- $this->course->$key = $value;
- }
- }
- // Loop through each piece of module data, constructing it
- static $modexists = array();
- foreach ($coursemodinfo->modinfo as $mod) {
- if (!isset($mod->name) || strval($mod->name) === '') {
- // something is wrong here
- continue;
- }
- // Skip modules which don't exist
- if (!array_key_exists($mod->mod, $modexists)) {
- $modexists[$mod->mod] = file_exists("$CFG->dirroot/mod/$mod->mod/lib.php");
- }
- if (!$modexists[$mod->mod]) {
- continue;
- }
- // Construct info for this module
- $cm = new cm_info($this, null, $mod, null);
- // Store module in instances and cms array
- if (!isset($this->instances[$cm->modname])) {
- $this->instances[$cm->modname] = array();
- }
- $this->instances[$cm->modname][$cm->instance] = $cm;
- $this->cms[$cm->id] = $cm;
- // Reconstruct sections. This works because modules are stored in order
- if (!isset($this->sections[$cm->sectionnum])) {
- $this->sections[$cm->sectionnum] = array();
- }
- $this->sections[$cm->sectionnum][] = $cm->id;
- }
- // Expand section objects
- $this->sectioninfo = array();
- foreach ($coursemodinfo->sectioncache as $number => $data) {
- $this->sectioninfo[$number] = new section_info($data, $number, null, null,
- $this, null);
- }
- }
- /**
- * This method can not be used anymore.
- *
- * @see course_modinfo::build_course_cache()
- * @deprecated since 2.6
- */
- public static function build_section_cache($courseid) {
- throw new coding_exception('Function course_modinfo::build_section_cache() can not be used anymore.' .
- ' Please use course_modinfo::build_course_cache() whenever applicable.');
- }
- /**
- * Builds a list of information about sections on a course to be stored in
- * the course cache. (Does not include information that is already cached
- * in some other way.)
- *
- * @param stdClass $course Course object (must contain fields
- * @return array Information about sections, indexed by section number (not id)
- */
- protected static function build_course_section_cache($course) {
- global $DB;
- // Get section data
- $sections = $DB->get_records('course_sections', array('course' => $course->id), 'section',
- 'section, id, course, name, summary, summaryformat, sequence, visible, availability');
- $compressedsections = array();
- $formatoptionsdef = course_get_format($course)->section_format_options();
- // Remove unnecessary data and add availability
- foreach ($sections as $number => $section) {
- // Add cached options from course format to $section object
- foreach ($formatoptionsdef as $key => $option) {
- if (!empty($option['cache'])) {
- $formatoptions = course_get_format($course)->get_format_options($section);
- if (!array_key_exists('cachedefault', $option) || $option['cachedefault'] !== $formatoptions[$key]) {
- $section->$key = $formatoptions[$key];
- }
- }
- }
- // Clone just in case it is reused elsewhere
- $compressedsections[$number] = clone($section);
- section_info::convert_for_section_cache($compressedsections[$number]);
- }
- return $compressedsections;
- }
- /**
- * Gets a lock for rebuilding the cache of a single course.
- *
- * Caller must release the returned lock.
- *
- * This is used to ensure that the cache rebuild doesn't happen multiple times in parallel.
- * This function will wait up to 1 minute for the lock to be obtained. If the lock cannot
- * be obtained, it throws an exception.
- *
- * @param int $courseid Course id
- * @return \core\lock\lock Lock (must be released!)
- * @throws moodle_exception If the lock cannot be obtained
- */
- protected static function get_course_cache_lock($courseid) {
- // Get database lock to ensure this doesn't happen multiple times in parallel. Wait a
- // reasonable time for the lock to be released, so we can give a suitable error message.
- // In case the system crashes while building the course cache, the lock will automatically
- // expire after a (slightly longer) period.
- $lockfactory = \core\lock\lock_config::get_lock_factory('core_modinfo');
- $lock = $lockfactory->get_lock('build_course_cache_' . $courseid,
- self::COURSE_CACHE_LOCK_WAIT, self::COURSE_CACHE_LOCK_EXPIRY);
- if (!$lock) {
- throw new moodle_exception('locktimeout', '', '', null,
- 'core_modinfo/build_course_cache_' . $courseid);
- }
- return $lock;
- }
- /**
- * Builds and stores in MUC object containing information about course
- * modules and sections together with cached fields from table course.
- *
- * @param stdClass $course object from DB table course. Must have property 'id'
- * but preferably should have all cached fields.
- * @return stdClass object with all cached keys of the course plus fields modinfo and sectioncache.
- * The same object is stored in MUC
- * @throws moodle_exception if course is not found (if $course object misses some of the
- * necessary fields it is re-requested from database)
- */
- public static function build_course_cache($course) {
- if (empty($course->id)) {
- throw new coding_exception('Object $course is missing required property \id\'');
- }
- $lock = self::get_course_cache_lock($course->id);
- try {
- return self::inner_build_course_cache($course, $lock);
- } finally {
- $lock->release();
- }
- }
- /**
- * Called to build course cache when there is already a lock obtained.
- *
- * @param stdClass $course object from DB table course
- * @param \core\lock\lock $lock Lock object - not actually used, just there to indicate you have a lock
- * @return stdClass Course object that has been stored in MUC
- */
- protected static function inner_build_course_cache($course, \core\lock\lock $lock) {
- global $DB, $CFG;
- require_once("{$CFG->dirroot}/course/lib.php");
- // Ensure object has all necessary fields.
- foreach (self::$cachedfields as $key) {
- if (!isset($course->$key)) {
- $course = $DB->get_record('course', array('id' => $course->id),
- implode(',', array_merge(array('id'), self::$cachedfields)), MUST_EXIST);
- break;
- }
- }
- // Retrieve all information about activities and sections.
- // This may take time on large courses and it is possible that another user modifies the same course during this process.
- // Field cacherev stored in both DB and cache will ensure that cached data matches the current course state.
- $coursemodinfo = new stdClass();
- $coursemodinfo->modinfo = get_array_of_activities($course->id);
- $coursemodinfo->sectioncache = self::build_course_section_cache($course);
- foreach (self::$cachedfields as $key) {
- $coursemodinfo->$key = $course->$key;
- }
- // Set the accumulated activities and sections information in cache, together with cacherev.
- $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
- $cachecoursemodinfo->set($course->id, $coursemodinfo);
- return $coursemodinfo;
- }
- }
- /**
- * Data about a single module on a course. This contains most of the fields in the course_modules
- * table, plus additional data when required.
- *
- * The object can be accessed by core or any plugin (i.e. course format, block, filter, etc.) as
- * get_fast_modinfo($courseorid)->cms[$coursemoduleid]
- * or
- * get_fast_modinfo($courseorid)->instances[$moduletype][$instanceid]
- *
- * There are three stages when activity module can add/modify data in this object:
- *
- * <b>Stage 1 - during building the cache.</b>
- * Allows to add to the course cache static user-independent information about the module.
- * Modules should try to include only absolutely necessary information that may be required
- * when displaying course view page. The information is stored in application-level cache
- * and reset when {@link rebuild_course_cache()} is called or cache is purged by admin.
- *
- * Modules can implement callback XXX_get_coursemodule_info() returning instance of object
- * {@link cached_cm_info}
- *
- * <b>Stage 2 - dynamic data.</b>
- * Dynamic data is user-dependend, it is stored in request-level cache. To reset this cache
- * {@link get_fast_modinfo()} with $reset argument may be called.
- *
- * Dynamic data is obtained when any of the following properties/methods is requested:
- * - {@link cm_info::$url}
- * - {@link cm_info::$name}
- * - {@link cm_info::$onclick}
- * - {@link cm_info::get_icon_url()}
- * - {@link cm_info::$uservisible}
- * - {@link cm_info::$available}
- * - {@link cm_info::$availableinfo}
- * - plus any of the properties listed in Stage 3.
- *
- * Modules can implement callback <b>XXX_cm_info_dynamic()</b> and inside this callback they
- * are allowed to use any of the following set methods:
- * - {@link cm_info::set_available()}
- * - {@link cm_info::set_name()}
- * - {@link cm_info::set_no_view_link()}
- * - {@link cm_info::set_user_visible()}
- * - {@link cm_info::set_on_click()}
- * - {@link cm_info::set_icon_url()}
- * Any methods affecting view elements can also be set in this callback.
- *
- * <b>Stage 3 (view data).</b>
- * Also user-dependend data stored in request-level cache. Second stage is created
- * because populating the view data can be expensive as it may access much more
- * Moodle APIs such as filters, user information, output renderers and we
- * don't want to request it until necessary.
- * View data is obtained when any of the following properties/methods is requested:
- * - {@link cm_info::$afterediticons}
- * - {@link cm_info::$content}
- * - {@link cm_info::get_formatted_content()}
- * - {@link cm_info::$extraclasses}
- * - {@link cm_info::$afterlink}
- *
- * Modules can implement callback <b>XXX_cm_info_view()</b> and inside this callback they
- * are allowed to use any of the following set methods:
- * - {@link cm_info::set_after_edit_icons()}
- * - {@link cm_info::set_after_link()}
- * - {@link cm_info::set_content()}
- * - {@link cm_info::set_extra_classes()}
- *
- * @property-read int $id Course-module ID - from course_modules table
- * @property-read int $instance Module instance (ID within module table) - from course_modules table
- * @property-read int $course Course ID - from course_modules table
- * @property-read string $idnumber 'ID number' from course-modules table (arbitrary text set by user) - from
- * course_modules table
- * @property-read int $added Time that this course-module was added (unix time) - from course_modules table
- * @property-read int $visible Visible setting (0 or 1; if this is 0, students cannot see/access the activity) - from
- * course_modules table
- * @property-read int $visibleoncoursepage Visible on course page setting - from course_modules table, adjusted to
- * whether course format allows this module to have the "stealth" mode
- * @property-read int $visibleold Old visible setting (if the entire section is hidden, the previous value for
- * visible is stored in this field) - from course_modules table
- * @property-read int $groupmode Group mode (one of the constants NOGROUPS, SEPARATEGROUPS, or VISIBLEGROUPS) - from
- * course_modules table. Use {@link cm_info::$effectivegroupmode} to find the actual group mode that may be forced by course.
- * @property-read int $groupingid Grouping ID (0 = all groupings)
- * @property-read bool $coursegroupmodeforce Indicates whether the course containing the module has forced the groupmode
- * This means that cm_info::$groupmode should be ignored and cm_info::$coursegroupmode be used instead
- * @property-read int $coursegroupmode Group mode (one of the constants NOGROUPS, SEPARATEGROUPS, or VISIBLEGROUPS) - from
- * course table - as specified for the course containing the module
- * Effective only if {@link cm_info::$coursegroupmodeforce} is set
- * @property-read int $effectivegroupmode Effective group mode for this module (one of the constants NOGROUPS, SEPARATEGROUPS,
- * or VISIBLEGROUPS). This can be different from groupmode set for the module if the groupmode is forced for the course.
- * This value will always be NOGROUPS if module type does not support group mode.
- * @property-read int $indent Indent level on course page (0 = no indent) - from course_modules table
- * @property-read int $completion Activity completion setting for this activity, COMPLETION_TRACKING_xx constant - from
- * course_modules table
- * @property-read mixed $completiongradeitemnumber Set to the item number (usually 0) if completion depends on a particular
- * grade of this activity, or null if completion does not depend on a grade - from course_modules table
- * @property-read int $completionview 1 if 'on view' completion is enabled, 0 otherwise - from course_modules table
- * @property-read int $completionexpected Set to a unix time if completion of this activity is expected at a
- * particular time, 0 if no time set - from course_modules table
- * @property-read string $availability Availability information as JSON string or null if none -
- * from course_modules table
- * @property-read int $showdescription Controls whether the description of the activity displays on the course main page (in
- * addition to anywhere it might display within the activity itself). 0 = do not show
- * on main page, 1 = show on main page.
- * @property-read string $extra (deprecated) Extra HTML that is put in an unhelpful part of the HTML when displaying this module in
- * course page - from cached data in modinfo field. Deprecated, replaced by ->extraclasses and ->onclick
- * @property-read string $icon Name of icon to use - from cached data in modinfo field
- * @property-read string $iconcomponent Component that contains icon - from cached data in modinfo field
- * @property-read string $modname Name of module e.g. 'forum' (this is the same name as the module's main database
- * table) - from cached data in modinfo field
- * @property-read int $module ID of module type - from course_modules table
- * @property-read string $name Name of module instance for display on page e.g. 'General discussion forum' - from cached
- * data in modinfo field
- * @property-read int $sectionnum Section number that this course-module is in (section 0 = above the calendar, section 1
- * = week/topic 1, etc) - from cached data in modinfo field
- * @property-read int $section Section id - from course_modules table
- * @property-read array $conditionscompletion Availability conditions for this course-module based on the completion of other
- * course-modules (array from other course-module id to required completion state for that
- * module) - from cached data in modinfo field
- * @property-read array $conditionsgrade Availability conditions for this course-module based on course grades (array from
- * grade item id to object with ->min, ->max fields) - from cached data in modinfo field
- * @property-read array $conditionsfield Availability conditions for this course-module based on user fields
- * @property-read bool $available True if this course-module is available to students i.e. if all availability conditions
- * are met - obtained dynamically
- * @property-read string $availableinfo If course-module is not available to students, this string gives information about
- * availability which can be displayed to students and/or staff (e.g. 'Available from 3
- * January 2010') for display on main page - obtained dynamically
- * @property-read bool $uservisible True if this course-module is available to the CURRENT user (for example, if current user
- * has viewhiddenactivities capability, they can access the course-module even if it is not
- * visible or not available, so this would be true in that case)
- * @property-read context_module $context Module context
- * @property-read string $modfullname Returns a localised human-readable name of the module type - calculated on request
- * @property-read string $modplural Returns a localised human-readable name of the module type in plural form - calculated on request
- * @property-read string $content Content to display on main (view) page - calculated on request
- * @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
- * @property-read string $extraclasses Extra CSS classes to add to html output for this activity on main page - calculated on request
- * @property-read string $onclick Content of HTML on-click attribute already escaped - calculated on request
- * @property-read mixed $customdata Optional custom data stored in modinfo cache for this activity, or null if none
- * @property-read string $afterlink Extra HTML code to display after link - calculated on request
- * @property-read string $afterediticons Extra HTML code to display after editing icons (e.g. more icons) - calculated on request
- * @property-read bool $deletioninprogress True if this course module is scheduled for deletion, false otherwise.
- */
- class cm_info implements IteratorAggregate {
- /**
- * State: Only basic data from modinfo cache is available.
- */
- const STATE_BASIC = 0;
- /**
- * State: In the process of building dynamic data (to avoid recursive calls to obtain_dynamic_data())
- */
- const STATE_BUILDING_DYNAMIC = 1;
- /**
- * State: Dynamic data is available too.
- */
- const STATE_DYNAMIC = 2;
- /**
- * State: In the process of building view data (to avoid recursive calls to obtain_view_data())
- */
- const STATE_BUILDING_VIEW = 3;
- /**
- * State: View data (for course page) is available.
- */
- const STATE_VIEW = 4;
- /**
- * Parent object
- * @var course_modinfo
- */
- private $modinfo;
- /**
- * Level of information stored inside this object (STATE_xx constant)
- * @var int
- */
- private $state;
- /**
- * Course-module ID - from course_modules table
- * @var int
- */
- private $id;
- /**
- * Module instance (ID within module table) - from course_modules table
- * @var int
- */
- private $instance;
- /**
- * 'ID number' from course-modules table (arbitrary text set by user) - from
- * course_modules table
- * @var string
- */
- private $idnumber;
- /**
- * Time that this course-module was added (unix time) - from course_modules table
- * @var int
- */
- private $added;
- /**
- * This variable is not used and is included here only so it can be documented.
- * Once the database entry is removed from course_modules, it should be deleted
- * here too.
- * @var int
- * @deprecated Do not use this variable
- */
- private $score;
- /**
- * Visible setting (0 or 1; if this is 0, students cannot see/access the activity) - from
- * course_modules table
- * @var int
- */
- private $visible;
- /**
- * Visible on course page setting - from course_modules table
- * @var int
- */
- private $visibleoncoursepage;
- /**
- * Old visible setting (if the entire section is hidden, the previous value for
- * visible is stored in this field) - from course_modules table
- * @var int
- */
- private $visibleold;
- /**
- * Group mode (one of the constants NONE, SEPARATEGROUPS, or VISIBLEGROUPS) - from
- * course_modules table
- * @var int
- */
- private $groupmode;
- /**
- * Grouping ID (0 = all groupings)
- * @var int
- */
- private $groupingid;
- /**
- * Indent level on course page (0 = no indent) - from course_modules table
- * @var int
- */
- private $indent;
- /**
- * Activity completion setting for this activity, COMPLETION_TRACKING_xx constant - from
- * course_modules table
- * @var int
- */
- private $completion;
- /**
- * Set to the item number (usually 0) if completion depends on a particular
- * grade of this activity, or null if completion does not depend on a grade - from
- * course_modules table
- * @var mixed
- */
- private $completiongradeitemnumber;
- /**
- * 1 if 'on view' completion is enabled, 0 otherwise - from course_modules table
- * @var int
- */
- private $completionview;
- /**
- * Set to a unix time if completion of this activity is expected at a
- * particular time, 0 if no time set - from course_modules table
- * @var int
- */
- private $completionexpected;
- /**
- * Availability information as JSON string or null if none - from course_modules table
- * @var string
- */
- private $availability;
- /**
- * Controls whether the description of the activity displays on the course main page (in
- * addition to anywhere it might display within the activity itself). 0 = do not show
- * on main page, 1 = show on main page.
- * @var int
- */
- private $showdescription;
- /**
- * Extra HTML that is put in an unhelpful part of the HTML when displaying this module in
- * course page - from cached data in modinfo field
- * @deprecated This is crazy, don't use it. Replaced by ->extraclasses and ->onclick
- * @var string
- */
- private $extra;
- /**
- * Name of icon to use - from cached data in modinfo field
- * @var string
- */
- private $icon;
- /**
- * Component that contains icon - from cached data in modinfo field
- * @var string
- */
- private $iconcomponent;
- /**
- * Name of module e.g. 'forum' (this is the same name as the module's main database
- * table) - from cached data in modinfo field
- * @var string
- */
- private $modname;
- /**
- * ID of module - from course_modules table
- * @var int
- */
- private $module;
- /**
- * Name of module instance for display on page e.g. 'General discussion forum' - from cached
- * data in modinfo field
- * @var string
- */
- private $name;
- /**
- * Section number that this course-module is in (section 0 = above the calendar, section 1
- * = week/topic 1, etc) - from cached data in modinfo field
- * @var int
- */
- private $sectionnum;
- /**
- * Section id - from course_modules table
- * @var int
- */
- private $section;
- /**
- * Availability conditions for this course-module based on the completion of other
- * course-modules (array from other course-module id to required completion state for that
- * module) - from cached data in modinfo field
- * @var array
- */
- private $conditionscompletion;
- /**
- * Availability conditions for this course-module based on course grades (array from
- * grade item id to object with ->min, ->max fields) - from cached data in modinfo field
- * @var array
- */
- private $conditionsgrade;
- /**
- * Availability conditions for this course-module based on user fields
- * @var array
- */
- private $conditionsfield;
- /**
- * True if this course-module is available to students i.e. if all availability conditions
- * are met - obtained dynamically
- * @var bool
- */
- private $available;
- /**
- * If course-module is not available to students, this string gives information about
- * availability which can be displayed to students and/or staff (e.g. 'Available from 3
- * January 2010') for display on main page - obtained dynamically
- * @var string
- */
- private $availableinfo;
- /**
- * True if this course-module is available to the CURRENT user (for example, if current user
- * has viewhiddenactivities capability, they can access the course-module even if it is not
- * visible or not available, so this would be true in that case)
- * @var bool
- */
- private $uservisible;
- /**
- * True if this course-module is visible to the CURRENT user on the course page
- * @var bool
- */
- private $uservisibleoncoursepage;
- /**
- * @var moodle_url
- */
- private $url;
- /**
- * @var string
- */
- private $content;
- /**
- * @var bool
- */
- private $contentisformatted;
- /**
- * @var string
- */
- private $extraclasses;
- /**
- * @var moodle_url full external url pointing to icon image for activity
- */
- private $iconurl;
- /**
- * @var string
- */
- private $onclick;
- /**
- * @var mixed
- */
- private $customdata;
- /**
- * @var string
- */
- private $afterlink;
- /**
- * @var string
- */
- private $afterediticons;
- /**
- * @var bool representing the deletion state of the module. True if the mod is scheduled for deletion.
- */
- private $deletioninprogress;
- /**
- * List of class read-only properties and their getter methods.
- * Used by magic functions __get(), __isset(), __empty()
- * @var array
- */
- private static $standardproperties = array(
- 'url' => 'get_url',
- 'content' => 'get_content',
- 'extraclasses' => 'get_extra_classes',
- 'onclick' => 'get_on_click',
- 'customdata' => 'get_custom_data',
- 'afterlink' => 'get_after_link',
- 'afterediticons' => 'get_after_edit_icons',
- 'modfullname' => 'get_module_type_name',
- 'modplural' => 'get_module_type_name_plural',
- 'id' => false,
- 'added' => false,
- 'availability' => false,
- 'available' => 'get_available',
- 'availableinfo' => 'get_available_info',
- 'completion' => false,
- 'completionexpected' => false,
- 'completiongradeitemnumber' => false,
- 'completionview' => false,
- 'conditionscompletion' => false,
- 'conditionsfield' => false,
- 'conditionsgrade' => false,
- 'context' => 'get_context',
- 'course' => 'get_course_id',
- 'coursegroupmode' => 'get_course_groupmode',
- 'coursegroupmodeforce' => 'get_course_groupmodeforce',
- 'effectivegroupmode' => 'get_effective_groupmode',
- 'extra' => false,
- 'groupingid' => false,
- 'groupmembersonly' => 'get_deprecated_group_members_only',
- 'groupmode' => false,
- 'icon' => false,
- 'iconcomponent' => false,
- 'idnumber' => false,
- 'indent' => false,
- 'instance' => false,
- 'modname' => false,
- 'module' => false,
- 'name' => 'get_name',
- 'score' => false,
- 'section' => false,
- 'sectionnum' => false,
- 'showdescription' => false,
- 'uservisible' => 'get_user_visible',
- 'visible' => false,
- 'visibleoncoursepage' => false,
- 'visibleold' => false,
- 'deletioninprogress' => false
- );
- /**
- * List of methods with no arguments that were public prior to Moodle 2.6.
- *
- * They can still be accessed publicly via magic __call() function with no warnings
- * but are not listed in the class methods list.
- * For the consistency of the code it is better to use corresponding properties.
- *
- * These methods be deprecated completely in later versions.
- *
- * @var array $standardmethods
- */
- private static $standardmethods = array(
- // Following methods are not recommended to use because there have associated read-only properties.
- 'get_url',
- 'get_content',
- 'get_extra_classes',
- 'get_on_click',
- 'get_custom_data',
- 'get_after_link',
- 'get_after_edit_icons',
- // Method obtain_dynamic_data() should not be called from outside of this class but it was public before Moodle 2.6.
- 'obtain_dynamic_data',
- );
- /**
- * Magic method to call functions that are now declared as private but were public in Moodle before 2.6.
- * These private methods can not be used anymore.
- *
- * @param string $name
- * @param array $arguments
- * @return mixed
- * @throws coding_exception
- */
- public function __call($name, $arguments) {
- if (in_array($name, self::$standardmethods)) {
- $message = "cm_info::$name() can not be used anymore.";
- if ($alternative = array_search($name, self::$standardproperties)) {
- $message .= " Please use the property cm_info->$alternative instead.";
- }
- throw new coding_exception($message);
- }
- throw new coding_exception("Method cm_info::{$name}() does not exist");
- }
- /**
- * Magic method getter
- *
- * @param string $name
- * @return mixed
- */
- public function __get($name) {
- if (isset(self::$standardproperties[$name])) {
- if ($method = self::$standardproperties[$name]) {
- return $this->$method();
- } else {
- return $this->$name;
- }
- } else {
- debugging('Invalid cm_info property accessed: '.$name);
- return null;
- }
- }
- /**
- * Implementation of IteratorAggregate::getIterator(), allows to cycle through properties
- * and use {@link convert_to_array()}
- *
- * @return ArrayIterator
- */
- public function getIterator() {
- // Make sure dynamic properties are retrieved prior to view properties.
- $this->obtain_dynamic_data();
- $ret = array();
- // Do not iterate over deprecated properties.
- $props = self::$standardproperties;
- unset($props['groupmembersonly']);
- foreach ($props as $key => $unused) {
- $ret[$key] = $this->__get($key);
- }
- return new ArrayIterator($ret);
- }
- /**
- * Magic method for function isset()
- *
- * @param string $name
- * @return bool
- */
- public function __isset($name) {
- if (isset(self::$standardproperties[$name])) {
- $value = $this->__get($name);
- return isset($value);
- }
- return false;
- }
- /**
- * Magic method for function empty()
- *
- * @param string $name
- * @return bool
- */
- public function __empty($name) {
- if (isset(self::$standardproperties[$name])) {
- $value = $this->__get($name);
- …
Large files files are truncated, but you can click here to view the full file