Merge branch 'MDL-44773-27' of git://github.com/FMCorz/moodle into MOODLE_27_STABLE
[moodle.git] / lib / modinfolib.php
blob7d5529130b9376b45d4bc172ea8a4be9ed941250
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 /**
58 * List of fields from DB table 'course' that are cached in MUC and are always present in course_modinfo::$course
59 * @var array
61 public static $cachedfields = array('shortname', 'fullname', 'format',
62 'enablecompletion', 'groupmode', 'groupmodeforce', 'cacherev');
64 /**
65 * For convenience we store the course object here as it is needed in other parts of code
66 * @var stdClass
68 private $course;
70 /**
71 * Array of section data from cache
72 * @var section_info[]
74 private $sectioninfo;
76 /**
77 * User ID
78 * @var int
80 private $userid;
82 /**
83 * Array from int (section num, e.g. 0) => array of int (course-module id); this list only
84 * includes sections that actually contain at least one course-module
85 * @var array
87 private $sections;
89 /**
90 * Array from int (cm id) => cm_info object
91 * @var cm_info[]
93 private $cms;
95 /**
96 * Array from string (modname) => int (instance id) => cm_info object
97 * @var cm_info[][]
99 private $instances;
102 * Groups that the current user belongs to. This value is calculated on first
103 * request to the property or function.
104 * When set, it is an array of grouping id => array of group id => group id.
105 * Includes grouping id 0 for 'all groups'.
106 * @var int[][]
108 private $groups;
111 * List of class read-only properties and their getter methods.
112 * Used by magic functions __get(), __isset(), __empty()
113 * @var array
115 private static $standardproperties = array(
116 'courseid' => 'get_course_id',
117 'userid' => 'get_user_id',
118 'sections' => 'get_sections',
119 'cms' => 'get_cms',
120 'instances' => 'get_instances',
121 'groups' => 'get_groups_all',
125 * Magic method getter
127 * @param string $name
128 * @return mixed
130 public function __get($name) {
131 if (isset(self::$standardproperties[$name])) {
132 $method = self::$standardproperties[$name];
133 return $this->$method();
134 } else {
135 debugging('Invalid course_modinfo property accessed: '.$name);
136 return null;
141 * Magic method for function isset()
143 * @param string $name
144 * @return bool
146 public function __isset($name) {
147 if (isset(self::$standardproperties[$name])) {
148 $value = $this->__get($name);
149 return isset($value);
151 return false;
155 * Magic method for function empty()
157 * @param string $name
158 * @return bool
160 public function __empty($name) {
161 if (isset(self::$standardproperties[$name])) {
162 $value = $this->__get($name);
163 return empty($value);
165 return true;
169 * Magic method setter
171 * Will display the developer warning when trying to set/overwrite existing property.
173 * @param string $name
174 * @param mixed $value
176 public function __set($name, $value) {
177 debugging("It is not allowed to set the property course_modinfo::\${$name}", DEBUG_DEVELOPER);
181 * Returns course object that was used in the first {@link get_fast_modinfo()} call.
183 * It may not contain all fields from DB table {course} but always has at least the following:
184 * id,shortname,fullname,format,enablecompletion,groupmode,groupmodeforce,cacherev
186 * @return stdClass
188 public function get_course() {
189 return $this->course;
193 * @return int Course ID
195 public function get_course_id() {
196 return $this->course->id;
200 * @return int User ID
202 public function get_user_id() {
203 return $this->userid;
207 * @return array Array from section number (e.g. 0) to array of course-module IDs in that
208 * section; this only includes sections that contain at least one course-module
210 public function get_sections() {
211 return $this->sections;
215 * @return cm_info[] Array from course-module instance to cm_info object within this course, in
216 * order of appearance
218 public function get_cms() {
219 return $this->cms;
223 * Obtains a single course-module object (for a course-module that is on this course).
224 * @param int $cmid Course-module ID
225 * @return cm_info Information about that course-module
226 * @throws moodle_exception If the course-module does not exist
228 public function get_cm($cmid) {
229 if (empty($this->cms[$cmid])) {
230 throw new moodle_exception('invalidcoursemodule', 'error');
232 return $this->cms[$cmid];
236 * Obtains all module instances on this course.
237 * @return cm_info[][] Array from module name => array from instance id => cm_info
239 public function get_instances() {
240 return $this->instances;
244 * Returns array of localised human-readable module names used in this course
246 * @param bool $plural if true returns the plural form of modules names
247 * @return array
249 public function get_used_module_names($plural = false) {
250 $modnames = get_module_types_names($plural);
251 $modnamesused = array();
252 foreach ($this->get_cms() as $cmid => $mod) {
253 if (isset($modnames[$mod->modname]) && $mod->uservisible) {
254 $modnamesused[$mod->modname] = $modnames[$mod->modname];
257 core_collator::asort($modnamesused);
258 return $modnamesused;
262 * Obtains all instances of a particular module on this course.
263 * @param $modname Name of module (not full frankenstyle) e.g. 'label'
264 * @return cm_info[] Array from instance id => cm_info for modules on this course; empty if none
266 public function get_instances_of($modname) {
267 if (empty($this->instances[$modname])) {
268 return array();
270 return $this->instances[$modname];
274 * Groups that the current user belongs to organised by grouping id. Calculated on the first request.
275 * @return int[][] array of grouping id => array of group id => group id. Includes grouping id 0 for 'all groups'
277 private function get_groups_all() {
278 if (is_null($this->groups)) {
279 // NOTE: Performance could be improved here. The system caches user groups
280 // in $USER->groupmember[$courseid] => array of groupid=>groupid. Unfortunately this
281 // structure does not include grouping information. It probably could be changed to
282 // do so, without a significant performance hit on login, thus saving this one query
283 // each request.
284 $this->groups = groups_get_user_groups($this->course->id, $this->userid);
286 return $this->groups;
290 * Returns groups that the current user belongs to on the course. Note: If not already
291 * available, this may make a database query.
292 * @param int $groupingid Grouping ID or 0 (default) for all groups
293 * @return int[] Array of int (group id) => int (same group id again); empty array if none
295 public function get_groups($groupingid = 0) {
296 $allgroups = $this->get_groups_all();
297 if (!isset($allgroups[$groupingid])) {
298 return array();
300 return $allgroups[$groupingid];
304 * Gets all sections as array from section number => data about section.
305 * @return section_info[] Array of section_info objects organised by section number
307 public function get_section_info_all() {
308 return $this->sectioninfo;
312 * Gets data about specific numbered section.
313 * @param int $sectionnumber Number (not id) of section
314 * @param int $strictness Use MUST_EXIST to throw exception if it doesn't
315 * @return section_info Information for numbered section or null if not found
317 public function get_section_info($sectionnumber, $strictness = IGNORE_MISSING) {
318 if (!array_key_exists($sectionnumber, $this->sectioninfo)) {
319 if ($strictness === MUST_EXIST) {
320 throw new moodle_exception('sectionnotexist');
321 } else {
322 return null;
325 return $this->sectioninfo[$sectionnumber];
329 * Static cache for generated course_modinfo instances
331 * @see course_modinfo::instance()
332 * @see course_modinfo::clear_instance_cache()
333 * @var course_modinfo[]
335 protected static $instancecache = array();
338 * Timestamps (microtime) when the course_modinfo instances were last accessed
340 * It is used to remove the least recent accessed instances when static cache is full
342 * @var float[]
344 protected static $cacheaccessed = array();
347 * Clears the cache used in course_modinfo::instance()
349 * Used in {@link get_fast_modinfo()} when called with argument $reset = true
350 * and in {@link rebuild_course_cache()}
352 * @param null|int|stdClass $courseorid if specified removes only cached value for this course
354 public static function clear_instance_cache($courseorid = null) {
355 if (empty($courseorid)) {
356 self::$instancecache = array();
357 self::$cacheaccessed = array();
358 return;
360 if (is_object($courseorid)) {
361 $courseorid = $courseorid->id;
363 if (isset(self::$instancecache[$courseorid])) {
364 // Unsetting static variable in PHP is peculiar, it removes the reference,
365 // but data remain in memory. Prior to unsetting, the varable needs to be
366 // set to empty to remove its remains from memory.
367 self::$instancecache[$courseorid] = '';
368 unset(self::$instancecache[$courseorid]);
369 unset(self::$cacheaccessed[$courseorid]);
374 * Returns the instance of course_modinfo for the specified course and specified user
376 * This function uses static cache for the retrieved instances. The cache
377 * size is limited by MAX_MODINFO_CACHE_SIZE. If instance is not found in
378 * the static cache or it was created for another user or the cacherev validation
379 * failed - a new instance is constructed and returned.
381 * Used in {@link get_fast_modinfo()}
383 * @param int|stdClass $courseorid object from DB table 'course' (must have field 'id'
384 * and recommended to have field 'cacherev') or just a course id
385 * @param int $userid User id to populate 'availble' and 'uservisible' attributes of modules and sections.
386 * Set to 0 for current user (default). Set to -1 to avoid calculation of dynamic user-depended data.
387 * @return course_modinfo
389 public static function instance($courseorid, $userid = 0) {
390 global $USER;
391 if (is_object($courseorid)) {
392 $course = $courseorid;
393 } else {
394 $course = (object)array('id' => $courseorid);
396 if (empty($userid)) {
397 $userid = $USER->id;
400 if (!empty(self::$instancecache[$course->id])) {
401 if (self::$instancecache[$course->id]->userid == $userid &&
402 (!isset($course->cacherev) ||
403 $course->cacherev == self::$instancecache[$course->id]->get_course()->cacherev)) {
404 // This course's modinfo for the same user was recently retrieved, return cached.
405 self::$cacheaccessed[$course->id] = microtime(true);
406 return self::$instancecache[$course->id];
407 } else {
408 // Prevent potential reference problems when switching users.
409 self::clear_instance_cache($course->id);
412 $modinfo = new course_modinfo($course, $userid);
414 // We have a limit of MAX_MODINFO_CACHE_SIZE entries to store in static variable.
415 if (count(self::$instancecache) >= MAX_MODINFO_CACHE_SIZE) {
416 // Find the course that was the least recently accessed.
417 asort(self::$cacheaccessed, SORT_NUMERIC);
418 $courseidtoremove = key(array_reverse(self::$cacheaccessed, true));
419 self::clear_instance_cache($courseidtoremove);
422 // Add modinfo to the static cache.
423 self::$instancecache[$course->id] = $modinfo;
424 self::$cacheaccessed[$course->id] = microtime(true);
426 return $modinfo;
430 * Constructs based on course.
431 * Note: This constructor should not usually be called directly.
432 * Use get_fast_modinfo($course) instead as this maintains a cache.
433 * @param stdClass $course course object, only property id is required.
434 * @param int $userid User ID
435 * @throws moodle_exception if course is not found
437 public function __construct($course, $userid) {
438 global $CFG, $COURSE, $SITE, $DB;
440 if (!isset($course->cacherev)) {
441 // We require presence of property cacherev to validate the course cache.
442 // No need to clone the $COURSE or $SITE object here because we clone it below anyway.
443 $course = get_course($course->id, false);
446 $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
448 // Retrieve modinfo from cache. If not present or cacherev mismatches, call rebuild and retrieve again.
449 $coursemodinfo = $cachecoursemodinfo->get($course->id);
450 if ($coursemodinfo === false || ($course->cacherev != $coursemodinfo->cacherev)) {
451 $coursemodinfo = self::build_course_cache($course);
454 // Set initial values
455 $this->userid = $userid;
456 $this->sections = array();
457 $this->cms = array();
458 $this->instances = array();
459 $this->groups = null;
461 // If we haven't already preloaded contexts for the course, do it now
462 // Modules are also cached here as long as it's the first time this course has been preloaded.
463 context_helper::preload_course($course->id);
465 // Quick integrity check: as a result of race conditions modinfo may not be regenerated after the change.
466 // It is especially dangerous if modinfo contains the deleted course module, as it results in fatal error.
467 // We can check it very cheap by validating the existence of module context.
468 if ($course->id == $COURSE->id || $course->id == $SITE->id) {
469 // Only verify current course (or frontpage) as pages with many courses may not have module contexts cached.
470 // (Uncached modules will result in a very slow verification).
471 foreach ($coursemodinfo->modinfo as $mod) {
472 if (!context_module::instance($mod->cm, IGNORE_MISSING)) {
473 debugging('Course cache integrity check failed: course module with id '. $mod->cm.
474 ' does not have context. Rebuilding cache for course '. $course->id);
475 // Re-request the course record from DB as well, don't use get_course() here.
476 $course = $DB->get_record('course', array('id' => $course->id), '*', MUST_EXIST);
477 $coursemodinfo = self::build_course_cache($course);
478 break;
483 // Overwrite unset fields in $course object with cached values, store the course object.
484 $this->course = fullclone($course);
485 foreach ($coursemodinfo as $key => $value) {
486 if ($key !== 'modinfo' && $key !== 'sectioncache' &&
487 (!isset($this->course->$key) || $key === 'cacherev')) {
488 $this->course->$key = $value;
492 // Loop through each piece of module data, constructing it
493 static $modexists = array();
494 foreach ($coursemodinfo->modinfo as $mod) {
495 if (empty($mod->name)) {
496 // something is wrong here
497 continue;
500 // Skip modules which don't exist
501 if (!array_key_exists($mod->mod, $modexists)) {
502 $modexists[$mod->mod] = file_exists("$CFG->dirroot/mod/$mod->mod/lib.php");
504 if (!$modexists[$mod->mod]) {
505 continue;
508 // Construct info for this module
509 $cm = new cm_info($this, null, $mod, null);
511 // Store module in instances and cms array
512 if (!isset($this->instances[$cm->modname])) {
513 $this->instances[$cm->modname] = array();
515 $this->instances[$cm->modname][$cm->instance] = $cm;
516 $this->cms[$cm->id] = $cm;
518 // Reconstruct sections. This works because modules are stored in order
519 if (!isset($this->sections[$cm->sectionnum])) {
520 $this->sections[$cm->sectionnum] = array();
522 $this->sections[$cm->sectionnum][] = $cm->id;
525 // Expand section objects
526 $this->sectioninfo = array();
527 foreach ($coursemodinfo->sectioncache as $number => $data) {
528 $this->sectioninfo[$number] = new section_info($data, $number, null, null,
529 $this, null);
534 * Builds a list of information about sections on a course to be stored in
535 * the course cache. (Does not include information that is already cached
536 * in some other way.)
538 * This function will be removed in 2.7
540 * @deprecated since 2.6
541 * @param int $courseid Course ID
542 * @return array Information about sections, indexed by section number (not id)
544 public static function build_section_cache($courseid) {
545 global $DB;
546 debugging('Function course_modinfo::build_section_cache() is deprecated. It can only be used internally to build course cache.');
547 $course = $DB->get_record('course', array('id' => $course->id),
548 array_merge(array('id'), self::$cachedfields), MUST_EXIST);
549 return self::build_course_section_cache($course);
553 * Builds a list of information about sections on a course to be stored in
554 * the course cache. (Does not include information that is already cached
555 * in some other way.)
557 * @param stdClass $course Course object (must contain fields
558 * @return array Information about sections, indexed by section number (not id)
560 protected static function build_course_section_cache($course) {
561 global $DB;
563 // Get section data
564 $sections = $DB->get_records('course_sections', array('course' => $course->id), 'section',
565 'section, id, course, name, summary, summaryformat, sequence, visible, ' .
566 'availability');
567 $compressedsections = array();
569 $formatoptionsdef = course_get_format($course)->section_format_options();
570 // Remove unnecessary data and add availability
571 foreach ($sections as $number => $section) {
572 // Add cached options from course format to $section object
573 foreach ($formatoptionsdef as $key => $option) {
574 if (!empty($option['cache'])) {
575 $formatoptions = course_get_format($course)->get_format_options($section);
576 if (!array_key_exists('cachedefault', $option) || $option['cachedefault'] !== $formatoptions[$key]) {
577 $section->$key = $formatoptions[$key];
581 // Clone just in case it is reused elsewhere
582 $compressedsections[$number] = clone($section);
583 section_info::convert_for_section_cache($compressedsections[$number]);
586 return $compressedsections;
590 * Builds and stores in MUC object containing information about course
591 * modules and sections together with cached fields from table course.
593 * @param stdClass $course object from DB table course. Must have property 'id'
594 * but preferably should have all cached fields.
595 * @return stdClass object with all cached keys of the course plus fields modinfo and sectioncache.
596 * The same object is stored in MUC
597 * @throws moodle_exception if course is not found (if $course object misses some of the
598 * necessary fields it is re-requested from database)
600 public static function build_course_cache($course) {
601 global $DB, $CFG;
602 require_once("$CFG->dirroot/course/lib.php");
603 if (empty($course->id)) {
604 throw new coding_exception('Object $course is missing required property \id\'');
606 // Ensure object has all necessary fields.
607 foreach (self::$cachedfields as $key) {
608 if (!isset($course->$key)) {
609 $course = $DB->get_record('course', array('id' => $course->id),
610 implode(',', array_merge(array('id'), self::$cachedfields)), MUST_EXIST);
611 break;
614 // Retrieve all information about activities and sections.
615 // This may take time on large courses and it is possible that another user modifies the same course during this process.
616 // Field cacherev stored in both DB and cache will ensure that cached data matches the current course state.
617 $coursemodinfo = new stdClass();
618 $coursemodinfo->modinfo = get_array_of_activities($course->id);
619 $coursemodinfo->sectioncache = self::build_course_section_cache($course);
620 foreach (self::$cachedfields as $key) {
621 $coursemodinfo->$key = $course->$key;
623 // Set the accumulated activities and sections information in cache, together with cacherev.
624 $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
625 $cachecoursemodinfo->set($course->id, $coursemodinfo);
626 return $coursemodinfo;
632 * Data about a single module on a course. This contains most of the fields in the course_modules
633 * table, plus additional data when required.
635 * The object can be accessed by core or any plugin (i.e. course format, block, filter, etc.) as
636 * get_fast_modinfo($courseorid)->cms[$coursemoduleid]
637 * or
638 * get_fast_modinfo($courseorid)->instances[$moduletype][$instanceid]
640 * There are three stages when activity module can add/modify data in this object:
642 * <b>Stage 1 - during building the cache.</b>
643 * Allows to add to the course cache static user-independent information about the module.
644 * Modules should try to include only absolutely necessary information that may be required
645 * when displaying course view page. The information is stored in application-level cache
646 * and reset when {@link rebuild_course_cache()} is called or cache is purged by admin.
648 * Modules can implement callback XXX_get_coursemodule_info() returning instance of object
649 * {@link cached_cm_info}
651 * <b>Stage 2 - dynamic data.</b>
652 * Dynamic data is user-dependend, it is stored in request-level cache. To reset this cache
653 * {@link get_fast_modinfo()} with $reset argument may be called.
655 * Dynamic data is obtained when any of the following properties/methods is requested:
656 * - {@link cm_info::$url}
657 * - {@link cm_info::$name}
658 * - {@link cm_info::$onclick}
659 * - {@link cm_info::get_icon_url()}
660 * - {@link cm_info::$uservisible}
661 * - {@link cm_info::$available}
662 * - {@link cm_info::$availableinfo}
663 * - plus any of the properties listed in Stage 3.
665 * Modules can implement callback <b>XXX_cm_info_dynamic()</b> and inside this callback they
666 * are allowed to use any of the following set methods:
667 * - {@link cm_info::set_available()}
668 * - {@link cm_info::set_name()}
669 * - {@link cm_info::set_no_view_link()}
670 * - {@link cm_info::set_user_visible()}
671 * - {@link cm_info::set_on_click()}
672 * - {@link cm_info::set_icon_url()}
673 * Any methods affecting view elements can also be set in this callback.
675 * <b>Stage 3 (view data).</b>
676 * Also user-dependend data stored in request-level cache. Second stage is created
677 * because populating the view data can be expensive as it may access much more
678 * Moodle APIs such as filters, user information, output renderers and we
679 * don't want to request it until necessary.
680 * View data is obtained when any of the following properties/methods is requested:
681 * - {@link cm_info::$afterediticons}
682 * - {@link cm_info::$content}
683 * - {@link cm_info::get_formatted_content()}
684 * - {@link cm_info::$extraclasses}
685 * - {@link cm_info::$afterlink}
687 * Modules can implement callback <b>XXX_cm_info_view()</b> and inside this callback they
688 * are allowed to use any of the following set methods:
689 * - {@link cm_info::set_after_edit_icons()}
690 * - {@link cm_info::set_after_link()}
691 * - {@link cm_info::set_content()}
692 * - {@link cm_info::set_extra_classes()}
694 * @property-read int $id Course-module ID - from course_modules table
695 * @property-read int $instance Module instance (ID within module table) - from course_modules table
696 * @property-read int $course Course ID - from course_modules table
697 * @property-read string $idnumber 'ID number' from course-modules table (arbitrary text set by user) - from
698 * course_modules table
699 * @property-read int $added Time that this course-module was added (unix time) - from course_modules table
700 * @property-read int $visible Visible setting (0 or 1; if this is 0, students cannot see/access the activity) - from
701 * course_modules table
702 * @property-read int $visibleold Old visible setting (if the entire section is hidden, the previous value for
703 * visible is stored in this field) - from course_modules table
704 * @property-read int $groupmode Group mode (one of the constants NOGROUPS, SEPARATEGROUPS, or VISIBLEGROUPS) - from
705 * course_modules table. Use {@link cm_info::$effectivegroupmode} to find the actual group mode that may be forced by course.
706 * @property-read int $groupingid Grouping ID (0 = all groupings)
707 * @property-read int $groupmembersonly Group members only (if set to 1, only members of a suitable group see this link on the
708 * course page; 0 = everyone sees it even if they don't belong to a suitable group) - from
709 * course_modules table
710 * @property-read bool $coursegroupmodeforce Indicates whether the course containing the module has forced the groupmode
711 * This means that cm_info::$groupmode should be ignored and cm_info::$coursegroupmode be used instead
712 * @property-read int $coursegroupmode Group mode (one of the constants NOGROUPS, SEPARATEGROUPS, or VISIBLEGROUPS) - from
713 * course table - as specified for the course containing the module
714 * Effective only if {@link cm_info::$coursegroupmodeforce} is set
715 * @property-read int $effectivegroupmode Effective group mode for this module (one of the constants NOGROUPS, SEPARATEGROUPS,
716 * or VISIBLEGROUPS). This can be different from groupmode set for the module if the groupmode is forced for the course.
717 * This value will always be NOGROUPS if module type does not support group mode.
718 * @property-read int $indent Indent level on course page (0 = no indent) - from course_modules table
719 * @property-read int $completion Activity completion setting for this activity, COMPLETION_TRACKING_xx constant - from
720 * course_modules table
721 * @property-read mixed $completiongradeitemnumber Set to the item number (usually 0) if completion depends on a particular
722 * grade of this activity, or null if completion does not depend on a grade - from course_modules table
723 * @property-read int $completionview 1 if 'on view' completion is enabled, 0 otherwise - from course_modules table
724 * @property-read int $completionexpected Set to a unix time if completion of this activity is expected at a
725 * particular time, 0 if no time set - from course_modules table
726 * @property-read string $availability Availability information as JSON string or null if none -
727 * from course_modules table
728 * @property-read int $showdescription Controls whether the description of the activity displays on the course main page (in
729 * addition to anywhere it might display within the activity itself). 0 = do not show
730 * on main page, 1 = show on main page.
731 * @property-read string $extra (deprecated) Extra HTML that is put in an unhelpful part of the HTML when displaying this module in
732 * course page - from cached data in modinfo field. Deprecated, replaced by ->extraclasses and ->onclick
733 * @property-read string $icon Name of icon to use - from cached data in modinfo field
734 * @property-read string $iconcomponent Component that contains icon - from cached data in modinfo field
735 * @property-read string $modname Name of module e.g. 'forum' (this is the same name as the module's main database
736 * table) - from cached data in modinfo field
737 * @property-read int $module ID of module type - from course_modules table
738 * @property-read string $name Name of module instance for display on page e.g. 'General discussion forum' - from cached
739 * data in modinfo field
740 * @property-read int $sectionnum Section number that this course-module is in (section 0 = above the calendar, section 1
741 * = week/topic 1, etc) - from cached data in modinfo field
742 * @property-read int $section Section id - from course_modules table
743 * @property-read array $conditionscompletion Availability conditions for this course-module based on the completion of other
744 * course-modules (array from other course-module id to required completion state for that
745 * module) - from cached data in modinfo field
746 * @property-read array $conditionsgrade Availability conditions for this course-module based on course grades (array from
747 * grade item id to object with ->min, ->max fields) - from cached data in modinfo field
748 * @property-read array $conditionsfield Availability conditions for this course-module based on user fields
749 * @property-read bool $available True if this course-module is available to students i.e. if all availability conditions
750 * are met - obtained dynamically
751 * @property-read string $availableinfo If course-module is not available to students, this string gives information about
752 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
753 * January 2010') for display on main page - obtained dynamically
754 * @property-read bool $uservisible True if this course-module is available to the CURRENT user (for example, if current user
755 * has viewhiddenactivities capability, they can access the course-module even if it is not
756 * visible or not available, so this would be true in that case)
757 * @property-read context_module $context Module context
758 * @property-read string $modfullname Returns a localised human-readable name of the module type - calculated on request
759 * @property-read string $modplural Returns a localised human-readable name of the module type in plural form - calculated on request
760 * @property-read string $content Content to display on main (view) page - calculated on request
761 * @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
762 * @property-read string $extraclasses Extra CSS classes to add to html output for this activity on main page - calculated on request
763 * @property-read string $onclick Content of HTML on-click attribute already escaped - calculated on request
764 * @property-read mixed $customdata Optional custom data stored in modinfo cache for this activity, or null if none
765 * @property-read string $afterlink Extra HTML code to display after link - calculated on request
766 * @property-read string $afterediticons Extra HTML code to display after editing icons (e.g. more icons) - calculated on request
768 class cm_info implements IteratorAggregate {
770 * State: Only basic data from modinfo cache is available.
772 const STATE_BASIC = 0;
775 * State: In the process of building dynamic data (to avoid recursive calls to obtain_dynamic_data())
777 const STATE_BUILDING_DYNAMIC = 1;
780 * State: Dynamic data is available too.
782 const STATE_DYNAMIC = 2;
785 * State: In the process of building view data (to avoid recursive calls to obtain_view_data())
787 const STATE_BUILDING_VIEW = 3;
790 * State: View data (for course page) is available.
792 const STATE_VIEW = 4;
795 * Parent object
796 * @var course_modinfo
798 private $modinfo;
801 * Level of information stored inside this object (STATE_xx constant)
802 * @var int
804 private $state;
807 * Course-module ID - from course_modules table
808 * @var int
810 private $id;
813 * Module instance (ID within module table) - from course_modules table
814 * @var int
816 private $instance;
819 * 'ID number' from course-modules table (arbitrary text set by user) - from
820 * course_modules table
821 * @var string
823 private $idnumber;
826 * Time that this course-module was added (unix time) - from course_modules table
827 * @var int
829 private $added;
832 * This variable is not used and is included here only so it can be documented.
833 * Once the database entry is removed from course_modules, it should be deleted
834 * here too.
835 * @var int
836 * @deprecated Do not use this variable
838 private $score;
841 * Visible setting (0 or 1; if this is 0, students cannot see/access the activity) - from
842 * course_modules table
843 * @var int
845 private $visible;
848 * Old visible setting (if the entire section is hidden, the previous value for
849 * visible is stored in this field) - from course_modules table
850 * @var int
852 private $visibleold;
855 * Group mode (one of the constants NONE, SEPARATEGROUPS, or VISIBLEGROUPS) - from
856 * course_modules table
857 * @var int
859 private $groupmode;
862 * Grouping ID (0 = all groupings)
863 * @var int
865 private $groupingid;
868 * Group members only (if set to 1, only members of a suitable group see this link on the
869 * course page; 0 = everyone sees it even if they don't belong to a suitable group) - from
870 * course_modules table
871 * @var int
873 private $groupmembersonly;
876 * Indent level on course page (0 = no indent) - from course_modules table
877 * @var int
879 private $indent;
882 * Activity completion setting for this activity, COMPLETION_TRACKING_xx constant - from
883 * course_modules table
884 * @var int
886 private $completion;
889 * Set to the item number (usually 0) if completion depends on a particular
890 * grade of this activity, or null if completion does not depend on a grade - from
891 * course_modules table
892 * @var mixed
894 private $completiongradeitemnumber;
897 * 1 if 'on view' completion is enabled, 0 otherwise - from course_modules table
898 * @var int
900 private $completionview;
903 * Set to a unix time if completion of this activity is expected at a
904 * particular time, 0 if no time set - from course_modules table
905 * @var int
907 private $completionexpected;
910 * Availability information as JSON string or null if none - from course_modules table
911 * @var string
913 private $availability;
916 * Controls whether the description of the activity displays on the course main page (in
917 * addition to anywhere it might display within the activity itself). 0 = do not show
918 * on main page, 1 = show on main page.
919 * @var int
921 private $showdescription;
924 * Extra HTML that is put in an unhelpful part of the HTML when displaying this module in
925 * course page - from cached data in modinfo field
926 * @deprecated This is crazy, don't use it. Replaced by ->extraclasses and ->onclick
927 * @var string
929 private $extra;
932 * Name of icon to use - from cached data in modinfo field
933 * @var string
935 private $icon;
938 * Component that contains icon - from cached data in modinfo field
939 * @var string
941 private $iconcomponent;
944 * Name of module e.g. 'forum' (this is the same name as the module's main database
945 * table) - from cached data in modinfo field
946 * @var string
948 private $modname;
951 * ID of module - from course_modules table
952 * @var int
954 private $module;
957 * Name of module instance for display on page e.g. 'General discussion forum' - from cached
958 * data in modinfo field
959 * @var string
961 private $name;
964 * Section number that this course-module is in (section 0 = above the calendar, section 1
965 * = week/topic 1, etc) - from cached data in modinfo field
966 * @var int
968 private $sectionnum;
971 * Section id - from course_modules table
972 * @var int
974 private $section;
977 * Availability conditions for this course-module based on the completion of other
978 * course-modules (array from other course-module id to required completion state for that
979 * module) - from cached data in modinfo field
980 * @var array
982 private $conditionscompletion;
985 * Availability conditions for this course-module based on course grades (array from
986 * grade item id to object with ->min, ->max fields) - from cached data in modinfo field
987 * @var array
989 private $conditionsgrade;
992 * Availability conditions for this course-module based on user fields
993 * @var array
995 private $conditionsfield;
998 * True if this course-module is available to students i.e. if all availability conditions
999 * are met - obtained dynamically
1000 * @var bool
1002 private $available;
1005 * If course-module is not available to students, this string gives information about
1006 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
1007 * January 2010') for display on main page - obtained dynamically
1008 * @var string
1010 private $availableinfo;
1013 * True if this course-module is available to the CURRENT user (for example, if current user
1014 * has viewhiddenactivities capability, they can access the course-module even if it is not
1015 * visible or not available, so this would be true in that case)
1016 * @var bool
1018 private $uservisible;
1021 * @var moodle_url
1023 private $url;
1026 * @var string
1028 private $content;
1031 * @var string
1033 private $extraclasses;
1036 * @var moodle_url full external url pointing to icon image for activity
1038 private $iconurl;
1041 * @var string
1043 private $onclick;
1046 * @var mixed
1048 private $customdata;
1051 * @var string
1053 private $afterlink;
1056 * @var string
1058 private $afterediticons;
1061 * List of class read-only properties and their getter methods.
1062 * Used by magic functions __get(), __isset(), __empty()
1063 * @var array
1065 private static $standardproperties = array(
1066 'url' => 'get_url',
1067 'content' => 'get_content',
1068 'extraclasses' => 'get_extra_classes',
1069 'onclick' => 'get_on_click',
1070 'customdata' => 'get_custom_data',
1071 'afterlink' => 'get_after_link',
1072 'afterediticons' => 'get_after_edit_icons',
1073 'modfullname' => 'get_module_type_name',
1074 'modplural' => 'get_module_type_name_plural',
1075 'id' => false,
1076 'added' => false,
1077 'availability' => false,
1078 'available' => 'get_available',
1079 'availablefrom' => 'get_deprecated_available_date',
1080 'availableinfo' => 'get_available_info',
1081 'availableuntil' => 'get_deprecated_available_date',
1082 'completion' => false,
1083 'completionexpected' => false,
1084 'completiongradeitemnumber' => false,
1085 'completionview' => false,
1086 'conditionscompletion' => false,
1087 'conditionsfield' => false,
1088 'conditionsgrade' => false,
1089 'context' => 'get_context',
1090 'course' => 'get_course_id',
1091 'coursegroupmode' => 'get_course_groupmode',
1092 'coursegroupmodeforce' => 'get_course_groupmodeforce',
1093 'effectivegroupmode' => 'get_effective_groupmode',
1094 'extra' => false,
1095 'groupingid' => false,
1096 'groupmembersonly' => false,
1097 'groupmode' => false,
1098 'icon' => false,
1099 'iconcomponent' => false,
1100 'idnumber' => false,
1101 'indent' => false,
1102 'instance' => false,
1103 'modname' => false,
1104 'module' => false,
1105 'name' => 'get_name',
1106 'score' => false,
1107 'section' => false,
1108 'sectionnum' => false,
1109 'showavailability' => 'get_show_availability',
1110 'showdescription' => false,
1111 'uservisible' => 'get_user_visible',
1112 'visible' => false,
1113 'visibleold' => false,
1117 * List of methods with no arguments that were public prior to Moodle 2.6.
1119 * They can still be accessed publicly via magic __call() function with no warnings
1120 * but are not listed in the class methods list.
1121 * For the consistency of the code it is better to use corresponding properties.
1123 * These methods be deprecated completely in later versions.
1125 * @var array $standardmethods
1127 private static $standardmethods = array(
1128 // Following methods are not recommended to use because there have associated read-only properties.
1129 'get_url',
1130 'get_content',
1131 'get_extra_classes',
1132 'get_on_click',
1133 'get_custom_data',
1134 'get_after_link',
1135 'get_after_edit_icons',
1136 // Method obtain_dynamic_data() should not be called from outside of this class but it was public before Moodle 2.6.
1137 'obtain_dynamic_data',
1141 * Magic method to call functions that are now declared as private now but
1142 * were public in Moodle before 2.6. Developers can access them without
1143 * any warnings but they are not listed in the class methods list.
1145 * @param string $name
1146 * @param array $arguments
1147 * @return mixed
1149 public function __call($name, $arguments) {
1150 global $CFG;
1152 if (in_array($name, self::$standardmethods)) {
1153 if ($CFG->debugdeveloper) {
1154 if ($alternative = array_search($name, self::$standardproperties)) {
1155 // All standard methods do not have arguments anyway.
1156 debugging("cm_info::$name() is deprecated, please use the property cm_info->$alternative instead.", DEBUG_DEVELOPER);
1157 } else {
1158 debugging("cm_info::$name() is deprecated and should not be used.", DEBUG_DEVELOPER);
1161 // All standard methods do not have arguments anyway.
1162 return $this->$name();
1164 throw new coding_exception("Method cm_info::{$name}() does not exist");
1168 * Magic method getter
1170 * @param string $name
1171 * @return mixed
1173 public function __get($name) {
1174 if (isset(self::$standardproperties[$name])) {
1175 if ($method = self::$standardproperties[$name]) {
1176 return $this->$method();
1177 } else {
1178 return $this->$name;
1180 } else {
1181 debugging('Invalid cm_info property accessed: '.$name);
1182 return null;
1187 * Implementation of IteratorAggregate::getIterator(), allows to cycle through properties
1188 * and use {@link convert_to_array()}
1190 * @return ArrayIterator
1192 public function getIterator() {
1193 // Make sure dynamic properties are retrieved prior to view properties.
1194 $this->obtain_dynamic_data();
1195 $ret = array();
1197 // Do not iterate over deprecated properties.
1198 $props = self::$standardproperties;
1199 unset($props['showavailability']);
1200 unset($props['availablefrom']);
1201 unset($props['availableuntil']);
1203 foreach ($props as $key => $unused) {
1204 $ret[$key] = $this->__get($key);
1206 return new ArrayIterator($ret);
1210 * Magic method for function isset()
1212 * @param string $name
1213 * @return bool
1215 public function __isset($name) {
1216 if (isset(self::$standardproperties[$name])) {
1217 $value = $this->__get($name);
1218 return isset($value);
1220 return false;
1224 * Magic method for function empty()
1226 * @param string $name
1227 * @return bool
1229 public function __empty($name) {
1230 if (isset(self::$standardproperties[$name])) {
1231 $value = $this->__get($name);
1232 return empty($value);
1234 return true;
1238 * Magic method setter
1240 * Will display the developer warning when trying to set/overwrite property.
1242 * @param string $name
1243 * @param mixed $value
1245 public function __set($name, $value) {
1246 debugging("It is not allowed to set the property cm_info::\${$name}", DEBUG_DEVELOPER);
1250 * @return bool True if this module has a 'view' page that should be linked to in navigation
1251 * etc (note: modules may still have a view.php file, but return false if this is not
1252 * intended to be linked to from 'normal' parts of the interface; this is what label does).
1254 public function has_view() {
1255 return !is_null($this->url);
1259 * @return moodle_url URL to link to for this module, or null if it doesn't have a view page
1261 private function get_url() {
1262 $this->obtain_dynamic_data();
1263 return $this->url;
1267 * Obtains content to display on main (view) page.
1268 * Note: Will collect view data, if not already obtained.
1269 * @return string Content to display on main page below link, or empty string if none
1271 private function get_content() {
1272 $this->obtain_view_data();
1273 return $this->content;
1277 * Returns the content to display on course/overview page, formatted and passed through filters
1279 * if $options['context'] is not specified, the module context is used
1281 * @param array|stdClass $options formatting options, see {@link format_text()}
1282 * @return string
1284 public function get_formatted_content($options = array()) {
1285 $this->obtain_view_data();
1286 if (empty($this->content)) {
1287 return '';
1289 // Improve filter performance by preloading filter setttings for all
1290 // activities on the course (this does nothing if called multiple
1291 // times)
1292 filter_preload_activities($this->get_modinfo());
1294 $options = (array)$options;
1295 if (!isset($options['context'])) {
1296 $options['context'] = $this->get_context();
1298 return format_text($this->content, FORMAT_HTML, $options);
1302 * Getter method for property $name, ensures that dynamic data is obtained.
1303 * @return string
1305 private function get_name() {
1306 $this->obtain_dynamic_data();
1307 return $this->name;
1311 * Returns the name to display on course/overview page, formatted and passed through filters
1313 * if $options['context'] is not specified, the module context is used
1315 * @param array|stdClass $options formatting options, see {@link format_string()}
1316 * @return string
1318 public function get_formatted_name($options = array()) {
1319 $options = (array)$options;
1320 if (!isset($options['context'])) {
1321 $options['context'] = $this->get_context();
1323 return format_string($this->get_name(), true, $options);
1327 * Note: Will collect view data, if not already obtained.
1328 * @return string Extra CSS classes to add to html output for this activity on main page
1330 private function get_extra_classes() {
1331 $this->obtain_view_data();
1332 return $this->extraclasses;
1336 * @return string Content of HTML on-click attribute. This string will be used literally
1337 * as a string so should be pre-escaped.
1339 private function get_on_click() {
1340 // Does not need view data; may be used by navigation
1341 $this->obtain_dynamic_data();
1342 return $this->onclick;
1345 * @return mixed Optional custom data stored in modinfo cache for this activity, or null if none
1347 private function get_custom_data() {
1348 return $this->customdata;
1352 * Note: Will collect view data, if not already obtained.
1353 * @return string Extra HTML code to display after link
1355 private function get_after_link() {
1356 $this->obtain_view_data();
1357 return $this->afterlink;
1361 * Note: Will collect view data, if not already obtained.
1362 * @return string Extra HTML code to display after editing icons (e.g. more icons)
1364 private function get_after_edit_icons() {
1365 $this->obtain_view_data();
1366 return $this->afterediticons;
1370 * @param moodle_core_renderer $output Output render to use, or null for default (global)
1371 * @return moodle_url Icon URL for a suitable icon to put beside this cm
1373 public function get_icon_url($output = null) {
1374 global $OUTPUT;
1375 $this->obtain_dynamic_data();
1376 if (!$output) {
1377 $output = $OUTPUT;
1379 // Support modules setting their own, external, icon image
1380 if (!empty($this->iconurl)) {
1381 $icon = $this->iconurl;
1383 // Fallback to normal local icon + component procesing
1384 } else if (!empty($this->icon)) {
1385 if (substr($this->icon, 0, 4) === 'mod/') {
1386 list($modname, $iconname) = explode('/', substr($this->icon, 4), 2);
1387 $icon = $output->pix_url($iconname, $modname);
1388 } else {
1389 if (!empty($this->iconcomponent)) {
1390 // Icon has specified component
1391 $icon = $output->pix_url($this->icon, $this->iconcomponent);
1392 } else {
1393 // Icon does not have specified component, use default
1394 $icon = $output->pix_url($this->icon);
1397 } else {
1398 $icon = $output->pix_url('icon', $this->modname);
1400 return $icon;
1404 * Returns a localised human-readable name of the module type
1406 * @param bool $plural return plural form
1407 * @return string
1409 public function get_module_type_name($plural = false) {
1410 $modnames = get_module_types_names($plural);
1411 if (isset($modnames[$this->modname])) {
1412 return $modnames[$this->modname];
1413 } else {
1414 return null;
1419 * Returns a localised human-readable name of the module type in plural form - calculated on request
1421 * @return string
1423 private function get_module_type_name_plural() {
1424 return $this->get_module_type_name(true);
1428 * @return course_modinfo Modinfo object that this came from
1430 public function get_modinfo() {
1431 return $this->modinfo;
1435 * Returns course object that was used in the first {@link get_fast_modinfo()} call.
1437 * It may not contain all fields from DB table {course} but always has at least the following:
1438 * id,shortname,fullname,format,enablecompletion,groupmode,groupmodeforce,cacherev
1440 * If the course object lacks the field you need you can use the global
1441 * function {@link get_course()} that will save extra query if you access
1442 * current course or frontpage course.
1444 * @return stdClass
1446 public function get_course() {
1447 return $this->modinfo->get_course();
1451 * Returns course id for which the modinfo was generated.
1453 * @return int
1455 private function get_course_id() {
1456 return $this->modinfo->get_course_id();
1460 * Returns group mode used for the course containing the module
1462 * @return int one of constants NOGROUPS, SEPARATEGROUPS, VISIBLEGROUPS
1464 private function get_course_groupmode() {
1465 return $this->modinfo->get_course()->groupmode;
1469 * Returns whether group mode is forced for the course containing the module
1471 * @return bool
1473 private function get_course_groupmodeforce() {
1474 return $this->modinfo->get_course()->groupmodeforce;
1478 * Returns effective groupmode of the module that may be overwritten by forced course groupmode.
1480 * @return int one of constants NOGROUPS, SEPARATEGROUPS, VISIBLEGROUPS
1482 private function get_effective_groupmode() {
1483 $groupmode = $this->groupmode;
1484 if ($this->modinfo->get_course()->groupmodeforce) {
1485 $groupmode = $this->modinfo->get_course()->groupmode;
1486 if ($groupmode != NOGROUPS && !plugin_supports('mod', $this->modname, FEATURE_GROUPS, 0)) {
1487 $groupmode = NOGROUPS;
1490 return $groupmode;
1494 * @return context_module Current module context
1496 private function get_context() {
1497 return context_module::instance($this->id);
1501 * Returns itself in the form of stdClass.
1503 * The object includes all fields that table course_modules has and additionally
1504 * fields 'name', 'modname', 'sectionnum' (if requested).
1506 * This can be used as a faster alternative to {@link get_coursemodule_from_id()}
1508 * @param bool $additionalfields include additional fields 'name', 'modname', 'sectionnum'
1509 * @return stdClass
1511 public function get_course_module_record($additionalfields = false) {
1512 $cmrecord = new stdClass();
1514 // Standard fields from table course_modules.
1515 static $cmfields = array('id', 'course', 'module', 'instance', 'section', 'idnumber', 'added',
1516 'score', 'indent', 'visible', 'visibleold', 'groupmode', 'groupingid', 'groupmembersonly',
1517 'completion', 'completiongradeitemnumber', 'completionview', 'completionexpected',
1518 'showdescription', 'availability');
1519 foreach ($cmfields as $key) {
1520 $cmrecord->$key = $this->$key;
1523 // Additional fields that function get_coursemodule_from_id() adds.
1524 if ($additionalfields) {
1525 $cmrecord->name = $this->name;
1526 $cmrecord->modname = $this->modname;
1527 $cmrecord->sectionnum = $this->sectionnum;
1530 return $cmrecord;
1533 // Set functions
1534 ////////////////
1537 * Sets content to display on course view page below link (if present).
1538 * @param string $content New content as HTML string (empty string if none)
1539 * @return void
1541 public function set_content($content) {
1542 $this->content = $content;
1546 * Sets extra classes to include in CSS.
1547 * @param string $extraclasses Extra classes (empty string if none)
1548 * @return void
1550 public function set_extra_classes($extraclasses) {
1551 $this->extraclasses = $extraclasses;
1555 * Sets the external full url that points to the icon being used
1556 * by the activity. Useful for external-tool modules (lti...)
1557 * If set, takes precedence over $icon and $iconcomponent
1559 * @param moodle_url $iconurl full external url pointing to icon image for activity
1560 * @return void
1562 public function set_icon_url(moodle_url $iconurl) {
1563 $this->iconurl = $iconurl;
1567 * Sets value of on-click attribute for JavaScript.
1568 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1569 * @param string $onclick New onclick attribute which should be HTML-escaped
1570 * (empty string if none)
1571 * @return void
1573 public function set_on_click($onclick) {
1574 $this->check_not_view_only();
1575 $this->onclick = $onclick;
1579 * Sets HTML that displays after link on course view page.
1580 * @param string $afterlink HTML string (empty string if none)
1581 * @return void
1583 public function set_after_link($afterlink) {
1584 $this->afterlink = $afterlink;
1588 * Sets HTML that displays after edit icons on course view page.
1589 * @param string $afterediticons HTML string (empty string if none)
1590 * @return void
1592 public function set_after_edit_icons($afterediticons) {
1593 $this->afterediticons = $afterediticons;
1597 * Changes the name (text of link) for this module instance.
1598 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1599 * @param string $name Name of activity / link text
1600 * @return void
1602 public function set_name($name) {
1603 if ($this->state < self::STATE_BUILDING_DYNAMIC) {
1604 $this->update_user_visible();
1606 $this->name = $name;
1610 * Turns off the view link for this module instance.
1611 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1612 * @return void
1614 public function set_no_view_link() {
1615 $this->check_not_view_only();
1616 $this->url = null;
1620 * Sets the 'uservisible' flag. This can be used (by setting false) to prevent access and
1621 * display of this module link for the current user.
1622 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1623 * @param bool $uservisible
1624 * @return void
1626 public function set_user_visible($uservisible) {
1627 $this->check_not_view_only();
1628 $this->uservisible = $uservisible;
1632 * Sets the 'available' flag and related details. This flag is normally used to make
1633 * course modules unavailable until a certain date or condition is met. (When a course
1634 * module is unavailable, it is still visible to users who have viewhiddenactivities
1635 * permission.)
1637 * When this is function is called, user-visible status is recalculated automatically.
1639 * The $showavailability flag does not really do anything any more, but is retained
1640 * for backward compatibility. Setting this to false will cause $availableinfo to
1641 * be ignored.
1643 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1644 * @param bool $available False if this item is not 'available'
1645 * @param int $showavailability 0 = do not show this item at all if it's not available,
1646 * 1 = show this item greyed out with the following message
1647 * @param string $availableinfo Information about why this is not available, or
1648 * empty string if not displaying
1649 * @return void
1651 public function set_available($available, $showavailability=0, $availableinfo='') {
1652 $this->check_not_view_only();
1653 $this->available = $available;
1654 if (!$showavailability) {
1655 $availableinfo = '';
1657 $this->availableinfo = $availableinfo;
1658 $this->update_user_visible();
1662 * Some set functions can only be called from _cm_info_dynamic and not _cm_info_view.
1663 * This is because they may affect parts of this object which are used on pages other
1664 * than the view page (e.g. in the navigation block, or when checking access on
1665 * module pages).
1666 * @return void
1668 private function check_not_view_only() {
1669 if ($this->state >= self::STATE_DYNAMIC) {
1670 throw new coding_exception('Cannot set this data from _cm_info_view because it may ' .
1671 'affect other pages as well as view');
1676 * Constructor should not be called directly; use {@link get_fast_modinfo()}
1678 * @param course_modinfo $modinfo Parent object
1679 * @param stdClass $notused1 Argument not used
1680 * @param stdClass $mod Module object from the modinfo field of course table
1681 * @param stdClass $notused2 Argument not used
1683 public function __construct(course_modinfo $modinfo, $notused1, $mod, $notused2) {
1684 $this->modinfo = $modinfo;
1686 $this->id = $mod->cm;
1687 $this->instance = $mod->id;
1688 $this->modname = $mod->mod;
1689 $this->idnumber = isset($mod->idnumber) ? $mod->idnumber : '';
1690 $this->name = $mod->name;
1691 $this->visible = $mod->visible;
1692 $this->sectionnum = $mod->section; // Note weirdness with name here
1693 $this->groupmode = isset($mod->groupmode) ? $mod->groupmode : 0;
1694 $this->groupingid = isset($mod->groupingid) ? $mod->groupingid : 0;
1695 $this->groupmembersonly = isset($mod->groupmembersonly) ? $mod->groupmembersonly : 0;
1696 $this->indent = isset($mod->indent) ? $mod->indent : 0;
1697 $this->extra = isset($mod->extra) ? $mod->extra : '';
1698 $this->extraclasses = isset($mod->extraclasses) ? $mod->extraclasses : '';
1699 // iconurl may be stored as either string or instance of moodle_url.
1700 $this->iconurl = isset($mod->iconurl) ? new moodle_url($mod->iconurl) : '';
1701 $this->onclick = isset($mod->onclick) ? $mod->onclick : '';
1702 $this->content = isset($mod->content) ? $mod->content : '';
1703 $this->icon = isset($mod->icon) ? $mod->icon : '';
1704 $this->iconcomponent = isset($mod->iconcomponent) ? $mod->iconcomponent : '';
1705 $this->customdata = isset($mod->customdata) ? $mod->customdata : '';
1706 $this->showdescription = isset($mod->showdescription) ? $mod->showdescription : 0;
1707 $this->state = self::STATE_BASIC;
1709 $this->section = isset($mod->sectionid) ? $mod->sectionid : 0;
1710 $this->module = isset($mod->module) ? $mod->module : 0;
1711 $this->added = isset($mod->added) ? $mod->added : 0;
1712 $this->score = isset($mod->score) ? $mod->score : 0;
1713 $this->visibleold = isset($mod->visibleold) ? $mod->visibleold : 0;
1715 // Note: it saves effort and database space to always include the
1716 // availability and completion fields, even if availability or completion
1717 // are actually disabled
1718 $this->completion = isset($mod->completion) ? $mod->completion : 0;
1719 $this->completiongradeitemnumber = isset($mod->completiongradeitemnumber)
1720 ? $mod->completiongradeitemnumber : null;
1721 $this->completionview = isset($mod->completionview)
1722 ? $mod->completionview : 0;
1723 $this->completionexpected = isset($mod->completionexpected)
1724 ? $mod->completionexpected : 0;
1725 $this->availability = isset($mod->availability) ? $mod->availability : null;
1726 $this->conditionscompletion = isset($mod->conditionscompletion)
1727 ? $mod->conditionscompletion : array();
1728 $this->conditionsgrade = isset($mod->conditionsgrade)
1729 ? $mod->conditionsgrade : array();
1730 $this->conditionsfield = isset($mod->conditionsfield)
1731 ? $mod->conditionsfield : array();
1733 static $modviews = array();
1734 if (!isset($modviews[$this->modname])) {
1735 $modviews[$this->modname] = !plugin_supports('mod', $this->modname,
1736 FEATURE_NO_VIEW_LINK);
1738 $this->url = $modviews[$this->modname]
1739 ? new moodle_url('/mod/' . $this->modname . '/view.php', array('id'=>$this->id))
1740 : null;
1744 * If dynamic data for this course-module is not yet available, gets it.
1746 * This function is automatically called when requesting any course_modinfo property
1747 * that can be modified by modules (have a set_xxx method).
1749 * Dynamic data is data which does not come directly from the cache but is calculated at
1750 * runtime based on the current user. Primarily this concerns whether the user can access
1751 * the module or not.
1753 * As part of this function, the module's _cm_info_dynamic function from its lib.php will
1754 * be called (if it exists).
1755 * @return void
1757 private function obtain_dynamic_data() {
1758 global $CFG;
1759 $userid = $this->modinfo->get_user_id();
1760 if ($this->state >= self::STATE_BUILDING_DYNAMIC || $userid == -1) {
1761 return;
1763 $this->state = self::STATE_BUILDING_DYNAMIC;
1765 if (!empty($CFG->enableavailability)) {
1766 require_once($CFG->libdir. '/conditionlib.php');
1767 // Get availability information.
1768 $ci = new \core_availability\info_module($this);
1770 // Note that the modinfo currently available only includes minimal details (basic data)
1771 // but we know that this function does not need anything more than basic data.
1772 $this->available = $ci->is_available($this->availableinfo, true,
1773 $userid, $this->modinfo);
1775 // Check parent section
1776 $parentsection = $this->modinfo->get_section_info($this->sectionnum);
1777 if (!$parentsection->available) {
1778 // Do not store info from section here, as that is already
1779 // presented from the section (if appropriate) - just change
1780 // the flag
1781 $this->available = false;
1783 } else {
1784 $this->available = true;
1787 // Update visible state for current user
1788 $this->update_user_visible();
1790 // Let module make dynamic changes at this point
1791 $this->call_mod_function('cm_info_dynamic');
1792 $this->state = self::STATE_DYNAMIC;
1796 * Getter method for property $uservisible, ensures that dynamic data is retrieved.
1797 * @return bool
1799 private function get_user_visible() {
1800 $this->obtain_dynamic_data();
1801 return $this->uservisible;
1805 * Getter method for property $available, ensures that dynamic data is retrieved
1806 * @return bool
1808 private function get_available() {
1809 $this->obtain_dynamic_data();
1810 return $this->available;
1814 * Getter method for property $showavailability. Works by checking the
1815 * availableinfo property to see if it's empty or not.
1817 * @return int
1818 * @deprecated Since Moodle 2.7
1820 private function get_show_availability() {
1821 debugging('$cm->showavailability property has been deprecated. You ' .
1822 'can replace it by checking if $cm->availableinfo has content.',
1823 DEBUG_DEVELOPER);
1824 return ($this->get_available_info() !== '') ? 1 : 0;
1828 * Getter method for $availablefrom and $availableuntil. Just returns zero
1829 * as these are no longer supported.
1831 * @return int Zero
1832 * @deprecated Since Moodle 2.7
1834 private function get_deprecated_available_date() {
1835 debugging('$cm->availablefrom and $cm->availableuntil have been deprecated. This ' .
1836 'information is no longer available as the system provides more complex ' .
1837 'options (for example, there might be different dates for different users).',
1838 DEBUG_DEVELOPER);
1839 return 0;
1843 * Getter method for property $availableinfo, ensures that dynamic data is retrieved
1844 * @return type
1846 private function get_available_info() {
1847 $this->obtain_dynamic_data();
1848 return $this->availableinfo;
1852 * Works out whether activity is available to the current user
1854 * If the activity is unavailable, additional checks are required to determine if its hidden or greyed out
1856 * @see is_user_access_restricted_by_group()
1857 * @see is_user_access_restricted_by_conditional_access()
1858 * @return void
1860 private function update_user_visible() {
1861 $userid = $this->modinfo->get_user_id();
1862 if ($userid == -1) {
1863 return null;
1865 $this->uservisible = true;
1867 // If the user cannot access the activity set the uservisible flag to false.
1868 // Additional checks are required to determine whether the activity is entirely hidden or just greyed out.
1869 if ((!$this->visible or !$this->get_available()) and
1870 !has_capability('moodle/course:viewhiddenactivities', $this->get_context(), $userid)) {
1872 $this->uservisible = false;
1875 // Check group membership.
1876 if ($this->is_user_access_restricted_by_group() ||
1877 $this->is_user_access_restricted_by_capability()) {
1879 $this->uservisible = false;
1880 // Ensure activity is completely hidden from the user.
1881 $this->availableinfo = '';
1886 * Checks whether the module's group settings restrict the current user's access
1888 * @return bool True if the user access is restricted
1890 public function is_user_access_restricted_by_group() {
1891 global $CFG;
1893 if (!empty($CFG->enablegroupmembersonly) and !empty($this->groupmembersonly)) {
1894 $userid = $this->modinfo->get_user_id();
1895 if ($userid == -1) {
1896 return null;
1898 if (!has_capability('moodle/site:accessallgroups', $this->get_context(), $userid)) {
1899 // If the activity has 'group members only' and you don't have accessallgroups...
1900 $groups = $this->modinfo->get_groups($this->groupingid);
1901 if (empty($groups)) {
1902 // ...and you don't belong to a group, then set it so you can't see/access it
1903 return true;
1907 return false;
1911 * Checks whether mod/...:view capability restricts the current user's access.
1913 * @return bool True if the user access is restricted.
1915 public function is_user_access_restricted_by_capability() {
1916 $userid = $this->modinfo->get_user_id();
1917 if ($userid == -1) {
1918 return null;
1920 $capability = 'mod/' . $this->modname . ':view';
1921 $capabilityinfo = get_capability_info($capability);
1922 if (!$capabilityinfo) {
1923 // Capability does not exist, no one is prevented from seeing the activity.
1924 return false;
1927 // You are blocked if you don't have the capability.
1928 return !has_capability($capability, $this->get_context(), $userid);
1932 * Checks whether the module's conditional access settings mean that the
1933 * user cannot see the activity at all
1935 * This is deprecated because it is confusing (name sounds like it's about
1936 * access restriction but it is actually about display), is not used
1937 * anywhere, and is not necessary. Nobody (outside conditional libraries)
1938 * should care what it is that restricted something.
1940 * @return bool True if the user cannot see the module. False if the activity is either available or should be greyed out.
1941 * @deprecated since 2.7
1943 public function is_user_access_restricted_by_conditional_access() {
1944 global $CFG;
1945 debugging('cm_info::is_user_access_restricted_by_conditional_access() ' .
1946 'is deprecated; this function is not needed (use $cm->uservisible ' .
1947 'and $cm->availableinfo) to decide whether it should be available ' .
1948 'or appear)', DEBUG_DEVELOPER);
1950 if (empty($CFG->enableavailability)) {
1951 return false;
1954 $userid = $this->modinfo->get_user_id();
1955 if ($userid == -1) {
1956 return null;
1959 // Return false if user can access the activity, or if its availability
1960 // info is set (= should be displayed even though not accessible).
1961 return !$this->get_user_visible() && !$this->get_available_info();
1965 * Calls a module function (if exists), passing in one parameter: this object.
1966 * @param string $type Name of function e.g. if this is 'grooblezorb' and the modname is
1967 * 'forum' then it will try to call 'mod_forum_grooblezorb' or 'forum_grooblezorb'
1968 * @return void
1970 private function call_mod_function($type) {
1971 global $CFG;
1972 $libfile = $CFG->dirroot . '/mod/' . $this->modname . '/lib.php';
1973 if (file_exists($libfile)) {
1974 include_once($libfile);
1975 $function = 'mod_' . $this->modname . '_' . $type;
1976 if (function_exists($function)) {
1977 $function($this);
1978 } else {
1979 $function = $this->modname . '_' . $type;
1980 if (function_exists($function)) {
1981 $function($this);
1988 * If view data for this course-module is not yet available, obtains it.
1990 * This function is automatically called if any of the functions (marked) which require
1991 * view data are called.
1993 * View data is data which is needed only for displaying the course main page (& any similar
1994 * functionality on other pages) but is not needed in general. Obtaining view data may have
1995 * a performance cost.
1997 * As part of this function, the module's _cm_info_view function from its lib.php will
1998 * be called (if it exists).
1999 * @return void
2001 private function obtain_view_data() {
2002 if ($this->state >= self::STATE_BUILDING_VIEW || $this->modinfo->get_user_id() == -1) {
2003 return;
2005 $this->obtain_dynamic_data();
2006 $this->state = self::STATE_BUILDING_VIEW;
2008 // Let module make changes at this point
2009 $this->call_mod_function('cm_info_view');
2010 $this->state = self::STATE_VIEW;
2016 * Returns reference to full info about modules in course (including visibility).
2017 * Cached and as fast as possible (0 or 1 db query).
2019 * use get_fast_modinfo($courseid, 0, true) to reset the static cache for particular course
2020 * use get_fast_modinfo(0, 0, true) to reset the static cache for all courses
2022 * use rebuild_course_cache($courseid, true) to reset the application AND static cache
2023 * for particular course when it's contents has changed
2025 * @param int|stdClass $courseorid object from DB table 'course' (must have field 'id'
2026 * and recommended to have field 'cacherev') or just a course id. Just course id
2027 * is enough when calling get_fast_modinfo() for current course or site or when
2028 * calling for any other course for the second time.
2029 * @param int $userid User id to populate 'availble' and 'uservisible' attributes of modules and sections.
2030 * Set to 0 for current user (default). Set to -1 to avoid calculation of dynamic user-depended data.
2031 * @param bool $resetonly whether we want to get modinfo or just reset the cache
2032 * @return course_modinfo|null Module information for course, or null if resetting
2033 * @throws moodle_exception when course is not found (nothing is thrown if resetting)
2035 function get_fast_modinfo($courseorid, $userid = 0, $resetonly = false) {
2036 // compartibility with syntax prior to 2.4:
2037 if ($courseorid === 'reset') {
2038 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);
2039 $courseorid = 0;
2040 $resetonly = true;
2043 // Function get_fast_modinfo() can never be called during upgrade unless it is used for clearing cache only.
2044 if (!$resetonly) {
2045 upgrade_ensure_not_running();
2048 // Function is called with $reset = true
2049 if ($resetonly) {
2050 course_modinfo::clear_instance_cache($courseorid);
2051 return null;
2054 // Function is called with $reset = false, retrieve modinfo
2055 return course_modinfo::instance($courseorid, $userid);
2059 * Rebuilds or resets the cached list of course activities stored in MUC.
2061 * rebuild_course_cache() must NEVER be called from lib/db/upgrade.php.
2062 * At the same time course cache may ONLY be cleared using this function in
2063 * upgrade scripts of plugins.
2065 * During the bulk operations if it is necessary to reset cache of multiple
2066 * courses it is enough to call {@link increment_revision_number()} for the
2067 * table 'course' and field 'cacherev' specifying affected courses in select.
2069 * Cached course information is stored in MUC core/coursemodinfo and is
2070 * validated with the DB field {course}.cacherev
2072 * @global moodle_database $DB
2073 * @param int $courseid id of course to rebuild, empty means all
2074 * @param boolean $clearonly only clear the cache, gets rebuild automatically on the fly.
2075 * Recommended to set to true to avoid unnecessary multiple rebuilding.
2077 function rebuild_course_cache($courseid=0, $clearonly=false) {
2078 global $COURSE, $SITE, $DB, $CFG;
2080 // Function rebuild_course_cache() can not be called during upgrade unless it's clear only.
2081 if (!$clearonly && !upgrade_ensure_not_running(true)) {
2082 $clearonly = true;
2085 // Destroy navigation caches
2086 navigation_cache::destroy_volatile_caches();
2088 if (class_exists('format_base')) {
2089 // if file containing class is not loaded, there is no cache there anyway
2090 format_base::reset_course_cache($courseid);
2093 $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
2094 if (empty($courseid)) {
2095 // Clearing caches for all courses.
2096 increment_revision_number('course', 'cacherev', '');
2097 $cachecoursemodinfo->purge();
2098 course_modinfo::clear_instance_cache();
2099 // Update global values too.
2100 $sitecacherev = $DB->get_field('course', 'cacherev', array('id' => SITEID));
2101 $SITE->cachrev = $sitecacherev;
2102 if ($COURSE->id == SITEID) {
2103 $COURSE->cacherev = $sitecacherev;
2104 } else {
2105 $COURSE->cacherev = $DB->get_field('course', 'cacherev', array('id' => $COURSE->id));
2107 } else {
2108 // Clearing cache for one course, make sure it is deleted from user request cache as well.
2109 increment_revision_number('course', 'cacherev', 'id = :id', array('id' => $courseid));
2110 $cachecoursemodinfo->delete($courseid);
2111 course_modinfo::clear_instance_cache($courseid);
2112 // Update global values too.
2113 if ($courseid == $COURSE->id || $courseid == $SITE->id) {
2114 $cacherev = $DB->get_field('course', 'cacherev', array('id' => $courseid));
2115 if ($courseid == $COURSE->id) {
2116 $COURSE->cacherev = $cacherev;
2118 if ($courseid == $SITE->id) {
2119 $SITE->cachrev = $cacherev;
2124 if ($clearonly) {
2125 return;
2128 if ($courseid) {
2129 $select = array('id'=>$courseid);
2130 } else {
2131 $select = array();
2132 core_php_time_limit::raise(); // this could take a while! MDL-10954
2135 $rs = $DB->get_recordset("course", $select,'','id,'.join(',', course_modinfo::$cachedfields));
2136 // Rebuild cache for each course.
2137 foreach ($rs as $course) {
2138 course_modinfo::build_course_cache($course);
2140 $rs->close();
2145 * Class that is the return value for the _get_coursemodule_info module API function.
2147 * Note: For backward compatibility, you can also return a stdclass object from that function.
2148 * The difference is that the stdclass object may contain an 'extra' field (deprecated,
2149 * use extraclasses and onclick instead). The stdclass object may not contain
2150 * the new fields defined here (content, extraclasses, customdata).
2152 class cached_cm_info {
2154 * Name (text of link) for this activity; Leave unset to accept default name
2155 * @var string
2157 public $name;
2160 * Name of icon for this activity. Normally, this should be used together with $iconcomponent
2161 * to define the icon, as per pix_url function.
2162 * For backward compatibility, if this value is of the form 'mod/forum/icon' then an icon
2163 * within that module will be used.
2164 * @see cm_info::get_icon_url()
2165 * @see renderer_base::pix_url()
2166 * @var string
2168 public $icon;
2171 * Component for icon for this activity, as per pix_url; leave blank to use default 'moodle'
2172 * component
2173 * @see renderer_base::pix_url()
2174 * @var string
2176 public $iconcomponent;
2179 * HTML content to be displayed on the main page below the link (if any) for this course-module
2180 * @var string
2182 public $content;
2185 * Custom data to be stored in modinfo for this activity; useful if there are cases when
2186 * internal information for this activity type needs to be accessible from elsewhere on the
2187 * course without making database queries. May be of any type but should be short.
2188 * @var mixed
2190 public $customdata;
2193 * Extra CSS class or classes to be added when this activity is displayed on the main page;
2194 * space-separated string
2195 * @var string
2197 public $extraclasses;
2200 * External URL image to be used by activity as icon, useful for some external-tool modules
2201 * like lti. If set, takes precedence over $icon and $iconcomponent
2202 * @var $moodle_url
2204 public $iconurl;
2207 * Content of onclick JavaScript; escaped HTML to be inserted as attribute value
2208 * @var string
2210 public $onclick;
2215 * Data about a single section on a course. This contains the fields from the
2216 * course_sections table, plus additional data when required.
2218 * @property-read int $id Section ID - from course_sections table
2219 * @property-read int $course Course ID - from course_sections table
2220 * @property-read int $section Section number - from course_sections table
2221 * @property-read string $name Section name if specified - from course_sections table
2222 * @property-read int $visible Section visibility (1 = visible) - from course_sections table
2223 * @property-read string $summary Section summary text if specified - from course_sections table
2224 * @property-read int $summaryformat Section summary text format (FORMAT_xx constant) - from course_sections table
2225 * @property-read string $availability Availability information as JSON string -
2226 * from course_sections table
2227 * @property-read array $conditionscompletion Availability conditions for this section based on the completion of
2228 * course-modules (array from course-module id to required completion state
2229 * for that module) - from cached data in sectioncache field
2230 * @property-read array $conditionsgrade Availability conditions for this section based on course grades (array from
2231 * grade item id to object with ->min, ->max fields) - from cached data in
2232 * sectioncache field
2233 * @property-read array $conditionsfield Availability conditions for this section based on user fields
2234 * @property-read bool $available True if this section is available to the given user i.e. if all availability conditions
2235 * are met - obtained dynamically
2236 * @property-read string $availableinfo If section is not available to some users, this string gives information about
2237 * availability which can be displayed to students and/or staff (e.g. 'Available from 3 January 2010')
2238 * for display on main page - obtained dynamically
2239 * @property-read bool $uservisible True if this section is available to the given user (for example, if current user
2240 * has viewhiddensections capability, they can access the section even if it is not
2241 * visible or not available, so this would be true in that case) - obtained dynamically
2242 * @property-read string $sequence Comma-separated list of all modules in the section. Note, this field may not exactly
2243 * match course_sections.sequence if later has references to non-existing modules or not modules of not available module types.
2244 * @property-read course_modinfo $modinfo
2246 class section_info implements IteratorAggregate {
2248 * Section ID - from course_sections table
2249 * @var int
2251 private $_id;
2254 * Section number - from course_sections table
2255 * @var int
2257 private $_section;
2260 * Section name if specified - from course_sections table
2261 * @var string
2263 private $_name;
2266 * Section visibility (1 = visible) - from course_sections table
2267 * @var int
2269 private $_visible;
2272 * Section summary text if specified - from course_sections table
2273 * @var string
2275 private $_summary;
2278 * Section summary text format (FORMAT_xx constant) - from course_sections table
2279 * @var int
2281 private $_summaryformat;
2284 * Availability information as JSON string - from course_sections table
2285 * @var string
2287 private $_availability;
2290 * Availability conditions for this section based on the completion of
2291 * course-modules (array from course-module id to required completion state
2292 * for that module) - from cached data in sectioncache field
2293 * @var array
2295 private $_conditionscompletion;
2298 * Availability conditions for this section based on course grades (array from
2299 * grade item id to object with ->min, ->max fields) - from cached data in
2300 * sectioncache field
2301 * @var array
2303 private $_conditionsgrade;
2306 * Availability conditions for this section based on user fields
2307 * @var array
2309 private $_conditionsfield;
2312 * True if this section is available to students i.e. if all availability conditions
2313 * are met - obtained dynamically on request, see function {@link section_info::get_available()}
2314 * @var bool|null
2316 private $_available;
2319 * If section is not available to some users, this string gives information about
2320 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
2321 * January 2010') for display on main page - obtained dynamically on request, see
2322 * function {@link section_info::get_availableinfo()}
2323 * @var string
2325 private $_availableinfo;
2328 * True if this section is available to the CURRENT user (for example, if current user
2329 * has viewhiddensections capability, they can access the section even if it is not
2330 * visible or not available, so this would be true in that case) - obtained dynamically
2331 * on request, see function {@link section_info::get_uservisible()}
2332 * @var bool|null
2334 private $_uservisible;
2337 * Default values for sectioncache fields; if a field has this value, it won't
2338 * be stored in the sectioncache cache, to save space. Checks are done by ===
2339 * which means values must all be strings.
2340 * @var array
2342 private static $sectioncachedefaults = array(
2343 'name' => null,
2344 'summary' => '',
2345 'summaryformat' => '1', // FORMAT_HTML, but must be a string
2346 'visible' => '1',
2347 'availability' => null,
2351 * Stores format options that have been cached when building 'coursecache'
2352 * When the format option is requested we look first if it has been cached
2353 * @var array
2355 private $cachedformatoptions = array();
2358 * Stores the list of all possible section options defined in each used course format.
2359 * @var array
2361 static private $sectionformatoptions = array();
2364 * Stores the modinfo object passed in constructor, may be used when requesting
2365 * dynamically obtained attributes such as available, availableinfo, uservisible.
2366 * Also used to retrun information about current course or user.
2367 * @var course_modinfo
2369 private $modinfo;
2372 * Constructs object from database information plus extra required data.
2373 * @param object $data Array entry from cached sectioncache
2374 * @param int $number Section number (array key)
2375 * @param int $notused1 argument not used (informaion is available in $modinfo)
2376 * @param int $notused2 argument not used (informaion is available in $modinfo)
2377 * @param course_modinfo $modinfo Owner (needed for checking availability)
2378 * @param int $notused3 argument not used (informaion is available in $modinfo)
2380 public function __construct($data, $number, $notused1, $notused2, $modinfo, $notused3) {
2381 global $CFG;
2382 require_once($CFG->dirroot.'/course/lib.php');
2384 // Data that is always present
2385 $this->_id = $data->id;
2387 $defaults = self::$sectioncachedefaults +
2388 array('conditionscompletion' => array(),
2389 'conditionsgrade' => array(),
2390 'conditionsfield' => array());
2392 // Data that may use default values to save cache size
2393 foreach ($defaults as $field => $value) {
2394 if (isset($data->{$field})) {
2395 $this->{'_'.$field} = $data->{$field};
2396 } else {
2397 $this->{'_'.$field} = $value;
2401 // Other data from constructor arguments.
2402 $this->_section = $number;
2403 $this->modinfo = $modinfo;
2405 // Cached course format data.
2406 $course = $modinfo->get_course();
2407 if (!isset(self::$sectionformatoptions[$course->format])) {
2408 // Store list of section format options defined in each used course format.
2409 // They do not depend on particular course but only on its format.
2410 self::$sectionformatoptions[$course->format] =
2411 course_get_format($course)->section_format_options();
2413 foreach (self::$sectionformatoptions[$course->format] as $field => $option) {
2414 if (!empty($option['cache'])) {
2415 if (isset($data->{$field})) {
2416 $this->cachedformatoptions[$field] = $data->{$field};
2417 } else if (array_key_exists('cachedefault', $option)) {
2418 $this->cachedformatoptions[$field] = $option['cachedefault'];
2425 * Magic method to check if the property is set
2427 * @param string $name name of the property
2428 * @return bool
2430 public function __isset($name) {
2431 if (method_exists($this, 'get_'.$name) ||
2432 property_exists($this, '_'.$name) ||
2433 array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
2434 $value = $this->__get($name);
2435 return isset($value);
2437 return false;
2441 * Magic method to check if the property is empty
2443 * @param string $name name of the property
2444 * @return bool
2446 public function __empty($name) {
2447 if (method_exists($this, 'get_'.$name) ||
2448 property_exists($this, '_'.$name) ||
2449 array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
2450 $value = $this->__get($name);
2451 return empty($value);
2453 return true;
2457 * Magic method to retrieve the property, this is either basic section property
2458 * or availability information or additional properties added by course format
2460 * @param string $name name of the property
2461 * @return bool
2463 public function __get($name) {
2464 if (method_exists($this, 'get_'.$name)) {
2465 return $this->{'get_'.$name}();
2467 if (property_exists($this, '_'.$name)) {
2468 return $this->{'_'.$name};
2470 if (array_key_exists($name, $this->cachedformatoptions)) {
2471 return $this->cachedformatoptions[$name];
2473 // precheck if the option is defined in format to avoid unnecessary DB queries in get_format_options()
2474 if (array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
2475 $formatoptions = course_get_format($this->modinfo->get_course())->get_format_options($this);
2476 return $formatoptions[$name];
2478 debugging('Invalid section_info property accessed! '.$name);
2479 return null;
2483 * Finds whether this section is available at the moment for the current user.
2485 * The value can be accessed publicly as $sectioninfo->available
2487 * @return bool
2489 private function get_available() {
2490 global $CFG;
2491 $userid = $this->modinfo->get_user_id();
2492 if ($this->_available !== null || $userid == -1) {
2493 // Has already been calculated or does not need calculation.
2494 return $this->_available;
2496 if (!empty($CFG->enableavailability)) {
2497 require_once($CFG->libdir. '/conditionlib.php');
2498 // Get availability information.
2499 $ci = new \core_availability\info_section($this);
2500 $this->_available = $ci->is_available($this->_availableinfo, true,
2501 $userid, $this->modinfo);
2502 } else {
2503 $this->_available = true;
2504 $this->_availableinfo = '';
2506 return $this->_available;
2510 * Returns the availability text shown next to the section on course page.
2512 * @return string
2514 private function get_availableinfo() {
2515 // Make sure $this->_available has been calculated, it may also fill the _availableinfo property.
2516 $this->get_available();
2517 $userid = $this->modinfo->get_user_id();
2518 if ($this->_availableinfo !== null || $userid == -1) {
2519 // It has been already calculated or does not need calculation.
2520 return $this->_availableinfo;
2522 $this->_availableinfo = '';
2523 // Display grouping info if available & not already displaying
2524 // (it would already display if current user doesn't have access)
2525 // for people with managegroups - same logic/class as grouping label
2526 // on individual activities.
2527 $context = context_course::instance($this->get_course());
2528 if ($this->_groupingid && has_capability('moodle/course:managegroups', $context, $userid)) {
2529 $groupings = groups_get_all_groupings($this->get_course());
2530 $this->_availableinfo = html_writer::tag('span', '(' . format_string(
2531 $groupings[$this->_groupingid]->name, true, array('context' => $context)) .
2532 ')', array('class' => 'groupinglabel'));
2534 return $this->_availableinfo;
2538 * Implementation of IteratorAggregate::getIterator(), allows to cycle through properties
2539 * and use {@link convert_to_array()}
2541 * @return ArrayIterator
2543 public function getIterator() {
2544 $ret = array();
2545 foreach (get_object_vars($this) as $key => $value) {
2546 if (substr($key, 0, 1) == '_') {
2547 if (method_exists($this, 'get'.$key)) {
2548 $ret[substr($key, 1)] = $this->{'get'.$key}();
2549 } else {
2550 $ret[substr($key, 1)] = $this->$key;
2554 $ret['sequence'] = $this->get_sequence();
2555 $ret['course'] = $this->get_course();
2556 $ret = array_merge($ret, course_get_format($this->modinfo->get_course())->get_format_options($this->_section));
2557 return new ArrayIterator($ret);
2561 * Works out whether activity is visible *for current user* - if this is false, they
2562 * aren't allowed to access it.
2564 * @return bool
2566 private function get_uservisible() {
2567 $userid = $this->modinfo->get_user_id();
2568 if ($this->_uservisible !== null || $userid == -1) {
2569 // Has already been calculated or does not need calculation.
2570 return $this->_uservisible;
2572 $this->_uservisible = true;
2573 if (!$this->_visible || !$this->get_available()) {
2574 $coursecontext = context_course::instance($this->get_course());
2575 if (!has_capability('moodle/course:viewhiddensections', $coursecontext, $userid)) {
2576 $this->_uservisible = false;
2579 return $this->_uservisible;
2583 * Getter method for property $showavailability. Works by checking the
2584 * availableinfo property to see if it's empty or not.
2586 * @return int
2587 * @deprecated Since Moodle 2.7
2589 private function get_showavailability() {
2590 debugging('$section->showavailability property has been deprecated. You ' .
2591 'can replace it by checking if $section->availableinfo has content.',
2592 DEBUG_DEVELOPER);
2593 return ($this->get_availableinfo() !== '') ? 1 : 0;
2597 * Getter method for $availablefrom. Just returns zero as no longer supported.
2599 * @return int Zero
2600 * @deprecated Since Moodle 2.7
2602 private function get_availablefrom() {
2603 debugging('$section->availablefrom has been deprecated. This ' .
2604 'information is no longer available as the system provides more complex ' .
2605 'options (for example, there might be different dates for different users).',
2606 DEBUG_DEVELOPER);
2607 return 0;
2611 * Getter method for $availablefrom. Just returns zero as no longer supported.
2613 * @return int Zero
2614 * @deprecated Since Moodle 2.7
2616 private function get_availableuntil() {
2617 debugging('$section->availableuntil has been deprecated. This ' .
2618 'information is no longer available as the system provides more complex ' .
2619 'options (for example, there might be different dates for different users).',
2620 DEBUG_DEVELOPER);
2621 return 0;
2625 * Getter method for $groupingid. Just returns zero as no longer supported.
2627 * @return int Zero
2628 * @deprecated Since Moodle 2.7
2630 private function get_groupingid() {
2631 debugging('$section->groupingid has been deprecated. This ' .
2632 'information is no longer available as the system provides more complex ' .
2633 'options (for example, combining multiple groupings).',
2634 DEBUG_DEVELOPER);
2635 return 0;
2639 * Restores the course_sections.sequence value
2641 * @return string
2643 private function get_sequence() {
2644 if (!empty($this->modinfo->sections[$this->_section])) {
2645 return implode(',', $this->modinfo->sections[$this->_section]);
2646 } else {
2647 return '';
2652 * Returns course ID - from course_sections table
2654 * @return int
2656 private function get_course() {
2657 return $this->modinfo->get_course_id();
2661 * Modinfo object
2663 * @return course_modinfo
2665 private function get_modinfo() {
2666 return $this->modinfo;
2670 * Prepares section data for inclusion in sectioncache cache, removing items
2671 * that are set to defaults, and adding availability data if required.
2673 * Called by build_section_cache in course_modinfo only; do not use otherwise.
2674 * @param object $section Raw section data object
2676 public static function convert_for_section_cache($section) {
2677 global $CFG;
2679 // Course id stored in course table
2680 unset($section->course);
2681 // Section number stored in array key
2682 unset($section->section);
2683 // Sequence stored implicity in modinfo $sections array
2684 unset($section->sequence);
2686 // Remove default data
2687 foreach (self::$sectioncachedefaults as $field => $value) {
2688 // Exact compare as strings to avoid problems if some strings are set
2689 // to "0" etc.
2690 if (isset($section->{$field}) && $section->{$field} === $value) {
2691 unset($section->{$field});