Merge branch 'MDL-37781-workshop-schedule_23' of git://github.com/mudrd8mz/moodle...
[moodle.git] / lib / modinfolib.php
blob5b8d3ef60b04e5eb796fae37a4bdc7760a30ade5
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 class course_modinfo extends stdClass {
44 // For convenience we store the course object here as it is needed in other parts of code
45 private $course;
46 // Array of section data from cache
47 private $sectioninfo;
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().
55 /**
56 * Course ID
57 * @var int
58 * @deprecated For new code, use get_course_id instead.
60 public $courseid;
62 /**
63 * User ID
64 * @var int
65 * @deprecated For new code, use get_user_id instead.
67 public $userid;
69 /**
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
72 * @var array
73 * @deprecated For new code, use get_sections instead
75 public $sections;
77 /**
78 * Array from int (cm id) => cm_info object
79 * @var array
80 * @deprecated For new code, use get_cms or get_cm instead.
82 public $cms;
84 /**
85 * Array from string (modname) => int (instance id) => cm_info object
86 * @var array
87 * @deprecated For new code, use get_instances or get_instances_of instead.
89 public $instances;
91 /**
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'.
95 * @var array
96 * @deprecated Don't use this! For new code, use get_groups.
98 public $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() {
137 return $this->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 * Obtains all instances of a particular module on this course.
163 * @param $modname Name of module (not full frankenstyle) e.g. 'label'
164 * @return array Array from instance id => cm_info for modules on this course; empty if none
166 public function get_instances_of($modname) {
167 if (empty($this->instances[$modname])) {
168 return array();
170 return $this->instances[$modname];
174 * Returns groups that the current user belongs to on the course. Note: If not already
175 * available, this may make a database query.
176 * @param int $groupingid Grouping ID or 0 (default) for all groups
177 * @return array Array of int (group id) => int (same group id again); empty array if none
179 public function get_groups($groupingid=0) {
180 if (is_null($this->groups)) {
181 // NOTE: Performance could be improved here. The system caches user groups
182 // in $USER->groupmember[$courseid] => array of groupid=>groupid. Unfortunately this
183 // structure does not include grouping information. It probably could be changed to
184 // do so, without a significant performance hit on login, thus saving this one query
185 // each request.
186 $this->groups = groups_get_user_groups($this->courseid, $this->userid);
188 if (!isset($this->groups[$groupingid])) {
189 return array();
191 return $this->groups[$groupingid];
195 * Gets all sections as array from section number => data about section.
196 * @return array Array of section_info objects organised by section number
198 public function get_section_info_all() {
199 return $this->sectioninfo;
203 * Gets data about specific numbered section.
204 * @param int $sectionnumber Number (not id) of section
205 * @param int $strictness Use MUST_EXIST to throw exception if it doesn't
206 * @return section_info Information for numbered section or null if not found
208 public function get_section_info($sectionnumber, $strictness = IGNORE_MISSING) {
209 if (!array_key_exists($sectionnumber, $this->sectioninfo)) {
210 if ($strictness === MUST_EXIST) {
211 throw new moodle_exception('sectionnotexist');
212 } else {
213 return null;
216 return $this->sectioninfo[$sectionnumber];
220 * Constructs based on course.
221 * Note: This constructor should not usually be called directly.
222 * Use get_fast_modinfo($course) instead as this maintains a cache.
223 * @param object $course Moodle course object, which may include modinfo
224 * @param int $userid User ID
226 public function __construct($course, $userid) {
227 global $CFG, $DB;
229 // Check modinfo field is set. If not, build and load it.
230 if (empty($course->modinfo) || empty($course->sectioncache)) {
231 rebuild_course_cache($course->id);
232 $course = $DB->get_record('course', array('id'=>$course->id), '*', MUST_EXIST);
235 // Set initial values
236 $this->courseid = $course->id;
237 $this->userid = $userid;
238 $this->sections = array();
239 $this->cms = array();
240 $this->instances = array();
241 $this->groups = null;
242 $this->course = $course;
244 // Load modinfo field into memory as PHP object and check it's valid
245 $info = unserialize($course->modinfo);
246 if (!is_array($info)) {
247 // hmm, something is wrong - lets try to fix it
248 rebuild_course_cache($course->id);
249 $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
250 $info = unserialize($course->modinfo);
251 if (!is_array($info)) {
252 // If it still fails, abort
253 debugging('Problem with "modinfo" data for this course');
254 return;
258 // Load sectioncache field into memory as PHP object and check it's valid
259 $sectioncache = unserialize($course->sectioncache);
260 if (!is_array($sectioncache) || empty($sectioncache)) {
261 // hmm, something is wrong - let's fix it
262 rebuild_course_cache($course->id);
263 $course->sectioncache = $DB->get_field('course', 'sectioncache', array('id'=>$course->id));
264 $sectioncache = unserialize($course->sectioncache);
265 if (!is_array($sectioncache)) {
266 // If it still fails, abort
267 debugging('Problem with "sectioncache" data for this course');
268 return;
272 // If we haven't already preloaded contexts for the course, do it now
273 preload_course_contexts($course->id);
275 // Loop through each piece of module data, constructing it
276 $modexists = array();
277 foreach ($info as $mod) {
278 if (empty($mod->name)) {
279 // something is wrong here
280 continue;
283 // Skip modules which don't exist
284 if (empty($modexists[$mod->mod])) {
285 if (!file_exists("$CFG->dirroot/mod/$mod->mod/lib.php")) {
286 continue;
288 $modexists[$mod->mod] = true;
291 // Construct info for this module
292 $cm = new cm_info($this, $course, $mod, $info);
294 // Store module in instances and cms array
295 if (!isset($this->instances[$cm->modname])) {
296 $this->instances[$cm->modname] = array();
298 $this->instances[$cm->modname][$cm->instance] = $cm;
299 $this->cms[$cm->id] = $cm;
301 // Reconstruct sections. This works because modules are stored in order
302 if (!isset($this->sections[$cm->sectionnum])) {
303 $this->sections[$cm->sectionnum] = array();
305 $this->sections[$cm->sectionnum][] = $cm->id;
308 // Expand section objects
309 $this->sectioninfo = array();
310 foreach ($sectioncache as $number => $data) {
311 // Calculate sequence
312 if (isset($this->sections[$number])) {
313 $sequence = implode(',', $this->sections[$number]);
314 } else {
315 $sequence = '';
317 // Expand
318 $this->sectioninfo[$number] = new section_info($data, $number, $course->id, $sequence,
319 $this, $userid);
322 // We need at least 'dynamic' data from each course-module (this is basically the remaining
323 // data which was always present in previous version of get_fast_modinfo, so it's required
324 // for BC). Creating it in a second pass is necessary because obtain_dynamic_data sometimes
325 // needs to be able to refer to a 'complete' (with basic data) modinfo.
326 foreach ($this->cms as $cm) {
327 $cm->obtain_dynamic_data();
332 * Builds a list of information about sections on a course to be stored in
333 * the course cache. (Does not include information that is already cached
334 * in some other way.)
336 * Used internally by rebuild_course_cache function; do not use otherwise.
337 * @param int $courseid Course ID
338 * @return array Information about sections, indexed by section number (not id)
340 public static function build_section_cache($courseid) {
341 global $DB;
343 // Get section data
344 $sections = $DB->get_records('course_sections', array('course' => $courseid), 'section',
345 'section, id, course, name, summary, summaryformat, sequence, visible, ' .
346 'availablefrom, availableuntil, showavailability, groupingid');
347 $compressedsections = array();
349 // Remove unnecessary data and add availability
350 foreach ($sections as $number => $section) {
351 // Clone just in case it is reused elsewhere (get_all_sections cache)
352 $compressedsections[$number] = clone($section);
353 section_info::convert_for_section_cache($compressedsections[$number]);
356 return $compressedsections;
362 * Data about a single module on a course. This contains most of the fields in the course_modules
363 * table, plus additional data when required.
365 * This object has many public fields; code should treat all these fields as read-only and set
366 * data only using the supplied set functions. Setting the fields directly is not supported
367 * and may cause problems later.
369 class cm_info extends stdClass {
371 * State: Only basic data from modinfo cache is available.
373 const STATE_BASIC = 0;
376 * State: Dynamic data is available too.
378 const STATE_DYNAMIC = 1;
381 * State: View data (for course page) is available.
383 const STATE_VIEW = 2;
386 * Parent object
387 * @var course_modinfo
389 private $modinfo;
392 * Level of information stored inside this object (STATE_xx constant)
393 * @var int
395 private $state;
397 // Existing data fields
398 ///////////////////////
401 * Course-module ID - from course_modules table
402 * @var int
404 public $id;
407 * Module instance (ID within module table) - from course_modules table
408 * @var int
410 public $instance;
413 * Course ID - from course_modules table
414 * @var int
416 public $course;
419 * 'ID number' from course-modules table (arbitrary text set by user) - from
420 * course_modules table
421 * @var string
423 public $idnumber;
426 * Time that this course-module was added (unix time) - from course_modules table
427 * @var int
429 public $added;
432 * This variable is not used and is included here only so it can be documented.
433 * Once the database entry is removed from course_modules, it should be deleted
434 * here too.
435 * @var int
436 * @deprecated Do not use this variable
438 public $score;
441 * Visible setting (0 or 1; if this is 0, students cannot see/access the activity) - from
442 * course_modules table
443 * @var int
445 public $visible;
448 * Old visible setting (if the entire section is hidden, the previous value for
449 * visible is stored in this field) - from course_modules table
450 * @var int
452 public $visibleold;
455 * Group mode (one of the constants NONE, SEPARATEGROUPS, or VISIBLEGROUPS) - from
456 * course_modules table
457 * @var int
459 public $groupmode;
462 * Grouping ID (0 = all groupings)
463 * @var int
465 public $groupingid;
468 * Group members only (if set to 1, only members of a suitable group see this link on the
469 * course page; 0 = everyone sees it even if they don't belong to a suitable group) - from
470 * course_modules table
471 * @var int
473 public $groupmembersonly;
476 * Indent level on course page (0 = no indent) - from course_modules table
477 * @var int
479 public $indent;
482 * Activity completion setting for this activity, COMPLETION_TRACKING_xx constant - from
483 * course_modules table
484 * @var int
486 public $completion;
489 * Set to the item number (usually 0) if completion depends on a particular
490 * grade of this activity, or null if completion does not depend on a grade - from
491 * course_modules table
492 * @var mixed
494 public $completiongradeitemnumber;
497 * 1 if 'on view' completion is enabled, 0 otherwise - from course_modules table
498 * @var int
500 public $completionview;
503 * Set to a unix time if completion of this activity is expected at a
504 * particular time, 0 if no time set - from course_modules table
505 * @var int
507 public $completionexpected;
510 * Available date for this activity (0 if not set, or set to seconds since epoch; before this
511 * date, activity does not display to students) - from course_modules table
512 * @var int
514 public $availablefrom;
517 * Available until date for this activity (0 if not set, or set to seconds since epoch; from
518 * this date, activity does not display to students) - from course_modules table
519 * @var int
521 public $availableuntil;
524 * When activity is unavailable, this field controls whether it is shown to students (0 =
525 * hide completely, 1 = show greyed out with information about when it will be available) -
526 * from course_modules table
527 * @var int
529 public $showavailability;
532 * Controls whether the description of the activity displays on the course main page (in
533 * addition to anywhere it might display within the activity itself). 0 = do not show
534 * on main page, 1 = show on main page.
535 * @var int
537 public $showdescription;
540 * Extra HTML that is put in an unhelpful part of the HTML when displaying this module in
541 * course page - from cached data in modinfo field
542 * @deprecated This is crazy, don't use it. Replaced by ->extraclasses and ->onclick
543 * @var string
545 public $extra;
548 * Name of icon to use - from cached data in modinfo field
549 * @var string
551 public $icon;
554 * Component that contains icon - from cached data in modinfo field
555 * @var string
557 public $iconcomponent;
560 * Name of module e.g. 'forum' (this is the same name as the module's main database
561 * table) - from cached data in modinfo field
562 * @var string
564 public $modname;
567 * ID of module - from course_modules table
568 * @var int
570 public $module;
573 * Name of module instance for display on page e.g. 'General discussion forum' - from cached
574 * data in modinfo field
575 * @var string
577 public $name;
580 * Section number that this course-module is in (section 0 = above the calendar, section 1
581 * = week/topic 1, etc) - from cached data in modinfo field
582 * @var string
584 public $sectionnum;
587 * Section id - from course_modules table
588 * @var int
590 public $section;
593 * Availability conditions for this course-module based on the completion of other
594 * course-modules (array from other course-module id to required completion state for that
595 * module) - from cached data in modinfo field
596 * @var array
598 public $conditionscompletion;
601 * Availability conditions for this course-module based on course grades (array from
602 * grade item id to object with ->min, ->max fields) - from cached data in modinfo field
603 * @var array
605 public $conditionsgrade;
608 * Plural name of module type, e.g. 'Forums' - from lang file
609 * @deprecated Do not use this value (you can obtain it by calling get_string instead); it
610 * will be removed in a future version (see later TODO in this file)
611 * @var string
613 public $modplural;
616 * True if this course-module is available to students i.e. if all availability conditions
617 * are met - obtained dynamically
618 * @var bool
620 public $available;
623 * If course-module is not available to students, this string gives information about
624 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
625 * January 2010') for display on main page - obtained dynamically
626 * @var string
628 public $availableinfo;
631 * True if this course-module is available to the CURRENT user (for example, if current user
632 * has viewhiddenactivities capability, they can access the course-module even if it is not
633 * visible or not available, so this would be true in that case)
634 * @var bool
636 public $uservisible;
639 * Module context - hacky shortcut
640 * @deprecated
641 * @var stdClass
643 public $context;
646 // New data available only via functions
647 ////////////////////////////////////////
650 * @var moodle_url
652 private $url;
655 * @var string
657 private $content;
660 * @var string
662 private $extraclasses;
665 * @var moodle_url full external url pointing to icon image for activity
667 private $iconurl;
670 * @var string
672 private $onclick;
675 * @var mixed
677 private $customdata;
680 * @var string
682 private $afterlink;
685 * @var string
687 private $afterediticons;
690 * @return bool True if this module has a 'view' page that should be linked to in navigation
691 * etc (note: modules may still have a view.php file, but return false if this is not
692 * intended to be linked to from 'normal' parts of the interface; this is what label does).
694 public function has_view() {
695 return !is_null($this->url);
699 * @return moodle_url URL to link to for this module, or null if it doesn't have a view page
701 public function get_url() {
702 return $this->url;
706 * Obtains content to display on main (view) page.
707 * Note: Will collect view data, if not already obtained.
708 * @return string Content to display on main page below link, or empty string if none
710 public function get_content() {
711 $this->obtain_view_data();
712 return $this->content;
716 * Note: Will collect view data, if not already obtained.
717 * @return string Extra CSS classes to add to html output for this activity on main page
719 public function get_extra_classes() {
720 $this->obtain_view_data();
721 return $this->extraclasses;
725 * @return string Content of HTML on-click attribute. This string will be used literally
726 * as a string so should be pre-escaped.
728 public function get_on_click() {
729 // Does not need view data; may be used by navigation
730 return $this->onclick;
733 * @return mixed Optional custom data stored in modinfo cache for this activity, or null if none
735 public function get_custom_data() {
736 return $this->customdata;
740 * Note: Will collect view data, if not already obtained.
741 * @return string Extra HTML code to display after link
743 public function get_after_link() {
744 $this->obtain_view_data();
745 return $this->afterlink;
749 * Note: Will collect view data, if not already obtained.
750 * @return string Extra HTML code to display after editing icons (e.g. more icons)
752 public function get_after_edit_icons() {
753 $this->obtain_view_data();
754 return $this->afterediticons;
758 * @param moodle_core_renderer $output Output render to use, or null for default (global)
759 * @return moodle_url Icon URL for a suitable icon to put beside this cm
761 public function get_icon_url($output = null) {
762 global $OUTPUT;
763 if (!$output) {
764 $output = $OUTPUT;
766 // Support modules setting their own, external, icon image
767 if (!empty($this->iconurl)) {
768 $icon = $this->iconurl;
770 // Fallback to normal local icon + component procesing
771 } else if (!empty($this->icon)) {
772 if (substr($this->icon, 0, 4) === 'mod/') {
773 list($modname, $iconname) = explode('/', substr($this->icon, 4), 2);
774 $icon = $output->pix_url($iconname, $modname);
775 } else {
776 if (!empty($this->iconcomponent)) {
777 // Icon has specified component
778 $icon = $output->pix_url($this->icon, $this->iconcomponent);
779 } else {
780 // Icon does not have specified component, use default
781 $icon = $output->pix_url($this->icon);
784 } else {
785 $icon = $output->pix_url('icon', $this->modname);
787 return $icon;
791 * @return course_modinfo Modinfo object that this came from
793 public function get_modinfo() {
794 return $this->modinfo;
798 * @return object Moodle course object that was used to construct this data
800 public function get_course() {
801 return $this->modinfo->get_course();
804 // Set functions
805 ////////////////
808 * Sets content to display on course view page below link (if present).
809 * @param string $content New content as HTML string (empty string if none)
810 * @return void
812 public function set_content($content) {
813 $this->content = $content;
817 * Sets extra classes to include in CSS.
818 * @param string $extraclasses Extra classes (empty string if none)
819 * @return void
821 public function set_extra_classes($extraclasses) {
822 $this->extraclasses = $extraclasses;
826 * Sets the external full url that points to the icon being used
827 * by the activity. Useful for external-tool modules (lti...)
828 * If set, takes precedence over $icon and $iconcomponent
830 * @param moodle_url $iconurl full external url pointing to icon image for activity
831 * @return void
833 public function set_icon_url(moodle_url $iconurl) {
834 $this->iconurl = $iconurl;
838 * Sets value of on-click attribute for JavaScript.
839 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
840 * @param string $onclick New onclick attribute which should be HTML-escaped
841 * (empty string if none)
842 * @return void
844 public function set_on_click($onclick) {
845 $this->check_not_view_only();
846 $this->onclick = $onclick;
850 * Sets HTML that displays after link on course view page.
851 * @param string $afterlink HTML string (empty string if none)
852 * @return void
854 public function set_after_link($afterlink) {
855 $this->afterlink = $afterlink;
859 * Sets HTML that displays after edit icons on course view page.
860 * @param string $afterediticons HTML string (empty string if none)
861 * @return void
863 public function set_after_edit_icons($afterediticons) {
864 $this->afterediticons = $afterediticons;
868 * Changes the name (text of link) for this module instance.
869 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
870 * @param string $name Name of activity / link text
871 * @return void
873 public function set_name($name) {
874 $this->update_user_visible();
875 $this->name = $name;
879 * Turns off the view link for this module instance.
880 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
881 * @return void
883 public function set_no_view_link() {
884 $this->check_not_view_only();
885 $this->url = null;
889 * Sets the 'uservisible' flag. This can be used (by setting false) to prevent access and
890 * display of this module link for the current user.
891 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
892 * @param bool $uservisible
893 * @return void
895 public function set_user_visible($uservisible) {
896 $this->check_not_view_only();
897 $this->uservisible = $uservisible;
901 * Sets the 'available' flag and related details. This flag is normally used to make
902 * course modules unavailable until a certain date or condition is met. (When a course
903 * module is unavailable, it is still visible to users who have viewhiddenactivities
904 * permission.)
906 * When this is function is called, user-visible status is recalculated automatically.
908 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
909 * @param bool $available False if this item is not 'available'
910 * @param int $showavailability 0 = do not show this item at all if it's not available,
911 * 1 = show this item greyed out with the following message
912 * @param string $availableinfo Information about why this is not available which displays
913 * to those who have viewhiddenactivities, and to everyone if showavailability is set;
914 * note that this function replaces the existing data (if any)
915 * @return void
917 public function set_available($available, $showavailability=0, $availableinfo='') {
918 $this->check_not_view_only();
919 $this->available = $available;
920 $this->showavailability = $showavailability;
921 $this->availableinfo = $availableinfo;
922 $this->update_user_visible();
926 * Some set functions can only be called from _cm_info_dynamic and not _cm_info_view.
927 * This is because they may affect parts of this object which are used on pages other
928 * than the view page (e.g. in the navigation block, or when checking access on
929 * module pages).
930 * @return void
932 private function check_not_view_only() {
933 if ($this->state >= self::STATE_DYNAMIC) {
934 throw new coding_exception('Cannot set this data from _cm_info_view because it may ' .
935 'affect other pages as well as view');
940 * Constructor should not be called directly; use get_fast_modinfo.
941 * @param course_modinfo $modinfo Parent object
942 * @param object $course Course row
943 * @param object $mod Module object from the modinfo field of course table
944 * @param object $info Entire object from modinfo field of course table
946 public function __construct(course_modinfo $modinfo, $course, $mod, $info) {
947 global $CFG;
948 $this->modinfo = $modinfo;
950 $this->id = $mod->cm;
951 $this->instance = $mod->id;
952 $this->course = $course->id;
953 $this->modname = $mod->mod;
954 $this->idnumber = isset($mod->idnumber) ? $mod->idnumber : '';
955 $this->name = $mod->name;
956 $this->visible = $mod->visible;
957 $this->sectionnum = $mod->section; // Note weirdness with name here
958 $this->groupmode = isset($mod->groupmode) ? $mod->groupmode : 0;
959 $this->groupingid = isset($mod->groupingid) ? $mod->groupingid : 0;
960 $this->groupmembersonly = isset($mod->groupmembersonly) ? $mod->groupmembersonly : 0;
961 $this->indent = isset($mod->indent) ? $mod->indent : 0;
962 $this->extra = isset($mod->extra) ? $mod->extra : '';
963 $this->extraclasses = isset($mod->extraclasses) ? $mod->extraclasses : '';
964 $this->iconurl = isset($mod->iconurl) ? $mod->iconurl : '';
965 $this->onclick = isset($mod->onclick) ? $mod->onclick : '';
966 $this->content = isset($mod->content) ? $mod->content : '';
967 $this->icon = isset($mod->icon) ? $mod->icon : '';
968 $this->iconcomponent = isset($mod->iconcomponent) ? $mod->iconcomponent : '';
969 $this->customdata = isset($mod->customdata) ? $mod->customdata : '';
970 $this->context = get_context_instance(CONTEXT_MODULE, $mod->cm);
971 $this->showdescription = isset($mod->showdescription) ? $mod->showdescription : 0;
972 $this->state = self::STATE_BASIC;
974 // This special case handles old label data. Labels used to use the 'name' field for
975 // content
976 if ($this->modname === 'label' && $this->content === '') {
977 $this->content = $this->extra;
978 $this->extra = '';
981 // Note: These fields from $cm were not present in cm_info in Moodle
982 // 2.0.2 and prior. They may not be available if course cache hasn't
983 // been rebuilt since then.
984 $this->section = isset($mod->sectionid) ? $mod->sectionid : 0;
985 $this->module = isset($mod->module) ? $mod->module : 0;
986 $this->added = isset($mod->added) ? $mod->added : 0;
987 $this->score = isset($mod->score) ? $mod->score : 0;
988 $this->visibleold = isset($mod->visibleold) ? $mod->visibleold : 0;
990 // Note: it saves effort and database space to always include the
991 // availability and completion fields, even if availability or completion
992 // are actually disabled
993 $this->completion = isset($mod->completion) ? $mod->completion : 0;
994 $this->completiongradeitemnumber = isset($mod->completiongradeitemnumber)
995 ? $mod->completiongradeitemnumber : null;
996 $this->completionview = isset($mod->completionview)
997 ? $mod->completionview : 0;
998 $this->completionexpected = isset($mod->completionexpected)
999 ? $mod->completionexpected : 0;
1000 $this->showavailability = isset($mod->showavailability) ? $mod->showavailability : 0;
1001 $this->availablefrom = isset($mod->availablefrom) ? $mod->availablefrom : 0;
1002 $this->availableuntil = isset($mod->availableuntil) ? $mod->availableuntil : 0;
1003 $this->conditionscompletion = isset($mod->conditionscompletion)
1004 ? $mod->conditionscompletion : array();
1005 $this->conditionsgrade = isset($mod->conditionsgrade)
1006 ? $mod->conditionsgrade : array();
1008 // Get module plural name.
1009 // TODO This was a very old performance hack and should now be removed as the information
1010 // certainly doesn't belong in modinfo. On a 'normal' page this is only used in the
1011 // activity_modules block, so if it needs caching, it should be cached there.
1012 static $modplurals;
1013 if (!isset($modplurals[$this->modname])) {
1014 $modplurals[$this->modname] = get_string('modulenameplural', $this->modname);
1016 $this->modplural = $modplurals[$this->modname];
1018 static $modviews;
1019 if (!isset($modviews[$this->modname])) {
1020 $modviews[$this->modname] = !plugin_supports('mod', $this->modname,
1021 FEATURE_NO_VIEW_LINK);
1023 $this->url = $modviews[$this->modname]
1024 ? new moodle_url('/mod/' . $this->modname . '/view.php', array('id'=>$this->id))
1025 : null;
1029 * If dynamic data for this course-module is not yet available, gets it.
1031 * This function is automatically called when constructing course_modinfo, so users don't
1032 * need to call it.
1034 * Dynamic data is data which does not come directly from the cache but is calculated at
1035 * runtime based on the current user. Primarily this concerns whether the user can access
1036 * the module or not.
1038 * As part of this function, the module's _cm_info_dynamic function from its lib.php will
1039 * be called (if it exists).
1040 * @return void
1042 public function obtain_dynamic_data() {
1043 global $CFG;
1044 if ($this->state >= self::STATE_DYNAMIC) {
1045 return;
1047 $userid = $this->modinfo->get_user_id();
1049 if (!empty($CFG->enableavailability)) {
1050 // Get availability information
1051 $ci = new condition_info($this);
1052 // Note that the modinfo currently available only includes minimal details (basic data)
1053 // so passing it to this function is a bit dangerous as it would cause infinite
1054 // recursion if it tried to get dynamic data, however we know that this function only
1055 // uses basic data.
1056 $this->available = $ci->is_available($this->availableinfo, true,
1057 $userid, $this->modinfo);
1059 // Check parent section
1060 $parentsection = $this->modinfo->get_section_info($this->sectionnum);
1061 if (!$parentsection->available) {
1062 // Do not store info from section here, as that is already
1063 // presented from the section (if appropriate) - just change
1064 // the flag
1065 $this->available = false;
1067 } else {
1068 $this->available = true;
1071 // Update visible state for current user
1072 $this->update_user_visible();
1074 // Let module make dynamic changes at this point
1075 $this->call_mod_function('cm_info_dynamic');
1076 $this->state = self::STATE_DYNAMIC;
1080 * Works out whether activity is available to the current user
1082 * If the activity is unavailable, additional checks are required to determine if its hidden or greyed out
1084 * @see is_user_access_restricted_by_group()
1085 * @see is_user_access_restricted_by_conditional_access()
1086 * @return void
1088 private function update_user_visible() {
1089 global $CFG;
1090 $modcontext = get_context_instance(CONTEXT_MODULE, $this->id);
1091 $userid = $this->modinfo->get_user_id();
1092 $this->uservisible = true;
1094 // If the user cannot access the activity set the uservisible flag to false.
1095 // Additional checks are required to determine whether the activity is entirely hidden or just greyed out.
1096 if ((!$this->visible or !$this->available) and
1097 !has_capability('moodle/course:viewhiddenactivities', $modcontext, $userid)) {
1099 $this->uservisible = false;
1102 // Check group membership.
1103 if ($this->is_user_access_restricted_by_group()) {
1105 $this->uservisible = false;
1106 // Ensure activity is completely hidden from the user.
1107 $this->showavailability = 0;
1112 * Checks whether the module's group settings restrict the current user's access
1114 * @return bool True if the user access is restricted
1116 public function is_user_access_restricted_by_group() {
1117 global $CFG;
1119 if (!empty($CFG->enablegroupmembersonly) and !empty($this->groupmembersonly)) {
1120 $modcontext = context_module::instance($this->id);
1121 $userid = $this->modinfo->get_user_id();
1122 if (!has_capability('moodle/site:accessallgroups', $modcontext, $userid)) {
1123 // If the activity has 'group members only' and you don't have accessallgroups...
1124 $groups = $this->modinfo->get_groups($this->groupingid);
1125 if (empty($groups)) {
1126 // ...and you don't belong to a group, then set it so you can't see/access it
1127 return true;
1131 return false;
1135 * Checks whether the module's conditional access settings mean that the user cannot see the activity at all
1137 * @return bool True if the user cannot see the module. False if the activity is either available or should be greyed out.
1139 public function is_user_access_restricted_by_conditional_access() {
1140 global $CFG, $USER;
1142 if (empty($CFG->enableavailability)) {
1143 return false;
1146 // If module will always be visible anyway (but greyed out), don't bother checking anything else
1147 if ($this->showavailability == CONDITION_STUDENTVIEW_SHOW) {
1148 return false;
1151 // Can the user see hidden modules?
1152 $modcontext = context_module::instance($this->id);
1153 $userid = $this->modinfo->get_user_id();
1154 if (has_capability('moodle/course:viewhiddenactivities', $modcontext, $userid)) {
1155 return false;
1158 // Is the module hidden due to unmet conditions?
1159 if (!$this->available) {
1160 return true;
1163 return false;
1167 * Calls a module function (if exists), passing in one parameter: this object.
1168 * @param string $type Name of function e.g. if this is 'grooblezorb' and the modname is
1169 * 'forum' then it will try to call 'mod_forum_grooblezorb' or 'forum_grooblezorb'
1170 * @return void
1172 private function call_mod_function($type) {
1173 global $CFG;
1174 $libfile = $CFG->dirroot . '/mod/' . $this->modname . '/lib.php';
1175 if (file_exists($libfile)) {
1176 include_once($libfile);
1177 $function = 'mod_' . $this->modname . '_' . $type;
1178 if (function_exists($function)) {
1179 $function($this);
1180 } else {
1181 $function = $this->modname . '_' . $type;
1182 if (function_exists($function)) {
1183 $function($this);
1190 * If view data for this course-module is not yet available, obtains it.
1192 * This function is automatically called if any of the functions (marked) which require
1193 * view data are called.
1195 * View data is data which is needed only for displaying the course main page (& any similar
1196 * functionality on other pages) but is not needed in general. Obtaining view data may have
1197 * a performance cost.
1199 * As part of this function, the module's _cm_info_view function from its lib.php will
1200 * be called (if it exists).
1201 * @return void
1203 private function obtain_view_data() {
1204 if ($this->state >= self::STATE_VIEW) {
1205 return;
1208 // Let module make changes at this point
1209 $this->call_mod_function('cm_info_view');
1210 $this->state = self::STATE_VIEW;
1216 * Returns reference to full info about modules in course (including visibility).
1217 * Cached and as fast as possible (0 or 1 db query).
1219 * @global object
1220 * @global object
1221 * @global moodle_database
1222 * @uses MAX_MODINFO_CACHE_SIZE
1223 * @param mixed $course object or 'reset' string to reset caches, modinfo may be updated in db
1224 * @param int $userid Defaults to current user id
1225 * @return course_modinfo Module information for course, or null if resetting
1227 function get_fast_modinfo(&$course, $userid=0) {
1228 global $CFG, $USER, $DB;
1229 require_once($CFG->dirroot.'/course/lib.php');
1231 if (!empty($CFG->enableavailability)) {
1232 require_once($CFG->libdir.'/conditionlib.php');
1235 static $cache = array();
1237 if ($course === 'reset') {
1238 $cache = array();
1239 return null;
1242 if (empty($userid)) {
1243 $userid = $USER->id;
1246 if (array_key_exists($course->id, $cache) and $cache[$course->id]->userid == $userid) {
1247 return $cache[$course->id];
1250 if (!property_exists($course, 'modinfo')) {
1251 debugging('Coding problem - missing course modinfo property in get_fast_modinfo() call');
1254 if (!property_exists($course, 'sectioncache')) {
1255 debugging('Coding problem - missing course sectioncache property in get_fast_modinfo() call');
1258 unset($cache[$course->id]); // prevent potential reference problems when switching users
1260 $cache[$course->id] = new course_modinfo($course, $userid);
1262 // Ensure cache does not use too much RAM
1263 if (count($cache) > MAX_MODINFO_CACHE_SIZE) {
1264 reset($cache);
1265 $key = key($cache);
1266 unset($cache[$key]->instances);
1267 unset($cache[$key]->cms);
1268 unset($cache[$key]);
1271 return $cache[$course->id];
1275 * Rebuilds the cached list of course activities stored in the database
1276 * @param int $courseid - id of course to rebuild, empty means all
1277 * @param boolean $clearonly - only clear the modinfo fields, gets rebuild automatically on the fly
1279 function rebuild_course_cache($courseid=0, $clearonly=false) {
1280 global $COURSE, $DB, $CFG;
1282 // Destroy navigation caches
1283 navigation_cache::destroy_volatile_caches();
1285 if ($clearonly) {
1286 if (empty($courseid)) {
1287 $DB->set_field('course', 'modinfo', null);
1288 $DB->set_field('course', 'sectioncache', null);
1289 } else {
1290 // Clear both fields in one update
1291 $resetobj = (object)array('id' => $courseid, 'modinfo' => null, 'sectioncache' => null);
1292 $DB->update_record('course', $resetobj);
1294 // update cached global COURSE too ;-)
1295 if ($courseid == $COURSE->id or empty($courseid)) {
1296 $COURSE->modinfo = null;
1297 $COURSE->sectioncache = null;
1299 // reset the fast modinfo cache
1300 $reset = 'reset';
1301 get_fast_modinfo($reset);
1302 return;
1305 require_once("$CFG->dirroot/course/lib.php");
1307 if ($courseid) {
1308 $select = array('id'=>$courseid);
1309 } else {
1310 $select = array();
1311 @set_time_limit(0); // this could take a while! MDL-10954
1314 $rs = $DB->get_recordset("course", $select,'','id,fullname');
1315 foreach ($rs as $course) {
1316 $modinfo = serialize(get_array_of_activities($course->id));
1317 $sectioncache = serialize(course_modinfo::build_section_cache($course->id));
1318 $updateobj = (object)array('id' => $course->id,
1319 'modinfo' => $modinfo, 'sectioncache' => $sectioncache);
1320 $DB->update_record("course", $updateobj);
1321 // update cached global COURSE too ;-)
1322 if ($course->id == $COURSE->id) {
1323 $COURSE->modinfo = $modinfo;
1324 $COURSE->sectioncache = $sectioncache;
1327 $rs->close();
1328 // reset the fast modinfo cache
1329 $reset = 'reset';
1330 get_fast_modinfo($reset);
1335 * Class that is the return value for the _get_coursemodule_info module API function.
1337 * Note: For backward compatibility, you can also return a stdclass object from that function.
1338 * The difference is that the stdclass object may contain an 'extra' field (deprecated because
1339 * it was crazy, except for label which uses it differently). The stdclass object may not contain
1340 * the new fields defined here (content, extraclasses, customdata).
1342 class cached_cm_info {
1344 * Name (text of link) for this activity; Leave unset to accept default name
1345 * @var string
1347 public $name;
1350 * Name of icon for this activity. Normally, this should be used together with $iconcomponent
1351 * to define the icon, as per pix_url function.
1352 * For backward compatibility, if this value is of the form 'mod/forum/icon' then an icon
1353 * within that module will be used.
1354 * @see cm_info::get_icon_url()
1355 * @see renderer_base::pix_url()
1356 * @var string
1358 public $icon;
1361 * Component for icon for this activity, as per pix_url; leave blank to use default 'moodle'
1362 * component
1363 * @see renderer_base::pix_url()
1364 * @var string
1366 public $iconcomponent;
1369 * HTML content to be displayed on the main page below the link (if any) for this course-module
1370 * @var string
1372 public $content;
1375 * Custom data to be stored in modinfo for this activity; useful if there are cases when
1376 * internal information for this activity type needs to be accessible from elsewhere on the
1377 * course without making database queries. May be of any type but should be short.
1378 * @var mixed
1380 public $customdata;
1383 * Extra CSS class or classes to be added when this activity is displayed on the main page;
1384 * space-separated string
1385 * @var string
1387 public $extraclasses;
1390 * External URL image to be used by activity as icon, useful for some external-tool modules
1391 * like lti. If set, takes precedence over $icon and $iconcomponent
1392 * @var $moodle_url
1394 public $iconurl;
1397 * Content of onclick JavaScript; escaped HTML to be inserted as attribute value
1398 * @var string
1400 public $onclick;
1405 * Data about a single section on a course. This contains the fields from the
1406 * course_sections table, plus additional data when required.
1408 class section_info extends stdClass {
1410 * Section ID - from course_sections table
1411 * @var int
1413 public $id;
1416 * Course ID - from course_sections table
1417 * @var int
1419 public $course;
1422 * Section number - from course_sections table
1423 * @var int
1425 public $section;
1428 * Section name if specified - from course_sections table
1429 * @var string
1431 public $name;
1434 * Section visibility (1 = visible) - from course_sections table
1435 * @var int
1437 public $visible;
1440 * Section summary text if specified - from course_sections table
1441 * @var string
1443 public $summary;
1446 * Section summary text format (FORMAT_xx constant) - from course_sections table
1447 * @var int
1449 public $summaryformat;
1452 * When section is unavailable, this field controls whether it is shown to students (0 =
1453 * hide completely, 1 = show greyed out with information about when it will be available) -
1454 * from course_sections table
1455 * @var int
1457 public $showavailability;
1460 * Available date for this section (0 if not set, or set to seconds since epoch; before this
1461 * date, section does not display to students) - from course_sections table
1462 * @var int
1464 public $availablefrom;
1467 * Available until date for this section (0 if not set, or set to seconds since epoch; from
1468 * this date, section does not display to students) - from course_sections table
1469 * @var int
1471 public $availableuntil;
1474 * If section is restricted to users of a particular grouping, this is its id
1475 * (0 if not set) - from course_sections table
1476 * @var int
1478 public $groupingid;
1481 * Availability conditions for this section based on the completion of
1482 * course-modules (array from course-module id to required completion state
1483 * for that module) - from cached data in sectioncache field
1484 * @var array
1486 public $conditionscompletion;
1489 * Availability conditions for this section based on course grades (array from
1490 * grade item id to object with ->min, ->max fields) - from cached data in
1491 * sectioncache field
1492 * @var array
1494 public $conditionsgrade;
1497 * True if this section is available to students i.e. if all availability conditions
1498 * are met - obtained dynamically
1499 * @var bool
1501 public $available;
1504 * If section is not available to students, this string gives information about
1505 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
1506 * January 2010') for display on main page - obtained dynamically
1507 * @var string
1509 public $availableinfo;
1512 * True if this section is available to the CURRENT user (for example, if current user
1513 * has viewhiddensections capability, they can access the section even if it is not
1514 * visible or not available, so this would be true in that case)
1515 * @var bool
1517 public $uservisible;
1520 * Default values for sectioncache fields; if a field has this value, it won't
1521 * be stored in the sectioncache cache, to save space. Checks are done by ===
1522 * which means values must all be strings.
1523 * @var array
1525 private static $sectioncachedefaults = array(
1526 'name' => null,
1527 'summary' => '',
1528 'summaryformat' => '1', // FORMAT_HTML, but must be a string
1529 'visible' => '1',
1530 'showavailability' => '0',
1531 'availablefrom' => '0',
1532 'availableuntil' => '0',
1533 'groupingid' => '0',
1537 * Constructs object from database information plus extra required data.
1538 * @param object $data Array entry from cached sectioncache
1539 * @param int $number Section number (array key)
1540 * @param int $courseid Course ID
1541 * @param int $sequence Sequence of course-module ids contained within
1542 * @param course_modinfo $modinfo Owner (needed for checking availability)
1543 * @param int $userid User ID
1545 public function __construct($data, $number, $courseid, $sequence, $modinfo, $userid) {
1546 global $CFG;
1548 // Data that is always present
1549 $this->id = $data->id;
1551 // Data that may use default values to save cache size
1552 foreach (self::$sectioncachedefaults as $field => $value) {
1553 if (isset($data->{$field})) {
1554 $this->{$field} = $data->{$field};
1555 } else {
1556 $this->{$field} = $value;
1560 // Data with array defaults
1561 $this->conditionscompletion = isset($data->conditionscompletion)
1562 ? $data->conditionscompletion : array();
1563 $this->conditionsgrade = isset($data->conditionsgrade)
1564 ? $data->conditionsgrade : array();
1566 // Other data from other places
1567 $this->course = $courseid;
1568 $this->section = $number;
1569 $this->sequence = $sequence;
1571 // Availability data
1572 if (!empty($CFG->enableavailability)) {
1573 // Get availability information
1574 $ci = new condition_info_section($this);
1575 $this->available = $ci->is_available($this->availableinfo, true,
1576 $userid, $modinfo);
1577 // Display grouping info if available & not already displaying
1578 // (it would already display if current user doesn't have access)
1579 // for people with managegroups - same logic/class as grouping label
1580 // on individual activities.
1581 $context = context_course::instance($courseid);
1582 if ($this->availableinfo === '' && $this->groupingid &&
1583 has_capability('moodle/course:managegroups', $context)) {
1584 $groupings = groups_get_all_groupings($courseid);
1585 $this->availableinfo = html_writer::tag('span', '(' . format_string(
1586 $groupings[$this->groupingid]->name, true, array('context' => $context)) .
1587 ')', array('class' => 'groupinglabel'));
1589 } else {
1590 $this->available = true;
1593 // Update visibility for current user
1594 $this->update_user_visible($userid);
1598 * Works out whether activity is visible *for current user* - if this is false, they
1599 * aren't allowed to access it.
1600 * @param int $userid User ID
1601 * @return void
1603 private function update_user_visible($userid) {
1604 global $CFG;
1605 $coursecontext = context_course::instance($this->course);
1606 $this->uservisible = true;
1607 if ((!$this->visible || !$this->available) &&
1608 !has_capability('moodle/course:viewhiddensections', $coursecontext, $userid)) {
1609 $this->uservisible = false;
1614 * Prepares section data for inclusion in sectioncache cache, removing items
1615 * that are set to defaults, and adding availability data if required.
1617 * Called by build_section_cache in course_modinfo only; do not use otherwise.
1618 * @param object $section Raw section data object
1620 public static function convert_for_section_cache($section) {
1621 global $CFG;
1623 // Course id stored in course table
1624 unset($section->course);
1625 // Section number stored in array key
1626 unset($section->section);
1627 // Sequence stored implicity in modinfo $sections array
1628 unset($section->sequence);
1630 // Add availability data if turned on
1631 if ($CFG->enableavailability) {
1632 require_once($CFG->dirroot . '/lib/conditionlib.php');
1633 condition_info_section::fill_availability_conditions($section);
1634 if (count($section->conditionscompletion) == 0) {
1635 unset($section->conditionscompletion);
1637 if (count($section->conditionsgrade) == 0) {
1638 unset($section->conditionsgrade);
1642 // Remove default data
1643 foreach (self::$sectioncachedefaults as $field => $value) {
1644 // Exact compare as strings to avoid problems if some strings are set
1645 // to "0" etc.
1646 if (isset($section->{$field}) && $section->{$field} === $value) {
1647 unset($section->{$field});