Merge branch 'MDL-42392-26' of git://github.com/andrewnicols/moodle into MOODLE_26_STABLE
[moodle.git] / lib / modinfolib.php
blob17a499c82067220727f3d9a646aa28407e2ea775
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 if (in_array($name, self::$standardmethods)) {
1171 // All standard methods do not have arguments anyway.
1172 return $this->$name();
1174 throw new coding_exception("Method cm_info::{$name}() does not exist");
1178 * Magic method getter
1180 * @param string $name
1181 * @return mixed
1183 public function __get($name) {
1184 if (isset(self::$standardproperties[$name])) {
1185 if ($method = self::$standardproperties[$name]) {
1186 return $this->$method();
1187 } else {
1188 return $this->$name;
1190 } else {
1191 debugging('Invalid cm_info property accessed: '.$name);
1192 return null;
1197 * Implementation of IteratorAggregate::getIterator(), allows to cycle through properties
1198 * and use {@link convert_to_array()}
1200 * @return ArrayIterator
1202 public function getIterator() {
1203 // Make sure dynamic properties are retrieved prior to view properties.
1204 $this->obtain_dynamic_data();
1205 $ret = array();
1206 foreach (self::$standardproperties as $key => $unused) {
1207 $ret[$key] = $this->__get($key);
1209 return new ArrayIterator($ret);
1213 * Magic method for function isset()
1215 * @param string $name
1216 * @return bool
1218 public function __isset($name) {
1219 if (isset(self::$standardproperties[$name])) {
1220 $value = $this->__get($name);
1221 return isset($value);
1223 return false;
1227 * Magic method for function empty()
1229 * @param string $name
1230 * @return bool
1232 public function __empty($name) {
1233 if (isset(self::$standardproperties[$name])) {
1234 $value = $this->__get($name);
1235 return empty($value);
1237 return true;
1241 * Magic method setter
1243 * Will display the developer warning when trying to set/overwrite property.
1245 * @param string $name
1246 * @param mixed $value
1248 public function __set($name, $value) {
1249 debugging("It is not allowed to set the property cm_info::\${$name}", DEBUG_DEVELOPER);
1253 * @return bool True if this module has a 'view' page that should be linked to in navigation
1254 * etc (note: modules may still have a view.php file, but return false if this is not
1255 * intended to be linked to from 'normal' parts of the interface; this is what label does).
1257 public function has_view() {
1258 return !is_null($this->url);
1262 * @return moodle_url URL to link to for this module, or null if it doesn't have a view page
1264 private function get_url() {
1265 $this->obtain_dynamic_data();
1266 return $this->url;
1270 * Obtains content to display on main (view) page.
1271 * Note: Will collect view data, if not already obtained.
1272 * @return string Content to display on main page below link, or empty string if none
1274 private function get_content() {
1275 $this->obtain_view_data();
1276 return $this->content;
1280 * Returns the content to display on course/overview page, formatted and passed through filters
1282 * if $options['context'] is not specified, the module context is used
1284 * @param array|stdClass $options formatting options, see {@link format_text()}
1285 * @return string
1287 public function get_formatted_content($options = array()) {
1288 $this->obtain_view_data();
1289 if (empty($this->content)) {
1290 return '';
1292 // Improve filter performance by preloading filter setttings for all
1293 // activities on the course (this does nothing if called multiple
1294 // times)
1295 filter_preload_activities($this->get_modinfo());
1297 $options = (array)$options;
1298 if (!isset($options['context'])) {
1299 $options['context'] = $this->get_context();
1301 return format_text($this->content, FORMAT_HTML, $options);
1305 * Getter method for property $name, ensures that dynamic data is obtained.
1306 * @return string
1308 private function get_name() {
1309 $this->obtain_dynamic_data();
1310 return $this->name;
1314 * Returns the name to display on course/overview page, formatted and passed through filters
1316 * if $options['context'] is not specified, the module context is used
1318 * @param array|stdClass $options formatting options, see {@link format_string()}
1319 * @return string
1321 public function get_formatted_name($options = array()) {
1322 $options = (array)$options;
1323 if (!isset($options['context'])) {
1324 $options['context'] = $this->get_context();
1326 return format_string($this->get_name(), true, $options);
1330 * Note: Will collect view data, if not already obtained.
1331 * @return string Extra CSS classes to add to html output for this activity on main page
1333 private function get_extra_classes() {
1334 $this->obtain_view_data();
1335 return $this->extraclasses;
1339 * @return string Content of HTML on-click attribute. This string will be used literally
1340 * as a string so should be pre-escaped.
1342 private function get_on_click() {
1343 // Does not need view data; may be used by navigation
1344 $this->obtain_dynamic_data();
1345 return $this->onclick;
1348 * @return mixed Optional custom data stored in modinfo cache for this activity, or null if none
1350 private function get_custom_data() {
1351 return $this->customdata;
1355 * Note: Will collect view data, if not already obtained.
1356 * @return string Extra HTML code to display after link
1358 private function get_after_link() {
1359 $this->obtain_view_data();
1360 return $this->afterlink;
1364 * Note: Will collect view data, if not already obtained.
1365 * @return string Extra HTML code to display after editing icons (e.g. more icons)
1367 private function get_after_edit_icons() {
1368 $this->obtain_view_data();
1369 return $this->afterediticons;
1373 * @param moodle_core_renderer $output Output render to use, or null for default (global)
1374 * @return moodle_url Icon URL for a suitable icon to put beside this cm
1376 public function get_icon_url($output = null) {
1377 global $OUTPUT;
1378 $this->obtain_dynamic_data();
1379 if (!$output) {
1380 $output = $OUTPUT;
1382 // Support modules setting their own, external, icon image
1383 if (!empty($this->iconurl)) {
1384 $icon = $this->iconurl;
1386 // Fallback to normal local icon + component procesing
1387 } else if (!empty($this->icon)) {
1388 if (substr($this->icon, 0, 4) === 'mod/') {
1389 list($modname, $iconname) = explode('/', substr($this->icon, 4), 2);
1390 $icon = $output->pix_url($iconname, $modname);
1391 } else {
1392 if (!empty($this->iconcomponent)) {
1393 // Icon has specified component
1394 $icon = $output->pix_url($this->icon, $this->iconcomponent);
1395 } else {
1396 // Icon does not have specified component, use default
1397 $icon = $output->pix_url($this->icon);
1400 } else {
1401 $icon = $output->pix_url('icon', $this->modname);
1403 return $icon;
1407 * Returns a localised human-readable name of the module type
1409 * @param bool $plural return plural form
1410 * @return string
1412 public function get_module_type_name($plural = false) {
1413 $modnames = get_module_types_names($plural);
1414 if (isset($modnames[$this->modname])) {
1415 return $modnames[$this->modname];
1416 } else {
1417 return null;
1422 * Returns a localised human-readable name of the module type in plural form - calculated on request
1424 * @return string
1426 private function get_module_type_name_plural() {
1427 return $this->get_module_type_name(true);
1431 * @return course_modinfo Modinfo object that this came from
1433 public function get_modinfo() {
1434 return $this->modinfo;
1438 * Returns course object that was used in the first {@link get_fast_modinfo()} call.
1440 * It may not contain all fields from DB table {course} but always has at least the following:
1441 * id,shortname,fullname,format,enablecompletion,groupmode,groupmodeforce,cacherev
1443 * If the course object lacks the field you need you can use the global
1444 * function {@link get_course()} that will save extra query if you access
1445 * current course or frontpage course.
1447 * @return stdClass
1449 public function get_course() {
1450 return $this->modinfo->get_course();
1454 * Returns course id for which the modinfo was generated.
1456 * @return int
1458 private function get_course_id() {
1459 return $this->modinfo->get_course_id();
1463 * Returns group mode used for the course containing the module
1465 * @return int one of constants NOGROUPS, SEPARATEGROUPS, VISIBLEGROUPS
1467 private function get_course_groupmode() {
1468 return $this->modinfo->get_course()->groupmode;
1472 * Returns whether group mode is forced for the course containing the module
1474 * @return bool
1476 private function get_course_groupmodeforce() {
1477 return $this->modinfo->get_course()->groupmodeforce;
1481 * Returns effective groupmode of the module that may be overwritten by forced course groupmode.
1483 * @return int one of constants NOGROUPS, SEPARATEGROUPS, VISIBLEGROUPS
1485 private function get_effective_groupmode() {
1486 $groupmode = $this->groupmode;
1487 if ($this->modinfo->get_course()->groupmodeforce) {
1488 $groupmode = $this->modinfo->get_course()->groupmode;
1489 if ($groupmode != NOGROUPS && !plugin_supports('mod', $this->modname, FEATURE_GROUPS, 0)) {
1490 $groupmode = NOGROUPS;
1493 return $groupmode;
1497 * @return context_module Current module context
1499 private function get_context() {
1500 return context_module::instance($this->id);
1503 // Set functions
1504 ////////////////
1507 * Sets content to display on course view page below link (if present).
1508 * @param string $content New content as HTML string (empty string if none)
1509 * @return void
1511 public function set_content($content) {
1512 $this->content = $content;
1516 * Sets extra classes to include in CSS.
1517 * @param string $extraclasses Extra classes (empty string if none)
1518 * @return void
1520 public function set_extra_classes($extraclasses) {
1521 $this->extraclasses = $extraclasses;
1525 * Sets the external full url that points to the icon being used
1526 * by the activity. Useful for external-tool modules (lti...)
1527 * If set, takes precedence over $icon and $iconcomponent
1529 * @param moodle_url $iconurl full external url pointing to icon image for activity
1530 * @return void
1532 public function set_icon_url(moodle_url $iconurl) {
1533 $this->iconurl = $iconurl;
1537 * Sets value of on-click attribute for JavaScript.
1538 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1539 * @param string $onclick New onclick attribute which should be HTML-escaped
1540 * (empty string if none)
1541 * @return void
1543 public function set_on_click($onclick) {
1544 $this->check_not_view_only();
1545 $this->onclick = $onclick;
1549 * Sets HTML that displays after link on course view page.
1550 * @param string $afterlink HTML string (empty string if none)
1551 * @return void
1553 public function set_after_link($afterlink) {
1554 $this->afterlink = $afterlink;
1558 * Sets HTML that displays after edit icons on course view page.
1559 * @param string $afterediticons HTML string (empty string if none)
1560 * @return void
1562 public function set_after_edit_icons($afterediticons) {
1563 $this->afterediticons = $afterediticons;
1567 * Changes the name (text of link) for this module instance.
1568 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1569 * @param string $name Name of activity / link text
1570 * @return void
1572 public function set_name($name) {
1573 if ($this->state < self::STATE_BUILDING_DYNAMIC) {
1574 $this->update_user_visible();
1576 $this->name = $name;
1580 * Turns off the view link for this module instance.
1581 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1582 * @return void
1584 public function set_no_view_link() {
1585 $this->check_not_view_only();
1586 $this->url = null;
1590 * Sets the 'uservisible' flag. This can be used (by setting false) to prevent access and
1591 * display of this module link for the current user.
1592 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1593 * @param bool $uservisible
1594 * @return void
1596 public function set_user_visible($uservisible) {
1597 $this->check_not_view_only();
1598 $this->uservisible = $uservisible;
1602 * Sets the 'available' flag and related details. This flag is normally used to make
1603 * course modules unavailable until a certain date or condition is met. (When a course
1604 * module is unavailable, it is still visible to users who have viewhiddenactivities
1605 * permission.)
1607 * When this is function is called, user-visible status is recalculated automatically.
1609 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1610 * @param bool $available False if this item is not 'available'
1611 * @param int $showavailability 0 = do not show this item at all if it's not available,
1612 * 1 = show this item greyed out with the following message
1613 * @param string $availableinfo Information about why this is not available which displays
1614 * to those who have viewhiddenactivities, and to everyone if showavailability is set;
1615 * note that this function replaces the existing data (if any)
1616 * @return void
1618 public function set_available($available, $showavailability=0, $availableinfo='') {
1619 $this->check_not_view_only();
1620 $this->available = $available;
1621 $this->showavailability = $showavailability;
1622 $this->availableinfo = $availableinfo;
1623 $this->update_user_visible();
1627 * Some set functions can only be called from _cm_info_dynamic and not _cm_info_view.
1628 * This is because they may affect parts of this object which are used on pages other
1629 * than the view page (e.g. in the navigation block, or when checking access on
1630 * module pages).
1631 * @return void
1633 private function check_not_view_only() {
1634 if ($this->state >= self::STATE_DYNAMIC) {
1635 throw new coding_exception('Cannot set this data from _cm_info_view because it may ' .
1636 'affect other pages as well as view');
1641 * Constructor should not be called directly; use {@link get_fast_modinfo()}
1643 * @param course_modinfo $modinfo Parent object
1644 * @param stdClass $notused1 Argument not used
1645 * @param stdClass $mod Module object from the modinfo field of course table
1646 * @param stdClass $notused2 Argument not used
1648 public function __construct(course_modinfo $modinfo, $notused1, $mod, $notused2) {
1649 $this->modinfo = $modinfo;
1651 $this->id = $mod->cm;
1652 $this->instance = $mod->id;
1653 $this->modname = $mod->mod;
1654 $this->idnumber = isset($mod->idnumber) ? $mod->idnumber : '';
1655 $this->name = $mod->name;
1656 $this->visible = $mod->visible;
1657 $this->sectionnum = $mod->section; // Note weirdness with name here
1658 $this->groupmode = isset($mod->groupmode) ? $mod->groupmode : 0;
1659 $this->groupingid = isset($mod->groupingid) ? $mod->groupingid : 0;
1660 $this->groupmembersonly = isset($mod->groupmembersonly) ? $mod->groupmembersonly : 0;
1661 $this->indent = isset($mod->indent) ? $mod->indent : 0;
1662 $this->extra = isset($mod->extra) ? $mod->extra : '';
1663 $this->extraclasses = isset($mod->extraclasses) ? $mod->extraclasses : '';
1664 // iconurl may be stored as either string or instance of moodle_url.
1665 $this->iconurl = isset($mod->iconurl) ? new moodle_url($mod->iconurl) : '';
1666 $this->onclick = isset($mod->onclick) ? $mod->onclick : '';
1667 $this->content = isset($mod->content) ? $mod->content : '';
1668 $this->icon = isset($mod->icon) ? $mod->icon : '';
1669 $this->iconcomponent = isset($mod->iconcomponent) ? $mod->iconcomponent : '';
1670 $this->customdata = isset($mod->customdata) ? $mod->customdata : '';
1671 $this->showdescription = isset($mod->showdescription) ? $mod->showdescription : 0;
1672 $this->state = self::STATE_BASIC;
1674 $this->section = isset($mod->sectionid) ? $mod->sectionid : 0;
1675 $this->module = isset($mod->module) ? $mod->module : 0;
1676 $this->added = isset($mod->added) ? $mod->added : 0;
1677 $this->score = isset($mod->score) ? $mod->score : 0;
1678 $this->visibleold = isset($mod->visibleold) ? $mod->visibleold : 0;
1680 // Note: it saves effort and database space to always include the
1681 // availability and completion fields, even if availability or completion
1682 // are actually disabled
1683 $this->completion = isset($mod->completion) ? $mod->completion : 0;
1684 $this->completiongradeitemnumber = isset($mod->completiongradeitemnumber)
1685 ? $mod->completiongradeitemnumber : null;
1686 $this->completionview = isset($mod->completionview)
1687 ? $mod->completionview : 0;
1688 $this->completionexpected = isset($mod->completionexpected)
1689 ? $mod->completionexpected : 0;
1690 $this->showavailability = isset($mod->showavailability) ? $mod->showavailability : 0;
1691 $this->availablefrom = isset($mod->availablefrom) ? $mod->availablefrom : 0;
1692 $this->availableuntil = isset($mod->availableuntil) ? $mod->availableuntil : 0;
1693 $this->conditionscompletion = isset($mod->conditionscompletion)
1694 ? $mod->conditionscompletion : array();
1695 $this->conditionsgrade = isset($mod->conditionsgrade)
1696 ? $mod->conditionsgrade : array();
1697 $this->conditionsfield = isset($mod->conditionsfield)
1698 ? $mod->conditionsfield : array();
1700 static $modviews = array();
1701 if (!isset($modviews[$this->modname])) {
1702 $modviews[$this->modname] = !plugin_supports('mod', $this->modname,
1703 FEATURE_NO_VIEW_LINK);
1705 $this->url = $modviews[$this->modname]
1706 ? new moodle_url('/mod/' . $this->modname . '/view.php', array('id'=>$this->id))
1707 : null;
1711 * If dynamic data for this course-module is not yet available, gets it.
1713 * This function is automatically called when requesting any course_modinfo property
1714 * that can be modified by modules (have a set_xxx method).
1716 * Dynamic data is data which does not come directly from the cache but is calculated at
1717 * runtime based on the current user. Primarily this concerns whether the user can access
1718 * the module or not.
1720 * As part of this function, the module's _cm_info_dynamic function from its lib.php will
1721 * be called (if it exists).
1722 * @return void
1724 private function obtain_dynamic_data() {
1725 global $CFG;
1726 $userid = $this->modinfo->get_user_id();
1727 if ($this->state >= self::STATE_BUILDING_DYNAMIC || $userid == -1) {
1728 return;
1730 $this->state = self::STATE_BUILDING_DYNAMIC;
1732 if (!empty($CFG->enableavailability)) {
1733 require_once($CFG->libdir. '/conditionlib.php');
1734 // Get availability information
1735 $ci = new condition_info($this);
1736 // Note that the modinfo currently available only includes minimal details (basic data)
1737 // but we know that this function does not need anything more than basic data.
1738 $this->available = $ci->is_available($this->availableinfo, true,
1739 $userid, $this->modinfo);
1741 // Check parent section
1742 $parentsection = $this->modinfo->get_section_info($this->sectionnum);
1743 if (!$parentsection->available) {
1744 // Do not store info from section here, as that is already
1745 // presented from the section (if appropriate) - just change
1746 // the flag
1747 $this->available = false;
1749 } else {
1750 $this->available = true;
1753 // Update visible state for current user
1754 $this->update_user_visible();
1756 // Let module make dynamic changes at this point
1757 $this->call_mod_function('cm_info_dynamic');
1758 $this->state = self::STATE_DYNAMIC;
1762 * Getter method for property $uservisible, ensures that dynamic data is retrieved.
1763 * @return bool
1765 private function get_user_visible() {
1766 $this->obtain_dynamic_data();
1767 return $this->uservisible;
1771 * Getter method for property $available, ensures that dynamic data is retrieved
1772 * @return bool
1774 private function get_available() {
1775 $this->obtain_dynamic_data();
1776 return $this->available;
1780 * Getter method for property $showavailability, ensures that dynamic data is retrieved
1781 * @return int
1783 private function get_show_availability() {
1784 $this->obtain_dynamic_data();
1785 return $this->showavailability;
1789 * Getter method for property $availableinfo, ensures that dynamic data is retrieved
1790 * @return type
1792 private function get_available_info() {
1793 $this->obtain_dynamic_data();
1794 return $this->availableinfo;
1798 * Works out whether activity is available to the current user
1800 * If the activity is unavailable, additional checks are required to determine if its hidden or greyed out
1802 * @see is_user_access_restricted_by_group()
1803 * @see is_user_access_restricted_by_conditional_access()
1804 * @return void
1806 private function update_user_visible() {
1807 $userid = $this->modinfo->get_user_id();
1808 if ($userid == -1) {
1809 return null;
1811 $this->uservisible = true;
1813 // If the user cannot access the activity set the uservisible flag to false.
1814 // Additional checks are required to determine whether the activity is entirely hidden or just greyed out.
1815 if ((!$this->visible or !$this->get_available()) and
1816 !has_capability('moodle/course:viewhiddenactivities', $this->get_context(), $userid)) {
1818 $this->uservisible = false;
1821 // Check group membership.
1822 if ($this->is_user_access_restricted_by_group() ||
1823 $this->is_user_access_restricted_by_capability()) {
1825 $this->uservisible = false;
1826 // Ensure activity is completely hidden from the user.
1827 $this->showavailability = 0;
1832 * Checks whether the module's group settings restrict the current user's access
1834 * @return bool True if the user access is restricted
1836 public function is_user_access_restricted_by_group() {
1837 global $CFG;
1839 if (!empty($CFG->enablegroupmembersonly) and !empty($this->groupmembersonly)) {
1840 $userid = $this->modinfo->get_user_id();
1841 if ($userid == -1) {
1842 return null;
1844 if (!has_capability('moodle/site:accessallgroups', $this->get_context(), $userid)) {
1845 // If the activity has 'group members only' and you don't have accessallgroups...
1846 $groups = $this->modinfo->get_groups($this->groupingid);
1847 if (empty($groups)) {
1848 // ...and you don't belong to a group, then set it so you can't see/access it
1849 return true;
1853 return false;
1857 * Checks whether mod/...:view capability restricts the current user's access.
1859 * @return bool True if the user access is restricted.
1861 public function is_user_access_restricted_by_capability() {
1862 $userid = $this->modinfo->get_user_id();
1863 if ($userid == -1) {
1864 return null;
1866 $capability = 'mod/' . $this->modname . ':view';
1867 $capabilityinfo = get_capability_info($capability);
1868 if (!$capabilityinfo) {
1869 // Capability does not exist, no one is prevented from seeing the activity.
1870 return false;
1873 // You are blocked if you don't have the capability.
1874 return !has_capability($capability, $this->get_context(), $userid);
1878 * Checks whether the module's conditional access settings mean that the user cannot see the activity at all
1880 * @return bool True if the user cannot see the module. False if the activity is either available or should be greyed out.
1882 public function is_user_access_restricted_by_conditional_access() {
1883 global $CFG;
1885 if (empty($CFG->enableavailability)) {
1886 return false;
1889 $userid = $this->modinfo->get_user_id();
1890 if ($userid == -1) {
1891 return null;
1894 // If module will always be visible anyway (but greyed out), don't bother checking anything else
1895 if ($this->get_show_availability() == CONDITION_STUDENTVIEW_SHOW) {
1896 return false;
1899 // Can the user see hidden modules?
1900 if (has_capability('moodle/course:viewhiddenactivities', $this->get_context(), $userid)) {
1901 return false;
1904 // Is the module hidden due to unmet conditions?
1905 if (!$this->get_available()) {
1906 return true;
1909 return false;
1913 * Calls a module function (if exists), passing in one parameter: this object.
1914 * @param string $type Name of function e.g. if this is 'grooblezorb' and the modname is
1915 * 'forum' then it will try to call 'mod_forum_grooblezorb' or 'forum_grooblezorb'
1916 * @return void
1918 private function call_mod_function($type) {
1919 global $CFG;
1920 $libfile = $CFG->dirroot . '/mod/' . $this->modname . '/lib.php';
1921 if (file_exists($libfile)) {
1922 include_once($libfile);
1923 $function = 'mod_' . $this->modname . '_' . $type;
1924 if (function_exists($function)) {
1925 $function($this);
1926 } else {
1927 $function = $this->modname . '_' . $type;
1928 if (function_exists($function)) {
1929 $function($this);
1936 * If view data for this course-module is not yet available, obtains it.
1938 * This function is automatically called if any of the functions (marked) which require
1939 * view data are called.
1941 * View data is data which is needed only for displaying the course main page (& any similar
1942 * functionality on other pages) but is not needed in general. Obtaining view data may have
1943 * a performance cost.
1945 * As part of this function, the module's _cm_info_view function from its lib.php will
1946 * be called (if it exists).
1947 * @return void
1949 private function obtain_view_data() {
1950 if ($this->state >= self::STATE_BUILDING_VIEW || $this->modinfo->get_user_id() == -1) {
1951 return;
1953 $this->obtain_dynamic_data();
1954 $this->state = self::STATE_BUILDING_VIEW;
1956 // Let module make changes at this point
1957 $this->call_mod_function('cm_info_view');
1958 $this->state = self::STATE_VIEW;
1964 * Returns reference to full info about modules in course (including visibility).
1965 * Cached and as fast as possible (0 or 1 db query).
1967 * use get_fast_modinfo($courseid, 0, true) to reset the static cache for particular course
1968 * use get_fast_modinfo(0, 0, true) to reset the static cache for all courses
1970 * use rebuild_course_cache($courseid, true) to reset the application AND static cache
1971 * for particular course when it's contents has changed
1973 * @param int|stdClass $courseorid object from DB table 'course' (must have field 'id'
1974 * and recommended to have field 'cacherev') or just a course id. Just course id
1975 * is enough when calling get_fast_modinfo() for current course or site or when
1976 * calling for any other course for the second time.
1977 * @param int $userid User id to populate 'availble' and 'uservisible' attributes of modules and sections.
1978 * Set to 0 for current user (default). Set to -1 to avoid calculation of dynamic user-depended data.
1979 * @param bool $resetonly whether we want to get modinfo or just reset the cache
1980 * @return course_modinfo|null Module information for course, or null if resetting
1981 * @throws moodle_exception when course is not found (nothing is thrown if resetting)
1983 function get_fast_modinfo($courseorid, $userid = 0, $resetonly = false) {
1984 // compartibility with syntax prior to 2.4:
1985 if ($courseorid === 'reset') {
1986 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);
1987 $courseorid = 0;
1988 $resetonly = true;
1991 // Function get_fast_modinfo() can never be called during upgrade unless it is used for clearing cache only.
1992 if (!$resetonly) {
1993 upgrade_ensure_not_running();
1996 // Function is called with $reset = true
1997 if ($resetonly) {
1998 course_modinfo::clear_instance_cache($courseorid);
1999 return null;
2002 // Function is called with $reset = false, retrieve modinfo
2003 return course_modinfo::instance($courseorid, $userid);
2007 * Rebuilds or resets the cached list of course activities stored in MUC.
2009 * rebuild_course_cache() must NEVER be called from lib/db/upgrade.php.
2010 * At the same time course cache may ONLY be cleared using this function in
2011 * upgrade scripts of plugins.
2013 * During the bulk operations if it is necessary to reset cache of multiple
2014 * courses it is enough to call {@link increment_revision_number()} for the
2015 * table 'course' and field 'cacherev' specifying affected courses in select.
2017 * Cached course information is stored in MUC core/coursemodinfo and is
2018 * validated with the DB field {course}.cacherev
2020 * @global moodle_database $DB
2021 * @param int $courseid id of course to rebuild, empty means all
2022 * @param boolean $clearonly only clear the cache, gets rebuild automatically on the fly.
2023 * Recommended to set to true to avoid unnecessary multiple rebuilding.
2025 function rebuild_course_cache($courseid=0, $clearonly=false) {
2026 global $COURSE, $SITE, $DB, $CFG;
2028 // Function rebuild_course_cache() can not be called during upgrade unless it's clear only.
2029 if (!$clearonly && !upgrade_ensure_not_running(true)) {
2030 $clearonly = true;
2033 // Destroy navigation caches
2034 navigation_cache::destroy_volatile_caches();
2036 if (class_exists('format_base')) {
2037 // if file containing class is not loaded, there is no cache there anyway
2038 format_base::reset_course_cache($courseid);
2041 $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
2042 if (empty($courseid)) {
2043 // Clearing caches for all courses.
2044 increment_revision_number('course', 'cacherev', '');
2045 $cachecoursemodinfo->purge();
2046 course_modinfo::clear_instance_cache();
2047 // Update global values too.
2048 $sitecacherev = $DB->get_field('course', 'cacherev', array('id' => SITEID));
2049 $SITE->cachrev = $sitecacherev;
2050 if ($COURSE->id == SITEID) {
2051 $COURSE->cacherev = $sitecacherev;
2052 } else {
2053 $COURSE->cacherev = $DB->get_field('course', 'cacherev', array('id' => $COURSE->id));
2055 } else {
2056 // Clearing cache for one course, make sure it is deleted from user request cache as well.
2057 increment_revision_number('course', 'cacherev', 'id = :id', array('id' => $courseid));
2058 $cachecoursemodinfo->delete($courseid);
2059 course_modinfo::clear_instance_cache($courseid);
2060 // Update global values too.
2061 if ($courseid == $COURSE->id || $courseid == $SITE->id) {
2062 $cacherev = $DB->get_field('course', 'cacherev', array('id' => $courseid));
2063 if ($courseid == $COURSE->id) {
2064 $COURSE->cacherev = $cacherev;
2066 if ($courseid == $SITE->id) {
2067 $SITE->cachrev = $cacherev;
2072 if ($clearonly) {
2073 return;
2076 if ($courseid) {
2077 $select = array('id'=>$courseid);
2078 } else {
2079 $select = array();
2080 @set_time_limit(0); // this could take a while! MDL-10954
2083 $rs = $DB->get_recordset("course", $select,'','id,'.join(',', course_modinfo::$cachedfields));
2084 // Rebuild cache for each course.
2085 foreach ($rs as $course) {
2086 course_modinfo::build_course_cache($course);
2088 $rs->close();
2093 * Class that is the return value for the _get_coursemodule_info module API function.
2095 * Note: For backward compatibility, you can also return a stdclass object from that function.
2096 * The difference is that the stdclass object may contain an 'extra' field (deprecated,
2097 * use extraclasses and onclick instead). The stdclass object may not contain
2098 * the new fields defined here (content, extraclasses, customdata).
2100 class cached_cm_info {
2102 * Name (text of link) for this activity; Leave unset to accept default name
2103 * @var string
2105 public $name;
2108 * Name of icon for this activity. Normally, this should be used together with $iconcomponent
2109 * to define the icon, as per pix_url function.
2110 * For backward compatibility, if this value is of the form 'mod/forum/icon' then an icon
2111 * within that module will be used.
2112 * @see cm_info::get_icon_url()
2113 * @see renderer_base::pix_url()
2114 * @var string
2116 public $icon;
2119 * Component for icon for this activity, as per pix_url; leave blank to use default 'moodle'
2120 * component
2121 * @see renderer_base::pix_url()
2122 * @var string
2124 public $iconcomponent;
2127 * HTML content to be displayed on the main page below the link (if any) for this course-module
2128 * @var string
2130 public $content;
2133 * Custom data to be stored in modinfo for this activity; useful if there are cases when
2134 * internal information for this activity type needs to be accessible from elsewhere on the
2135 * course without making database queries. May be of any type but should be short.
2136 * @var mixed
2138 public $customdata;
2141 * Extra CSS class or classes to be added when this activity is displayed on the main page;
2142 * space-separated string
2143 * @var string
2145 public $extraclasses;
2148 * External URL image to be used by activity as icon, useful for some external-tool modules
2149 * like lti. If set, takes precedence over $icon and $iconcomponent
2150 * @var $moodle_url
2152 public $iconurl;
2155 * Content of onclick JavaScript; escaped HTML to be inserted as attribute value
2156 * @var string
2158 public $onclick;
2163 * Data about a single section on a course. This contains the fields from the
2164 * course_sections table, plus additional data when required.
2166 * @property-read int $id Section ID - from course_sections table
2167 * @property-read int $course Course ID - from course_sections table
2168 * @property-read int $section Section number - from course_sections table
2169 * @property-read string $name Section name if specified - from course_sections table
2170 * @property-read int $visible Section visibility (1 = visible) - from course_sections table
2171 * @property-read string $summary Section summary text if specified - from course_sections table
2172 * @property-read int $summaryformat Section summary text format (FORMAT_xx constant) - from course_sections table
2173 * @property-read int $showavailability When section is unavailable, this field controls whether it is shown to students (0 =
2174 * hide completely, 1 = show greyed out with information about when it will be available) -
2175 * from course_sections table
2176 * @property-read int $availablefrom Available date for this section (0 if not set, or set to seconds since epoch;
2177 * before this date, section does not display to students) - from course_sections table
2178 * @property-read int $availableuntil Available until date for this section (0 if not set, or set to seconds since epoch;
2179 * from this date, section does not display to students) - from course_sections table
2180 * @property-read int $groupingid If section is restricted to users of a particular grouping, this is its id (0 if not set) -
2181 * from course_sections table
2182 * @property-read array $conditionscompletion Availability conditions for this section based on the completion of
2183 * course-modules (array from course-module id to required completion state
2184 * for that module) - from cached data in sectioncache field
2185 * @property-read array $conditionsgrade Availability conditions for this section based on course grades (array from
2186 * grade item id to object with ->min, ->max fields) - from cached data in
2187 * sectioncache field
2188 * @property-read array $conditionsfield Availability conditions for this section based on user fields
2189 * @property-read bool $available True if this section is available to the given user i.e. if all availability conditions
2190 * are met - obtained dynamically
2191 * @property-read string $availableinfo If section is not available to some users, this string gives information about
2192 * availability which can be displayed to students and/or staff (e.g. 'Available from 3 January 2010')
2193 * for display on main page - obtained dynamically
2194 * @property-read bool $uservisible True if this section is available to the given user (for example, if current user
2195 * has viewhiddensections capability, they can access the section even if it is not
2196 * visible or not available, so this would be true in that case) - obtained dynamically
2197 * @property-read string $sequence Comma-separated list of all modules in the section. Note, this field may not exactly
2198 * match course_sections.sequence if later has references to non-existing modules or not modules of not available module types.
2200 class section_info implements IteratorAggregate {
2202 * Section ID - from course_sections table
2203 * @var int
2205 private $_id;
2208 * Section number - from course_sections table
2209 * @var int
2211 private $_section;
2214 * Section name if specified - from course_sections table
2215 * @var string
2217 private $_name;
2220 * Section visibility (1 = visible) - from course_sections table
2221 * @var int
2223 private $_visible;
2226 * Section summary text if specified - from course_sections table
2227 * @var string
2229 private $_summary;
2232 * Section summary text format (FORMAT_xx constant) - from course_sections table
2233 * @var int
2235 private $_summaryformat;
2238 * When section is unavailable, this field controls whether it is shown to students (0 =
2239 * hide completely, 1 = show greyed out with information about when it will be available) -
2240 * from course_sections table
2241 * @var int
2243 private $_showavailability;
2246 * Available date for this section (0 if not set, or set to seconds since epoch; before this
2247 * date, section does not display to students) - from course_sections table
2248 * @var int
2250 private $_availablefrom;
2253 * Available until date for this section (0 if not set, or set to seconds since epoch; from
2254 * this date, section does not display to students) - from course_sections table
2255 * @var int
2257 private $_availableuntil;
2260 * If section is restricted to users of a particular grouping, this is its id
2261 * (0 if not set) - from course_sections table
2262 * @var int
2264 private $_groupingid;
2267 * Availability conditions for this section based on the completion of
2268 * course-modules (array from course-module id to required completion state
2269 * for that module) - from cached data in sectioncache field
2270 * @var array
2272 private $_conditionscompletion;
2275 * Availability conditions for this section based on course grades (array from
2276 * grade item id to object with ->min, ->max fields) - from cached data in
2277 * sectioncache field
2278 * @var array
2280 private $_conditionsgrade;
2283 * Availability conditions for this section based on user fields
2284 * @var array
2286 private $_conditionsfield;
2289 * True if this section is available to students i.e. if all availability conditions
2290 * are met - obtained dynamically on request, see function {@link section_info::get_available()}
2291 * @var bool|null
2293 private $_available;
2296 * If section is not available to some users, this string gives information about
2297 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
2298 * January 2010') for display on main page - obtained dynamically on request, see
2299 * function {@link section_info::get_availableinfo()}
2300 * @var string
2302 private $_availableinfo;
2305 * True if this section is available to the CURRENT user (for example, if current user
2306 * has viewhiddensections capability, they can access the section even if it is not
2307 * visible or not available, so this would be true in that case) - obtained dynamically
2308 * on request, see function {@link section_info::get_uservisible()}
2309 * @var bool|null
2311 private $_uservisible;
2314 * Default values for sectioncache fields; if a field has this value, it won't
2315 * be stored in the sectioncache cache, to save space. Checks are done by ===
2316 * which means values must all be strings.
2317 * @var array
2319 private static $sectioncachedefaults = array(
2320 'name' => null,
2321 'summary' => '',
2322 'summaryformat' => '1', // FORMAT_HTML, but must be a string
2323 'visible' => '1',
2324 'showavailability' => '0',
2325 'availablefrom' => '0',
2326 'availableuntil' => '0',
2327 'groupingid' => '0',
2331 * Stores format options that have been cached when building 'coursecache'
2332 * When the format option is requested we look first if it has been cached
2333 * @var array
2335 private $cachedformatoptions = array();
2338 * Stores the list of all possible section options defined in each used course format.
2339 * @var array
2341 static private $sectionformatoptions = array();
2344 * Stores the modinfo object passed in constructor, may be used when requesting
2345 * dynamically obtained attributes such as available, availableinfo, uservisible.
2346 * Also used to retrun information about current course or user.
2347 * @var course_modinfo
2349 private $modinfo;
2352 * Constructs object from database information plus extra required data.
2353 * @param object $data Array entry from cached sectioncache
2354 * @param int $number Section number (array key)
2355 * @param int $notused1 argument not used (informaion is available in $modinfo)
2356 * @param int $notused2 argument not used (informaion is available in $modinfo)
2357 * @param course_modinfo $modinfo Owner (needed for checking availability)
2358 * @param int $notused3 argument not used (informaion is available in $modinfo)
2360 public function __construct($data, $number, $notused1, $notused2, $modinfo, $notused3) {
2361 global $CFG;
2362 require_once($CFG->dirroot.'/course/lib.php');
2364 // Data that is always present
2365 $this->_id = $data->id;
2367 $defaults = self::$sectioncachedefaults +
2368 array('conditionscompletion' => array(),
2369 'conditionsgrade' => array(),
2370 'conditionsfield' => array());
2372 // Data that may use default values to save cache size
2373 foreach ($defaults as $field => $value) {
2374 if (isset($data->{$field})) {
2375 $this->{'_'.$field} = $data->{$field};
2376 } else {
2377 $this->{'_'.$field} = $value;
2381 // Other data from constructor arguments.
2382 $this->_section = $number;
2383 $this->modinfo = $modinfo;
2385 // Cached course format data.
2386 $course = $modinfo->get_course();
2387 if (!isset(self::$sectionformatoptions[$course->format])) {
2388 // Store list of section format options defined in each used course format.
2389 // They do not depend on particular course but only on its format.
2390 self::$sectionformatoptions[$course->format] =
2391 course_get_format($course)->section_format_options();
2393 foreach (self::$sectionformatoptions[$course->format] as $field => $option) {
2394 if (!empty($option['cache'])) {
2395 if (isset($data->{$field})) {
2396 $this->cachedformatoptions[$field] = $data->{$field};
2397 } else if (array_key_exists('cachedefault', $option)) {
2398 $this->cachedformatoptions[$field] = $option['cachedefault'];
2405 * Magic method to check if the property is set
2407 * @param string $name name of the property
2408 * @return bool
2410 public function __isset($name) {
2411 if (method_exists($this, 'get_'.$name) ||
2412 property_exists($this, '_'.$name) ||
2413 array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
2414 $value = $this->__get($name);
2415 return isset($value);
2417 return false;
2421 * Magic method to check if the property is empty
2423 * @param string $name name of the property
2424 * @return bool
2426 public function __empty($name) {
2427 if (method_exists($this, 'get_'.$name) ||
2428 property_exists($this, '_'.$name) ||
2429 array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
2430 $value = $this->__get($name);
2431 return empty($value);
2433 return true;
2437 * Magic method to retrieve the property, this is either basic section property
2438 * or availability information or additional properties added by course format
2440 * @param string $name name of the property
2441 * @return bool
2443 public function __get($name) {
2444 if (method_exists($this, 'get_'.$name)) {
2445 return $this->{'get_'.$name}();
2447 if (property_exists($this, '_'.$name)) {
2448 return $this->{'_'.$name};
2450 if (array_key_exists($name, $this->cachedformatoptions)) {
2451 return $this->cachedformatoptions[$name];
2453 // precheck if the option is defined in format to avoid unnecessary DB queries in get_format_options()
2454 if (array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
2455 $formatoptions = course_get_format($this->modinfo->get_course())->get_format_options($this);
2456 return $formatoptions[$name];
2458 debugging('Invalid section_info property accessed! '.$name);
2459 return null;
2463 * Finds whether this section is available at the moment for the current user.
2465 * The value can be accessed publicly as $sectioninfo->available
2467 * @return bool
2469 private function get_available() {
2470 global $CFG;
2471 $userid = $this->modinfo->get_user_id();
2472 if ($this->_available !== null || $userid == -1) {
2473 // Has already been calculated or does not need calculation.
2474 return $this->_available;
2476 if (!empty($CFG->enableavailability)) {
2477 require_once($CFG->libdir. '/conditionlib.php');
2478 // Get availability information
2479 $ci = new condition_info_section($this);
2480 $this->_available = $ci->is_available($this->_availableinfo, true,
2481 $userid, $this->modinfo);
2482 if ($this->_availableinfo === '' && $this->_groupingid) {
2483 // Still may have some extra text in availableinfo because of groupping.
2484 // Set as undefined so the next call to get_availabeinfo() calculates it.
2485 $this->_availableinfo = null;
2487 } else {
2488 $this->_available = true;
2489 $this->_availableinfo = '';
2491 return $this->_available;
2495 * Returns the availability text shown next to the section on course page.
2497 * @return string
2499 private function get_availableinfo() {
2500 // Make sure $this->_available has been calculated, it may also fill the _availableinfo property.
2501 $this->get_available();
2502 $userid = $this->modinfo->get_user_id();
2503 if ($this->_availableinfo !== null || $userid == -1) {
2504 // It has been already calculated or does not need calculation.
2505 return $this->_availableinfo;
2507 $this->_availableinfo = '';
2508 // Display grouping info if available & not already displaying
2509 // (it would already display if current user doesn't have access)
2510 // for people with managegroups - same logic/class as grouping label
2511 // on individual activities.
2512 $context = context_course::instance($this->get_course());
2513 if ($this->_groupingid && has_capability('moodle/course:managegroups', $context, $userid)) {
2514 $groupings = groups_get_all_groupings($this->get_course());
2515 $this->_availableinfo = html_writer::tag('span', '(' . format_string(
2516 $groupings[$this->_groupingid]->name, true, array('context' => $context)) .
2517 ')', array('class' => 'groupinglabel'));
2519 return $this->_availableinfo;
2523 * Implementation of IteratorAggregate::getIterator(), allows to cycle through properties
2524 * and use {@link convert_to_array()}
2526 * @return ArrayIterator
2528 public function getIterator() {
2529 $ret = array();
2530 foreach (get_object_vars($this) as $key => $value) {
2531 if (substr($key, 0, 1) == '_') {
2532 if (method_exists($this, 'get'.$key)) {
2533 $ret[substr($key, 1)] = $this->{'get'.$key}();
2534 } else {
2535 $ret[substr($key, 1)] = $this->$key;
2539 $ret['sequence'] = $this->get_sequence();
2540 $ret['course'] = $this->get_course();
2541 $ret = array_merge($ret, course_get_format($this->modinfo->get_course())->get_format_options($this->_section));
2542 return new ArrayIterator($ret);
2546 * Works out whether activity is visible *for current user* - if this is false, they
2547 * aren't allowed to access it.
2549 * @return bool
2551 private function get_uservisible() {
2552 $userid = $this->modinfo->get_user_id();
2553 if ($this->_uservisible !== null || $userid == -1) {
2554 // Has already been calculated or does not need calculation.
2555 return $this->_uservisible;
2557 $this->_uservisible = true;
2558 if (!$this->_visible || !$this->get_available()) {
2559 $coursecontext = context_course::instance($this->get_course());
2560 if (!has_capability('moodle/course:viewhiddensections', $coursecontext, $userid)) {
2561 $this->_uservisible = false;
2564 return $this->_uservisible;
2568 * Restores the course_sections.sequence value
2570 * @return string
2572 private function get_sequence() {
2573 if (!empty($this->modinfo->sections[$this->_section])) {
2574 return implode(',', $this->modinfo->sections[$this->_section]);
2575 } else {
2576 return '';
2581 * Returns course ID - from course_sections table
2583 * @return int
2585 private function get_course() {
2586 return $this->modinfo->get_course_id();
2590 * Prepares section data for inclusion in sectioncache cache, removing items
2591 * that are set to defaults, and adding availability data if required.
2593 * Called by build_section_cache in course_modinfo only; do not use otherwise.
2594 * @param object $section Raw section data object
2596 public static function convert_for_section_cache($section) {
2597 global $CFG;
2599 // Course id stored in course table
2600 unset($section->course);
2601 // Section number stored in array key
2602 unset($section->section);
2603 // Sequence stored implicity in modinfo $sections array
2604 unset($section->sequence);
2606 // Add availability data if turned on
2607 if ($CFG->enableavailability) {
2608 require_once($CFG->dirroot . '/lib/conditionlib.php');
2609 condition_info_section::fill_availability_conditions($section);
2610 if (count($section->conditionscompletion) == 0) {
2611 unset($section->conditionscompletion);
2613 if (count($section->conditionsgrade) == 0) {
2614 unset($section->conditionsgrade);
2618 // Remove default data
2619 foreach (self::$sectioncachedefaults as $field => $value) {
2620 // Exact compare as strings to avoid problems if some strings are set
2621 // to "0" etc.
2622 if (isset($section->{$field}) && $section->{$field} === $value) {
2623 unset($section->{$field});