Merge branch 'MDL-63700-master' of git://github.com/mickhawkins/moodle
[moodle.git] / lib / modinfolib.php
blob8541eab51d1b29e49dc2c8c77b2d44f8422f6a03
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 int (cm id) => cm_info object
97 * @var cm_info[]
99 private $cms;
102 * Array from string (modname) => int (instance id) => cm_info object
103 * @var cm_info[][]
105 private $instances;
108 * Groups that the current user belongs to. This value is calculated on first
109 * request to the property or function.
110 * When set, it is an array of grouping id => array of group id => group id.
111 * Includes grouping id 0 for 'all groups'.
112 * @var int[][]
114 private $groups;
117 * List of class read-only properties and their getter methods.
118 * Used by magic functions __get(), __isset(), __empty()
119 * @var array
121 private static $standardproperties = array(
122 'courseid' => 'get_course_id',
123 'userid' => 'get_user_id',
124 'sections' => 'get_sections',
125 'cms' => 'get_cms',
126 'instances' => 'get_instances',
127 'groups' => 'get_groups_all',
131 * Magic method getter
133 * @param string $name
134 * @return mixed
136 public function __get($name) {
137 if (isset(self::$standardproperties[$name])) {
138 $method = self::$standardproperties[$name];
139 return $this->$method();
140 } else {
141 debugging('Invalid course_modinfo property accessed: '.$name);
142 return null;
147 * Magic method for function isset()
149 * @param string $name
150 * @return bool
152 public function __isset($name) {
153 if (isset(self::$standardproperties[$name])) {
154 $value = $this->__get($name);
155 return isset($value);
157 return false;
161 * Magic method for function empty()
163 * @param string $name
164 * @return bool
166 public function __empty($name) {
167 if (isset(self::$standardproperties[$name])) {
168 $value = $this->__get($name);
169 return empty($value);
171 return true;
175 * Magic method setter
177 * Will display the developer warning when trying to set/overwrite existing property.
179 * @param string $name
180 * @param mixed $value
182 public function __set($name, $value) {
183 debugging("It is not allowed to set the property course_modinfo::\${$name}", DEBUG_DEVELOPER);
187 * Returns course object that was used in the first {@link get_fast_modinfo()} call.
189 * It may not contain all fields from DB table {course} but always has at least the following:
190 * id,shortname,fullname,format,enablecompletion,groupmode,groupmodeforce,cacherev
192 * @return stdClass
194 public function get_course() {
195 return $this->course;
199 * @return int Course ID
201 public function get_course_id() {
202 return $this->course->id;
206 * @return int User ID
208 public function get_user_id() {
209 return $this->userid;
213 * @return array Array from section number (e.g. 0) to array of course-module IDs in that
214 * section; this only includes sections that contain at least one course-module
216 public function get_sections() {
217 return $this->sections;
221 * @return cm_info[] Array from course-module instance to cm_info object within this course, in
222 * order of appearance
224 public function get_cms() {
225 return $this->cms;
229 * Obtains a single course-module object (for a course-module that is on this course).
230 * @param int $cmid Course-module ID
231 * @return cm_info Information about that course-module
232 * @throws moodle_exception If the course-module does not exist
234 public function get_cm($cmid) {
235 if (empty($this->cms[$cmid])) {
236 throw new moodle_exception('invalidcoursemodule', 'error');
238 return $this->cms[$cmid];
242 * Obtains all module instances on this course.
243 * @return cm_info[][] Array from module name => array from instance id => cm_info
245 public function get_instances() {
246 return $this->instances;
250 * Returns array of localised human-readable module names used in this course
252 * @param bool $plural if true returns the plural form of modules names
253 * @return array
255 public function get_used_module_names($plural = false) {
256 $modnames = get_module_types_names($plural);
257 $modnamesused = array();
258 foreach ($this->get_cms() as $cmid => $mod) {
259 if (!isset($modnamesused[$mod->modname]) && isset($modnames[$mod->modname]) && $mod->uservisible) {
260 $modnamesused[$mod->modname] = $modnames[$mod->modname];
263 core_collator::asort($modnamesused);
264 return $modnamesused;
268 * Obtains all instances of a particular module on this course.
269 * @param $modname Name of module (not full frankenstyle) e.g. 'label'
270 * @return cm_info[] Array from instance id => cm_info for modules on this course; empty if none
272 public function get_instances_of($modname) {
273 if (empty($this->instances[$modname])) {
274 return array();
276 return $this->instances[$modname];
280 * Groups that the current user belongs to organised by grouping id. Calculated on the first request.
281 * @return int[][] array of grouping id => array of group id => group id. Includes grouping id 0 for 'all groups'
283 private function get_groups_all() {
284 if (is_null($this->groups)) {
285 // NOTE: Performance could be improved here. The system caches user groups
286 // in $USER->groupmember[$courseid] => array of groupid=>groupid. Unfortunately this
287 // structure does not include grouping information. It probably could be changed to
288 // do so, without a significant performance hit on login, thus saving this one query
289 // each request.
290 $this->groups = groups_get_user_groups($this->course->id, $this->userid);
292 return $this->groups;
296 * Returns groups that the current user belongs to on the course. Note: If not already
297 * available, this may make a database query.
298 * @param int $groupingid Grouping ID or 0 (default) for all groups
299 * @return int[] Array of int (group id) => int (same group id again); empty array if none
301 public function get_groups($groupingid = 0) {
302 $allgroups = $this->get_groups_all();
303 if (!isset($allgroups[$groupingid])) {
304 return array();
306 return $allgroups[$groupingid];
310 * Gets all sections as array from section number => data about section.
311 * @return section_info[] Array of section_info objects organised by section number
313 public function get_section_info_all() {
314 return $this->sectioninfo;
318 * Gets data about specific numbered section.
319 * @param int $sectionnumber Number (not id) of section
320 * @param int $strictness Use MUST_EXIST to throw exception if it doesn't
321 * @return section_info Information for numbered section or null if not found
323 public function get_section_info($sectionnumber, $strictness = IGNORE_MISSING) {
324 if (!array_key_exists($sectionnumber, $this->sectioninfo)) {
325 if ($strictness === MUST_EXIST) {
326 throw new moodle_exception('sectionnotexist');
327 } else {
328 return null;
331 return $this->sectioninfo[$sectionnumber];
335 * Static cache for generated course_modinfo instances
337 * @see course_modinfo::instance()
338 * @see course_modinfo::clear_instance_cache()
339 * @var course_modinfo[]
341 protected static $instancecache = array();
344 * Timestamps (microtime) when the course_modinfo instances were last accessed
346 * It is used to remove the least recent accessed instances when static cache is full
348 * @var float[]
350 protected static $cacheaccessed = array();
353 * Clears the cache used in course_modinfo::instance()
355 * Used in {@link get_fast_modinfo()} when called with argument $reset = true
356 * and in {@link rebuild_course_cache()}
358 * @param null|int|stdClass $courseorid if specified removes only cached value for this course
360 public static function clear_instance_cache($courseorid = null) {
361 if (empty($courseorid)) {
362 self::$instancecache = array();
363 self::$cacheaccessed = array();
364 return;
366 if (is_object($courseorid)) {
367 $courseorid = $courseorid->id;
369 if (isset(self::$instancecache[$courseorid])) {
370 // Unsetting static variable in PHP is peculiar, it removes the reference,
371 // but data remain in memory. Prior to unsetting, the varable needs to be
372 // set to empty to remove its remains from memory.
373 self::$instancecache[$courseorid] = '';
374 unset(self::$instancecache[$courseorid]);
375 unset(self::$cacheaccessed[$courseorid]);
380 * Returns the instance of course_modinfo for the specified course and specified user
382 * This function uses static cache for the retrieved instances. The cache
383 * size is limited by MAX_MODINFO_CACHE_SIZE. If instance is not found in
384 * the static cache or it was created for another user or the cacherev validation
385 * failed - a new instance is constructed and returned.
387 * Used in {@link get_fast_modinfo()}
389 * @param int|stdClass $courseorid object from DB table 'course' (must have field 'id'
390 * and recommended to have field 'cacherev') or just a course id
391 * @param int $userid User id to populate 'availble' and 'uservisible' attributes of modules and sections.
392 * Set to 0 for current user (default). Set to -1 to avoid calculation of dynamic user-depended data.
393 * @return course_modinfo
395 public static function instance($courseorid, $userid = 0) {
396 global $USER;
397 if (is_object($courseorid)) {
398 $course = $courseorid;
399 } else {
400 $course = (object)array('id' => $courseorid);
402 if (empty($userid)) {
403 $userid = $USER->id;
406 if (!empty(self::$instancecache[$course->id])) {
407 if (self::$instancecache[$course->id]->userid == $userid &&
408 (!isset($course->cacherev) ||
409 $course->cacherev == self::$instancecache[$course->id]->get_course()->cacherev)) {
410 // This course's modinfo for the same user was recently retrieved, return cached.
411 self::$cacheaccessed[$course->id] = microtime(true);
412 return self::$instancecache[$course->id];
413 } else {
414 // Prevent potential reference problems when switching users.
415 self::clear_instance_cache($course->id);
418 $modinfo = new course_modinfo($course, $userid);
420 // We have a limit of MAX_MODINFO_CACHE_SIZE entries to store in static variable.
421 if (count(self::$instancecache) >= MAX_MODINFO_CACHE_SIZE) {
422 // Find the course that was the least recently accessed.
423 asort(self::$cacheaccessed, SORT_NUMERIC);
424 $courseidtoremove = key(array_reverse(self::$cacheaccessed, true));
425 self::clear_instance_cache($courseidtoremove);
428 // Add modinfo to the static cache.
429 self::$instancecache[$course->id] = $modinfo;
430 self::$cacheaccessed[$course->id] = microtime(true);
432 return $modinfo;
436 * Constructs based on course.
437 * Note: This constructor should not usually be called directly.
438 * Use get_fast_modinfo($course) instead as this maintains a cache.
439 * @param stdClass $course course object, only property id is required.
440 * @param int $userid User ID
441 * @throws moodle_exception if course is not found
443 public function __construct($course, $userid) {
444 global $CFG, $COURSE, $SITE, $DB;
446 if (!isset($course->cacherev)) {
447 // We require presence of property cacherev to validate the course cache.
448 // No need to clone the $COURSE or $SITE object here because we clone it below anyway.
449 $course = get_course($course->id, false);
452 $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
454 // Retrieve modinfo from cache. If not present or cacherev mismatches, call rebuild and retrieve again.
455 $coursemodinfo = $cachecoursemodinfo->get($course->id);
456 if ($coursemodinfo === false || ($course->cacherev != $coursemodinfo->cacherev)) {
457 $lock = self::get_course_cache_lock($course->id);
458 try {
459 // Only actually do the build if it's still needed after getting the lock (not if
460 // somebody else, who might have been holding the lock, built it already).
461 $coursemodinfo = $cachecoursemodinfo->get($course->id);
462 if ($coursemodinfo === false || ($course->cacherev != $coursemodinfo->cacherev)) {
463 $coursemodinfo = self::inner_build_course_cache($course, $lock);
465 } finally {
466 $lock->release();
470 // Set initial values
471 $this->userid = $userid;
472 $this->sections = array();
473 $this->cms = array();
474 $this->instances = array();
475 $this->groups = null;
477 // If we haven't already preloaded contexts for the course, do it now
478 // Modules are also cached here as long as it's the first time this course has been preloaded.
479 context_helper::preload_course($course->id);
481 // Quick integrity check: as a result of race conditions modinfo may not be regenerated after the change.
482 // It is especially dangerous if modinfo contains the deleted course module, as it results in fatal error.
483 // We can check it very cheap by validating the existence of module context.
484 if ($course->id == $COURSE->id || $course->id == $SITE->id) {
485 // Only verify current course (or frontpage) as pages with many courses may not have module contexts cached.
486 // (Uncached modules will result in a very slow verification).
487 foreach ($coursemodinfo->modinfo as $mod) {
488 if (!context_module::instance($mod->cm, IGNORE_MISSING)) {
489 debugging('Course cache integrity check failed: course module with id '. $mod->cm.
490 ' does not have context. Rebuilding cache for course '. $course->id);
491 // Re-request the course record from DB as well, don't use get_course() here.
492 $course = $DB->get_record('course', array('id' => $course->id), '*', MUST_EXIST);
493 $coursemodinfo = self::build_course_cache($course);
494 break;
499 // Overwrite unset fields in $course object with cached values, store the course object.
500 $this->course = fullclone($course);
501 foreach ($coursemodinfo as $key => $value) {
502 if ($key !== 'modinfo' && $key !== 'sectioncache' &&
503 (!isset($this->course->$key) || $key === 'cacherev')) {
504 $this->course->$key = $value;
508 // Loop through each piece of module data, constructing it
509 static $modexists = array();
510 foreach ($coursemodinfo->modinfo as $mod) {
511 if (!isset($mod->name) || strval($mod->name) === '') {
512 // something is wrong here
513 continue;
516 // Skip modules which don't exist
517 if (!array_key_exists($mod->mod, $modexists)) {
518 $modexists[$mod->mod] = file_exists("$CFG->dirroot/mod/$mod->mod/lib.php");
520 if (!$modexists[$mod->mod]) {
521 continue;
524 // Construct info for this module
525 $cm = new cm_info($this, null, $mod, null);
527 // Store module in instances and cms array
528 if (!isset($this->instances[$cm->modname])) {
529 $this->instances[$cm->modname] = array();
531 $this->instances[$cm->modname][$cm->instance] = $cm;
532 $this->cms[$cm->id] = $cm;
534 // Reconstruct sections. This works because modules are stored in order
535 if (!isset($this->sections[$cm->sectionnum])) {
536 $this->sections[$cm->sectionnum] = array();
538 $this->sections[$cm->sectionnum][] = $cm->id;
541 // Expand section objects
542 $this->sectioninfo = array();
543 foreach ($coursemodinfo->sectioncache as $number => $data) {
544 $this->sectioninfo[$number] = new section_info($data, $number, null, null,
545 $this, null);
550 * This method can not be used anymore.
552 * @see course_modinfo::build_course_cache()
553 * @deprecated since 2.6
555 public static function build_section_cache($courseid) {
556 throw new coding_exception('Function course_modinfo::build_section_cache() can not be used anymore.' .
557 ' Please use course_modinfo::build_course_cache() whenever applicable.');
561 * Builds a list of information about sections on a course to be stored in
562 * the course cache. (Does not include information that is already cached
563 * in some other way.)
565 * @param stdClass $course Course object (must contain fields
566 * @return array Information about sections, indexed by section number (not id)
568 protected static function build_course_section_cache($course) {
569 global $DB;
571 // Get section data
572 $sections = $DB->get_records('course_sections', array('course' => $course->id), 'section',
573 'section, id, course, name, summary, summaryformat, sequence, visible, availability');
574 $compressedsections = array();
576 $formatoptionsdef = course_get_format($course)->section_format_options();
577 // Remove unnecessary data and add availability
578 foreach ($sections as $number => $section) {
579 // Add cached options from course format to $section object
580 foreach ($formatoptionsdef as $key => $option) {
581 if (!empty($option['cache'])) {
582 $formatoptions = course_get_format($course)->get_format_options($section);
583 if (!array_key_exists('cachedefault', $option) || $option['cachedefault'] !== $formatoptions[$key]) {
584 $section->$key = $formatoptions[$key];
588 // Clone just in case it is reused elsewhere
589 $compressedsections[$number] = clone($section);
590 section_info::convert_for_section_cache($compressedsections[$number]);
593 return $compressedsections;
597 * Gets a lock for rebuilding the cache of a single course.
599 * Caller must release the returned lock.
601 * This is used to ensure that the cache rebuild doesn't happen multiple times in parallel.
602 * This function will wait up to 1 minute for the lock to be obtained. If the lock cannot
603 * be obtained, it throws an exception.
605 * @param int $courseid Course id
606 * @return \core\lock\lock Lock (must be released!)
607 * @throws moodle_exception If the lock cannot be obtained
609 protected static function get_course_cache_lock($courseid) {
610 // Get database lock to ensure this doesn't happen multiple times in parallel. Wait a
611 // reasonable time for the lock to be released, so we can give a suitable error message.
612 // In case the system crashes while building the course cache, the lock will automatically
613 // expire after a (slightly longer) period.
614 $lockfactory = \core\lock\lock_config::get_lock_factory('core_modinfo');
615 $lock = $lockfactory->get_lock('build_course_cache_' . $courseid,
616 self::COURSE_CACHE_LOCK_WAIT, self::COURSE_CACHE_LOCK_EXPIRY);
617 if (!$lock) {
618 throw new moodle_exception('locktimeout', '', '', null,
619 'core_modinfo/build_course_cache_' . $courseid);
621 return $lock;
625 * Builds and stores in MUC object containing information about course
626 * modules and sections together with cached fields from table course.
628 * @param stdClass $course object from DB table course. Must have property 'id'
629 * but preferably should have all cached fields.
630 * @return stdClass object with all cached keys of the course plus fields modinfo and sectioncache.
631 * The same object is stored in MUC
632 * @throws moodle_exception if course is not found (if $course object misses some of the
633 * necessary fields it is re-requested from database)
635 public static function build_course_cache($course) {
636 if (empty($course->id)) {
637 throw new coding_exception('Object $course is missing required property \id\'');
640 $lock = self::get_course_cache_lock($course->id);
641 try {
642 return self::inner_build_course_cache($course, $lock);
643 } finally {
644 $lock->release();
649 * Called to build course cache when there is already a lock obtained.
651 * @param stdClass $course object from DB table course
652 * @param \core\lock\lock $lock Lock object - not actually used, just there to indicate you have a lock
653 * @return stdClass Course object that has been stored in MUC
655 protected static function inner_build_course_cache($course, \core\lock\lock $lock) {
656 global $DB, $CFG;
657 require_once("{$CFG->dirroot}/course/lib.php");
659 // Ensure object has all necessary fields.
660 foreach (self::$cachedfields as $key) {
661 if (!isset($course->$key)) {
662 $course = $DB->get_record('course', array('id' => $course->id),
663 implode(',', array_merge(array('id'), self::$cachedfields)), MUST_EXIST);
664 break;
667 // Retrieve all information about activities and sections.
668 // This may take time on large courses and it is possible that another user modifies the same course during this process.
669 // Field cacherev stored in both DB and cache will ensure that cached data matches the current course state.
670 $coursemodinfo = new stdClass();
671 $coursemodinfo->modinfo = get_array_of_activities($course->id);
672 $coursemodinfo->sectioncache = self::build_course_section_cache($course);
673 foreach (self::$cachedfields as $key) {
674 $coursemodinfo->$key = $course->$key;
676 // Set the accumulated activities and sections information in cache, together with cacherev.
677 $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
678 $cachecoursemodinfo->set($course->id, $coursemodinfo);
679 return $coursemodinfo;
685 * Data about a single module on a course. This contains most of the fields in the course_modules
686 * table, plus additional data when required.
688 * The object can be accessed by core or any plugin (i.e. course format, block, filter, etc.) as
689 * get_fast_modinfo($courseorid)->cms[$coursemoduleid]
690 * or
691 * get_fast_modinfo($courseorid)->instances[$moduletype][$instanceid]
693 * There are three stages when activity module can add/modify data in this object:
695 * <b>Stage 1 - during building the cache.</b>
696 * Allows to add to the course cache static user-independent information about the module.
697 * Modules should try to include only absolutely necessary information that may be required
698 * when displaying course view page. The information is stored in application-level cache
699 * and reset when {@link rebuild_course_cache()} is called or cache is purged by admin.
701 * Modules can implement callback XXX_get_coursemodule_info() returning instance of object
702 * {@link cached_cm_info}
704 * <b>Stage 2 - dynamic data.</b>
705 * Dynamic data is user-dependend, it is stored in request-level cache. To reset this cache
706 * {@link get_fast_modinfo()} with $reset argument may be called.
708 * Dynamic data is obtained when any of the following properties/methods is requested:
709 * - {@link cm_info::$url}
710 * - {@link cm_info::$name}
711 * - {@link cm_info::$onclick}
712 * - {@link cm_info::get_icon_url()}
713 * - {@link cm_info::$uservisible}
714 * - {@link cm_info::$available}
715 * - {@link cm_info::$availableinfo}
716 * - plus any of the properties listed in Stage 3.
718 * Modules can implement callback <b>XXX_cm_info_dynamic()</b> and inside this callback they
719 * are allowed to use any of the following set methods:
720 * - {@link cm_info::set_available()}
721 * - {@link cm_info::set_name()}
722 * - {@link cm_info::set_no_view_link()}
723 * - {@link cm_info::set_user_visible()}
724 * - {@link cm_info::set_on_click()}
725 * - {@link cm_info::set_icon_url()}
726 * Any methods affecting view elements can also be set in this callback.
728 * <b>Stage 3 (view data).</b>
729 * Also user-dependend data stored in request-level cache. Second stage is created
730 * because populating the view data can be expensive as it may access much more
731 * Moodle APIs such as filters, user information, output renderers and we
732 * don't want to request it until necessary.
733 * View data is obtained when any of the following properties/methods is requested:
734 * - {@link cm_info::$afterediticons}
735 * - {@link cm_info::$content}
736 * - {@link cm_info::get_formatted_content()}
737 * - {@link cm_info::$extraclasses}
738 * - {@link cm_info::$afterlink}
740 * Modules can implement callback <b>XXX_cm_info_view()</b> and inside this callback they
741 * are allowed to use any of the following set methods:
742 * - {@link cm_info::set_after_edit_icons()}
743 * - {@link cm_info::set_after_link()}
744 * - {@link cm_info::set_content()}
745 * - {@link cm_info::set_extra_classes()}
747 * @property-read int $id Course-module ID - from course_modules table
748 * @property-read int $instance Module instance (ID within module table) - from course_modules table
749 * @property-read int $course Course ID - from course_modules table
750 * @property-read string $idnumber 'ID number' from course-modules table (arbitrary text set by user) - from
751 * course_modules table
752 * @property-read int $added Time that this course-module was added (unix time) - from course_modules table
753 * @property-read int $visible Visible setting (0 or 1; if this is 0, students cannot see/access the activity) - from
754 * course_modules table
755 * @property-read int $visibleoncoursepage Visible on course page setting - from course_modules table, adjusted to
756 * whether course format allows this module to have the "stealth" mode
757 * @property-read int $visibleold Old visible setting (if the entire section is hidden, the previous value for
758 * visible is stored in this field) - from course_modules table
759 * @property-read int $groupmode Group mode (one of the constants NOGROUPS, SEPARATEGROUPS, or VISIBLEGROUPS) - from
760 * course_modules table. Use {@link cm_info::$effectivegroupmode} to find the actual group mode that may be forced by course.
761 * @property-read int $groupingid Grouping ID (0 = all groupings)
762 * @property-read bool $coursegroupmodeforce Indicates whether the course containing the module has forced the groupmode
763 * This means that cm_info::$groupmode should be ignored and cm_info::$coursegroupmode be used instead
764 * @property-read int $coursegroupmode Group mode (one of the constants NOGROUPS, SEPARATEGROUPS, or VISIBLEGROUPS) - from
765 * course table - as specified for the course containing the module
766 * Effective only if {@link cm_info::$coursegroupmodeforce} is set
767 * @property-read int $effectivegroupmode Effective group mode for this module (one of the constants NOGROUPS, SEPARATEGROUPS,
768 * or VISIBLEGROUPS). This can be different from groupmode set for the module if the groupmode is forced for the course.
769 * This value will always be NOGROUPS if module type does not support group mode.
770 * @property-read int $indent Indent level on course page (0 = no indent) - from course_modules table
771 * @property-read int $completion Activity completion setting for this activity, COMPLETION_TRACKING_xx constant - from
772 * course_modules table
773 * @property-read mixed $completiongradeitemnumber Set to the item number (usually 0) if completion depends on a particular
774 * grade of this activity, or null if completion does not depend on a grade - from course_modules table
775 * @property-read int $completionview 1 if 'on view' completion is enabled, 0 otherwise - from course_modules table
776 * @property-read int $completionexpected Set to a unix time if completion of this activity is expected at a
777 * particular time, 0 if no time set - from course_modules table
778 * @property-read string $availability Availability information as JSON string or null if none -
779 * from course_modules table
780 * @property-read int $showdescription Controls whether the description of the activity displays on the course main page (in
781 * addition to anywhere it might display within the activity itself). 0 = do not show
782 * on main page, 1 = show on main page.
783 * @property-read string $extra (deprecated) Extra HTML that is put in an unhelpful part of the HTML when displaying this module in
784 * course page - from cached data in modinfo field. Deprecated, replaced by ->extraclasses and ->onclick
785 * @property-read string $icon Name of icon to use - from cached data in modinfo field
786 * @property-read string $iconcomponent Component that contains icon - from cached data in modinfo field
787 * @property-read string $modname Name of module e.g. 'forum' (this is the same name as the module's main database
788 * table) - from cached data in modinfo field
789 * @property-read int $module ID of module type - from course_modules table
790 * @property-read string $name Name of module instance for display on page e.g. 'General discussion forum' - from cached
791 * data in modinfo field
792 * @property-read int $sectionnum Section number that this course-module is in (section 0 = above the calendar, section 1
793 * = week/topic 1, etc) - from cached data in modinfo field
794 * @property-read int $section Section id - from course_modules table
795 * @property-read array $conditionscompletion Availability conditions for this course-module based on the completion of other
796 * course-modules (array from other course-module id to required completion state for that
797 * module) - from cached data in modinfo field
798 * @property-read array $conditionsgrade Availability conditions for this course-module based on course grades (array from
799 * grade item id to object with ->min, ->max fields) - from cached data in modinfo field
800 * @property-read array $conditionsfield Availability conditions for this course-module based on user fields
801 * @property-read bool $available True if this course-module is available to students i.e. if all availability conditions
802 * are met - obtained dynamically
803 * @property-read string $availableinfo If course-module is not available to students, this string gives information about
804 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
805 * January 2010') for display on main page - obtained dynamically
806 * @property-read bool $uservisible True if this course-module is available to the CURRENT user (for example, if current user
807 * has viewhiddenactivities capability, they can access the course-module even if it is not
808 * visible or not available, so this would be true in that case)
809 * @property-read context_module $context Module context
810 * @property-read string $modfullname Returns a localised human-readable name of the module type - calculated on request
811 * @property-read string $modplural Returns a localised human-readable name of the module type in plural form - calculated on request
812 * @property-read string $content Content to display on main (view) page - calculated on request
813 * @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
814 * @property-read string $extraclasses Extra CSS classes to add to html output for this activity on main page - calculated on request
815 * @property-read string $onclick Content of HTML on-click attribute already escaped - calculated on request
816 * @property-read mixed $customdata Optional custom data stored in modinfo cache for this activity, or null if none
817 * @property-read string $afterlink Extra HTML code to display after link - calculated on request
818 * @property-read string $afterediticons Extra HTML code to display after editing icons (e.g. more icons) - calculated on request
819 * @property-read bool $deletioninprogress True if this course module is scheduled for deletion, false otherwise.
821 class cm_info implements IteratorAggregate {
823 * State: Only basic data from modinfo cache is available.
825 const STATE_BASIC = 0;
828 * State: In the process of building dynamic data (to avoid recursive calls to obtain_dynamic_data())
830 const STATE_BUILDING_DYNAMIC = 1;
833 * State: Dynamic data is available too.
835 const STATE_DYNAMIC = 2;
838 * State: In the process of building view data (to avoid recursive calls to obtain_view_data())
840 const STATE_BUILDING_VIEW = 3;
843 * State: View data (for course page) is available.
845 const STATE_VIEW = 4;
848 * Parent object
849 * @var course_modinfo
851 private $modinfo;
854 * Level of information stored inside this object (STATE_xx constant)
855 * @var int
857 private $state;
860 * Course-module ID - from course_modules table
861 * @var int
863 private $id;
866 * Module instance (ID within module table) - from course_modules table
867 * @var int
869 private $instance;
872 * 'ID number' from course-modules table (arbitrary text set by user) - from
873 * course_modules table
874 * @var string
876 private $idnumber;
879 * Time that this course-module was added (unix time) - from course_modules table
880 * @var int
882 private $added;
885 * This variable is not used and is included here only so it can be documented.
886 * Once the database entry is removed from course_modules, it should be deleted
887 * here too.
888 * @var int
889 * @deprecated Do not use this variable
891 private $score;
894 * Visible setting (0 or 1; if this is 0, students cannot see/access the activity) - from
895 * course_modules table
896 * @var int
898 private $visible;
901 * Visible on course page setting - from course_modules table
902 * @var int
904 private $visibleoncoursepage;
907 * Old visible setting (if the entire section is hidden, the previous value for
908 * visible is stored in this field) - from course_modules table
909 * @var int
911 private $visibleold;
914 * Group mode (one of the constants NONE, SEPARATEGROUPS, or VISIBLEGROUPS) - from
915 * course_modules table
916 * @var int
918 private $groupmode;
921 * Grouping ID (0 = all groupings)
922 * @var int
924 private $groupingid;
927 * Indent level on course page (0 = no indent) - from course_modules table
928 * @var int
930 private $indent;
933 * Activity completion setting for this activity, COMPLETION_TRACKING_xx constant - from
934 * course_modules table
935 * @var int
937 private $completion;
940 * Set to the item number (usually 0) if completion depends on a particular
941 * grade of this activity, or null if completion does not depend on a grade - from
942 * course_modules table
943 * @var mixed
945 private $completiongradeitemnumber;
948 * 1 if 'on view' completion is enabled, 0 otherwise - from course_modules table
949 * @var int
951 private $completionview;
954 * Set to a unix time if completion of this activity is expected at a
955 * particular time, 0 if no time set - from course_modules table
956 * @var int
958 private $completionexpected;
961 * Availability information as JSON string or null if none - from course_modules table
962 * @var string
964 private $availability;
967 * Controls whether the description of the activity displays on the course main page (in
968 * addition to anywhere it might display within the activity itself). 0 = do not show
969 * on main page, 1 = show on main page.
970 * @var int
972 private $showdescription;
975 * Extra HTML that is put in an unhelpful part of the HTML when displaying this module in
976 * course page - from cached data in modinfo field
977 * @deprecated This is crazy, don't use it. Replaced by ->extraclasses and ->onclick
978 * @var string
980 private $extra;
983 * Name of icon to use - from cached data in modinfo field
984 * @var string
986 private $icon;
989 * Component that contains icon - from cached data in modinfo field
990 * @var string
992 private $iconcomponent;
995 * Name of module e.g. 'forum' (this is the same name as the module's main database
996 * table) - from cached data in modinfo field
997 * @var string
999 private $modname;
1002 * ID of module - from course_modules table
1003 * @var int
1005 private $module;
1008 * Name of module instance for display on page e.g. 'General discussion forum' - from cached
1009 * data in modinfo field
1010 * @var string
1012 private $name;
1015 * Section number that this course-module is in (section 0 = above the calendar, section 1
1016 * = week/topic 1, etc) - from cached data in modinfo field
1017 * @var int
1019 private $sectionnum;
1022 * Section id - from course_modules table
1023 * @var int
1025 private $section;
1028 * Availability conditions for this course-module based on the completion of other
1029 * course-modules (array from other course-module id to required completion state for that
1030 * module) - from cached data in modinfo field
1031 * @var array
1033 private $conditionscompletion;
1036 * Availability conditions for this course-module based on course grades (array from
1037 * grade item id to object with ->min, ->max fields) - from cached data in modinfo field
1038 * @var array
1040 private $conditionsgrade;
1043 * Availability conditions for this course-module based on user fields
1044 * @var array
1046 private $conditionsfield;
1049 * True if this course-module is available to students i.e. if all availability conditions
1050 * are met - obtained dynamically
1051 * @var bool
1053 private $available;
1056 * If course-module is not available to students, this string gives information about
1057 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
1058 * January 2010') for display on main page - obtained dynamically
1059 * @var string
1061 private $availableinfo;
1064 * True if this course-module is available to the CURRENT user (for example, if current user
1065 * has viewhiddenactivities capability, they can access the course-module even if it is not
1066 * visible or not available, so this would be true in that case)
1067 * @var bool
1069 private $uservisible;
1072 * True if this course-module is visible to the CURRENT user on the course page
1073 * @var bool
1075 private $uservisibleoncoursepage;
1078 * @var moodle_url
1080 private $url;
1083 * @var string
1085 private $content;
1088 * @var bool
1090 private $contentisformatted;
1093 * @var string
1095 private $extraclasses;
1098 * @var moodle_url full external url pointing to icon image for activity
1100 private $iconurl;
1103 * @var string
1105 private $onclick;
1108 * @var mixed
1110 private $customdata;
1113 * @var string
1115 private $afterlink;
1118 * @var string
1120 private $afterediticons;
1123 * @var bool representing the deletion state of the module. True if the mod is scheduled for deletion.
1125 private $deletioninprogress;
1128 * List of class read-only properties and their getter methods.
1129 * Used by magic functions __get(), __isset(), __empty()
1130 * @var array
1132 private static $standardproperties = array(
1133 'url' => 'get_url',
1134 'content' => 'get_content',
1135 'extraclasses' => 'get_extra_classes',
1136 'onclick' => 'get_on_click',
1137 'customdata' => 'get_custom_data',
1138 'afterlink' => 'get_after_link',
1139 'afterediticons' => 'get_after_edit_icons',
1140 'modfullname' => 'get_module_type_name',
1141 'modplural' => 'get_module_type_name_plural',
1142 'id' => false,
1143 'added' => false,
1144 'availability' => false,
1145 'available' => 'get_available',
1146 'availableinfo' => 'get_available_info',
1147 'completion' => false,
1148 'completionexpected' => false,
1149 'completiongradeitemnumber' => false,
1150 'completionview' => false,
1151 'conditionscompletion' => false,
1152 'conditionsfield' => false,
1153 'conditionsgrade' => false,
1154 'context' => 'get_context',
1155 'course' => 'get_course_id',
1156 'coursegroupmode' => 'get_course_groupmode',
1157 'coursegroupmodeforce' => 'get_course_groupmodeforce',
1158 'effectivegroupmode' => 'get_effective_groupmode',
1159 'extra' => false,
1160 'groupingid' => false,
1161 'groupmembersonly' => 'get_deprecated_group_members_only',
1162 'groupmode' => false,
1163 'icon' => false,
1164 'iconcomponent' => false,
1165 'idnumber' => false,
1166 'indent' => false,
1167 'instance' => false,
1168 'modname' => false,
1169 'module' => false,
1170 'name' => 'get_name',
1171 'score' => false,
1172 'section' => false,
1173 'sectionnum' => false,
1174 'showdescription' => false,
1175 'uservisible' => 'get_user_visible',
1176 'visible' => false,
1177 'visibleoncoursepage' => false,
1178 'visibleold' => false,
1179 'deletioninprogress' => false
1183 * List of methods with no arguments that were public prior to Moodle 2.6.
1185 * They can still be accessed publicly via magic __call() function with no warnings
1186 * but are not listed in the class methods list.
1187 * For the consistency of the code it is better to use corresponding properties.
1189 * These methods be deprecated completely in later versions.
1191 * @var array $standardmethods
1193 private static $standardmethods = array(
1194 // Following methods are not recommended to use because there have associated read-only properties.
1195 'get_url',
1196 'get_content',
1197 'get_extra_classes',
1198 'get_on_click',
1199 'get_custom_data',
1200 'get_after_link',
1201 'get_after_edit_icons',
1202 // Method obtain_dynamic_data() should not be called from outside of this class but it was public before Moodle 2.6.
1203 'obtain_dynamic_data',
1207 * Magic method to call functions that are now declared as private but were public in Moodle before 2.6.
1208 * These private methods can not be used anymore.
1210 * @param string $name
1211 * @param array $arguments
1212 * @return mixed
1213 * @throws coding_exception
1215 public function __call($name, $arguments) {
1216 if (in_array($name, self::$standardmethods)) {
1217 $message = "cm_info::$name() can not be used anymore.";
1218 if ($alternative = array_search($name, self::$standardproperties)) {
1219 $message .= " Please use the property cm_info->$alternative instead.";
1221 throw new coding_exception($message);
1223 throw new coding_exception("Method cm_info::{$name}() does not exist");
1227 * Magic method getter
1229 * @param string $name
1230 * @return mixed
1232 public function __get($name) {
1233 if (isset(self::$standardproperties[$name])) {
1234 if ($method = self::$standardproperties[$name]) {
1235 return $this->$method();
1236 } else {
1237 return $this->$name;
1239 } else {
1240 debugging('Invalid cm_info property accessed: '.$name);
1241 return null;
1246 * Implementation of IteratorAggregate::getIterator(), allows to cycle through properties
1247 * and use {@link convert_to_array()}
1249 * @return ArrayIterator
1251 public function getIterator() {
1252 // Make sure dynamic properties are retrieved prior to view properties.
1253 $this->obtain_dynamic_data();
1254 $ret = array();
1256 // Do not iterate over deprecated properties.
1257 $props = self::$standardproperties;
1258 unset($props['groupmembersonly']);
1260 foreach ($props as $key => $unused) {
1261 $ret[$key] = $this->__get($key);
1263 return new ArrayIterator($ret);
1267 * Magic method for function isset()
1269 * @param string $name
1270 * @return bool
1272 public function __isset($name) {
1273 if (isset(self::$standardproperties[$name])) {
1274 $value = $this->__get($name);
1275 return isset($value);
1277 return false;
1281 * Magic method for function empty()
1283 * @param string $name
1284 * @return bool
1286 public function __empty($name) {
1287 if (isset(self::$standardproperties[$name])) {
1288 $value = $this->__get($name);
1289 return empty($value);
1291 return true;
1295 * Magic method setter
1297 * Will display the developer warning when trying to set/overwrite property.
1299 * @param string $name
1300 * @param mixed $value
1302 public function __set($name, $value) {
1303 debugging("It is not allowed to set the property cm_info::\${$name}", DEBUG_DEVELOPER);
1307 * @return bool True if this module has a 'view' page that should be linked to in navigation
1308 * etc (note: modules may still have a view.php file, but return false if this is not
1309 * intended to be linked to from 'normal' parts of the interface; this is what label does).
1311 public function has_view() {
1312 return !is_null($this->url);
1316 * @return moodle_url URL to link to for this module, or null if it doesn't have a view page
1318 private function get_url() {
1319 $this->obtain_dynamic_data();
1320 return $this->url;
1324 * Obtains content to display on main (view) page.
1325 * Note: Will collect view data, if not already obtained.
1326 * @return string Content to display on main page below link, or empty string if none
1328 private function get_content() {
1329 $this->obtain_view_data();
1330 return $this->content;
1334 * Returns the content to display on course/overview page, formatted and passed through filters
1336 * if $options['context'] is not specified, the module context is used
1338 * @param array|stdClass $options formatting options, see {@link format_text()}
1339 * @return string
1341 public function get_formatted_content($options = array()) {
1342 $this->obtain_view_data();
1343 if (empty($this->content)) {
1344 return '';
1346 if ($this->contentisformatted) {
1347 return $this->content;
1350 // Improve filter performance by preloading filter setttings for all
1351 // activities on the course (this does nothing if called multiple
1352 // times)
1353 filter_preload_activities($this->get_modinfo());
1355 $options = (array)$options;
1356 if (!isset($options['context'])) {
1357 $options['context'] = $this->get_context();
1359 return format_text($this->content, FORMAT_HTML, $options);
1363 * Getter method for property $name, ensures that dynamic data is obtained.
1364 * @return string
1366 private function get_name() {
1367 $this->obtain_dynamic_data();
1368 return $this->name;
1372 * Returns the name to display on course/overview page, formatted and passed through filters
1374 * if $options['context'] is not specified, the module context is used
1376 * @param array|stdClass $options formatting options, see {@link format_string()}
1377 * @return string
1379 public function get_formatted_name($options = array()) {
1380 global $CFG;
1381 $options = (array)$options;
1382 if (!isset($options['context'])) {
1383 $options['context'] = $this->get_context();
1385 // Improve filter performance by preloading filter setttings for all
1386 // activities on the course (this does nothing if called multiple
1387 // times).
1388 if (!empty($CFG->filterall)) {
1389 filter_preload_activities($this->get_modinfo());
1391 return format_string($this->get_name(), true, $options);
1395 * Note: Will collect view data, if not already obtained.
1396 * @return string Extra CSS classes to add to html output for this activity on main page
1398 private function get_extra_classes() {
1399 $this->obtain_view_data();
1400 return $this->extraclasses;
1404 * @return string Content of HTML on-click attribute. This string will be used literally
1405 * as a string so should be pre-escaped.
1407 private function get_on_click() {
1408 // Does not need view data; may be used by navigation
1409 $this->obtain_dynamic_data();
1410 return $this->onclick;
1413 * @return mixed Optional custom data stored in modinfo cache for this activity, or null if none
1415 private function get_custom_data() {
1416 return $this->customdata;
1420 * Note: Will collect view data, if not already obtained.
1421 * @return string Extra HTML code to display after link
1423 private function get_after_link() {
1424 $this->obtain_view_data();
1425 return $this->afterlink;
1429 * Note: Will collect view data, if not already obtained.
1430 * @return string Extra HTML code to display after editing icons (e.g. more icons)
1432 private function get_after_edit_icons() {
1433 $this->obtain_view_data();
1434 return $this->afterediticons;
1438 * @param moodle_core_renderer $output Output render to use, or null for default (global)
1439 * @return moodle_url Icon URL for a suitable icon to put beside this cm
1441 public function get_icon_url($output = null) {
1442 global $OUTPUT;
1443 $this->obtain_dynamic_data();
1444 if (!$output) {
1445 $output = $OUTPUT;
1447 // Support modules setting their own, external, icon image
1448 if (!empty($this->iconurl)) {
1449 $icon = $this->iconurl;
1451 // Fallback to normal local icon + component procesing
1452 } else if (!empty($this->icon)) {
1453 if (substr($this->icon, 0, 4) === 'mod/') {
1454 list($modname, $iconname) = explode('/', substr($this->icon, 4), 2);
1455 $icon = $output->image_url($iconname, $modname);
1456 } else {
1457 if (!empty($this->iconcomponent)) {
1458 // Icon has specified component
1459 $icon = $output->image_url($this->icon, $this->iconcomponent);
1460 } else {
1461 // Icon does not have specified component, use default
1462 $icon = $output->image_url($this->icon);
1465 } else {
1466 $icon = $output->image_url('icon', $this->modname);
1468 return $icon;
1472 * @param string $textclasses additionnal classes for grouping label
1473 * @return string An empty string or HTML grouping label span tag
1475 public function get_grouping_label($textclasses = '') {
1476 $groupinglabel = '';
1477 if ($this->effectivegroupmode != NOGROUPS && !empty($this->groupingid) &&
1478 has_capability('moodle/course:managegroups', context_course::instance($this->course))) {
1479 $groupings = groups_get_all_groupings($this->course);
1480 $groupinglabel = html_writer::tag('span', '('.format_string($groupings[$this->groupingid]->name).')',
1481 array('class' => 'groupinglabel '.$textclasses));
1483 return $groupinglabel;
1487 * Returns a localised human-readable name of the module type
1489 * @param bool $plural return plural form
1490 * @return string
1492 public function get_module_type_name($plural = false) {
1493 $modnames = get_module_types_names($plural);
1494 if (isset($modnames[$this->modname])) {
1495 return $modnames[$this->modname];
1496 } else {
1497 return null;
1502 * Returns a localised human-readable name of the module type in plural form - calculated on request
1504 * @return string
1506 private function get_module_type_name_plural() {
1507 return $this->get_module_type_name(true);
1511 * @return course_modinfo Modinfo object that this came from
1513 public function get_modinfo() {
1514 return $this->modinfo;
1518 * Returns the section this module belongs to
1520 * @return section_info
1522 public function get_section_info() {
1523 return $this->modinfo->get_section_info($this->sectionnum);
1527 * Returns course object that was used in the first {@link get_fast_modinfo()} call.
1529 * It may not contain all fields from DB table {course} but always has at least the following:
1530 * id,shortname,fullname,format,enablecompletion,groupmode,groupmodeforce,cacherev
1532 * If the course object lacks the field you need you can use the global
1533 * function {@link get_course()} that will save extra query if you access
1534 * current course or frontpage course.
1536 * @return stdClass
1538 public function get_course() {
1539 return $this->modinfo->get_course();
1543 * Returns course id for which the modinfo was generated.
1545 * @return int
1547 private function get_course_id() {
1548 return $this->modinfo->get_course_id();
1552 * Returns group mode used for the course containing the module
1554 * @return int one of constants NOGROUPS, SEPARATEGROUPS, VISIBLEGROUPS
1556 private function get_course_groupmode() {
1557 return $this->modinfo->get_course()->groupmode;
1561 * Returns whether group mode is forced for the course containing the module
1563 * @return bool
1565 private function get_course_groupmodeforce() {
1566 return $this->modinfo->get_course()->groupmodeforce;
1570 * Returns effective groupmode of the module that may be overwritten by forced course groupmode.
1572 * @return int one of constants NOGROUPS, SEPARATEGROUPS, VISIBLEGROUPS
1574 private function get_effective_groupmode() {
1575 $groupmode = $this->groupmode;
1576 if ($this->modinfo->get_course()->groupmodeforce) {
1577 $groupmode = $this->modinfo->get_course()->groupmode;
1578 if ($groupmode != NOGROUPS && !plugin_supports('mod', $this->modname, FEATURE_GROUPS, 0)) {
1579 $groupmode = NOGROUPS;
1582 return $groupmode;
1586 * @return context_module Current module context
1588 private function get_context() {
1589 return context_module::instance($this->id);
1593 * Returns itself in the form of stdClass.
1595 * The object includes all fields that table course_modules has and additionally
1596 * fields 'name', 'modname', 'sectionnum' (if requested).
1598 * This can be used as a faster alternative to {@link get_coursemodule_from_id()}
1600 * @param bool $additionalfields include additional fields 'name', 'modname', 'sectionnum'
1601 * @return stdClass
1603 public function get_course_module_record($additionalfields = false) {
1604 $cmrecord = new stdClass();
1606 // Standard fields from table course_modules.
1607 static $cmfields = array('id', 'course', 'module', 'instance', 'section', 'idnumber', 'added',
1608 'score', 'indent', 'visible', 'visibleoncoursepage', 'visibleold', 'groupmode', 'groupingid',
1609 'completion', 'completiongradeitemnumber', 'completionview', 'completionexpected',
1610 'showdescription', 'availability', 'deletioninprogress');
1611 foreach ($cmfields as $key) {
1612 $cmrecord->$key = $this->$key;
1615 // Additional fields that function get_coursemodule_from_id() adds.
1616 if ($additionalfields) {
1617 $cmrecord->name = $this->name;
1618 $cmrecord->modname = $this->modname;
1619 $cmrecord->sectionnum = $this->sectionnum;
1622 return $cmrecord;
1625 // Set functions
1626 ////////////////
1629 * Sets content to display on course view page below link (if present).
1630 * @param string $content New content as HTML string (empty string if none)
1631 * @param bool $isformatted Whether user content is already passed through format_text/format_string and should not
1632 * be formatted again. This can be useful when module adds interactive elements on top of formatted user text.
1633 * @return void
1635 public function set_content($content, $isformatted = false) {
1636 $this->content = $content;
1637 $this->contentisformatted = $isformatted;
1641 * Sets extra classes to include in CSS.
1642 * @param string $extraclasses Extra classes (empty string if none)
1643 * @return void
1645 public function set_extra_classes($extraclasses) {
1646 $this->extraclasses = $extraclasses;
1650 * Sets the external full url that points to the icon being used
1651 * by the activity. Useful for external-tool modules (lti...)
1652 * If set, takes precedence over $icon and $iconcomponent
1654 * @param moodle_url $iconurl full external url pointing to icon image for activity
1655 * @return void
1657 public function set_icon_url(moodle_url $iconurl) {
1658 $this->iconurl = $iconurl;
1662 * Sets value of on-click attribute for JavaScript.
1663 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1664 * @param string $onclick New onclick attribute which should be HTML-escaped
1665 * (empty string if none)
1666 * @return void
1668 public function set_on_click($onclick) {
1669 $this->check_not_view_only();
1670 $this->onclick = $onclick;
1674 * Sets HTML that displays after link on course view page.
1675 * @param string $afterlink HTML string (empty string if none)
1676 * @return void
1678 public function set_after_link($afterlink) {
1679 $this->afterlink = $afterlink;
1683 * Sets HTML that displays after edit icons on course view page.
1684 * @param string $afterediticons HTML string (empty string if none)
1685 * @return void
1687 public function set_after_edit_icons($afterediticons) {
1688 $this->afterediticons = $afterediticons;
1692 * Changes the name (text of link) for this module instance.
1693 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1694 * @param string $name Name of activity / link text
1695 * @return void
1697 public function set_name($name) {
1698 if ($this->state < self::STATE_BUILDING_DYNAMIC) {
1699 $this->update_user_visible();
1701 $this->name = $name;
1705 * Turns off the view link for this module instance.
1706 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1707 * @return void
1709 public function set_no_view_link() {
1710 $this->check_not_view_only();
1711 $this->url = null;
1715 * Sets the 'uservisible' flag. This can be used (by setting false) to prevent access and
1716 * display of this module link for the current user.
1717 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1718 * @param bool $uservisible
1719 * @return void
1721 public function set_user_visible($uservisible) {
1722 $this->check_not_view_only();
1723 $this->uservisible = $uservisible;
1727 * Sets the 'available' flag and related details. This flag is normally used to make
1728 * course modules unavailable until a certain date or condition is met. (When a course
1729 * module is unavailable, it is still visible to users who have viewhiddenactivities
1730 * permission.)
1732 * When this is function is called, user-visible status is recalculated automatically.
1734 * The $showavailability flag does not really do anything any more, but is retained
1735 * for backward compatibility. Setting this to false will cause $availableinfo to
1736 * be ignored.
1738 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1739 * @param bool $available False if this item is not 'available'
1740 * @param int $showavailability 0 = do not show this item at all if it's not available,
1741 * 1 = show this item greyed out with the following message
1742 * @param string $availableinfo Information about why this is not available, or
1743 * empty string if not displaying
1744 * @return void
1746 public function set_available($available, $showavailability=0, $availableinfo='') {
1747 $this->check_not_view_only();
1748 $this->available = $available;
1749 if (!$showavailability) {
1750 $availableinfo = '';
1752 $this->availableinfo = $availableinfo;
1753 $this->update_user_visible();
1757 * Some set functions can only be called from _cm_info_dynamic and not _cm_info_view.
1758 * This is because they may affect parts of this object which are used on pages other
1759 * than the view page (e.g. in the navigation block, or when checking access on
1760 * module pages).
1761 * @return void
1763 private function check_not_view_only() {
1764 if ($this->state >= self::STATE_DYNAMIC) {
1765 throw new coding_exception('Cannot set this data from _cm_info_view because it may ' .
1766 'affect other pages as well as view');
1771 * Constructor should not be called directly; use {@link get_fast_modinfo()}
1773 * @param course_modinfo $modinfo Parent object
1774 * @param stdClass $notused1 Argument not used
1775 * @param stdClass $mod Module object from the modinfo field of course table
1776 * @param stdClass $notused2 Argument not used
1778 public function __construct(course_modinfo $modinfo, $notused1, $mod, $notused2) {
1779 $this->modinfo = $modinfo;
1781 $this->id = $mod->cm;
1782 $this->instance = $mod->id;
1783 $this->modname = $mod->mod;
1784 $this->idnumber = isset($mod->idnumber) ? $mod->idnumber : '';
1785 $this->name = $mod->name;
1786 $this->visible = $mod->visible;
1787 $this->visibleoncoursepage = $mod->visibleoncoursepage;
1788 $this->sectionnum = $mod->section; // Note weirdness with name here
1789 $this->groupmode = isset($mod->groupmode) ? $mod->groupmode : 0;
1790 $this->groupingid = isset($mod->groupingid) ? $mod->groupingid : 0;
1791 $this->indent = isset($mod->indent) ? $mod->indent : 0;
1792 $this->extra = isset($mod->extra) ? $mod->extra : '';
1793 $this->extraclasses = isset($mod->extraclasses) ? $mod->extraclasses : '';
1794 // iconurl may be stored as either string or instance of moodle_url.
1795 $this->iconurl = isset($mod->iconurl) ? new moodle_url($mod->iconurl) : '';
1796 $this->onclick = isset($mod->onclick) ? $mod->onclick : '';
1797 $this->content = isset($mod->content) ? $mod->content : '';
1798 $this->icon = isset($mod->icon) ? $mod->icon : '';
1799 $this->iconcomponent = isset($mod->iconcomponent) ? $mod->iconcomponent : '';
1800 $this->customdata = isset($mod->customdata) ? $mod->customdata : '';
1801 $this->showdescription = isset($mod->showdescription) ? $mod->showdescription : 0;
1802 $this->state = self::STATE_BASIC;
1804 $this->section = isset($mod->sectionid) ? $mod->sectionid : 0;
1805 $this->module = isset($mod->module) ? $mod->module : 0;
1806 $this->added = isset($mod->added) ? $mod->added : 0;
1807 $this->score = isset($mod->score) ? $mod->score : 0;
1808 $this->visibleold = isset($mod->visibleold) ? $mod->visibleold : 0;
1809 $this->deletioninprogress = isset($mod->deletioninprogress) ? $mod->deletioninprogress : 0;
1811 // Note: it saves effort and database space to always include the
1812 // availability and completion fields, even if availability or completion
1813 // are actually disabled
1814 $this->completion = isset($mod->completion) ? $mod->completion : 0;
1815 $this->completiongradeitemnumber = isset($mod->completiongradeitemnumber)
1816 ? $mod->completiongradeitemnumber : null;
1817 $this->completionview = isset($mod->completionview)
1818 ? $mod->completionview : 0;
1819 $this->completionexpected = isset($mod->completionexpected)
1820 ? $mod->completionexpected : 0;
1821 $this->availability = isset($mod->availability) ? $mod->availability : null;
1822 $this->conditionscompletion = isset($mod->conditionscompletion)
1823 ? $mod->conditionscompletion : array();
1824 $this->conditionsgrade = isset($mod->conditionsgrade)
1825 ? $mod->conditionsgrade : array();
1826 $this->conditionsfield = isset($mod->conditionsfield)
1827 ? $mod->conditionsfield : array();
1829 static $modviews = array();
1830 if (!isset($modviews[$this->modname])) {
1831 $modviews[$this->modname] = !plugin_supports('mod', $this->modname,
1832 FEATURE_NO_VIEW_LINK);
1834 $this->url = $modviews[$this->modname]
1835 ? new moodle_url('/mod/' . $this->modname . '/view.php', array('id'=>$this->id))
1836 : null;
1840 * Creates a cm_info object from a database record (also accepts cm_info
1841 * in which case it is just returned unchanged).
1843 * @param stdClass|cm_info|null|bool $cm Stdclass or cm_info (or null or false)
1844 * @param int $userid Optional userid (default to current)
1845 * @return cm_info|null Object as cm_info, or null if input was null/false
1847 public static function create($cm, $userid = 0) {
1848 // Null, false, etc. gets passed through as null.
1849 if (!$cm) {
1850 return null;
1852 // If it is already a cm_info object, just return it.
1853 if ($cm instanceof cm_info) {
1854 return $cm;
1856 // Otherwise load modinfo.
1857 if (empty($cm->id) || empty($cm->course)) {
1858 throw new coding_exception('$cm must contain ->id and ->course');
1860 $modinfo = get_fast_modinfo($cm->course, $userid);
1861 return $modinfo->get_cm($cm->id);
1865 * If dynamic data for this course-module is not yet available, gets it.
1867 * This function is automatically called when requesting any course_modinfo property
1868 * that can be modified by modules (have a set_xxx method).
1870 * Dynamic data is data which does not come directly from the cache but is calculated at
1871 * runtime based on the current user. Primarily this concerns whether the user can access
1872 * the module or not.
1874 * As part of this function, the module's _cm_info_dynamic function from its lib.php will
1875 * be called (if it exists).
1876 * @return void
1878 private function obtain_dynamic_data() {
1879 global $CFG;
1880 $userid = $this->modinfo->get_user_id();
1881 if ($this->state >= self::STATE_BUILDING_DYNAMIC || $userid == -1) {
1882 return;
1884 $this->state = self::STATE_BUILDING_DYNAMIC;
1886 if (!empty($CFG->enableavailability)) {
1887 // Get availability information.
1888 $ci = new \core_availability\info_module($this);
1890 // Note that the modinfo currently available only includes minimal details (basic data)
1891 // but we know that this function does not need anything more than basic data.
1892 $this->available = $ci->is_available($this->availableinfo, true,
1893 $userid, $this->modinfo);
1894 } else {
1895 $this->available = true;
1898 // Check parent section.
1899 if ($this->available) {
1900 $parentsection = $this->modinfo->get_section_info($this->sectionnum);
1901 if (!$parentsection->available) {
1902 // Do not store info from section here, as that is already
1903 // presented from the section (if appropriate) - just change
1904 // the flag
1905 $this->available = false;
1909 // Update visible state for current user.
1910 $this->update_user_visible();
1912 // Let module make dynamic changes at this point
1913 $this->call_mod_function('cm_info_dynamic');
1914 $this->state = self::STATE_DYNAMIC;
1918 * Getter method for property $uservisible, ensures that dynamic data is retrieved.
1919 * @return bool
1921 private function get_user_visible() {
1922 $this->obtain_dynamic_data();
1923 return $this->uservisible;
1927 * Returns whether this module is visible to the current user on course page
1929 * Activity may be visible on the course page but not available, for example
1930 * when it is hidden conditionally but the condition information is displayed.
1932 * @return bool
1934 public function is_visible_on_course_page() {
1935 $this->obtain_dynamic_data();
1936 return $this->uservisibleoncoursepage;
1940 * Whether this module is available but hidden from course page
1942 * "Stealth" modules are the ones that are not shown on course page but available by following url.
1943 * They are normally also displayed in grade reports and other reports.
1944 * Module will be stealth either if visibleoncoursepage=0 or it is a visible module inside the hidden
1945 * section.
1947 * @return bool
1949 public function is_stealth() {
1950 return !$this->visibleoncoursepage ||
1951 ($this->visible && ($section = $this->get_section_info()) && !$section->visible);
1955 * Getter method for property $available, ensures that dynamic data is retrieved
1956 * @return bool
1958 private function get_available() {
1959 $this->obtain_dynamic_data();
1960 return $this->available;
1964 * This method can not be used anymore.
1966 * @see \core_availability\info_module::filter_user_list()
1967 * @deprecated Since Moodle 2.8
1969 private function get_deprecated_group_members_only() {
1970 throw new coding_exception('$cm->groupmembersonly can not be used anymore. ' .
1971 'If used to restrict a list of enrolled users to only those who can ' .
1972 'access the module, consider \core_availability\info_module::filter_user_list.');
1976 * Getter method for property $availableinfo, ensures that dynamic data is retrieved
1978 * @return string Available info (HTML)
1980 private function get_available_info() {
1981 $this->obtain_dynamic_data();
1982 return $this->availableinfo;
1986 * Works out whether activity is available to the current user
1988 * If the activity is unavailable, additional checks are required to determine if its hidden or greyed out
1990 * @return void
1992 private function update_user_visible() {
1993 $userid = $this->modinfo->get_user_id();
1994 if ($userid == -1) {
1995 return null;
1997 $this->uservisible = true;
1999 // If the module is being deleted, set the uservisible state to false and return.
2000 if ($this->deletioninprogress) {
2001 $this->uservisible = false;
2002 return null;
2005 // If the user cannot access the activity set the uservisible flag to false.
2006 // Additional checks are required to determine whether the activity is entirely hidden or just greyed out.
2007 if ((!$this->visible && !has_capability('moodle/course:viewhiddenactivities', $this->get_context(), $userid)) ||
2008 (!$this->get_available() &&
2009 !has_capability('moodle/course:ignoreavailabilityrestrictions', $this->get_context(), $userid))) {
2011 $this->uservisible = false;
2014 // Check group membership.
2015 if ($this->is_user_access_restricted_by_capability()) {
2017 $this->uservisible = false;
2018 // Ensure activity is completely hidden from the user.
2019 $this->availableinfo = '';
2022 $this->uservisibleoncoursepage = $this->uservisible &&
2023 ($this->visibleoncoursepage ||
2024 has_capability('moodle/course:manageactivities', $this->get_context(), $userid) ||
2025 has_capability('moodle/course:activityvisibility', $this->get_context(), $userid));
2026 // Activity that is not available, not hidden from course page and has availability
2027 // info is actually visible on the course page (with availability info and without a link).
2028 if (!$this->uservisible && $this->visibleoncoursepage && $this->availableinfo) {
2029 $this->uservisibleoncoursepage = true;
2034 * This method has been deprecated and should not be used.
2036 * @see $uservisible
2037 * @deprecated Since Moodle 2.8
2039 public function is_user_access_restricted_by_group() {
2040 throw new coding_exception('cm_info::is_user_access_restricted_by_group() can not be used any more.' .
2041 ' Use $cm->uservisible to decide whether the current user can access an activity.');
2045 * Checks whether mod/...:view capability restricts the current user's access.
2047 * @return bool True if the user access is restricted.
2049 public function is_user_access_restricted_by_capability() {
2050 $userid = $this->modinfo->get_user_id();
2051 if ($userid == -1) {
2052 return null;
2054 $capability = 'mod/' . $this->modname . ':view';
2055 $capabilityinfo = get_capability_info($capability);
2056 if (!$capabilityinfo) {
2057 // Capability does not exist, no one is prevented from seeing the activity.
2058 return false;
2061 // You are blocked if you don't have the capability.
2062 return !has_capability($capability, $this->get_context(), $userid);
2066 * Checks whether the module's conditional access settings mean that the
2067 * user cannot see the activity at all
2069 * @deprecated since 2.7 MDL-44070
2071 public function is_user_access_restricted_by_conditional_access() {
2072 throw new coding_exception('cm_info::is_user_access_restricted_by_conditional_access() ' .
2073 'can not be used any more; this function is not needed (use $cm->uservisible ' .
2074 'and $cm->availableinfo to decide whether it should be available ' .
2075 'or appear)');
2079 * Calls a module function (if exists), passing in one parameter: this object.
2080 * @param string $type Name of function e.g. if this is 'grooblezorb' and the modname is
2081 * 'forum' then it will try to call 'mod_forum_grooblezorb' or 'forum_grooblezorb'
2082 * @return void
2084 private function call_mod_function($type) {
2085 global $CFG;
2086 $libfile = $CFG->dirroot . '/mod/' . $this->modname . '/lib.php';
2087 if (file_exists($libfile)) {
2088 include_once($libfile);
2089 $function = 'mod_' . $this->modname . '_' . $type;
2090 if (function_exists($function)) {
2091 $function($this);
2092 } else {
2093 $function = $this->modname . '_' . $type;
2094 if (function_exists($function)) {
2095 $function($this);
2102 * If view data for this course-module is not yet available, obtains it.
2104 * This function is automatically called if any of the functions (marked) which require
2105 * view data are called.
2107 * View data is data which is needed only for displaying the course main page (& any similar
2108 * functionality on other pages) but is not needed in general. Obtaining view data may have
2109 * a performance cost.
2111 * As part of this function, the module's _cm_info_view function from its lib.php will
2112 * be called (if it exists).
2113 * @return void
2115 private function obtain_view_data() {
2116 if ($this->state >= self::STATE_BUILDING_VIEW || $this->modinfo->get_user_id() == -1) {
2117 return;
2119 $this->obtain_dynamic_data();
2120 $this->state = self::STATE_BUILDING_VIEW;
2122 // Let module make changes at this point
2123 $this->call_mod_function('cm_info_view');
2124 $this->state = self::STATE_VIEW;
2130 * Returns reference to full info about modules in course (including visibility).
2131 * Cached and as fast as possible (0 or 1 db query).
2133 * use get_fast_modinfo($courseid, 0, true) to reset the static cache for particular course
2134 * use get_fast_modinfo(0, 0, true) to reset the static cache for all courses
2136 * use rebuild_course_cache($courseid, true) to reset the application AND static cache
2137 * for particular course when it's contents has changed
2139 * @param int|stdClass $courseorid object from DB table 'course' (must have field 'id'
2140 * and recommended to have field 'cacherev') or just a course id. Just course id
2141 * is enough when calling get_fast_modinfo() for current course or site or when
2142 * calling for any other course for the second time.
2143 * @param int $userid User id to populate 'availble' and 'uservisible' attributes of modules and sections.
2144 * Set to 0 for current user (default). Set to -1 to avoid calculation of dynamic user-depended data.
2145 * @param bool $resetonly whether we want to get modinfo or just reset the cache
2146 * @return course_modinfo|null Module information for course, or null if resetting
2147 * @throws moodle_exception when course is not found (nothing is thrown if resetting)
2149 function get_fast_modinfo($courseorid, $userid = 0, $resetonly = false) {
2150 // compartibility with syntax prior to 2.4:
2151 if ($courseorid === 'reset') {
2152 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);
2153 $courseorid = 0;
2154 $resetonly = true;
2157 // Function get_fast_modinfo() can never be called during upgrade unless it is used for clearing cache only.
2158 if (!$resetonly) {
2159 upgrade_ensure_not_running();
2162 // Function is called with $reset = true
2163 if ($resetonly) {
2164 course_modinfo::clear_instance_cache($courseorid);
2165 return null;
2168 // Function is called with $reset = false, retrieve modinfo
2169 return course_modinfo::instance($courseorid, $userid);
2173 * Efficiently retrieves the $course (stdclass) and $cm (cm_info) objects, given
2174 * a cmid. If module name is also provided, it will ensure the cm is of that type.
2176 * Usage:
2177 * list($course, $cm) = get_course_and_cm_from_cmid($cmid, 'forum');
2179 * Using this method has a performance advantage because it works by loading
2180 * modinfo for the course - which will then be cached and it is needed later
2181 * in most requests. It also guarantees that the $cm object is a cm_info and
2182 * not a stdclass.
2184 * The $course object can be supplied if already known and will speed
2185 * up this function - although it is more efficient to use this function to
2186 * get the course if you are starting from a cmid.
2188 * To avoid security problems and obscure bugs, you should always specify
2189 * $modulename if the cmid value came from user input.
2191 * By default this obtains information (for example, whether user can access
2192 * the activity) for current user, but you can specify a userid if required.
2194 * @param stdClass|int $cmorid Id of course-module, or database object
2195 * @param string $modulename Optional modulename (improves security)
2196 * @param stdClass|int $courseorid Optional course object if already loaded
2197 * @param int $userid Optional userid (default = current)
2198 * @return array Array with 2 elements $course and $cm
2199 * @throws moodle_exception If the item doesn't exist or is of wrong module name
2201 function get_course_and_cm_from_cmid($cmorid, $modulename = '', $courseorid = 0, $userid = 0) {
2202 global $DB;
2203 if (is_object($cmorid)) {
2204 $cmid = $cmorid->id;
2205 if (isset($cmorid->course)) {
2206 $courseid = (int)$cmorid->course;
2207 } else {
2208 $courseid = 0;
2210 } else {
2211 $cmid = (int)$cmorid;
2212 $courseid = 0;
2215 // Validate module name if supplied.
2216 if ($modulename && !core_component::is_valid_plugin_name('mod', $modulename)) {
2217 throw new coding_exception('Invalid modulename parameter');
2220 // Get course from last parameter if supplied.
2221 $course = null;
2222 if (is_object($courseorid)) {
2223 $course = $courseorid;
2224 } else if ($courseorid) {
2225 $courseid = (int)$courseorid;
2228 if (!$course) {
2229 if ($courseid) {
2230 // If course ID is known, get it using normal function.
2231 $course = get_course($courseid);
2232 } else {
2233 // Get course record in a single query based on cmid.
2234 $course = $DB->get_record_sql("
2235 SELECT c.*
2236 FROM {course_modules} cm
2237 JOIN {course} c ON c.id = cm.course
2238 WHERE cm.id = ?", array($cmid), MUST_EXIST);
2242 // Get cm from get_fast_modinfo.
2243 $modinfo = get_fast_modinfo($course, $userid);
2244 $cm = $modinfo->get_cm($cmid);
2245 if ($modulename && $cm->modname !== $modulename) {
2246 throw new moodle_exception('invalidcoursemodule', 'error');
2248 return array($course, $cm);
2252 * Efficiently retrieves the $course (stdclass) and $cm (cm_info) objects, given
2253 * an instance id or record and module name.
2255 * Usage:
2256 * list($course, $cm) = get_course_and_cm_from_instance($forum, 'forum');
2258 * Using this method has a performance advantage because it works by loading
2259 * modinfo for the course - which will then be cached and it is needed later
2260 * in most requests. It also guarantees that the $cm object is a cm_info and
2261 * not a stdclass.
2263 * The $course object can be supplied if already known and will speed
2264 * up this function - although it is more efficient to use this function to
2265 * get the course if you are starting from an instance id.
2267 * By default this obtains information (for example, whether user can access
2268 * the activity) for current user, but you can specify a userid if required.
2270 * @param stdclass|int $instanceorid Id of module instance, or database object
2271 * @param string $modulename Modulename (required)
2272 * @param stdClass|int $courseorid Optional course object if already loaded
2273 * @param int $userid Optional userid (default = current)
2274 * @return array Array with 2 elements $course and $cm
2275 * @throws moodle_exception If the item doesn't exist or is of wrong module name
2277 function get_course_and_cm_from_instance($instanceorid, $modulename, $courseorid = 0, $userid = 0) {
2278 global $DB;
2280 // Get data from parameter.
2281 if (is_object($instanceorid)) {
2282 $instanceid = $instanceorid->id;
2283 if (isset($instanceorid->course)) {
2284 $courseid = (int)$instanceorid->course;
2285 } else {
2286 $courseid = 0;
2288 } else {
2289 $instanceid = (int)$instanceorid;
2290 $courseid = 0;
2293 // Get course from last parameter if supplied.
2294 $course = null;
2295 if (is_object($courseorid)) {
2296 $course = $courseorid;
2297 } else if ($courseorid) {
2298 $courseid = (int)$courseorid;
2301 // Validate module name if supplied.
2302 if (!core_component::is_valid_plugin_name('mod', $modulename)) {
2303 throw new coding_exception('Invalid modulename parameter');
2306 if (!$course) {
2307 if ($courseid) {
2308 // If course ID is known, get it using normal function.
2309 $course = get_course($courseid);
2310 } else {
2311 // Get course record in a single query based on instance id.
2312 $pagetable = '{' . $modulename . '}';
2313 $course = $DB->get_record_sql("
2314 SELECT c.*
2315 FROM $pagetable instance
2316 JOIN {course} c ON c.id = instance.course
2317 WHERE instance.id = ?", array($instanceid), MUST_EXIST);
2321 // Get cm from get_fast_modinfo.
2322 $modinfo = get_fast_modinfo($course, $userid);
2323 $instances = $modinfo->get_instances_of($modulename);
2324 if (!array_key_exists($instanceid, $instances)) {
2325 throw new moodle_exception('invalidmoduleid', 'error', $instanceid);
2327 return array($course, $instances[$instanceid]);
2332 * Rebuilds or resets the cached list of course activities stored in MUC.
2334 * rebuild_course_cache() must NEVER be called from lib/db/upgrade.php.
2335 * At the same time course cache may ONLY be cleared using this function in
2336 * upgrade scripts of plugins.
2338 * During the bulk operations if it is necessary to reset cache of multiple
2339 * courses it is enough to call {@link increment_revision_number()} for the
2340 * table 'course' and field 'cacherev' specifying affected courses in select.
2342 * Cached course information is stored in MUC core/coursemodinfo and is
2343 * validated with the DB field {course}.cacherev
2345 * @global moodle_database $DB
2346 * @param int $courseid id of course to rebuild, empty means all
2347 * @param boolean $clearonly only clear the cache, gets rebuild automatically on the fly.
2348 * Recommended to set to true to avoid unnecessary multiple rebuilding.
2350 function rebuild_course_cache($courseid=0, $clearonly=false) {
2351 global $COURSE, $SITE, $DB, $CFG;
2353 // Function rebuild_course_cache() can not be called during upgrade unless it's clear only.
2354 if (!$clearonly && !upgrade_ensure_not_running(true)) {
2355 $clearonly = true;
2358 // Destroy navigation caches
2359 navigation_cache::destroy_volatile_caches();
2361 if (class_exists('format_base')) {
2362 // if file containing class is not loaded, there is no cache there anyway
2363 format_base::reset_course_cache($courseid);
2366 $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
2367 if (empty($courseid)) {
2368 // Clearing caches for all courses.
2369 increment_revision_number('course', 'cacherev', '');
2370 $cachecoursemodinfo->purge();
2371 course_modinfo::clear_instance_cache();
2372 // Update global values too.
2373 $sitecacherev = $DB->get_field('course', 'cacherev', array('id' => SITEID));
2374 $SITE->cachrev = $sitecacherev;
2375 if ($COURSE->id == SITEID) {
2376 $COURSE->cacherev = $sitecacherev;
2377 } else {
2378 $COURSE->cacherev = $DB->get_field('course', 'cacherev', array('id' => $COURSE->id));
2380 } else {
2381 // Clearing cache for one course, make sure it is deleted from user request cache as well.
2382 increment_revision_number('course', 'cacherev', 'id = :id', array('id' => $courseid));
2383 $cachecoursemodinfo->delete($courseid);
2384 course_modinfo::clear_instance_cache($courseid);
2385 // Update global values too.
2386 if ($courseid == $COURSE->id || $courseid == $SITE->id) {
2387 $cacherev = $DB->get_field('course', 'cacherev', array('id' => $courseid));
2388 if ($courseid == $COURSE->id) {
2389 $COURSE->cacherev = $cacherev;
2391 if ($courseid == $SITE->id) {
2392 $SITE->cachrev = $cacherev;
2397 if ($clearonly) {
2398 return;
2401 if ($courseid) {
2402 $select = array('id'=>$courseid);
2403 } else {
2404 $select = array();
2405 core_php_time_limit::raise(); // this could take a while! MDL-10954
2408 $rs = $DB->get_recordset("course", $select,'','id,'.join(',', course_modinfo::$cachedfields));
2409 // Rebuild cache for each course.
2410 foreach ($rs as $course) {
2411 course_modinfo::build_course_cache($course);
2413 $rs->close();
2418 * Class that is the return value for the _get_coursemodule_info module API function.
2420 * Note: For backward compatibility, you can also return a stdclass object from that function.
2421 * The difference is that the stdclass object may contain an 'extra' field (deprecated,
2422 * use extraclasses and onclick instead). The stdclass object may not contain
2423 * the new fields defined here (content, extraclasses, customdata).
2425 class cached_cm_info {
2427 * Name (text of link) for this activity; Leave unset to accept default name
2428 * @var string
2430 public $name;
2433 * Name of icon for this activity. Normally, this should be used together with $iconcomponent
2434 * to define the icon, as per image_url function.
2435 * For backward compatibility, if this value is of the form 'mod/forum/icon' then an icon
2436 * within that module will be used.
2437 * @see cm_info::get_icon_url()
2438 * @see renderer_base::image_url()
2439 * @var string
2441 public $icon;
2444 * Component for icon for this activity, as per image_url; leave blank to use default 'moodle'
2445 * component
2446 * @see renderer_base::image_url()
2447 * @var string
2449 public $iconcomponent;
2452 * HTML content to be displayed on the main page below the link (if any) for this course-module
2453 * @var string
2455 public $content;
2458 * Custom data to be stored in modinfo for this activity; useful if there are cases when
2459 * internal information for this activity type needs to be accessible from elsewhere on the
2460 * course without making database queries. May be of any type but should be short.
2461 * @var mixed
2463 public $customdata;
2466 * Extra CSS class or classes to be added when this activity is displayed on the main page;
2467 * space-separated string
2468 * @var string
2470 public $extraclasses;
2473 * External URL image to be used by activity as icon, useful for some external-tool modules
2474 * like lti. If set, takes precedence over $icon and $iconcomponent
2475 * @var $moodle_url
2477 public $iconurl;
2480 * Content of onclick JavaScript; escaped HTML to be inserted as attribute value
2481 * @var string
2483 public $onclick;
2488 * Data about a single section on a course. This contains the fields from the
2489 * course_sections table, plus additional data when required.
2491 * @property-read int $id Section ID - from course_sections table
2492 * @property-read int $course Course ID - from course_sections table
2493 * @property-read int $section Section number - from course_sections table
2494 * @property-read string $name Section name if specified - from course_sections table
2495 * @property-read int $visible Section visibility (1 = visible) - from course_sections table
2496 * @property-read string $summary Section summary text if specified - from course_sections table
2497 * @property-read int $summaryformat Section summary text format (FORMAT_xx constant) - from course_sections table
2498 * @property-read string $availability Availability information as JSON string -
2499 * from course_sections table
2500 * @property-read array $conditionscompletion Availability conditions for this section based on the completion of
2501 * course-modules (array from course-module id to required completion state
2502 * for that module) - from cached data in sectioncache field
2503 * @property-read array $conditionsgrade Availability conditions for this section based on course grades (array from
2504 * grade item id to object with ->min, ->max fields) - from cached data in
2505 * sectioncache field
2506 * @property-read array $conditionsfield Availability conditions for this section based on user fields
2507 * @property-read bool $available True if this section is available to the given user i.e. if all availability conditions
2508 * are met - obtained dynamically
2509 * @property-read string $availableinfo If section is not available to some users, this string gives information about
2510 * availability which can be displayed to students and/or staff (e.g. 'Available from 3 January 2010')
2511 * for display on main page - obtained dynamically
2512 * @property-read bool $uservisible True if this section is available to the given user (for example, if current user
2513 * has viewhiddensections capability, they can access the section even if it is not
2514 * visible or not available, so this would be true in that case) - obtained dynamically
2515 * @property-read string $sequence Comma-separated list of all modules in the section. Note, this field may not exactly
2516 * match course_sections.sequence if later has references to non-existing modules or not modules of not available module types.
2517 * @property-read course_modinfo $modinfo
2519 class section_info implements IteratorAggregate {
2521 * Section ID - from course_sections table
2522 * @var int
2524 private $_id;
2527 * Section number - from course_sections table
2528 * @var int
2530 private $_section;
2533 * Section name if specified - from course_sections table
2534 * @var string
2536 private $_name;
2539 * Section visibility (1 = visible) - from course_sections table
2540 * @var int
2542 private $_visible;
2545 * Section summary text if specified - from course_sections table
2546 * @var string
2548 private $_summary;
2551 * Section summary text format (FORMAT_xx constant) - from course_sections table
2552 * @var int
2554 private $_summaryformat;
2557 * Availability information as JSON string - from course_sections table
2558 * @var string
2560 private $_availability;
2563 * Availability conditions for this section based on the completion of
2564 * course-modules (array from course-module id to required completion state
2565 * for that module) - from cached data in sectioncache field
2566 * @var array
2568 private $_conditionscompletion;
2571 * Availability conditions for this section based on course grades (array from
2572 * grade item id to object with ->min, ->max fields) - from cached data in
2573 * sectioncache field
2574 * @var array
2576 private $_conditionsgrade;
2579 * Availability conditions for this section based on user fields
2580 * @var array
2582 private $_conditionsfield;
2585 * True if this section is available to students i.e. if all availability conditions
2586 * are met - obtained dynamically on request, see function {@link section_info::get_available()}
2587 * @var bool|null
2589 private $_available;
2592 * If section is not available to some users, this string gives information about
2593 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
2594 * January 2010') for display on main page - obtained dynamically on request, see
2595 * function {@link section_info::get_availableinfo()}
2596 * @var string
2598 private $_availableinfo;
2601 * True if this section is available to the CURRENT user (for example, if current user
2602 * has viewhiddensections capability, they can access the section even if it is not
2603 * visible or not available, so this would be true in that case) - obtained dynamically
2604 * on request, see function {@link section_info::get_uservisible()}
2605 * @var bool|null
2607 private $_uservisible;
2610 * Default values for sectioncache fields; if a field has this value, it won't
2611 * be stored in the sectioncache cache, to save space. Checks are done by ===
2612 * which means values must all be strings.
2613 * @var array
2615 private static $sectioncachedefaults = array(
2616 'name' => null,
2617 'summary' => '',
2618 'summaryformat' => '1', // FORMAT_HTML, but must be a string
2619 'visible' => '1',
2620 'availability' => null
2624 * Stores format options that have been cached when building 'coursecache'
2625 * When the format option is requested we look first if it has been cached
2626 * @var array
2628 private $cachedformatoptions = array();
2631 * Stores the list of all possible section options defined in each used course format.
2632 * @var array
2634 static private $sectionformatoptions = array();
2637 * Stores the modinfo object passed in constructor, may be used when requesting
2638 * dynamically obtained attributes such as available, availableinfo, uservisible.
2639 * Also used to retrun information about current course or user.
2640 * @var course_modinfo
2642 private $modinfo;
2645 * Constructs object from database information plus extra required data.
2646 * @param object $data Array entry from cached sectioncache
2647 * @param int $number Section number (array key)
2648 * @param int $notused1 argument not used (informaion is available in $modinfo)
2649 * @param int $notused2 argument not used (informaion is available in $modinfo)
2650 * @param course_modinfo $modinfo Owner (needed for checking availability)
2651 * @param int $notused3 argument not used (informaion is available in $modinfo)
2653 public function __construct($data, $number, $notused1, $notused2, $modinfo, $notused3) {
2654 global $CFG;
2655 require_once($CFG->dirroot.'/course/lib.php');
2657 // Data that is always present
2658 $this->_id = $data->id;
2660 $defaults = self::$sectioncachedefaults +
2661 array('conditionscompletion' => array(),
2662 'conditionsgrade' => array(),
2663 'conditionsfield' => array());
2665 // Data that may use default values to save cache size
2666 foreach ($defaults as $field => $value) {
2667 if (isset($data->{$field})) {
2668 $this->{'_'.$field} = $data->{$field};
2669 } else {
2670 $this->{'_'.$field} = $value;
2674 // Other data from constructor arguments.
2675 $this->_section = $number;
2676 $this->modinfo = $modinfo;
2678 // Cached course format data.
2679 $course = $modinfo->get_course();
2680 if (!isset(self::$sectionformatoptions[$course->format])) {
2681 // Store list of section format options defined in each used course format.
2682 // They do not depend on particular course but only on its format.
2683 self::$sectionformatoptions[$course->format] =
2684 course_get_format($course)->section_format_options();
2686 foreach (self::$sectionformatoptions[$course->format] as $field => $option) {
2687 if (!empty($option['cache'])) {
2688 if (isset($data->{$field})) {
2689 $this->cachedformatoptions[$field] = $data->{$field};
2690 } else if (array_key_exists('cachedefault', $option)) {
2691 $this->cachedformatoptions[$field] = $option['cachedefault'];
2698 * Magic method to check if the property is set
2700 * @param string $name name of the property
2701 * @return bool
2703 public function __isset($name) {
2704 if (method_exists($this, 'get_'.$name) ||
2705 property_exists($this, '_'.$name) ||
2706 array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
2707 $value = $this->__get($name);
2708 return isset($value);
2710 return false;
2714 * Magic method to check if the property is empty
2716 * @param string $name name of the property
2717 * @return bool
2719 public function __empty($name) {
2720 if (method_exists($this, 'get_'.$name) ||
2721 property_exists($this, '_'.$name) ||
2722 array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
2723 $value = $this->__get($name);
2724 return empty($value);
2726 return true;
2730 * Magic method to retrieve the property, this is either basic section property
2731 * or availability information or additional properties added by course format
2733 * @param string $name name of the property
2734 * @return bool
2736 public function __get($name) {
2737 if (method_exists($this, 'get_'.$name)) {
2738 return $this->{'get_'.$name}();
2740 if (property_exists($this, '_'.$name)) {
2741 return $this->{'_'.$name};
2743 if (array_key_exists($name, $this->cachedformatoptions)) {
2744 return $this->cachedformatoptions[$name];
2746 // precheck if the option is defined in format to avoid unnecessary DB queries in get_format_options()
2747 if (array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
2748 $formatoptions = course_get_format($this->modinfo->get_course())->get_format_options($this);
2749 return $formatoptions[$name];
2751 debugging('Invalid section_info property accessed! '.$name);
2752 return null;
2756 * Finds whether this section is available at the moment for the current user.
2758 * The value can be accessed publicly as $sectioninfo->available
2760 * @return bool
2762 private function get_available() {
2763 global $CFG;
2764 $userid = $this->modinfo->get_user_id();
2765 if ($this->_available !== null || $userid == -1) {
2766 // Has already been calculated or does not need calculation.
2767 return $this->_available;
2769 $this->_available = true;
2770 $this->_availableinfo = '';
2771 if (!empty($CFG->enableavailability)) {
2772 // Get availability information.
2773 $ci = new \core_availability\info_section($this);
2774 $this->_available = $ci->is_available($this->_availableinfo, true,
2775 $userid, $this->modinfo);
2777 // Execute the hook from the course format that may override the available/availableinfo properties.
2778 $currentavailable = $this->_available;
2779 course_get_format($this->modinfo->get_course())->
2780 section_get_available_hook($this, $this->_available, $this->_availableinfo);
2781 if (!$currentavailable && $this->_available) {
2782 debugging('section_get_available_hook() can not make unavailable section available', DEBUG_DEVELOPER);
2783 $this->_available = $currentavailable;
2785 return $this->_available;
2789 * Returns the availability text shown next to the section on course page.
2791 * @return string
2793 private function get_availableinfo() {
2794 // Calling get_available() will also fill the availableinfo property
2795 // (or leave it null if there is no userid).
2796 $this->get_available();
2797 return $this->_availableinfo;
2801 * Implementation of IteratorAggregate::getIterator(), allows to cycle through properties
2802 * and use {@link convert_to_array()}
2804 * @return ArrayIterator
2806 public function getIterator() {
2807 $ret = array();
2808 foreach (get_object_vars($this) as $key => $value) {
2809 if (substr($key, 0, 1) == '_') {
2810 if (method_exists($this, 'get'.$key)) {
2811 $ret[substr($key, 1)] = $this->{'get'.$key}();
2812 } else {
2813 $ret[substr($key, 1)] = $this->$key;
2817 $ret['sequence'] = $this->get_sequence();
2818 $ret['course'] = $this->get_course();
2819 $ret = array_merge($ret, course_get_format($this->modinfo->get_course())->get_format_options($this->_section));
2820 return new ArrayIterator($ret);
2824 * Works out whether activity is visible *for current user* - if this is false, they
2825 * aren't allowed to access it.
2827 * @return bool
2829 private function get_uservisible() {
2830 $userid = $this->modinfo->get_user_id();
2831 if ($this->_uservisible !== null || $userid == -1) {
2832 // Has already been calculated or does not need calculation.
2833 return $this->_uservisible;
2835 $this->_uservisible = true;
2836 if (!$this->_visible || !$this->get_available()) {
2837 $coursecontext = context_course::instance($this->get_course());
2838 if (!$this->_visible && !has_capability('moodle/course:viewhiddensections', $coursecontext, $userid) ||
2839 (!$this->get_available() &&
2840 !has_capability('moodle/course:ignoreavailabilityrestrictions', $coursecontext, $userid))) {
2842 $this->_uservisible = false;
2845 return $this->_uservisible;
2849 * Restores the course_sections.sequence value
2851 * @return string
2853 private function get_sequence() {
2854 if (!empty($this->modinfo->sections[$this->_section])) {
2855 return implode(',', $this->modinfo->sections[$this->_section]);
2856 } else {
2857 return '';
2862 * Returns course ID - from course_sections table
2864 * @return int
2866 private function get_course() {
2867 return $this->modinfo->get_course_id();
2871 * Modinfo object
2873 * @return course_modinfo
2875 private function get_modinfo() {
2876 return $this->modinfo;
2880 * Prepares section data for inclusion in sectioncache cache, removing items
2881 * that are set to defaults, and adding availability data if required.
2883 * Called by build_section_cache in course_modinfo only; do not use otherwise.
2884 * @param object $section Raw section data object
2886 public static function convert_for_section_cache($section) {
2887 global $CFG;
2889 // Course id stored in course table
2890 unset($section->course);
2891 // Section number stored in array key
2892 unset($section->section);
2893 // Sequence stored implicity in modinfo $sections array
2894 unset($section->sequence);
2896 // Remove default data
2897 foreach (self::$sectioncachedefaults as $field => $value) {
2898 // Exact compare as strings to avoid problems if some strings are set
2899 // to "0" etc.
2900 if (isset($section->{$field}) && $section->{$field} === $value) {
2901 unset($section->{$field});