2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
18 * modinfolib.php - Functions/classes relating to cached information about module instances on
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
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);
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 class course_modinfo extends stdClass {
44 // For convenience we store the course object here as it is needed in other parts of code
46 // Array of section data from cache
49 // Existing data fields
50 ///////////////////////
52 // These are public for backward compatibility. Note: it is not possible to retain BC
53 // using PHP magic get methods because behaviour is different with regard to empty().
58 * @deprecated For new code, use get_course_id instead.
65 * @deprecated For new code, use get_user_id instead.
70 * Array from int (section num, e.g. 0) => array of int (course-module id); this list only
71 * includes sections that actually contain at least one course-module
73 * @deprecated For new code, use get_sections instead
78 * Array from int (cm id) => cm_info object
80 * @deprecated For new code, use get_cms or get_cm instead.
85 * Array from string (modname) => int (instance id) => cm_info object
87 * @deprecated For new code, use get_instances or get_instances_of instead.
92 * Groups that the current user belongs to. This value is usually not available (set to null)
93 * unless the course has activities set to groupmembersonly. When set, it is an array of
94 * grouping id => array of group id => group id. Includes grouping id 0 for 'all groups'.
96 * @deprecated Don't use this! For new code, use get_groups.
100 // Get methods for data
101 ///////////////////////
104 * @return object Moodle course object that was used to construct this data
106 public function get_course() {
107 return $this->course;
111 * @return int Course ID
113 public function get_course_id() {
114 return $this->courseid;
118 * @return int User ID
120 public function get_user_id() {
121 return $this->userid;
125 * @return array Array from section number (e.g. 0) to array of course-module IDs in that
126 * section; this only includes sections that contain at least one course-module
128 public function get_sections() {
129 return $this->sections;
133 * @return array Array from course-module instance to cm_info object within this course, in
134 * order of appearance
136 public function get_cms() {
141 * Obtains a single course-module object (for a course-module that is on this course).
142 * @param int $cmid Course-module ID
143 * @return cm_info Information about that course-module
144 * @throws moodle_exception If the course-module does not exist
146 public function get_cm($cmid) {
147 if (empty($this->cms[$cmid])) {
148 throw new moodle_exception('invalidcoursemodule', 'error');
150 return $this->cms[$cmid];
154 * Obtains all module instances on this course.
155 * @return array Array from module name => array from instance id => cm_info
157 public function get_instances() {
158 return $this->instances;
162 * Returns array of localised human-readable module names used in this course
164 * @param bool $plural if true returns the plural form of modules names
167 public function get_used_module_names($plural = false) {
168 $modnames = get_module_types_names($plural);
169 $modnamesused = array();
170 foreach ($this->get_cms() as $cmid => $mod) {
171 if (isset($modnames[$mod->modname]) && $mod->uservisible) {
172 $modnamesused[$mod->modname] = $modnames[$mod->modname];
175 collatorlib::asort($modnamesused);
176 return $modnamesused;
180 * Obtains all instances of a particular module on this course.
181 * @param $modname Name of module (not full frankenstyle) e.g. 'label'
182 * @return array Array from instance id => cm_info for modules on this course; empty if none
184 public function get_instances_of($modname) {
185 if (empty($this->instances[$modname])) {
188 return $this->instances[$modname];
192 * Returns groups that the current user belongs to on the course. Note: If not already
193 * available, this may make a database query.
194 * @param int $groupingid Grouping ID or 0 (default) for all groups
195 * @return array Array of int (group id) => int (same group id again); empty array if none
197 public function get_groups($groupingid=0) {
198 if (is_null($this->groups)) {
199 // NOTE: Performance could be improved here. The system caches user groups
200 // in $USER->groupmember[$courseid] => array of groupid=>groupid. Unfortunately this
201 // structure does not include grouping information. It probably could be changed to
202 // do so, without a significant performance hit on login, thus saving this one query
204 $this->groups = groups_get_user_groups($this->courseid, $this->userid);
206 if (!isset($this->groups[$groupingid])) {
209 return $this->groups[$groupingid];
213 * Gets all sections as array from section number => data about section.
214 * @return array Array of section_info objects organised by section number
216 public function get_section_info_all() {
217 return $this->sectioninfo;
221 * Gets data about specific numbered section.
222 * @param int $sectionnumber Number (not id) of section
223 * @param int $strictness Use MUST_EXIST to throw exception if it doesn't
224 * @return section_info Information for numbered section or null if not found
226 public function get_section_info($sectionnumber, $strictness = IGNORE_MISSING) {
227 if (!array_key_exists($sectionnumber, $this->sectioninfo)) {
228 if ($strictness === MUST_EXIST) {
229 throw new moodle_exception('sectionnotexist');
234 return $this->sectioninfo[$sectionnumber];
238 * Constructs based on course.
239 * Note: This constructor should not usually be called directly.
240 * Use get_fast_modinfo($course) instead as this maintains a cache.
241 * @param object $course Moodle course object, which may include modinfo
242 * @param int $userid User ID
244 public function __construct($course, $userid) {
247 // Check modinfo field is set. If not, build and load it.
248 if (empty($course->modinfo) || empty($course->sectioncache)) {
249 rebuild_course_cache($course->id);
250 $course = $DB->get_record('course', array('id'=>$course->id), '*', MUST_EXIST);
253 // Set initial values
254 $this->courseid = $course->id;
255 $this->userid = $userid;
256 $this->sections = array();
257 $this->cms = array();
258 $this->instances = array();
259 $this->groups = null;
260 $this->course = $course;
262 // Load modinfo field into memory as PHP object and check it's valid
263 $info = unserialize($course->modinfo);
264 if (!is_array($info)) {
265 // hmm, something is wrong - lets try to fix it
266 rebuild_course_cache($course->id);
267 $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
268 $info = unserialize($course->modinfo);
269 if (!is_array($info)) {
270 // If it still fails, abort
271 debugging('Problem with "modinfo" data for this course');
276 // Load sectioncache field into memory as PHP object and check it's valid
277 $sectioncache = unserialize($course->sectioncache);
278 if (!is_array($sectioncache)) {
279 // hmm, something is wrong - let's fix it
280 rebuild_course_cache($course->id);
281 $course->sectioncache = $DB->get_field('course', 'sectioncache', array('id'=>$course->id));
282 $sectioncache = unserialize($course->sectioncache);
283 if (!is_array($sectioncache)) {
284 // If it still fails, abort
285 debugging('Problem with "sectioncache" data for this course');
290 // If we haven't already preloaded contexts for the course, do it now
291 preload_course_contexts($course->id);
293 // Loop through each piece of module data, constructing it
294 $modexists = array();
295 foreach ($info as $mod) {
296 if (empty($mod->name)) {
297 // something is wrong here
301 // Skip modules which don't exist
302 if (empty($modexists[$mod->mod])) {
303 if (!file_exists("$CFG->dirroot/mod/$mod->mod/lib.php")) {
306 $modexists[$mod->mod] = true;
309 // Construct info for this module
310 $cm = new cm_info($this, $course, $mod, $info);
312 // Store module in instances and cms array
313 if (!isset($this->instances[$cm->modname])) {
314 $this->instances[$cm->modname] = array();
316 $this->instances[$cm->modname][$cm->instance] = $cm;
317 $this->cms[$cm->id] = $cm;
319 // Reconstruct sections. This works because modules are stored in order
320 if (!isset($this->sections[$cm->sectionnum])) {
321 $this->sections[$cm->sectionnum] = array();
323 $this->sections[$cm->sectionnum][] = $cm->id;
326 // Expand section objects
327 $this->sectioninfo = array();
328 foreach ($sectioncache as $number => $data) {
329 // Calculate sequence
330 if (isset($this->sections[$number])) {
331 $sequence = implode(',', $this->sections[$number]);
336 $this->sectioninfo[$number] = new section_info($data, $number, $course->id, $sequence,
340 // We need at least 'dynamic' data from each course-module (this is basically the remaining
341 // data which was always present in previous version of get_fast_modinfo, so it's required
342 // for BC). Creating it in a second pass is necessary because obtain_dynamic_data sometimes
343 // needs to be able to refer to a 'complete' (with basic data) modinfo.
344 foreach ($this->cms as $cm) {
345 $cm->obtain_dynamic_data();
350 * Builds a list of information about sections on a course to be stored in
351 * the course cache. (Does not include information that is already cached
352 * in some other way.)
354 * Used internally by rebuild_course_cache function; do not use otherwise.
355 * @param int $courseid Course ID
356 * @return array Information about sections, indexed by section number (not id)
358 public static function build_section_cache($courseid) {
362 $sections = $DB->get_records('course_sections', array('course' => $courseid), 'section',
363 'section, id, course, name, summary, summaryformat, sequence, visible, ' .
364 'availablefrom, availableuntil, showavailability, groupingid');
365 $compressedsections = array();
367 $formatoptionsdef = course_get_format($courseid)->section_format_options();
368 // Remove unnecessary data and add availability
369 foreach ($sections as $number => $section) {
370 // Add cached options from course format to $section object
371 foreach ($formatoptionsdef as $key => $option) {
372 if (!empty($option['cache'])) {
373 $formatoptions = course_get_format($courseid)->get_format_options($section);
374 if (!array_key_exists('cachedefault', $option) || $option['cachedefault'] !== $formatoptions[$key]) {
375 $section->$key = $formatoptions[$key];
379 // Clone just in case it is reused elsewhere
380 $compressedsections[$number] = clone($section);
381 section_info::convert_for_section_cache($compressedsections[$number]);
384 return $compressedsections;
390 * Data about a single module on a course. This contains most of the fields in the course_modules
391 * table, plus additional data when required.
393 * This object has many public fields; code should treat all these fields as read-only and set
394 * data only using the supplied set functions. Setting the fields directly is not supported
395 * and may cause problems later.
397 class cm_info extends stdClass {
399 * State: Only basic data from modinfo cache is available.
401 const STATE_BASIC = 0;
404 * State: Dynamic data is available too.
406 const STATE_DYNAMIC = 1;
409 * State: View data (for course page) is available.
411 const STATE_VIEW = 2;
415 * @var course_modinfo
420 * Level of information stored inside this object (STATE_xx constant)
425 // Existing data fields
426 ///////////////////////
429 * Course-module ID - from course_modules table
435 * Module instance (ID within module table) - from course_modules table
441 * Course ID - from course_modules table
447 * 'ID number' from course-modules table (arbitrary text set by user) - from
448 * course_modules table
454 * Time that this course-module was added (unix time) - from course_modules table
460 * This variable is not used and is included here only so it can be documented.
461 * Once the database entry is removed from course_modules, it should be deleted
464 * @deprecated Do not use this variable
469 * Visible setting (0 or 1; if this is 0, students cannot see/access the activity) - from
470 * course_modules table
476 * Old visible setting (if the entire section is hidden, the previous value for
477 * visible is stored in this field) - from course_modules table
483 * Group mode (one of the constants NONE, SEPARATEGROUPS, or VISIBLEGROUPS) - from
484 * course_modules table
490 * Grouping ID (0 = all groupings)
496 * Group members only (if set to 1, only members of a suitable group see this link on the
497 * course page; 0 = everyone sees it even if they don't belong to a suitable group) - from
498 * course_modules table
501 public $groupmembersonly;
504 * Indicates whether the course containing the module has forced the groupmode
505 * This means that cm_info::$groupmode should be ignored and cm_info::$coursegroupmode be
509 public $coursegroupmodeforce;
512 * Group mode (one of the constants NONE, SEPARATEGROUPS, or VISIBLEGROUPS) - from
513 * course table - as specified for the course containing the module
514 * Effective only if cm_info::$coursegroupmodeforce is set
517 public $coursegroupmode;
520 * Indent level on course page (0 = no indent) - from course_modules table
526 * Activity completion setting for this activity, COMPLETION_TRACKING_xx constant - from
527 * course_modules table
533 * Set to the item number (usually 0) if completion depends on a particular
534 * grade of this activity, or null if completion does not depend on a grade - from
535 * course_modules table
538 public $completiongradeitemnumber;
541 * 1 if 'on view' completion is enabled, 0 otherwise - from course_modules table
544 public $completionview;
547 * Set to a unix time if completion of this activity is expected at a
548 * particular time, 0 if no time set - from course_modules table
551 public $completionexpected;
554 * Available date for this activity (0 if not set, or set to seconds since epoch; before this
555 * date, activity does not display to students) - from course_modules table
558 public $availablefrom;
561 * Available until date for this activity (0 if not set, or set to seconds since epoch; from
562 * this date, activity does not display to students) - from course_modules table
565 public $availableuntil;
568 * When activity is unavailable, this field controls whether it is shown to students (0 =
569 * hide completely, 1 = show greyed out with information about when it will be available) -
570 * from course_modules table
573 public $showavailability;
576 * Controls whether the description of the activity displays on the course main page (in
577 * addition to anywhere it might display within the activity itself). 0 = do not show
578 * on main page, 1 = show on main page.
581 public $showdescription;
584 * Extra HTML that is put in an unhelpful part of the HTML when displaying this module in
585 * course page - from cached data in modinfo field
586 * @deprecated This is crazy, don't use it. Replaced by ->extraclasses and ->onclick
592 * Name of icon to use - from cached data in modinfo field
598 * Component that contains icon - from cached data in modinfo field
601 public $iconcomponent;
604 * Name of module e.g. 'forum' (this is the same name as the module's main database
605 * table) - from cached data in modinfo field
611 * ID of module - from course_modules table
617 * Name of module instance for display on page e.g. 'General discussion forum' - from cached
618 * data in modinfo field
624 * Section number that this course-module is in (section 0 = above the calendar, section 1
625 * = week/topic 1, etc) - from cached data in modinfo field
631 * Section id - from course_modules table
637 * Availability conditions for this course-module based on the completion of other
638 * course-modules (array from other course-module id to required completion state for that
639 * module) - from cached data in modinfo field
642 public $conditionscompletion;
645 * Availability conditions for this course-module based on course grades (array from
646 * grade item id to object with ->min, ->max fields) - from cached data in modinfo field
649 public $conditionsgrade;
652 * Availability conditions for this course-module based on user fields
655 public $conditionsfield;
658 * True if this course-module is available to students i.e. if all availability conditions
659 * are met - obtained dynamically
665 * If course-module is not available to students, this string gives information about
666 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
667 * January 2010') for display on main page - obtained dynamically
670 public $availableinfo;
673 * True if this course-module is available to the CURRENT user (for example, if current user
674 * has viewhiddenactivities capability, they can access the course-module even if it is not
675 * visible or not available, so this would be true in that case)
681 * Module context - hacky shortcut
688 // New data available only via functions
689 ////////////////////////////////////////
704 private $extraclasses;
707 * @var moodle_url full external url pointing to icon image for activity
729 private $afterediticons;
732 * Magic method getter
734 * @param string $name
737 public function __get($name) {
740 return $this->get_module_type_name(true);
742 return $this->get_module_type_name();
744 debugging('Invalid cm_info property accessed: '.$name);
750 * @return bool True if this module has a 'view' page that should be linked to in navigation
751 * etc (note: modules may still have a view.php file, but return false if this is not
752 * intended to be linked to from 'normal' parts of the interface; this is what label does).
754 public function has_view() {
755 return !is_null($this->url);
759 * @return moodle_url URL to link to for this module, or null if it doesn't have a view page
761 public function get_url() {
766 * Obtains content to display on main (view) page.
767 * Note: Will collect view data, if not already obtained.
768 * @return string Content to display on main page below link, or empty string if none
770 public function get_content() {
771 $this->obtain_view_data();
772 return $this->content;
776 * Returns the content to display on course/overview page, formatted and passed through filters
778 * if $options['context'] is not specified, the module context is used
780 * @param array|stdClass $options formatting options, see {@link format_text()}
783 public function get_formatted_content($options = array()) {
784 $this->obtain_view_data();
785 if (empty($this->content)) {
788 // Improve filter performance by preloading filter setttings for all
789 // activities on the course (this does nothing if called multiple
791 filter_preload_activities($this->get_modinfo());
793 $options = (array)$options;
794 if (!isset($options['context'])) {
795 $options['context'] = context_module::instance($this->id);
797 return format_text($this->content, FORMAT_HTML, $options);
801 * Returns the name to display on course/overview page, formatted and passed through filters
803 * if $options['context'] is not specified, the module context is used
805 * @param array|stdClass $options formatting options, see {@link format_string()}
808 public function get_formatted_name($options = array()) {
809 $options = (array)$options;
810 if (!isset($options['context'])) {
811 $options['context'] = context_module::instance($this->id);
813 return format_string($this->name, true, $options);
817 * Note: Will collect view data, if not already obtained.
818 * @return string Extra CSS classes to add to html output for this activity on main page
820 public function get_extra_classes() {
821 $this->obtain_view_data();
822 return $this->extraclasses;
826 * @return string Content of HTML on-click attribute. This string will be used literally
827 * as a string so should be pre-escaped.
829 public function get_on_click() {
830 // Does not need view data; may be used by navigation
831 return $this->onclick;
834 * @return mixed Optional custom data stored in modinfo cache for this activity, or null if none
836 public function get_custom_data() {
837 return $this->customdata;
841 * Note: Will collect view data, if not already obtained.
842 * @return string Extra HTML code to display after link
844 public function get_after_link() {
845 $this->obtain_view_data();
846 return $this->afterlink;
850 * Note: Will collect view data, if not already obtained.
851 * @return string Extra HTML code to display after editing icons (e.g. more icons)
853 public function get_after_edit_icons() {
854 $this->obtain_view_data();
855 return $this->afterediticons;
859 * @param moodle_core_renderer $output Output render to use, or null for default (global)
860 * @return moodle_url Icon URL for a suitable icon to put beside this cm
862 public function get_icon_url($output = null) {
867 // Support modules setting their own, external, icon image
868 if (!empty($this->iconurl)) {
869 $icon = $this->iconurl;
871 // Fallback to normal local icon + component procesing
872 } else if (!empty($this->icon)) {
873 if (substr($this->icon, 0, 4) === 'mod/') {
874 list($modname, $iconname) = explode('/', substr($this->icon, 4), 2);
875 $icon = $output->pix_url($iconname, $modname);
877 if (!empty($this->iconcomponent)) {
878 // Icon has specified component
879 $icon = $output->pix_url($this->icon, $this->iconcomponent);
881 // Icon does not have specified component, use default
882 $icon = $output->pix_url($this->icon);
886 $icon = $output->pix_url('icon', $this->modname);
892 * Returns a localised human-readable name of the module type
894 * @param bool $plural return plural form
897 public function get_module_type_name($plural = false) {
898 $modnames = get_module_types_names($plural);
899 if (isset($modnames[$this->modname])) {
900 return $modnames[$this->modname];
907 * @return course_modinfo Modinfo object that this came from
909 public function get_modinfo() {
910 return $this->modinfo;
914 * @return object Moodle course object that was used to construct this data
916 public function get_course() {
917 return $this->modinfo->get_course();
924 * Sets content to display on course view page below link (if present).
925 * @param string $content New content as HTML string (empty string if none)
928 public function set_content($content) {
929 $this->content = $content;
933 * Sets extra classes to include in CSS.
934 * @param string $extraclasses Extra classes (empty string if none)
937 public function set_extra_classes($extraclasses) {
938 $this->extraclasses = $extraclasses;
942 * Sets the external full url that points to the icon being used
943 * by the activity. Useful for external-tool modules (lti...)
944 * If set, takes precedence over $icon and $iconcomponent
946 * @param moodle_url $iconurl full external url pointing to icon image for activity
949 public function set_icon_url(moodle_url $iconurl) {
950 $this->iconurl = $iconurl;
954 * Sets value of on-click attribute for JavaScript.
955 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
956 * @param string $onclick New onclick attribute which should be HTML-escaped
957 * (empty string if none)
960 public function set_on_click($onclick) {
961 $this->check_not_view_only();
962 $this->onclick = $onclick;
966 * Sets HTML that displays after link on course view page.
967 * @param string $afterlink HTML string (empty string if none)
970 public function set_after_link($afterlink) {
971 $this->afterlink = $afterlink;
975 * Sets HTML that displays after edit icons on course view page.
976 * @param string $afterediticons HTML string (empty string if none)
979 public function set_after_edit_icons($afterediticons) {
980 $this->afterediticons = $afterediticons;
984 * Changes the name (text of link) for this module instance.
985 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
986 * @param string $name Name of activity / link text
989 public function set_name($name) {
990 $this->update_user_visible();
995 * Turns off the view link for this module instance.
996 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
999 public function set_no_view_link() {
1000 $this->check_not_view_only();
1005 * Sets the 'uservisible' flag. This can be used (by setting false) to prevent access and
1006 * display of this module link for the current user.
1007 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1008 * @param bool $uservisible
1011 public function set_user_visible($uservisible) {
1012 $this->check_not_view_only();
1013 $this->uservisible = $uservisible;
1017 * Sets the 'available' flag and related details. This flag is normally used to make
1018 * course modules unavailable until a certain date or condition is met. (When a course
1019 * module is unavailable, it is still visible to users who have viewhiddenactivities
1022 * When this is function is called, user-visible status is recalculated automatically.
1024 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1025 * @param bool $available False if this item is not 'available'
1026 * @param int $showavailability 0 = do not show this item at all if it's not available,
1027 * 1 = show this item greyed out with the following message
1028 * @param string $availableinfo Information about why this is not available which displays
1029 * to those who have viewhiddenactivities, and to everyone if showavailability is set;
1030 * note that this function replaces the existing data (if any)
1033 public function set_available($available, $showavailability=0, $availableinfo='') {
1034 $this->check_not_view_only();
1035 $this->available = $available;
1036 $this->showavailability = $showavailability;
1037 $this->availableinfo = $availableinfo;
1038 $this->update_user_visible();
1042 * Some set functions can only be called from _cm_info_dynamic and not _cm_info_view.
1043 * This is because they may affect parts of this object which are used on pages other
1044 * than the view page (e.g. in the navigation block, or when checking access on
1048 private function check_not_view_only() {
1049 if ($this->state >= self::STATE_DYNAMIC) {
1050 throw new coding_exception('Cannot set this data from _cm_info_view because it may ' .
1051 'affect other pages as well as view');
1056 * Constructor should not be called directly; use get_fast_modinfo.
1057 * @param course_modinfo $modinfo Parent object
1058 * @param object $course Course row
1059 * @param object $mod Module object from the modinfo field of course table
1060 * @param object $info Entire object from modinfo field of course table
1062 public function __construct(course_modinfo $modinfo, $course, $mod, $info) {
1064 $this->modinfo = $modinfo;
1066 $this->id = $mod->cm;
1067 $this->instance = $mod->id;
1068 $this->course = $course->id;
1069 $this->modname = $mod->mod;
1070 $this->idnumber = isset($mod->idnumber) ? $mod->idnumber : '';
1071 $this->name = $mod->name;
1072 $this->visible = $mod->visible;
1073 $this->sectionnum = $mod->section; // Note weirdness with name here
1074 $this->groupmode = isset($mod->groupmode) ? $mod->groupmode : 0;
1075 $this->groupingid = isset($mod->groupingid) ? $mod->groupingid : 0;
1076 $this->groupmembersonly = isset($mod->groupmembersonly) ? $mod->groupmembersonly : 0;
1077 $this->coursegroupmodeforce = $course->groupmodeforce;
1078 $this->coursegroupmode = $course->groupmode;
1079 $this->indent = isset($mod->indent) ? $mod->indent : 0;
1080 $this->extra = isset($mod->extra) ? $mod->extra : '';
1081 $this->extraclasses = isset($mod->extraclasses) ? $mod->extraclasses : '';
1082 $this->iconurl = isset($mod->iconurl) ? $mod->iconurl : '';
1083 $this->onclick = isset($mod->onclick) ? $mod->onclick : '';
1084 $this->content = isset($mod->content) ? $mod->content : '';
1085 $this->icon = isset($mod->icon) ? $mod->icon : '';
1086 $this->iconcomponent = isset($mod->iconcomponent) ? $mod->iconcomponent : '';
1087 $this->customdata = isset($mod->customdata) ? $mod->customdata : '';
1088 $this->context = context_module::instance($mod->cm);
1089 $this->showdescription = isset($mod->showdescription) ? $mod->showdescription : 0;
1090 $this->state = self::STATE_BASIC;
1092 // Note: These fields from $cm were not present in cm_info in Moodle
1093 // 2.0.2 and prior. They may not be available if course cache hasn't
1094 // been rebuilt since then.
1095 $this->section = isset($mod->sectionid) ? $mod->sectionid : 0;
1096 $this->module = isset($mod->module) ? $mod->module : 0;
1097 $this->added = isset($mod->added) ? $mod->added : 0;
1098 $this->score = isset($mod->score) ? $mod->score : 0;
1099 $this->visibleold = isset($mod->visibleold) ? $mod->visibleold : 0;
1101 // Note: it saves effort and database space to always include the
1102 // availability and completion fields, even if availability or completion
1103 // are actually disabled
1104 $this->completion = isset($mod->completion) ? $mod->completion : 0;
1105 $this->completiongradeitemnumber = isset($mod->completiongradeitemnumber)
1106 ? $mod->completiongradeitemnumber : null;
1107 $this->completionview = isset($mod->completionview)
1108 ? $mod->completionview : 0;
1109 $this->completionexpected = isset($mod->completionexpected)
1110 ? $mod->completionexpected : 0;
1111 $this->showavailability = isset($mod->showavailability) ? $mod->showavailability : 0;
1112 $this->availablefrom = isset($mod->availablefrom) ? $mod->availablefrom : 0;
1113 $this->availableuntil = isset($mod->availableuntil) ? $mod->availableuntil : 0;
1114 $this->conditionscompletion = isset($mod->conditionscompletion)
1115 ? $mod->conditionscompletion : array();
1116 $this->conditionsgrade = isset($mod->conditionsgrade)
1117 ? $mod->conditionsgrade : array();
1118 $this->conditionsfield = isset($mod->conditionsfield)
1119 ? $mod->conditionsfield : array();
1122 if (!isset($modviews[$this->modname])) {
1123 $modviews[$this->modname] = !plugin_supports('mod', $this->modname,
1124 FEATURE_NO_VIEW_LINK);
1126 $this->url = $modviews[$this->modname]
1127 ? new moodle_url('/mod/' . $this->modname . '/view.php', array('id'=>$this->id))
1132 * If dynamic data for this course-module is not yet available, gets it.
1134 * This function is automatically called when constructing course_modinfo, so users don't
1137 * Dynamic data is data which does not come directly from the cache but is calculated at
1138 * runtime based on the current user. Primarily this concerns whether the user can access
1139 * the module or not.
1141 * As part of this function, the module's _cm_info_dynamic function from its lib.php will
1142 * be called (if it exists).
1145 public function obtain_dynamic_data() {
1147 if ($this->state >= self::STATE_DYNAMIC) {
1150 $userid = $this->modinfo->get_user_id();
1152 if (!empty($CFG->enableavailability)) {
1153 // Get availability information
1154 $ci = new condition_info($this);
1155 // Note that the modinfo currently available only includes minimal details (basic data)
1156 // so passing it to this function is a bit dangerous as it would cause infinite
1157 // recursion if it tried to get dynamic data, however we know that this function only
1159 $this->available = $ci->is_available($this->availableinfo, true,
1160 $userid, $this->modinfo);
1162 // Check parent section
1163 $parentsection = $this->modinfo->get_section_info($this->sectionnum);
1164 if (!$parentsection->available) {
1165 // Do not store info from section here, as that is already
1166 // presented from the section (if appropriate) - just change
1168 $this->available = false;
1171 $this->available = true;
1174 // Update visible state for current user
1175 $this->update_user_visible();
1177 // Let module make dynamic changes at this point
1178 $this->call_mod_function('cm_info_dynamic');
1179 $this->state = self::STATE_DYNAMIC;
1183 * Works out whether activity is available to the current user
1185 * If the activity is unavailable, additional checks are required to determine if its hidden or greyed out
1187 * @see is_user_access_restricted_by_group()
1188 * @see is_user_access_restricted_by_conditional_access()
1191 private function update_user_visible() {
1193 $modcontext = context_module::instance($this->id);
1194 $userid = $this->modinfo->get_user_id();
1195 $this->uservisible = true;
1197 // If the user cannot access the activity set the uservisible flag to false.
1198 // Additional checks are required to determine whether the activity is entirely hidden or just greyed out.
1199 if ((!$this->visible or !$this->available) and
1200 !has_capability('moodle/course:viewhiddenactivities', $modcontext, $userid)) {
1202 $this->uservisible = false;
1205 // Check group membership.
1206 if ($this->is_user_access_restricted_by_group()) {
1208 $this->uservisible = false;
1209 // Ensure activity is completely hidden from the user.
1210 $this->showavailability = 0;
1215 * Checks whether the module's group settings restrict the current user's access
1217 * @return bool True if the user access is restricted
1219 public function is_user_access_restricted_by_group() {
1222 if (!empty($CFG->enablegroupmembersonly) and !empty($this->groupmembersonly)) {
1223 $modcontext = context_module::instance($this->id);
1224 $userid = $this->modinfo->get_user_id();
1225 if (!has_capability('moodle/site:accessallgroups', $modcontext, $userid)) {
1226 // If the activity has 'group members only' and you don't have accessallgroups...
1227 $groups = $this->modinfo->get_groups($this->groupingid);
1228 if (empty($groups)) {
1229 // ...and you don't belong to a group, then set it so you can't see/access it
1238 * Checks whether the module's conditional access settings mean that the user cannot see the activity at all
1240 * @return bool True if the user cannot see the module. False if the activity is either available or should be greyed out.
1242 public function is_user_access_restricted_by_conditional_access() {
1245 if (empty($CFG->enableavailability)) {
1249 // If module will always be visible anyway (but greyed out), don't bother checking anything else
1250 if ($this->showavailability == CONDITION_STUDENTVIEW_SHOW) {
1254 // Can the user see hidden modules?
1255 $modcontext = context_module::instance($this->id);
1256 $userid = $this->modinfo->get_user_id();
1257 if (has_capability('moodle/course:viewhiddenactivities', $modcontext, $userid)) {
1261 // Is the module hidden due to unmet conditions?
1262 if (!$this->available) {
1270 * Calls a module function (if exists), passing in one parameter: this object.
1271 * @param string $type Name of function e.g. if this is 'grooblezorb' and the modname is
1272 * 'forum' then it will try to call 'mod_forum_grooblezorb' or 'forum_grooblezorb'
1275 private function call_mod_function($type) {
1277 $libfile = $CFG->dirroot . '/mod/' . $this->modname . '/lib.php';
1278 if (file_exists($libfile)) {
1279 include_once($libfile);
1280 $function = 'mod_' . $this->modname . '_' . $type;
1281 if (function_exists($function)) {
1284 $function = $this->modname . '_' . $type;
1285 if (function_exists($function)) {
1293 * If view data for this course-module is not yet available, obtains it.
1295 * This function is automatically called if any of the functions (marked) which require
1296 * view data are called.
1298 * View data is data which is needed only for displaying the course main page (& any similar
1299 * functionality on other pages) but is not needed in general. Obtaining view data may have
1300 * a performance cost.
1302 * As part of this function, the module's _cm_info_view function from its lib.php will
1303 * be called (if it exists).
1306 private function obtain_view_data() {
1307 if ($this->state >= self::STATE_VIEW) {
1311 // Let module make changes at this point
1312 $this->call_mod_function('cm_info_view');
1313 $this->state = self::STATE_VIEW;
1319 * Returns reference to full info about modules in course (including visibility).
1320 * Cached and as fast as possible (0 or 1 db query).
1322 * use get_fast_modinfo($courseid, 0, true) to reset the static cache for particular course
1323 * use get_fast_modinfo(0, 0, true) to reset the static cache for all courses
1325 * @uses MAX_MODINFO_CACHE_SIZE
1326 * @param int|stdClass $courseorid object from DB table 'course' or just a course id
1327 * @param int $userid User id to populate 'uservisible' attributes of modules and sections.
1328 * Set to 0 for current user (default)
1329 * @param bool $resetonly whether we want to get modinfo or just reset the cache
1330 * @return course_modinfo|null Module information for course, or null if resetting
1332 function get_fast_modinfo($courseorid, $userid = 0, $resetonly = false) {
1335 static $cache = array();
1337 // compartibility with syntax prior to 2.4:
1338 if ($courseorid === 'reset') {
1339 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);
1344 // Function get_fast_modinfo() can never be called during upgrade unless it is used for clearing cache only.
1346 upgrade_ensure_not_running();
1349 if (is_object($courseorid)) {
1350 $course = $courseorid;
1352 $course = (object)array('id' => $courseorid, 'modinfo' => null, 'sectioncache' => null);
1355 // Function is called with $reset = true
1357 if (isset($course->id) && $course->id > 0) {
1358 $cache[$course->id] = false;
1360 foreach (array_keys($cache) as $key) {
1361 $cache[$key] = false;
1367 // Function is called with $reset = false, retrieve modinfo
1368 if (empty($userid)) {
1369 $userid = $USER->id;
1372 if (array_key_exists($course->id, $cache)) {
1373 if ($cache[$course->id] === false) {
1374 // this course has been recently reset, do not rely on modinfo and sectioncache in $course
1375 $course->modinfo = null;
1376 $course->sectioncache = null;
1377 } else if ($cache[$course->id]->userid == $userid) {
1378 // this course's modinfo for the same user was recently retrieved, return cached
1379 return $cache[$course->id];
1383 if (!property_exists($course, 'modinfo')) {
1384 debugging('Coding problem - missing course modinfo property in get_fast_modinfo() call');
1387 if (!property_exists($course, 'sectioncache')) {
1388 debugging('Coding problem - missing course sectioncache property in get_fast_modinfo() call');
1391 unset($cache[$course->id]); // prevent potential reference problems when switching users
1393 $cache[$course->id] = new course_modinfo($course, $userid);
1395 // Ensure cache does not use too much RAM
1396 if (count($cache) > MAX_MODINFO_CACHE_SIZE) {
1399 unset($cache[$key]->instances);
1400 unset($cache[$key]->cms);
1401 unset($cache[$key]);
1404 return $cache[$course->id];
1408 * Rebuilds the cached list of course activities stored in the database
1409 * @param int $courseid - id of course to rebuild, empty means all
1410 * @param boolean $clearonly - only clear the modinfo fields, gets rebuild automatically on the fly
1412 function rebuild_course_cache($courseid=0, $clearonly=false) {
1413 global $COURSE, $SITE, $DB, $CFG;
1415 // Function rebuild_course_cache() can not be called during upgrade unless it's clear only.
1416 if (!$clearonly && !upgrade_ensure_not_running(true)) {
1420 // Destroy navigation caches
1421 navigation_cache::destroy_volatile_caches();
1423 if (class_exists('format_base')) {
1424 // if file containing class is not loaded, there is no cache there anyway
1425 format_base::reset_course_cache($courseid);
1429 if (empty($courseid)) {
1430 $DB->execute('UPDATE {course} set modinfo = ?, sectioncache = ?', array(null, null));
1432 // Clear both fields in one update
1433 $resetobj = (object)array('id' => $courseid, 'modinfo' => null, 'sectioncache' => null);
1434 $DB->update_record('course', $resetobj);
1436 // update cached global COURSE too ;-)
1437 if ($courseid == $COURSE->id or empty($courseid)) {
1438 $COURSE->modinfo = null;
1439 $COURSE->sectioncache = null;
1441 if ($courseid == $SITE->id) {
1442 $SITE->modinfo = null;
1443 $SITE->sectioncache = null;
1445 // reset the fast modinfo cache
1446 get_fast_modinfo($courseid, 0, true);
1450 require_once("$CFG->dirroot/course/lib.php");
1453 $select = array('id'=>$courseid);
1456 @set_time_limit(0); // this could take a while! MDL-10954
1459 $rs = $DB->get_recordset("course", $select,'','id,fullname');
1460 foreach ($rs as $course) {
1461 $modinfo = serialize(get_array_of_activities($course->id));
1462 $sectioncache = serialize(course_modinfo::build_section_cache($course->id));
1463 $updateobj = (object)array('id' => $course->id,
1464 'modinfo' => $modinfo, 'sectioncache' => $sectioncache);
1465 $DB->update_record("course", $updateobj);
1466 // update cached global COURSE too ;-)
1467 if ($course->id == $COURSE->id) {
1468 $COURSE->modinfo = $modinfo;
1469 $COURSE->sectioncache = $sectioncache;
1471 if ($course->id == $SITE->id) {
1472 $SITE->modinfo = $modinfo;
1473 $SITE->sectioncache = $sectioncache;
1477 // reset the fast modinfo cache
1478 get_fast_modinfo($courseid, 0, true);
1483 * Class that is the return value for the _get_coursemodule_info module API function.
1485 * Note: For backward compatibility, you can also return a stdclass object from that function.
1486 * The difference is that the stdclass object may contain an 'extra' field (deprecated,
1487 * use extraclasses and onclick instead). The stdclass object may not contain
1488 * the new fields defined here (content, extraclasses, customdata).
1490 class cached_cm_info {
1492 * Name (text of link) for this activity; Leave unset to accept default name
1498 * Name of icon for this activity. Normally, this should be used together with $iconcomponent
1499 * to define the icon, as per pix_url function.
1500 * For backward compatibility, if this value is of the form 'mod/forum/icon' then an icon
1501 * within that module will be used.
1502 * @see cm_info::get_icon_url()
1503 * @see renderer_base::pix_url()
1509 * Component for icon for this activity, as per pix_url; leave blank to use default 'moodle'
1511 * @see renderer_base::pix_url()
1514 public $iconcomponent;
1517 * HTML content to be displayed on the main page below the link (if any) for this course-module
1523 * Custom data to be stored in modinfo for this activity; useful if there are cases when
1524 * internal information for this activity type needs to be accessible from elsewhere on the
1525 * course without making database queries. May be of any type but should be short.
1531 * Extra CSS class or classes to be added when this activity is displayed on the main page;
1532 * space-separated string
1535 public $extraclasses;
1538 * External URL image to be used by activity as icon, useful for some external-tool modules
1539 * like lti. If set, takes precedence over $icon and $iconcomponent
1545 * Content of onclick JavaScript; escaped HTML to be inserted as attribute value
1553 * Data about a single section on a course. This contains the fields from the
1554 * course_sections table, plus additional data when required.
1556 class section_info implements IteratorAggregate {
1558 * Section ID - from course_sections table
1564 * Course ID - from course_sections table
1570 * Section number - from course_sections table
1576 * Section name if specified - from course_sections table
1582 * Section visibility (1 = visible) - from course_sections table
1588 * Section summary text if specified - from course_sections table
1594 * Section summary text format (FORMAT_xx constant) - from course_sections table
1597 private $_summaryformat;
1600 * When section is unavailable, this field controls whether it is shown to students (0 =
1601 * hide completely, 1 = show greyed out with information about when it will be available) -
1602 * from course_sections table
1605 private $_showavailability;
1608 * Available date for this section (0 if not set, or set to seconds since epoch; before this
1609 * date, section does not display to students) - from course_sections table
1612 private $_availablefrom;
1615 * Available until date for this section (0 if not set, or set to seconds since epoch; from
1616 * this date, section does not display to students) - from course_sections table
1619 private $_availableuntil;
1622 * If section is restricted to users of a particular grouping, this is its id
1623 * (0 if not set) - from course_sections table
1626 private $_groupingid;
1629 * Availability conditions for this section based on the completion of
1630 * course-modules (array from course-module id to required completion state
1631 * for that module) - from cached data in sectioncache field
1634 private $_conditionscompletion;
1637 * Availability conditions for this section based on course grades (array from
1638 * grade item id to object with ->min, ->max fields) - from cached data in
1639 * sectioncache field
1642 private $_conditionsgrade;
1645 * Availability conditions for this section based on user fields
1648 private $_conditionsfield;
1651 * True if this section is available to students i.e. if all availability conditions
1652 * are met - obtained dynamically
1655 private $_available;
1658 * If section is not available to students, this string gives information about
1659 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
1660 * January 2010') for display on main page - obtained dynamically
1663 private $_availableinfo;
1666 * True if this section is available to the CURRENT user (for example, if current user
1667 * has viewhiddensections capability, they can access the section even if it is not
1668 * visible or not available, so this would be true in that case)
1671 private $_uservisible;
1674 * Default values for sectioncache fields; if a field has this value, it won't
1675 * be stored in the sectioncache cache, to save space. Checks are done by ===
1676 * which means values must all be strings.
1679 private static $sectioncachedefaults = array(
1682 'summaryformat' => '1', // FORMAT_HTML, but must be a string
1684 'showavailability' => '0',
1685 'availablefrom' => '0',
1686 'availableuntil' => '0',
1687 'groupingid' => '0',
1691 * Stores format options that have been cached when building 'coursecache'
1692 * When the format option is requested we look first if it has been cached
1695 private $cachedformatoptions = array();
1698 * Constructs object from database information plus extra required data.
1699 * @param object $data Array entry from cached sectioncache
1700 * @param int $number Section number (array key)
1701 * @param int $courseid Course ID
1702 * @param int $sequence Sequence of course-module ids contained within
1703 * @param course_modinfo $modinfo Owner (needed for checking availability)
1704 * @param int $userid User ID
1706 public function __construct($data, $number, $courseid, $sequence, $modinfo, $userid) {
1708 require_once($CFG->dirroot.'/course/lib.php');
1710 // Data that is always present
1711 $this->_id = $data->id;
1713 $defaults = self::$sectioncachedefaults +
1714 array('conditionscompletion' => array(),
1715 'conditionsgrade' => array(),
1716 'conditionsfield' => array());
1718 // Data that may use default values to save cache size
1719 foreach ($defaults as $field => $value) {
1720 if (isset($data->{$field})) {
1721 $this->{'_'.$field} = $data->{$field};
1723 $this->{'_'.$field} = $value;
1727 // cached course format data
1728 $formatoptionsdef = course_get_format($courseid)->section_format_options();
1729 foreach ($formatoptionsdef as $field => $option) {
1730 if (!empty($option['cache'])) {
1731 if (isset($data->{$field})) {
1732 $this->cachedformatoptions[$field] = $data->{$field};
1733 } else if (array_key_exists('cachedefault', $option)) {
1734 $this->cachedformatoptions[$field] = $option['cachedefault'];
1739 // Other data from other places
1740 $this->_course = $courseid;
1741 $this->_section = $number;
1742 $this->_sequence = $sequence;
1744 // Availability data
1745 if (!empty($CFG->enableavailability)) {
1746 require_once($CFG->libdir. '/conditionlib.php');
1747 // Get availability information
1748 $ci = new condition_info_section($this);
1749 $this->_available = $ci->is_available($this->_availableinfo, true,
1751 // Display grouping info if available & not already displaying
1752 // (it would already display if current user doesn't have access)
1753 // for people with managegroups - same logic/class as grouping label
1754 // on individual activities.
1755 $context = context_course::instance($courseid);
1756 if ($this->_availableinfo === '' && $this->_groupingid &&
1757 has_capability('moodle/course:managegroups', $context)) {
1758 $groupings = groups_get_all_groupings($courseid);
1759 $this->_availableinfo = html_writer::tag('span', '(' . format_string(
1760 $groupings[$this->_groupingid]->name, true, array('context' => $context)) .
1761 ')', array('class' => 'groupinglabel'));
1764 $this->_available = true;
1767 // Update visibility for current user
1768 $this->update_user_visible($userid);
1772 * Magic method to check if the property is set
1774 * @param string $name name of the property
1777 public function __isset($name) {
1778 if (property_exists($this, '_'.$name)) {
1779 return isset($this->{'_'.$name});
1781 $defaultformatoptions = course_get_format($this->_course)->section_format_options();
1782 if (array_key_exists($name, $defaultformatoptions)) {
1783 $value = $this->__get($name);
1784 return isset($value);
1790 * Magic method to check if the property is empty
1792 * @param string $name name of the property
1795 public function __empty($name) {
1796 if (property_exists($this, '_'.$name)) {
1797 return empty($this->{'_'.$name});
1799 $defaultformatoptions = course_get_format($this->_course)->section_format_options();
1800 if (array_key_exists($name, $defaultformatoptions)) {
1801 $value = $this->__get($name);
1802 return empty($value);
1808 * Magic method to retrieve the property, this is either basic section property
1809 * or availability information or additional properties added by course format
1811 * @param string $name name of the property
1814 public function __get($name) {
1815 if (property_exists($this, '_'.$name)) {
1816 return $this->{'_'.$name};
1818 if (array_key_exists($name, $this->cachedformatoptions)) {
1819 return $this->cachedformatoptions[$name];
1821 $defaultformatoptions = course_get_format($this->_course)->section_format_options();
1822 // precheck if the option is defined in format to avoid unnecessary DB queries in get_format_options()
1823 if (array_key_exists($name, $defaultformatoptions)) {
1824 $formatoptions = course_get_format($this->_course)->get_format_options($this);
1825 return $formatoptions[$name];
1827 debugging('Invalid section_info property accessed! '.$name);
1832 * Implementation of IteratorAggregate::getIterator(), allows to cycle through properties
1833 * and use {@link convert_to_array()}
1835 * @return ArrayIterator
1837 public function getIterator() {
1839 foreach (get_object_vars($this) as $key => $value) {
1840 if (substr($key, 0, 1) == '_') {
1841 $ret[substr($key, 1)] = $this->$key;
1844 $ret = array_merge($ret, course_get_format($this->_course)->get_format_options($this));
1845 return new ArrayIterator($ret);
1849 * Works out whether activity is visible *for current user* - if this is false, they
1850 * aren't allowed to access it.
1851 * @param int $userid User ID
1854 private function update_user_visible($userid) {
1856 $coursecontext = context_course::instance($this->_course);
1857 $this->_uservisible = true;
1858 if ((!$this->_visible || !$this->_available) &&
1859 !has_capability('moodle/course:viewhiddensections', $coursecontext, $userid)) {
1860 $this->_uservisible = false;
1865 * Prepares section data for inclusion in sectioncache cache, removing items
1866 * that are set to defaults, and adding availability data if required.
1868 * Called by build_section_cache in course_modinfo only; do not use otherwise.
1869 * @param object $section Raw section data object
1871 public static function convert_for_section_cache($section) {
1874 // Course id stored in course table
1875 unset($section->course);
1876 // Section number stored in array key
1877 unset($section->section);
1878 // Sequence stored implicity in modinfo $sections array
1879 unset($section->sequence);
1881 // Add availability data if turned on
1882 if ($CFG->enableavailability) {
1883 require_once($CFG->dirroot . '/lib/conditionlib.php');
1884 condition_info_section::fill_availability_conditions($section);
1885 if (count($section->conditionscompletion) == 0) {
1886 unset($section->conditionscompletion);
1888 if (count($section->conditionsgrade) == 0) {
1889 unset($section->conditionsgrade);
1893 // Remove default data
1894 foreach (self::$sectioncachedefaults as $field => $value) {
1895 // Exact compare as strings to avoid problems if some strings are set
1897 if (isset($section->{$field}) && $section->{$field} === $value) {
1898 unset($section->{$field});