MDL-44017 Events: Added unit test for report_viewed events
[moodle.git] / lib / modinfolib.php
blob2890108712d39ed85645eb46010aa3c23e3f07a3
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 usually not available (set to null)
103 * unless the course has activities set to groupmembersonly. When set, it is an array of
104 * grouping id => array of group id => group id. Includes grouping id 0 for 'all groups'.
105 * @var int[][]
107 private $groups;
110 * List of class read-only properties and their getter methods.
111 * Used by magic functions __get(), __isset(), __empty()
112 * @var array
114 private static $standardproperties = array(
115 'courseid' => 'get_course_id',
116 'userid' => 'get_user_id',
117 'sections' => 'get_sections',
118 'cms' => 'get_cms',
119 'instances' => 'get_instances',
120 'groups' => 'get_groups_all',
124 * Magic method getter
126 * @param string $name
127 * @return mixed
129 public function __get($name) {
130 if (isset(self::$standardproperties[$name])) {
131 $method = self::$standardproperties[$name];
132 return $this->$method();
133 } else {
134 debugging('Invalid course_modinfo property accessed: '.$name);
135 return null;
140 * Magic method for function isset()
142 * @param string $name
143 * @return bool
145 public function __isset($name) {
146 if (isset(self::$standardproperties[$name])) {
147 $value = $this->__get($name);
148 return isset($value);
150 return false;
154 * Magic method for function empty()
156 * @param string $name
157 * @return bool
159 public function __empty($name) {
160 if (isset(self::$standardproperties[$name])) {
161 $value = $this->__get($name);
162 return empty($value);
164 return true;
168 * Magic method setter
170 * Will display the developer warning when trying to set/overwrite existing property.
172 * @param string $name
173 * @param mixed $value
175 public function __set($name, $value) {
176 debugging("It is not allowed to set the property course_modinfo::\${$name}", DEBUG_DEVELOPER);
180 * Returns course object that was used in the first {@link get_fast_modinfo()} call.
182 * It may not contain all fields from DB table {course} but always has at least the following:
183 * id,shortname,fullname,format,enablecompletion,groupmode,groupmodeforce,cacherev
185 * @return stdClass
187 public function get_course() {
188 return $this->course;
192 * @return int Course ID
194 public function get_course_id() {
195 return $this->course->id;
199 * @return int User ID
201 public function get_user_id() {
202 return $this->userid;
206 * @return array Array from section number (e.g. 0) to array of course-module IDs in that
207 * section; this only includes sections that contain at least one course-module
209 public function get_sections() {
210 return $this->sections;
214 * @return cm_info[] Array from course-module instance to cm_info object within this course, in
215 * order of appearance
217 public function get_cms() {
218 return $this->cms;
222 * Obtains a single course-module object (for a course-module that is on this course).
223 * @param int $cmid Course-module ID
224 * @return cm_info Information about that course-module
225 * @throws moodle_exception If the course-module does not exist
227 public function get_cm($cmid) {
228 if (empty($this->cms[$cmid])) {
229 throw new moodle_exception('invalidcoursemodule', 'error');
231 return $this->cms[$cmid];
235 * Obtains all module instances on this course.
236 * @return cm_info[][] Array from module name => array from instance id => cm_info
238 public function get_instances() {
239 return $this->instances;
243 * Returns array of localised human-readable module names used in this course
245 * @param bool $plural if true returns the plural form of modules names
246 * @return array
248 public function get_used_module_names($plural = false) {
249 $modnames = get_module_types_names($plural);
250 $modnamesused = array();
251 foreach ($this->get_cms() as $cmid => $mod) {
252 if (isset($modnames[$mod->modname]) && $mod->uservisible) {
253 $modnamesused[$mod->modname] = $modnames[$mod->modname];
256 core_collator::asort($modnamesused);
257 return $modnamesused;
261 * Obtains all instances of a particular module on this course.
262 * @param $modname Name of module (not full frankenstyle) e.g. 'label'
263 * @return cm_info[] Array from instance id => cm_info for modules on this course; empty if none
265 public function get_instances_of($modname) {
266 if (empty($this->instances[$modname])) {
267 return array();
269 return $this->instances[$modname];
273 * Groups that the current user belongs to organised by grouping id. Calculated on the first request.
274 * @return int[][] array of grouping id => array of group id => group id. Includes grouping id 0 for 'all groups'
276 private function get_groups_all() {
277 if (is_null($this->groups)) {
278 // NOTE: Performance could be improved here. The system caches user groups
279 // in $USER->groupmember[$courseid] => array of groupid=>groupid. Unfortunately this
280 // structure does not include grouping information. It probably could be changed to
281 // do so, without a significant performance hit on login, thus saving this one query
282 // each request.
283 $this->groups = groups_get_user_groups($this->course->id, $this->userid);
285 return $this->groups;
289 * Returns groups that the current user belongs to on the course. Note: If not already
290 * available, this may make a database query.
291 * @param int $groupingid Grouping ID or 0 (default) for all groups
292 * @return int[] Array of int (group id) => int (same group id again); empty array if none
294 public function get_groups($groupingid = 0) {
295 $allgroups = $this->get_groups_all();
296 if (!isset($allgroups[$groupingid])) {
297 return array();
299 return $allgroups[$groupingid];
303 * Gets all sections as array from section number => data about section.
304 * @return section_info[] Array of section_info objects organised by section number
306 public function get_section_info_all() {
307 return $this->sectioninfo;
311 * Gets data about specific numbered section.
312 * @param int $sectionnumber Number (not id) of section
313 * @param int $strictness Use MUST_EXIST to throw exception if it doesn't
314 * @return section_info Information for numbered section or null if not found
316 public function get_section_info($sectionnumber, $strictness = IGNORE_MISSING) {
317 if (!array_key_exists($sectionnumber, $this->sectioninfo)) {
318 if ($strictness === MUST_EXIST) {
319 throw new moodle_exception('sectionnotexist');
320 } else {
321 return null;
324 return $this->sectioninfo[$sectionnumber];
328 * Static cache for generated course_modinfo instances
330 * @see course_modinfo::instance()
331 * @see course_modinfo::clear_instance_cache()
332 * @var course_modinfo[]
334 protected static $instancecache = array();
337 * Timestamps (microtime) when the course_modinfo instances were last accessed
339 * It is used to remove the least recent accessed instances when static cache is full
341 * @var float[]
343 protected static $cacheaccessed = array();
346 * Clears the cache used in course_modinfo::instance()
348 * Used in {@link get_fast_modinfo()} when called with argument $reset = true
349 * and in {@link rebuild_course_cache()}
351 * @param null|int|stdClass $courseorid if specified removes only cached value for this course
353 public static function clear_instance_cache($courseorid = null) {
354 if (empty($courseorid)) {
355 self::$instancecache = array();
356 self::$cacheaccessed = array();
357 return;
359 if (is_object($courseorid)) {
360 $courseorid = $courseorid->id;
362 if (isset(self::$instancecache[$courseorid])) {
363 // Unsetting static variable in PHP is peculiar, it removes the reference,
364 // but data remain in memory. Prior to unsetting, the varable needs to be
365 // set to empty to remove its remains from memory.
366 self::$instancecache[$courseorid] = '';
367 unset(self::$instancecache[$courseorid]);
368 unset(self::$cacheaccessed[$courseorid]);
373 * Returns the instance of course_modinfo for the specified course and specified user
375 * This function uses static cache for the retrieved instances. The cache
376 * size is limited by MAX_MODINFO_CACHE_SIZE. If instance is not found in
377 * the static cache or it was created for another user or the cacherev validation
378 * failed - a new instance is constructed and returned.
380 * Used in {@link get_fast_modinfo()}
382 * @param int|stdClass $courseorid object from DB table 'course' (must have field 'id'
383 * and recommended to have field 'cacherev') or just a course id
384 * @param int $userid User id to populate 'availble' and 'uservisible' attributes of modules and sections.
385 * Set to 0 for current user (default). Set to -1 to avoid calculation of dynamic user-depended data.
386 * @return course_modinfo
388 public static function instance($courseorid, $userid = 0) {
389 global $USER;
390 if (is_object($courseorid)) {
391 $course = $courseorid;
392 } else {
393 $course = (object)array('id' => $courseorid);
395 if (empty($userid)) {
396 $userid = $USER->id;
399 if (!empty(self::$instancecache[$course->id])) {
400 if (self::$instancecache[$course->id]->userid == $userid &&
401 (!isset($course->cacherev) ||
402 $course->cacherev == self::$instancecache[$course->id]->get_course()->cacherev)) {
403 // This course's modinfo for the same user was recently retrieved, return cached.
404 self::$cacheaccessed[$course->id] = microtime(true);
405 return self::$instancecache[$course->id];
406 } else {
407 // Prevent potential reference problems when switching users.
408 self::clear_instance_cache($course->id);
411 $modinfo = new course_modinfo($course, $userid);
413 // We have a limit of MAX_MODINFO_CACHE_SIZE entries to store in static variable.
414 if (count(self::$instancecache) >= MAX_MODINFO_CACHE_SIZE) {
415 // Find the course that was the least recently accessed.
416 asort(self::$cacheaccessed, SORT_NUMERIC);
417 $courseidtoremove = key(array_reverse(self::$cacheaccessed, true));
418 self::clear_instance_cache($courseidtoremove);
421 // Add modinfo to the static cache.
422 self::$instancecache[$course->id] = $modinfo;
423 self::$cacheaccessed[$course->id] = microtime(true);
425 return $modinfo;
429 * Constructs based on course.
430 * Note: This constructor should not usually be called directly.
431 * Use get_fast_modinfo($course) instead as this maintains a cache.
432 * @param stdClass $course course object, only property id is required.
433 * @param int $userid User ID
434 * @throws moodle_exception if course is not found
436 public function __construct($course, $userid) {
437 global $CFG, $COURSE, $SITE, $DB;
439 if (!isset($course->cacherev)) {
440 // We require presence of property cacherev to validate the course cache.
441 // No need to clone the $COURSE or $SITE object here because we clone it below anyway.
442 $course = get_course($course->id, false);
445 $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
447 // Retrieve modinfo from cache. If not present or cacherev mismatches, call rebuild and retrieve again.
448 $coursemodinfo = $cachecoursemodinfo->get($course->id);
449 if ($coursemodinfo === false || ($course->cacherev != $coursemodinfo->cacherev)) {
450 $coursemodinfo = self::build_course_cache($course);
453 // Set initial values
454 $this->userid = $userid;
455 $this->sections = array();
456 $this->cms = array();
457 $this->instances = array();
458 $this->groups = null;
460 // If we haven't already preloaded contexts for the course, do it now
461 // Modules are also cached here as long as it's the first time this course has been preloaded.
462 context_helper::preload_course($course->id);
464 // Quick integrity check: as a result of race conditions modinfo may not be regenerated after the change.
465 // It is especially dangerous if modinfo contains the deleted course module, as it results in fatal error.
466 // We can check it very cheap by validating the existence of module context.
467 if ($course->id == $COURSE->id || $course->id == $SITE->id) {
468 // Only verify current course (or frontpage) as pages with many courses may not have module contexts cached.
469 // (Uncached modules will result in a very slow verification).
470 foreach ($coursemodinfo->modinfo as $mod) {
471 if (!context_module::instance($mod->cm, IGNORE_MISSING)) {
472 debugging('Course cache integrity check failed: course module with id '. $mod->cm.
473 ' does not have context. Rebuilding cache for course '. $course->id);
474 // Re-request the course record from DB as well, don't use get_course() here.
475 $course = $DB->get_record('course', array('id' => $course->id), '*', MUST_EXIST);
476 $coursemodinfo = self::build_course_cache($course);
477 break;
482 // Overwrite unset fields in $course object with cached values, store the course object.
483 $this->course = fullclone($course);
484 foreach ($coursemodinfo as $key => $value) {
485 if ($key !== 'modinfo' && $key !== 'sectioncache' &&
486 (!isset($this->course->$key) || $key === 'cacherev')) {
487 $this->course->$key = $value;
491 // Loop through each piece of module data, constructing it
492 static $modexists = array();
493 foreach ($coursemodinfo->modinfo as $mod) {
494 if (empty($mod->name)) {
495 // something is wrong here
496 continue;
499 // Skip modules which don't exist
500 if (!array_key_exists($mod->mod, $modexists)) {
501 $modexists[$mod->mod] = file_exists("$CFG->dirroot/mod/$mod->mod/lib.php");
503 if (!$modexists[$mod->mod]) {
504 continue;
507 // Construct info for this module
508 $cm = new cm_info($this, null, $mod, null);
510 // Store module in instances and cms array
511 if (!isset($this->instances[$cm->modname])) {
512 $this->instances[$cm->modname] = array();
514 $this->instances[$cm->modname][$cm->instance] = $cm;
515 $this->cms[$cm->id] = $cm;
517 // Reconstruct sections. This works because modules are stored in order
518 if (!isset($this->sections[$cm->sectionnum])) {
519 $this->sections[$cm->sectionnum] = array();
521 $this->sections[$cm->sectionnum][] = $cm->id;
524 // Expand section objects
525 $this->sectioninfo = array();
526 foreach ($coursemodinfo->sectioncache as $number => $data) {
527 $this->sectioninfo[$number] = new section_info($data, $number, null, null,
528 $this, null);
533 * Builds a list of information about sections on a course to be stored in
534 * the course cache. (Does not include information that is already cached
535 * in some other way.)
537 * This function will be removed in 2.7
539 * @deprecated since 2.6
540 * @param int $courseid Course ID
541 * @return array Information about sections, indexed by section number (not id)
543 public static function build_section_cache($courseid) {
544 global $DB;
545 debugging('Function course_modinfo::build_section_cache() is deprecated. It can only be used internally to build course cache.');
546 $course = $DB->get_record('course', array('id' => $course->id),
547 array_merge(array('id'), self::$cachedfields), MUST_EXIST);
548 return self::build_course_section_cache($course);
552 * Builds a list of information about sections on a course to be stored in
553 * the course cache. (Does not include information that is already cached
554 * in some other way.)
556 * @param stdClass $course Course object (must contain fields
557 * @return array Information about sections, indexed by section number (not id)
559 protected static function build_course_section_cache($course) {
560 global $DB;
562 // Get section data
563 $sections = $DB->get_records('course_sections', array('course' => $course->id), 'section',
564 'section, id, course, name, summary, summaryformat, sequence, visible, ' .
565 'availablefrom, availableuntil, showavailability, groupingid');
566 $compressedsections = array();
568 $formatoptionsdef = course_get_format($course)->section_format_options();
569 // Remove unnecessary data and add availability
570 foreach ($sections as $number => $section) {
571 // Add cached options from course format to $section object
572 foreach ($formatoptionsdef as $key => $option) {
573 if (!empty($option['cache'])) {
574 $formatoptions = course_get_format($course)->get_format_options($section);
575 if (!array_key_exists('cachedefault', $option) || $option['cachedefault'] !== $formatoptions[$key]) {
576 $section->$key = $formatoptions[$key];
580 // Clone just in case it is reused elsewhere
581 $compressedsections[$number] = clone($section);
582 section_info::convert_for_section_cache($compressedsections[$number]);
585 return $compressedsections;
589 * Builds and stores in MUC object containing information about course
590 * modules and sections together with cached fields from table course.
592 * @param stdClass $course object from DB table course. Must have property 'id'
593 * but preferably should have all cached fields.
594 * @return stdClass object with all cached keys of the course plus fields modinfo and sectioncache.
595 * The same object is stored in MUC
596 * @throws moodle_exception if course is not found (if $course object misses some of the
597 * necessary fields it is re-requested from database)
599 public static function build_course_cache($course) {
600 global $DB, $CFG;
601 require_once("$CFG->dirroot/course/lib.php");
602 if (empty($course->id)) {
603 throw new coding_exception('Object $course is missing required property \id\'');
605 // Ensure object has all necessary fields.
606 foreach (self::$cachedfields as $key) {
607 if (!isset($course->$key)) {
608 $course = $DB->get_record('course', array('id' => $course->id),
609 implode(',', array_merge(array('id'), self::$cachedfields)), MUST_EXIST);
610 break;
613 // Retrieve all information about activities and sections.
614 // This may take time on large courses and it is possible that another user modifies the same course during this process.
615 // Field cacherev stored in both DB and cache will ensure that cached data matches the current course state.
616 $coursemodinfo = new stdClass();
617 $coursemodinfo->modinfo = get_array_of_activities($course->id);
618 $coursemodinfo->sectioncache = self::build_course_section_cache($course);
619 foreach (self::$cachedfields as $key) {
620 $coursemodinfo->$key = $course->$key;
622 // Set the accumulated activities and sections information in cache, together with cacherev.
623 $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
624 $cachecoursemodinfo->set($course->id, $coursemodinfo);
625 return $coursemodinfo;
631 * Data about a single module on a course. This contains most of the fields in the course_modules
632 * table, plus additional data when required.
634 * The object can be accessed by core or any plugin (i.e. course format, block, filter, etc.) as
635 * get_fast_modinfo($courseorid)->cms[$coursemoduleid]
636 * or
637 * get_fast_modinfo($courseorid)->instances[$moduletype][$instanceid]
639 * There are three stages when activity module can add/modify data in this object:
641 * <b>Stage 1 - during building the cache.</b>
642 * Allows to add to the course cache static user-independent information about the module.
643 * Modules should try to include only absolutely necessary information that may be required
644 * when displaying course view page. The information is stored in application-level cache
645 * and reset when {@link rebuild_course_cache()} is called or cache is purged by admin.
647 * Modules can implement callback XXX_get_coursemodule_info() returning instance of object
648 * {@link cached_cm_info}
650 * <b>Stage 2 - dynamic data.</b>
651 * Dynamic data is user-dependend, it is stored in request-level cache. To reset this cache
652 * {@link get_fast_modinfo()} with $reset argument may be called.
654 * Dynamic data is obtained when any of the following properties/methods is requested:
655 * - {@link cm_info::$url}
656 * - {@link cm_info::$name}
657 * - {@link cm_info::$onclick}
658 * - {@link cm_info::get_icon_url()}
659 * - {@link cm_info::$uservisible}
660 * - {@link cm_info::$available}
661 * - {@link cm_info::$showavailability}
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 int $availablefrom Available date for this activity (0 if not set, or set to seconds since epoch; before this
727 * date, activity does not display to students) - from course_modules table
728 * @property-read int $availableuntil Available until date for this activity (0 if not set, or set to seconds since epoch; from
729 * this date, activity does not display to students) - from course_modules table
730 * @property-read int $showavailability When activity is unavailable, this field controls whether it is shown to students (0 =
731 * hide completely, 1 = show greyed out with information about when it will be available) -
732 * from course_modules table
733 * @property-read int $showdescription Controls whether the description of the activity displays on the course main page (in
734 * addition to anywhere it might display within the activity itself). 0 = do not show
735 * on main page, 1 = show on main page.
736 * @property-read string $extra (deprecated) Extra HTML that is put in an unhelpful part of the HTML when displaying this module in
737 * course page - from cached data in modinfo field. Deprecated, replaced by ->extraclasses and ->onclick
738 * @property-read string $icon Name of icon to use - from cached data in modinfo field
739 * @property-read string $iconcomponent Component that contains icon - from cached data in modinfo field
740 * @property-read string $modname Name of module e.g. 'forum' (this is the same name as the module's main database
741 * table) - from cached data in modinfo field
742 * @property-read int $module ID of module type - from course_modules table
743 * @property-read string $name Name of module instance for display on page e.g. 'General discussion forum' - from cached
744 * data in modinfo field
745 * @property-read int $sectionnum Section number that this course-module is in (section 0 = above the calendar, section 1
746 * = week/topic 1, etc) - from cached data in modinfo field
747 * @property-read int $section Section id - from course_modules table
748 * @property-read array $conditionscompletion Availability conditions for this course-module based on the completion of other
749 * course-modules (array from other course-module id to required completion state for that
750 * module) - from cached data in modinfo field
751 * @property-read array $conditionsgrade Availability conditions for this course-module based on course grades (array from
752 * grade item id to object with ->min, ->max fields) - from cached data in modinfo field
753 * @property-read array $conditionsfield Availability conditions for this course-module based on user fields
754 * @property-read bool $available True if this course-module is available to students i.e. if all availability conditions
755 * are met - obtained dynamically
756 * @property-read string $availableinfo If course-module is not available to students, this string gives information about
757 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
758 * January 2010') for display on main page - obtained dynamically
759 * @property-read bool $uservisible True if this course-module is available to the CURRENT user (for example, if current user
760 * has viewhiddenactivities capability, they can access the course-module even if it is not
761 * visible or not available, so this would be true in that case)
762 * @property-read context_module $context Module context
763 * @property-read string $modfullname Returns a localised human-readable name of the module type - calculated on request
764 * @property-read string $modplural Returns a localised human-readable name of the module type in plural form - calculated on request
765 * @property-read string $content Content to display on main (view) page - calculated on request
766 * @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
767 * @property-read string $extraclasses Extra CSS classes to add to html output for this activity on main page - calculated on request
768 * @property-read string $onclick Content of HTML on-click attribute already escaped - calculated on request
769 * @property-read mixed $customdata Optional custom data stored in modinfo cache for this activity, or null if none
770 * @property-read string $afterlink Extra HTML code to display after link - calculated on request
771 * @property-read string $afterediticons Extra HTML code to display after editing icons (e.g. more icons) - calculated on request
773 class cm_info implements IteratorAggregate {
775 * State: Only basic data from modinfo cache is available.
777 const STATE_BASIC = 0;
780 * State: In the process of building dynamic data (to avoid recursive calls to obtain_dynamic_data())
782 const STATE_BUILDING_DYNAMIC = 1;
785 * State: Dynamic data is available too.
787 const STATE_DYNAMIC = 2;
790 * State: In the process of building view data (to avoid recursive calls to obtain_view_data())
792 const STATE_BUILDING_VIEW = 3;
795 * State: View data (for course page) is available.
797 const STATE_VIEW = 4;
800 * Parent object
801 * @var course_modinfo
803 private $modinfo;
806 * Level of information stored inside this object (STATE_xx constant)
807 * @var int
809 private $state;
812 * Course-module ID - from course_modules table
813 * @var int
815 private $id;
818 * Module instance (ID within module table) - from course_modules table
819 * @var int
821 private $instance;
824 * 'ID number' from course-modules table (arbitrary text set by user) - from
825 * course_modules table
826 * @var string
828 private $idnumber;
831 * Time that this course-module was added (unix time) - from course_modules table
832 * @var int
834 private $added;
837 * This variable is not used and is included here only so it can be documented.
838 * Once the database entry is removed from course_modules, it should be deleted
839 * here too.
840 * @var int
841 * @deprecated Do not use this variable
843 private $score;
846 * Visible setting (0 or 1; if this is 0, students cannot see/access the activity) - from
847 * course_modules table
848 * @var int
850 private $visible;
853 * Old visible setting (if the entire section is hidden, the previous value for
854 * visible is stored in this field) - from course_modules table
855 * @var int
857 private $visibleold;
860 * Group mode (one of the constants NONE, SEPARATEGROUPS, or VISIBLEGROUPS) - from
861 * course_modules table
862 * @var int
864 private $groupmode;
867 * Grouping ID (0 = all groupings)
868 * @var int
870 private $groupingid;
873 * Group members only (if set to 1, only members of a suitable group see this link on the
874 * course page; 0 = everyone sees it even if they don't belong to a suitable group) - from
875 * course_modules table
876 * @var int
878 private $groupmembersonly;
881 * Indent level on course page (0 = no indent) - from course_modules table
882 * @var int
884 private $indent;
887 * Activity completion setting for this activity, COMPLETION_TRACKING_xx constant - from
888 * course_modules table
889 * @var int
891 private $completion;
894 * Set to the item number (usually 0) if completion depends on a particular
895 * grade of this activity, or null if completion does not depend on a grade - from
896 * course_modules table
897 * @var mixed
899 private $completiongradeitemnumber;
902 * 1 if 'on view' completion is enabled, 0 otherwise - from course_modules table
903 * @var int
905 private $completionview;
908 * Set to a unix time if completion of this activity is expected at a
909 * particular time, 0 if no time set - from course_modules table
910 * @var int
912 private $completionexpected;
915 * Available date for this activity (0 if not set, or set to seconds since epoch; before this
916 * date, activity does not display to students) - from course_modules table
917 * @var int
919 private $availablefrom;
922 * Available until date for this activity (0 if not set, or set to seconds since epoch; from
923 * this date, activity does not display to students) - from course_modules table
924 * @var int
926 private $availableuntil;
929 * When activity is unavailable, this field controls whether it is shown to students (0 =
930 * hide completely, 1 = show greyed out with information about when it will be available) -
931 * from course_modules table
932 * @var int
934 private $showavailability;
937 * Controls whether the description of the activity displays on the course main page (in
938 * addition to anywhere it might display within the activity itself). 0 = do not show
939 * on main page, 1 = show on main page.
940 * @var int
942 private $showdescription;
945 * Extra HTML that is put in an unhelpful part of the HTML when displaying this module in
946 * course page - from cached data in modinfo field
947 * @deprecated This is crazy, don't use it. Replaced by ->extraclasses and ->onclick
948 * @var string
950 private $extra;
953 * Name of icon to use - from cached data in modinfo field
954 * @var string
956 private $icon;
959 * Component that contains icon - from cached data in modinfo field
960 * @var string
962 private $iconcomponent;
965 * Name of module e.g. 'forum' (this is the same name as the module's main database
966 * table) - from cached data in modinfo field
967 * @var string
969 private $modname;
972 * ID of module - from course_modules table
973 * @var int
975 private $module;
978 * Name of module instance for display on page e.g. 'General discussion forum' - from cached
979 * data in modinfo field
980 * @var string
982 private $name;
985 * Section number that this course-module is in (section 0 = above the calendar, section 1
986 * = week/topic 1, etc) - from cached data in modinfo field
987 * @var int
989 private $sectionnum;
992 * Section id - from course_modules table
993 * @var int
995 private $section;
998 * Availability conditions for this course-module based on the completion of other
999 * course-modules (array from other course-module id to required completion state for that
1000 * module) - from cached data in modinfo field
1001 * @var array
1003 private $conditionscompletion;
1006 * Availability conditions for this course-module based on course grades (array from
1007 * grade item id to object with ->min, ->max fields) - from cached data in modinfo field
1008 * @var array
1010 private $conditionsgrade;
1013 * Availability conditions for this course-module based on user fields
1014 * @var array
1016 private $conditionsfield;
1019 * True if this course-module is available to students i.e. if all availability conditions
1020 * are met - obtained dynamically
1021 * @var bool
1023 private $available;
1026 * If course-module is not available to students, this string gives information about
1027 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
1028 * January 2010') for display on main page - obtained dynamically
1029 * @var string
1031 private $availableinfo;
1034 * True if this course-module is available to the CURRENT user (for example, if current user
1035 * has viewhiddenactivities capability, they can access the course-module even if it is not
1036 * visible or not available, so this would be true in that case)
1037 * @var bool
1039 private $uservisible;
1042 * @var moodle_url
1044 private $url;
1047 * @var string
1049 private $content;
1052 * @var string
1054 private $extraclasses;
1057 * @var moodle_url full external url pointing to icon image for activity
1059 private $iconurl;
1062 * @var string
1064 private $onclick;
1067 * @var mixed
1069 private $customdata;
1072 * @var string
1074 private $afterlink;
1077 * @var string
1079 private $afterediticons;
1082 * List of class read-only properties and their getter methods.
1083 * Used by magic functions __get(), __isset(), __empty()
1084 * @var array
1086 private static $standardproperties = array(
1087 'url' => 'get_url',
1088 'content' => 'get_content',
1089 'extraclasses' => 'get_extra_classes',
1090 'onclick' => 'get_on_click',
1091 'customdata' => 'get_custom_data',
1092 'afterlink' => 'get_after_link',
1093 'afterediticons' => 'get_after_edit_icons',
1094 'modfullname' => 'get_module_type_name',
1095 'modplural' => 'get_module_type_name_plural',
1096 'id' => false,
1097 'added' => false,
1098 'available' => 'get_available',
1099 'availablefrom' => false,
1100 'availableinfo' => 'get_available_info',
1101 'availableuntil' => false,
1102 'completion' => false,
1103 'completionexpected' => false,
1104 'completiongradeitemnumber' => false,
1105 'completionview' => false,
1106 'conditionscompletion' => false,
1107 'conditionsfield' => false,
1108 'conditionsgrade' => false,
1109 'context' => 'get_context',
1110 'course' => 'get_course_id',
1111 'coursegroupmode' => 'get_course_groupmode',
1112 'coursegroupmodeforce' => 'get_course_groupmodeforce',
1113 'effectivegroupmode' => 'get_effective_groupmode',
1114 'extra' => false,
1115 'groupingid' => false,
1116 'groupmembersonly' => false,
1117 'groupmode' => false,
1118 'icon' => false,
1119 'iconcomponent' => false,
1120 'idnumber' => false,
1121 'indent' => false,
1122 'instance' => false,
1123 'modname' => false,
1124 'module' => false,
1125 'name' => 'get_name',
1126 'score' => false,
1127 'section' => false,
1128 'sectionnum' => false,
1129 'showavailability' => 'get_show_availability',
1130 'showdescription' => false,
1131 'uservisible' => 'get_user_visible',
1132 'visible' => false,
1133 'visibleold' => false,
1137 * List of methods with no arguments that were public prior to Moodle 2.6.
1139 * They can still be accessed publicly via magic __call() function with no warnings
1140 * but are not listed in the class methods list.
1141 * For the consistency of the code it is better to use corresponding properties.
1143 * These methods be deprecated completely in later versions.
1145 * @var array $standardmethods
1147 private static $standardmethods = array(
1148 // Following methods are not recommended to use because there have associated read-only properties.
1149 'get_url',
1150 'get_content',
1151 'get_extra_classes',
1152 'get_on_click',
1153 'get_custom_data',
1154 'get_after_link',
1155 'get_after_edit_icons',
1156 // Method obtain_dynamic_data() should not be called from outside of this class but it was public before Moodle 2.6.
1157 'obtain_dynamic_data',
1161 * Magic method to call functions that are now declared as private now but
1162 * were public in Moodle before 2.6. Developers can access them without
1163 * any warnings but they are not listed in the class methods list.
1165 * @param string $name
1166 * @param array $arguments
1167 * @return mixed
1169 public function __call($name, $arguments) {
1170 global $CFG;
1172 if (in_array($name, self::$standardmethods)) {
1173 if ($CFG->debugdeveloper) {
1174 if ($alternative = array_search($name, self::$standardproperties)) {
1175 // All standard methods do not have arguments anyway.
1176 debugging("cm_info::$name() is deprecated, please use the property cm_info->$alternative instead.", DEBUG_DEVELOPER);
1177 } else {
1178 debugging("cm_info::$name() is deprecated and should not be used.", DEBUG_DEVELOPER);
1181 // All standard methods do not have arguments anyway.
1182 return $this->$name();
1184 throw new coding_exception("Method cm_info::{$name}() does not exist");
1188 * Magic method getter
1190 * @param string $name
1191 * @return mixed
1193 public function __get($name) {
1194 if (isset(self::$standardproperties[$name])) {
1195 if ($method = self::$standardproperties[$name]) {
1196 return $this->$method();
1197 } else {
1198 return $this->$name;
1200 } else {
1201 debugging('Invalid cm_info property accessed: '.$name);
1202 return null;
1207 * Implementation of IteratorAggregate::getIterator(), allows to cycle through properties
1208 * and use {@link convert_to_array()}
1210 * @return ArrayIterator
1212 public function getIterator() {
1213 // Make sure dynamic properties are retrieved prior to view properties.
1214 $this->obtain_dynamic_data();
1215 $ret = array();
1216 foreach (self::$standardproperties as $key => $unused) {
1217 $ret[$key] = $this->__get($key);
1219 return new ArrayIterator($ret);
1223 * Magic method for function isset()
1225 * @param string $name
1226 * @return bool
1228 public function __isset($name) {
1229 if (isset(self::$standardproperties[$name])) {
1230 $value = $this->__get($name);
1231 return isset($value);
1233 return false;
1237 * Magic method for function empty()
1239 * @param string $name
1240 * @return bool
1242 public function __empty($name) {
1243 if (isset(self::$standardproperties[$name])) {
1244 $value = $this->__get($name);
1245 return empty($value);
1247 return true;
1251 * Magic method setter
1253 * Will display the developer warning when trying to set/overwrite property.
1255 * @param string $name
1256 * @param mixed $value
1258 public function __set($name, $value) {
1259 debugging("It is not allowed to set the property cm_info::\${$name}", DEBUG_DEVELOPER);
1263 * @return bool True if this module has a 'view' page that should be linked to in navigation
1264 * etc (note: modules may still have a view.php file, but return false if this is not
1265 * intended to be linked to from 'normal' parts of the interface; this is what label does).
1267 public function has_view() {
1268 return !is_null($this->url);
1272 * @return moodle_url URL to link to for this module, or null if it doesn't have a view page
1274 private function get_url() {
1275 $this->obtain_dynamic_data();
1276 return $this->url;
1280 * Obtains content to display on main (view) page.
1281 * Note: Will collect view data, if not already obtained.
1282 * @return string Content to display on main page below link, or empty string if none
1284 private function get_content() {
1285 $this->obtain_view_data();
1286 return $this->content;
1290 * Returns the content to display on course/overview page, formatted and passed through filters
1292 * if $options['context'] is not specified, the module context is used
1294 * @param array|stdClass $options formatting options, see {@link format_text()}
1295 * @return string
1297 public function get_formatted_content($options = array()) {
1298 $this->obtain_view_data();
1299 if (empty($this->content)) {
1300 return '';
1302 // Improve filter performance by preloading filter setttings for all
1303 // activities on the course (this does nothing if called multiple
1304 // times)
1305 filter_preload_activities($this->get_modinfo());
1307 $options = (array)$options;
1308 if (!isset($options['context'])) {
1309 $options['context'] = $this->get_context();
1311 return format_text($this->content, FORMAT_HTML, $options);
1315 * Getter method for property $name, ensures that dynamic data is obtained.
1316 * @return string
1318 private function get_name() {
1319 $this->obtain_dynamic_data();
1320 return $this->name;
1324 * Returns the name to display on course/overview page, formatted and passed through filters
1326 * if $options['context'] is not specified, the module context is used
1328 * @param array|stdClass $options formatting options, see {@link format_string()}
1329 * @return string
1331 public function get_formatted_name($options = array()) {
1332 $options = (array)$options;
1333 if (!isset($options['context'])) {
1334 $options['context'] = $this->get_context();
1336 return format_string($this->get_name(), true, $options);
1340 * Note: Will collect view data, if not already obtained.
1341 * @return string Extra CSS classes to add to html output for this activity on main page
1343 private function get_extra_classes() {
1344 $this->obtain_view_data();
1345 return $this->extraclasses;
1349 * @return string Content of HTML on-click attribute. This string will be used literally
1350 * as a string so should be pre-escaped.
1352 private function get_on_click() {
1353 // Does not need view data; may be used by navigation
1354 $this->obtain_dynamic_data();
1355 return $this->onclick;
1358 * @return mixed Optional custom data stored in modinfo cache for this activity, or null if none
1360 private function get_custom_data() {
1361 return $this->customdata;
1365 * Note: Will collect view data, if not already obtained.
1366 * @return string Extra HTML code to display after link
1368 private function get_after_link() {
1369 $this->obtain_view_data();
1370 return $this->afterlink;
1374 * Note: Will collect view data, if not already obtained.
1375 * @return string Extra HTML code to display after editing icons (e.g. more icons)
1377 private function get_after_edit_icons() {
1378 $this->obtain_view_data();
1379 return $this->afterediticons;
1383 * @param moodle_core_renderer $output Output render to use, or null for default (global)
1384 * @return moodle_url Icon URL for a suitable icon to put beside this cm
1386 public function get_icon_url($output = null) {
1387 global $OUTPUT;
1388 $this->obtain_dynamic_data();
1389 if (!$output) {
1390 $output = $OUTPUT;
1392 // Support modules setting their own, external, icon image
1393 if (!empty($this->iconurl)) {
1394 $icon = $this->iconurl;
1396 // Fallback to normal local icon + component procesing
1397 } else if (!empty($this->icon)) {
1398 if (substr($this->icon, 0, 4) === 'mod/') {
1399 list($modname, $iconname) = explode('/', substr($this->icon, 4), 2);
1400 $icon = $output->pix_url($iconname, $modname);
1401 } else {
1402 if (!empty($this->iconcomponent)) {
1403 // Icon has specified component
1404 $icon = $output->pix_url($this->icon, $this->iconcomponent);
1405 } else {
1406 // Icon does not have specified component, use default
1407 $icon = $output->pix_url($this->icon);
1410 } else {
1411 $icon = $output->pix_url('icon', $this->modname);
1413 return $icon;
1417 * Returns a localised human-readable name of the module type
1419 * @param bool $plural return plural form
1420 * @return string
1422 public function get_module_type_name($plural = false) {
1423 $modnames = get_module_types_names($plural);
1424 if (isset($modnames[$this->modname])) {
1425 return $modnames[$this->modname];
1426 } else {
1427 return null;
1432 * Returns a localised human-readable name of the module type in plural form - calculated on request
1434 * @return string
1436 private function get_module_type_name_plural() {
1437 return $this->get_module_type_name(true);
1441 * @return course_modinfo Modinfo object that this came from
1443 public function get_modinfo() {
1444 return $this->modinfo;
1448 * Returns course object that was used in the first {@link get_fast_modinfo()} call.
1450 * It may not contain all fields from DB table {course} but always has at least the following:
1451 * id,shortname,fullname,format,enablecompletion,groupmode,groupmodeforce,cacherev
1453 * If the course object lacks the field you need you can use the global
1454 * function {@link get_course()} that will save extra query if you access
1455 * current course or frontpage course.
1457 * @return stdClass
1459 public function get_course() {
1460 return $this->modinfo->get_course();
1464 * Returns course id for which the modinfo was generated.
1466 * @return int
1468 private function get_course_id() {
1469 return $this->modinfo->get_course_id();
1473 * Returns group mode used for the course containing the module
1475 * @return int one of constants NOGROUPS, SEPARATEGROUPS, VISIBLEGROUPS
1477 private function get_course_groupmode() {
1478 return $this->modinfo->get_course()->groupmode;
1482 * Returns whether group mode is forced for the course containing the module
1484 * @return bool
1486 private function get_course_groupmodeforce() {
1487 return $this->modinfo->get_course()->groupmodeforce;
1491 * Returns effective groupmode of the module that may be overwritten by forced course groupmode.
1493 * @return int one of constants NOGROUPS, SEPARATEGROUPS, VISIBLEGROUPS
1495 private function get_effective_groupmode() {
1496 $groupmode = $this->groupmode;
1497 if ($this->modinfo->get_course()->groupmodeforce) {
1498 $groupmode = $this->modinfo->get_course()->groupmode;
1499 if ($groupmode != NOGROUPS && !plugin_supports('mod', $this->modname, FEATURE_GROUPS, 0)) {
1500 $groupmode = NOGROUPS;
1503 return $groupmode;
1507 * @return context_module Current module context
1509 private function get_context() {
1510 return context_module::instance($this->id);
1513 // Set functions
1514 ////////////////
1517 * Sets content to display on course view page below link (if present).
1518 * @param string $content New content as HTML string (empty string if none)
1519 * @return void
1521 public function set_content($content) {
1522 $this->content = $content;
1526 * Sets extra classes to include in CSS.
1527 * @param string $extraclasses Extra classes (empty string if none)
1528 * @return void
1530 public function set_extra_classes($extraclasses) {
1531 $this->extraclasses = $extraclasses;
1535 * Sets the external full url that points to the icon being used
1536 * by the activity. Useful for external-tool modules (lti...)
1537 * If set, takes precedence over $icon and $iconcomponent
1539 * @param moodle_url $iconurl full external url pointing to icon image for activity
1540 * @return void
1542 public function set_icon_url(moodle_url $iconurl) {
1543 $this->iconurl = $iconurl;
1547 * Sets value of on-click attribute for JavaScript.
1548 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1549 * @param string $onclick New onclick attribute which should be HTML-escaped
1550 * (empty string if none)
1551 * @return void
1553 public function set_on_click($onclick) {
1554 $this->check_not_view_only();
1555 $this->onclick = $onclick;
1559 * Sets HTML that displays after link on course view page.
1560 * @param string $afterlink HTML string (empty string if none)
1561 * @return void
1563 public function set_after_link($afterlink) {
1564 $this->afterlink = $afterlink;
1568 * Sets HTML that displays after edit icons on course view page.
1569 * @param string $afterediticons HTML string (empty string if none)
1570 * @return void
1572 public function set_after_edit_icons($afterediticons) {
1573 $this->afterediticons = $afterediticons;
1577 * Changes the name (text of link) for this module instance.
1578 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1579 * @param string $name Name of activity / link text
1580 * @return void
1582 public function set_name($name) {
1583 if ($this->state < self::STATE_BUILDING_DYNAMIC) {
1584 $this->update_user_visible();
1586 $this->name = $name;
1590 * Turns off the view link for this module instance.
1591 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1592 * @return void
1594 public function set_no_view_link() {
1595 $this->check_not_view_only();
1596 $this->url = null;
1600 * Sets the 'uservisible' flag. This can be used (by setting false) to prevent access and
1601 * display of this module link for the current user.
1602 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1603 * @param bool $uservisible
1604 * @return void
1606 public function set_user_visible($uservisible) {
1607 $this->check_not_view_only();
1608 $this->uservisible = $uservisible;
1612 * Sets the 'available' flag and related details. This flag is normally used to make
1613 * course modules unavailable until a certain date or condition is met. (When a course
1614 * module is unavailable, it is still visible to users who have viewhiddenactivities
1615 * permission.)
1617 * When this is function is called, user-visible status is recalculated automatically.
1619 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1620 * @param bool $available False if this item is not 'available'
1621 * @param int $showavailability 0 = do not show this item at all if it's not available,
1622 * 1 = show this item greyed out with the following message
1623 * @param string $availableinfo Information about why this is not available which displays
1624 * to those who have viewhiddenactivities, and to everyone if showavailability is set;
1625 * note that this function replaces the existing data (if any)
1626 * @return void
1628 public function set_available($available, $showavailability=0, $availableinfo='') {
1629 $this->check_not_view_only();
1630 $this->available = $available;
1631 $this->showavailability = $showavailability;
1632 $this->availableinfo = $availableinfo;
1633 $this->update_user_visible();
1637 * Some set functions can only be called from _cm_info_dynamic and not _cm_info_view.
1638 * This is because they may affect parts of this object which are used on pages other
1639 * than the view page (e.g. in the navigation block, or when checking access on
1640 * module pages).
1641 * @return void
1643 private function check_not_view_only() {
1644 if ($this->state >= self::STATE_DYNAMIC) {
1645 throw new coding_exception('Cannot set this data from _cm_info_view because it may ' .
1646 'affect other pages as well as view');
1651 * Constructor should not be called directly; use {@link get_fast_modinfo()}
1653 * @param course_modinfo $modinfo Parent object
1654 * @param stdClass $notused1 Argument not used
1655 * @param stdClass $mod Module object from the modinfo field of course table
1656 * @param stdClass $notused2 Argument not used
1658 public function __construct(course_modinfo $modinfo, $notused1, $mod, $notused2) {
1659 $this->modinfo = $modinfo;
1661 $this->id = $mod->cm;
1662 $this->instance = $mod->id;
1663 $this->modname = $mod->mod;
1664 $this->idnumber = isset($mod->idnumber) ? $mod->idnumber : '';
1665 $this->name = $mod->name;
1666 $this->visible = $mod->visible;
1667 $this->sectionnum = $mod->section; // Note weirdness with name here
1668 $this->groupmode = isset($mod->groupmode) ? $mod->groupmode : 0;
1669 $this->groupingid = isset($mod->groupingid) ? $mod->groupingid : 0;
1670 $this->groupmembersonly = isset($mod->groupmembersonly) ? $mod->groupmembersonly : 0;
1671 $this->indent = isset($mod->indent) ? $mod->indent : 0;
1672 $this->extra = isset($mod->extra) ? $mod->extra : '';
1673 $this->extraclasses = isset($mod->extraclasses) ? $mod->extraclasses : '';
1674 // iconurl may be stored as either string or instance of moodle_url.
1675 $this->iconurl = isset($mod->iconurl) ? new moodle_url($mod->iconurl) : '';
1676 $this->onclick = isset($mod->onclick) ? $mod->onclick : '';
1677 $this->content = isset($mod->content) ? $mod->content : '';
1678 $this->icon = isset($mod->icon) ? $mod->icon : '';
1679 $this->iconcomponent = isset($mod->iconcomponent) ? $mod->iconcomponent : '';
1680 $this->customdata = isset($mod->customdata) ? $mod->customdata : '';
1681 $this->showdescription = isset($mod->showdescription) ? $mod->showdescription : 0;
1682 $this->state = self::STATE_BASIC;
1684 $this->section = isset($mod->sectionid) ? $mod->sectionid : 0;
1685 $this->module = isset($mod->module) ? $mod->module : 0;
1686 $this->added = isset($mod->added) ? $mod->added : 0;
1687 $this->score = isset($mod->score) ? $mod->score : 0;
1688 $this->visibleold = isset($mod->visibleold) ? $mod->visibleold : 0;
1690 // Note: it saves effort and database space to always include the
1691 // availability and completion fields, even if availability or completion
1692 // are actually disabled
1693 $this->completion = isset($mod->completion) ? $mod->completion : 0;
1694 $this->completiongradeitemnumber = isset($mod->completiongradeitemnumber)
1695 ? $mod->completiongradeitemnumber : null;
1696 $this->completionview = isset($mod->completionview)
1697 ? $mod->completionview : 0;
1698 $this->completionexpected = isset($mod->completionexpected)
1699 ? $mod->completionexpected : 0;
1700 $this->showavailability = isset($mod->showavailability) ? $mod->showavailability : 0;
1701 $this->availablefrom = isset($mod->availablefrom) ? $mod->availablefrom : 0;
1702 $this->availableuntil = isset($mod->availableuntil) ? $mod->availableuntil : 0;
1703 $this->conditionscompletion = isset($mod->conditionscompletion)
1704 ? $mod->conditionscompletion : array();
1705 $this->conditionsgrade = isset($mod->conditionsgrade)
1706 ? $mod->conditionsgrade : array();
1707 $this->conditionsfield = isset($mod->conditionsfield)
1708 ? $mod->conditionsfield : array();
1710 static $modviews = array();
1711 if (!isset($modviews[$this->modname])) {
1712 $modviews[$this->modname] = !plugin_supports('mod', $this->modname,
1713 FEATURE_NO_VIEW_LINK);
1715 $this->url = $modviews[$this->modname]
1716 ? new moodle_url('/mod/' . $this->modname . '/view.php', array('id'=>$this->id))
1717 : null;
1721 * If dynamic data for this course-module is not yet available, gets it.
1723 * This function is automatically called when requesting any course_modinfo property
1724 * that can be modified by modules (have a set_xxx method).
1726 * Dynamic data is data which does not come directly from the cache but is calculated at
1727 * runtime based on the current user. Primarily this concerns whether the user can access
1728 * the module or not.
1730 * As part of this function, the module's _cm_info_dynamic function from its lib.php will
1731 * be called (if it exists).
1732 * @return void
1734 private function obtain_dynamic_data() {
1735 global $CFG;
1736 $userid = $this->modinfo->get_user_id();
1737 if ($this->state >= self::STATE_BUILDING_DYNAMIC || $userid == -1) {
1738 return;
1740 $this->state = self::STATE_BUILDING_DYNAMIC;
1742 if (!empty($CFG->enableavailability)) {
1743 require_once($CFG->libdir. '/conditionlib.php');
1744 // Get availability information
1745 $ci = new condition_info($this);
1746 // Note that the modinfo currently available only includes minimal details (basic data)
1747 // but we know that this function does not need anything more than basic data.
1748 $this->available = $ci->is_available($this->availableinfo, true,
1749 $userid, $this->modinfo);
1751 // Check parent section
1752 $parentsection = $this->modinfo->get_section_info($this->sectionnum);
1753 if (!$parentsection->available) {
1754 // Do not store info from section here, as that is already
1755 // presented from the section (if appropriate) - just change
1756 // the flag
1757 $this->available = false;
1759 } else {
1760 $this->available = true;
1763 // Update visible state for current user
1764 $this->update_user_visible();
1766 // Let module make dynamic changes at this point
1767 $this->call_mod_function('cm_info_dynamic');
1768 $this->state = self::STATE_DYNAMIC;
1772 * Getter method for property $uservisible, ensures that dynamic data is retrieved.
1773 * @return bool
1775 private function get_user_visible() {
1776 $this->obtain_dynamic_data();
1777 return $this->uservisible;
1781 * Getter method for property $available, ensures that dynamic data is retrieved
1782 * @return bool
1784 private function get_available() {
1785 $this->obtain_dynamic_data();
1786 return $this->available;
1790 * Getter method for property $showavailability, ensures that dynamic data is retrieved
1791 * @return int
1793 private function get_show_availability() {
1794 $this->obtain_dynamic_data();
1795 return $this->showavailability;
1799 * Getter method for property $availableinfo, ensures that dynamic data is retrieved
1800 * @return type
1802 private function get_available_info() {
1803 $this->obtain_dynamic_data();
1804 return $this->availableinfo;
1808 * Works out whether activity is available to the current user
1810 * If the activity is unavailable, additional checks are required to determine if its hidden or greyed out
1812 * @see is_user_access_restricted_by_group()
1813 * @see is_user_access_restricted_by_conditional_access()
1814 * @return void
1816 private function update_user_visible() {
1817 $userid = $this->modinfo->get_user_id();
1818 if ($userid == -1) {
1819 return null;
1821 $this->uservisible = true;
1823 // If the user cannot access the activity set the uservisible flag to false.
1824 // Additional checks are required to determine whether the activity is entirely hidden or just greyed out.
1825 if ((!$this->visible or !$this->get_available()) and
1826 !has_capability('moodle/course:viewhiddenactivities', $this->get_context(), $userid)) {
1828 $this->uservisible = false;
1831 // Check group membership.
1832 if ($this->is_user_access_restricted_by_group() ||
1833 $this->is_user_access_restricted_by_capability()) {
1835 $this->uservisible = false;
1836 // Ensure activity is completely hidden from the user.
1837 $this->showavailability = 0;
1842 * Checks whether the module's group settings restrict the current user's access
1844 * @return bool True if the user access is restricted
1846 public function is_user_access_restricted_by_group() {
1847 global $CFG;
1849 if (!empty($CFG->enablegroupmembersonly) and !empty($this->groupmembersonly)) {
1850 $userid = $this->modinfo->get_user_id();
1851 if ($userid == -1) {
1852 return null;
1854 if (!has_capability('moodle/site:accessallgroups', $this->get_context(), $userid)) {
1855 // If the activity has 'group members only' and you don't have accessallgroups...
1856 $groups = $this->modinfo->get_groups($this->groupingid);
1857 if (empty($groups)) {
1858 // ...and you don't belong to a group, then set it so you can't see/access it
1859 return true;
1863 return false;
1867 * Checks whether mod/...:view capability restricts the current user's access.
1869 * @return bool True if the user access is restricted.
1871 public function is_user_access_restricted_by_capability() {
1872 $userid = $this->modinfo->get_user_id();
1873 if ($userid == -1) {
1874 return null;
1876 $capability = 'mod/' . $this->modname . ':view';
1877 $capabilityinfo = get_capability_info($capability);
1878 if (!$capabilityinfo) {
1879 // Capability does not exist, no one is prevented from seeing the activity.
1880 return false;
1883 // You are blocked if you don't have the capability.
1884 return !has_capability($capability, $this->get_context(), $userid);
1888 * Checks whether the module's conditional access settings mean that the user cannot see the activity at all
1890 * @return bool True if the user cannot see the module. False if the activity is either available or should be greyed out.
1892 public function is_user_access_restricted_by_conditional_access() {
1893 global $CFG;
1895 if (empty($CFG->enableavailability)) {
1896 return false;
1899 $userid = $this->modinfo->get_user_id();
1900 if ($userid == -1) {
1901 return null;
1904 // If module will always be visible anyway (but greyed out), don't bother checking anything else
1905 if ($this->get_show_availability() == CONDITION_STUDENTVIEW_SHOW) {
1906 return false;
1909 // Can the user see hidden modules?
1910 if (has_capability('moodle/course:viewhiddenactivities', $this->get_context(), $userid)) {
1911 return false;
1914 // Is the module hidden due to unmet conditions?
1915 if (!$this->get_available()) {
1916 return true;
1919 return false;
1923 * Calls a module function (if exists), passing in one parameter: this object.
1924 * @param string $type Name of function e.g. if this is 'grooblezorb' and the modname is
1925 * 'forum' then it will try to call 'mod_forum_grooblezorb' or 'forum_grooblezorb'
1926 * @return void
1928 private function call_mod_function($type) {
1929 global $CFG;
1930 $libfile = $CFG->dirroot . '/mod/' . $this->modname . '/lib.php';
1931 if (file_exists($libfile)) {
1932 include_once($libfile);
1933 $function = 'mod_' . $this->modname . '_' . $type;
1934 if (function_exists($function)) {
1935 $function($this);
1936 } else {
1937 $function = $this->modname . '_' . $type;
1938 if (function_exists($function)) {
1939 $function($this);
1946 * If view data for this course-module is not yet available, obtains it.
1948 * This function is automatically called if any of the functions (marked) which require
1949 * view data are called.
1951 * View data is data which is needed only for displaying the course main page (& any similar
1952 * functionality on other pages) but is not needed in general. Obtaining view data may have
1953 * a performance cost.
1955 * As part of this function, the module's _cm_info_view function from its lib.php will
1956 * be called (if it exists).
1957 * @return void
1959 private function obtain_view_data() {
1960 if ($this->state >= self::STATE_BUILDING_VIEW || $this->modinfo->get_user_id() == -1) {
1961 return;
1963 $this->obtain_dynamic_data();
1964 $this->state = self::STATE_BUILDING_VIEW;
1966 // Let module make changes at this point
1967 $this->call_mod_function('cm_info_view');
1968 $this->state = self::STATE_VIEW;
1974 * Returns reference to full info about modules in course (including visibility).
1975 * Cached and as fast as possible (0 or 1 db query).
1977 * use get_fast_modinfo($courseid, 0, true) to reset the static cache for particular course
1978 * use get_fast_modinfo(0, 0, true) to reset the static cache for all courses
1980 * use rebuild_course_cache($courseid, true) to reset the application AND static cache
1981 * for particular course when it's contents has changed
1983 * @param int|stdClass $courseorid object from DB table 'course' (must have field 'id'
1984 * and recommended to have field 'cacherev') or just a course id. Just course id
1985 * is enough when calling get_fast_modinfo() for current course or site or when
1986 * calling for any other course for the second time.
1987 * @param int $userid User id to populate 'availble' and 'uservisible' attributes of modules and sections.
1988 * Set to 0 for current user (default). Set to -1 to avoid calculation of dynamic user-depended data.
1989 * @param bool $resetonly whether we want to get modinfo or just reset the cache
1990 * @return course_modinfo|null Module information for course, or null if resetting
1991 * @throws moodle_exception when course is not found (nothing is thrown if resetting)
1993 function get_fast_modinfo($courseorid, $userid = 0, $resetonly = false) {
1994 // compartibility with syntax prior to 2.4:
1995 if ($courseorid === 'reset') {
1996 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);
1997 $courseorid = 0;
1998 $resetonly = true;
2001 // Function get_fast_modinfo() can never be called during upgrade unless it is used for clearing cache only.
2002 if (!$resetonly) {
2003 upgrade_ensure_not_running();
2006 // Function is called with $reset = true
2007 if ($resetonly) {
2008 course_modinfo::clear_instance_cache($courseorid);
2009 return null;
2012 // Function is called with $reset = false, retrieve modinfo
2013 return course_modinfo::instance($courseorid, $userid);
2017 * Rebuilds or resets the cached list of course activities stored in MUC.
2019 * rebuild_course_cache() must NEVER be called from lib/db/upgrade.php.
2020 * At the same time course cache may ONLY be cleared using this function in
2021 * upgrade scripts of plugins.
2023 * During the bulk operations if it is necessary to reset cache of multiple
2024 * courses it is enough to call {@link increment_revision_number()} for the
2025 * table 'course' and field 'cacherev' specifying affected courses in select.
2027 * Cached course information is stored in MUC core/coursemodinfo and is
2028 * validated with the DB field {course}.cacherev
2030 * @global moodle_database $DB
2031 * @param int $courseid id of course to rebuild, empty means all
2032 * @param boolean $clearonly only clear the cache, gets rebuild automatically on the fly.
2033 * Recommended to set to true to avoid unnecessary multiple rebuilding.
2035 function rebuild_course_cache($courseid=0, $clearonly=false) {
2036 global $COURSE, $SITE, $DB, $CFG;
2038 // Function rebuild_course_cache() can not be called during upgrade unless it's clear only.
2039 if (!$clearonly && !upgrade_ensure_not_running(true)) {
2040 $clearonly = true;
2043 // Destroy navigation caches
2044 navigation_cache::destroy_volatile_caches();
2046 if (class_exists('format_base')) {
2047 // if file containing class is not loaded, there is no cache there anyway
2048 format_base::reset_course_cache($courseid);
2051 $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
2052 if (empty($courseid)) {
2053 // Clearing caches for all courses.
2054 increment_revision_number('course', 'cacherev', '');
2055 $cachecoursemodinfo->purge();
2056 course_modinfo::clear_instance_cache();
2057 // Update global values too.
2058 $sitecacherev = $DB->get_field('course', 'cacherev', array('id' => SITEID));
2059 $SITE->cachrev = $sitecacherev;
2060 if ($COURSE->id == SITEID) {
2061 $COURSE->cacherev = $sitecacherev;
2062 } else {
2063 $COURSE->cacherev = $DB->get_field('course', 'cacherev', array('id' => $COURSE->id));
2065 } else {
2066 // Clearing cache for one course, make sure it is deleted from user request cache as well.
2067 increment_revision_number('course', 'cacherev', 'id = :id', array('id' => $courseid));
2068 $cachecoursemodinfo->delete($courseid);
2069 course_modinfo::clear_instance_cache($courseid);
2070 // Update global values too.
2071 if ($courseid == $COURSE->id || $courseid == $SITE->id) {
2072 $cacherev = $DB->get_field('course', 'cacherev', array('id' => $courseid));
2073 if ($courseid == $COURSE->id) {
2074 $COURSE->cacherev = $cacherev;
2076 if ($courseid == $SITE->id) {
2077 $SITE->cachrev = $cacherev;
2082 if ($clearonly) {
2083 return;
2086 if ($courseid) {
2087 $select = array('id'=>$courseid);
2088 } else {
2089 $select = array();
2090 core_php_time_limit::raise(); // this could take a while! MDL-10954
2093 $rs = $DB->get_recordset("course", $select,'','id,'.join(',', course_modinfo::$cachedfields));
2094 // Rebuild cache for each course.
2095 foreach ($rs as $course) {
2096 course_modinfo::build_course_cache($course);
2098 $rs->close();
2103 * Class that is the return value for the _get_coursemodule_info module API function.
2105 * Note: For backward compatibility, you can also return a stdclass object from that function.
2106 * The difference is that the stdclass object may contain an 'extra' field (deprecated,
2107 * use extraclasses and onclick instead). The stdclass object may not contain
2108 * the new fields defined here (content, extraclasses, customdata).
2110 class cached_cm_info {
2112 * Name (text of link) for this activity; Leave unset to accept default name
2113 * @var string
2115 public $name;
2118 * Name of icon for this activity. Normally, this should be used together with $iconcomponent
2119 * to define the icon, as per pix_url function.
2120 * For backward compatibility, if this value is of the form 'mod/forum/icon' then an icon
2121 * within that module will be used.
2122 * @see cm_info::get_icon_url()
2123 * @see renderer_base::pix_url()
2124 * @var string
2126 public $icon;
2129 * Component for icon for this activity, as per pix_url; leave blank to use default 'moodle'
2130 * component
2131 * @see renderer_base::pix_url()
2132 * @var string
2134 public $iconcomponent;
2137 * HTML content to be displayed on the main page below the link (if any) for this course-module
2138 * @var string
2140 public $content;
2143 * Custom data to be stored in modinfo for this activity; useful if there are cases when
2144 * internal information for this activity type needs to be accessible from elsewhere on the
2145 * course without making database queries. May be of any type but should be short.
2146 * @var mixed
2148 public $customdata;
2151 * Extra CSS class or classes to be added when this activity is displayed on the main page;
2152 * space-separated string
2153 * @var string
2155 public $extraclasses;
2158 * External URL image to be used by activity as icon, useful for some external-tool modules
2159 * like lti. If set, takes precedence over $icon and $iconcomponent
2160 * @var $moodle_url
2162 public $iconurl;
2165 * Content of onclick JavaScript; escaped HTML to be inserted as attribute value
2166 * @var string
2168 public $onclick;
2173 * Data about a single section on a course. This contains the fields from the
2174 * course_sections table, plus additional data when required.
2176 * @property-read int $id Section ID - from course_sections table
2177 * @property-read int $course Course ID - from course_sections table
2178 * @property-read int $section Section number - from course_sections table
2179 * @property-read string $name Section name if specified - from course_sections table
2180 * @property-read int $visible Section visibility (1 = visible) - from course_sections table
2181 * @property-read string $summary Section summary text if specified - from course_sections table
2182 * @property-read int $summaryformat Section summary text format (FORMAT_xx constant) - from course_sections table
2183 * @property-read int $showavailability When section is unavailable, this field controls whether it is shown to students (0 =
2184 * hide completely, 1 = show greyed out with information about when it will be available) -
2185 * from course_sections table
2186 * @property-read int $availablefrom Available date for this section (0 if not set, or set to seconds since epoch;
2187 * before this date, section does not display to students) - from course_sections table
2188 * @property-read int $availableuntil Available until date for this section (0 if not set, or set to seconds since epoch;
2189 * from this date, section does not display to students) - from course_sections table
2190 * @property-read int $groupingid If section is restricted to users of a particular grouping, this is its id (0 if not set) -
2191 * from course_sections table
2192 * @property-read array $conditionscompletion Availability conditions for this section based on the completion of
2193 * course-modules (array from course-module id to required completion state
2194 * for that module) - from cached data in sectioncache field
2195 * @property-read array $conditionsgrade Availability conditions for this section based on course grades (array from
2196 * grade item id to object with ->min, ->max fields) - from cached data in
2197 * sectioncache field
2198 * @property-read array $conditionsfield Availability conditions for this section based on user fields
2199 * @property-read bool $available True if this section is available to the given user i.e. if all availability conditions
2200 * are met - obtained dynamically
2201 * @property-read string $availableinfo If section is not available to some users, this string gives information about
2202 * availability which can be displayed to students and/or staff (e.g. 'Available from 3 January 2010')
2203 * for display on main page - obtained dynamically
2204 * @property-read bool $uservisible True if this section is available to the given user (for example, if current user
2205 * has viewhiddensections capability, they can access the section even if it is not
2206 * visible or not available, so this would be true in that case) - obtained dynamically
2207 * @property-read string $sequence Comma-separated list of all modules in the section. Note, this field may not exactly
2208 * match course_sections.sequence if later has references to non-existing modules or not modules of not available module types.
2210 class section_info implements IteratorAggregate {
2212 * Section ID - from course_sections table
2213 * @var int
2215 private $_id;
2218 * Section number - from course_sections table
2219 * @var int
2221 private $_section;
2224 * Section name if specified - from course_sections table
2225 * @var string
2227 private $_name;
2230 * Section visibility (1 = visible) - from course_sections table
2231 * @var int
2233 private $_visible;
2236 * Section summary text if specified - from course_sections table
2237 * @var string
2239 private $_summary;
2242 * Section summary text format (FORMAT_xx constant) - from course_sections table
2243 * @var int
2245 private $_summaryformat;
2248 * When section is unavailable, this field controls whether it is shown to students (0 =
2249 * hide completely, 1 = show greyed out with information about when it will be available) -
2250 * from course_sections table
2251 * @var int
2253 private $_showavailability;
2256 * Available date for this section (0 if not set, or set to seconds since epoch; before this
2257 * date, section does not display to students) - from course_sections table
2258 * @var int
2260 private $_availablefrom;
2263 * Available until date for this section (0 if not set, or set to seconds since epoch; from
2264 * this date, section does not display to students) - from course_sections table
2265 * @var int
2267 private $_availableuntil;
2270 * If section is restricted to users of a particular grouping, this is its id
2271 * (0 if not set) - from course_sections table
2272 * @var int
2274 private $_groupingid;
2277 * Availability conditions for this section based on the completion of
2278 * course-modules (array from course-module id to required completion state
2279 * for that module) - from cached data in sectioncache field
2280 * @var array
2282 private $_conditionscompletion;
2285 * Availability conditions for this section based on course grades (array from
2286 * grade item id to object with ->min, ->max fields) - from cached data in
2287 * sectioncache field
2288 * @var array
2290 private $_conditionsgrade;
2293 * Availability conditions for this section based on user fields
2294 * @var array
2296 private $_conditionsfield;
2299 * True if this section is available to students i.e. if all availability conditions
2300 * are met - obtained dynamically on request, see function {@link section_info::get_available()}
2301 * @var bool|null
2303 private $_available;
2306 * If section is not available to some users, this string gives information about
2307 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
2308 * January 2010') for display on main page - obtained dynamically on request, see
2309 * function {@link section_info::get_availableinfo()}
2310 * @var string
2312 private $_availableinfo;
2315 * True if this section is available to the CURRENT user (for example, if current user
2316 * has viewhiddensections capability, they can access the section even if it is not
2317 * visible or not available, so this would be true in that case) - obtained dynamically
2318 * on request, see function {@link section_info::get_uservisible()}
2319 * @var bool|null
2321 private $_uservisible;
2324 * Default values for sectioncache fields; if a field has this value, it won't
2325 * be stored in the sectioncache cache, to save space. Checks are done by ===
2326 * which means values must all be strings.
2327 * @var array
2329 private static $sectioncachedefaults = array(
2330 'name' => null,
2331 'summary' => '',
2332 'summaryformat' => '1', // FORMAT_HTML, but must be a string
2333 'visible' => '1',
2334 'showavailability' => '0',
2335 'availablefrom' => '0',
2336 'availableuntil' => '0',
2337 'groupingid' => '0',
2341 * Stores format options that have been cached when building 'coursecache'
2342 * When the format option is requested we look first if it has been cached
2343 * @var array
2345 private $cachedformatoptions = array();
2348 * Stores the list of all possible section options defined in each used course format.
2349 * @var array
2351 static private $sectionformatoptions = array();
2354 * Stores the modinfo object passed in constructor, may be used when requesting
2355 * dynamically obtained attributes such as available, availableinfo, uservisible.
2356 * Also used to retrun information about current course or user.
2357 * @var course_modinfo
2359 private $modinfo;
2362 * Constructs object from database information plus extra required data.
2363 * @param object $data Array entry from cached sectioncache
2364 * @param int $number Section number (array key)
2365 * @param int $notused1 argument not used (informaion is available in $modinfo)
2366 * @param int $notused2 argument not used (informaion is available in $modinfo)
2367 * @param course_modinfo $modinfo Owner (needed for checking availability)
2368 * @param int $notused3 argument not used (informaion is available in $modinfo)
2370 public function __construct($data, $number, $notused1, $notused2, $modinfo, $notused3) {
2371 global $CFG;
2372 require_once($CFG->dirroot.'/course/lib.php');
2374 // Data that is always present
2375 $this->_id = $data->id;
2377 $defaults = self::$sectioncachedefaults +
2378 array('conditionscompletion' => array(),
2379 'conditionsgrade' => array(),
2380 'conditionsfield' => array());
2382 // Data that may use default values to save cache size
2383 foreach ($defaults as $field => $value) {
2384 if (isset($data->{$field})) {
2385 $this->{'_'.$field} = $data->{$field};
2386 } else {
2387 $this->{'_'.$field} = $value;
2391 // Other data from constructor arguments.
2392 $this->_section = $number;
2393 $this->modinfo = $modinfo;
2395 // Cached course format data.
2396 $course = $modinfo->get_course();
2397 if (!isset(self::$sectionformatoptions[$course->format])) {
2398 // Store list of section format options defined in each used course format.
2399 // They do not depend on particular course but only on its format.
2400 self::$sectionformatoptions[$course->format] =
2401 course_get_format($course)->section_format_options();
2403 foreach (self::$sectionformatoptions[$course->format] as $field => $option) {
2404 if (!empty($option['cache'])) {
2405 if (isset($data->{$field})) {
2406 $this->cachedformatoptions[$field] = $data->{$field};
2407 } else if (array_key_exists('cachedefault', $option)) {
2408 $this->cachedformatoptions[$field] = $option['cachedefault'];
2415 * Magic method to check if the property is set
2417 * @param string $name name of the property
2418 * @return bool
2420 public function __isset($name) {
2421 if (method_exists($this, 'get_'.$name) ||
2422 property_exists($this, '_'.$name) ||
2423 array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
2424 $value = $this->__get($name);
2425 return isset($value);
2427 return false;
2431 * Magic method to check if the property is empty
2433 * @param string $name name of the property
2434 * @return bool
2436 public function __empty($name) {
2437 if (method_exists($this, 'get_'.$name) ||
2438 property_exists($this, '_'.$name) ||
2439 array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
2440 $value = $this->__get($name);
2441 return empty($value);
2443 return true;
2447 * Magic method to retrieve the property, this is either basic section property
2448 * or availability information or additional properties added by course format
2450 * @param string $name name of the property
2451 * @return bool
2453 public function __get($name) {
2454 if (method_exists($this, 'get_'.$name)) {
2455 return $this->{'get_'.$name}();
2457 if (property_exists($this, '_'.$name)) {
2458 return $this->{'_'.$name};
2460 if (array_key_exists($name, $this->cachedformatoptions)) {
2461 return $this->cachedformatoptions[$name];
2463 // precheck if the option is defined in format to avoid unnecessary DB queries in get_format_options()
2464 if (array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
2465 $formatoptions = course_get_format($this->modinfo->get_course())->get_format_options($this);
2466 return $formatoptions[$name];
2468 debugging('Invalid section_info property accessed! '.$name);
2469 return null;
2473 * Finds whether this section is available at the moment for the current user.
2475 * The value can be accessed publicly as $sectioninfo->available
2477 * @return bool
2479 private function get_available() {
2480 global $CFG;
2481 $userid = $this->modinfo->get_user_id();
2482 if ($this->_available !== null || $userid == -1) {
2483 // Has already been calculated or does not need calculation.
2484 return $this->_available;
2486 if (!empty($CFG->enableavailability)) {
2487 require_once($CFG->libdir. '/conditionlib.php');
2488 // Get availability information
2489 $ci = new condition_info_section($this);
2490 $this->_available = $ci->is_available($this->_availableinfo, true,
2491 $userid, $this->modinfo);
2492 if ($this->_availableinfo === '' && $this->_groupingid) {
2493 // Still may have some extra text in availableinfo because of groupping.
2494 // Set as undefined so the next call to get_availabeinfo() calculates it.
2495 $this->_availableinfo = null;
2497 } else {
2498 $this->_available = true;
2499 $this->_availableinfo = '';
2501 return $this->_available;
2505 * Returns the availability text shown next to the section on course page.
2507 * @return string
2509 private function get_availableinfo() {
2510 // Make sure $this->_available has been calculated, it may also fill the _availableinfo property.
2511 $this->get_available();
2512 $userid = $this->modinfo->get_user_id();
2513 if ($this->_availableinfo !== null || $userid == -1) {
2514 // It has been already calculated or does not need calculation.
2515 return $this->_availableinfo;
2517 $this->_availableinfo = '';
2518 // Display grouping info if available & not already displaying
2519 // (it would already display if current user doesn't have access)
2520 // for people with managegroups - same logic/class as grouping label
2521 // on individual activities.
2522 $context = context_course::instance($this->get_course());
2523 if ($this->_groupingid && has_capability('moodle/course:managegroups', $context, $userid)) {
2524 $groupings = groups_get_all_groupings($this->get_course());
2525 $this->_availableinfo = html_writer::tag('span', '(' . format_string(
2526 $groupings[$this->_groupingid]->name, true, array('context' => $context)) .
2527 ')', array('class' => 'groupinglabel'));
2529 return $this->_availableinfo;
2533 * Implementation of IteratorAggregate::getIterator(), allows to cycle through properties
2534 * and use {@link convert_to_array()}
2536 * @return ArrayIterator
2538 public function getIterator() {
2539 $ret = array();
2540 foreach (get_object_vars($this) as $key => $value) {
2541 if (substr($key, 0, 1) == '_') {
2542 if (method_exists($this, 'get'.$key)) {
2543 $ret[substr($key, 1)] = $this->{'get'.$key}();
2544 } else {
2545 $ret[substr($key, 1)] = $this->$key;
2549 $ret['sequence'] = $this->get_sequence();
2550 $ret['course'] = $this->get_course();
2551 $ret = array_merge($ret, course_get_format($this->modinfo->get_course())->get_format_options($this->_section));
2552 return new ArrayIterator($ret);
2556 * Works out whether activity is visible *for current user* - if this is false, they
2557 * aren't allowed to access it.
2559 * @return bool
2561 private function get_uservisible() {
2562 $userid = $this->modinfo->get_user_id();
2563 if ($this->_uservisible !== null || $userid == -1) {
2564 // Has already been calculated or does not need calculation.
2565 return $this->_uservisible;
2567 $this->_uservisible = true;
2568 if (!$this->_visible || !$this->get_available()) {
2569 $coursecontext = context_course::instance($this->get_course());
2570 if (!has_capability('moodle/course:viewhiddensections', $coursecontext, $userid)) {
2571 $this->_uservisible = false;
2574 return $this->_uservisible;
2578 * Restores the course_sections.sequence value
2580 * @return string
2582 private function get_sequence() {
2583 if (!empty($this->modinfo->sections[$this->_section])) {
2584 return implode(',', $this->modinfo->sections[$this->_section]);
2585 } else {
2586 return '';
2591 * Returns course ID - from course_sections table
2593 * @return int
2595 private function get_course() {
2596 return $this->modinfo->get_course_id();
2600 * Prepares section data for inclusion in sectioncache cache, removing items
2601 * that are set to defaults, and adding availability data if required.
2603 * Called by build_section_cache in course_modinfo only; do not use otherwise.
2604 * @param object $section Raw section data object
2606 public static function convert_for_section_cache($section) {
2607 global $CFG;
2609 // Course id stored in course table
2610 unset($section->course);
2611 // Section number stored in array key
2612 unset($section->section);
2613 // Sequence stored implicity in modinfo $sections array
2614 unset($section->sequence);
2616 // Add availability data if turned on
2617 if ($CFG->enableavailability) {
2618 require_once($CFG->dirroot . '/lib/conditionlib.php');
2619 condition_info_section::fill_availability_conditions($section);
2620 if (count($section->conditionscompletion) == 0) {
2621 unset($section->conditionscompletion);
2623 if (count($section->conditionsgrade) == 0) {
2624 unset($section->conditionsgrade);
2628 // Remove default data
2629 foreach (self::$sectioncachedefaults as $field => $value) {
2630 // Exact compare as strings to avoid problems if some strings are set
2631 // to "0" etc.
2632 if (isset($section->{$field}) && $section->{$field} === $value) {
2633 unset($section->{$field});