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 * 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])) {
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
186 $this->groups
= groups_get_user_groups($this->courseid
, $this->userid
);
188 if (!isset($this->groups
[$groupingid])) {
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');
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) {
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');
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');
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
283 // Skip modules which don't exist
284 if (empty($modexists[$mod->mod
])) {
285 if (!file_exists("$CFG->dirroot/mod/$mod->mod/lib.php")) {
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]);
318 $this->sectioninfo
[$number] = new section_info($data, $number, $course->id
, $sequence,
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) {
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;
387 * @var course_modinfo
392 * Level of information stored inside this object (STATE_xx constant)
397 // Existing data fields
398 ///////////////////////
401 * Course-module ID - from course_modules table
407 * Module instance (ID within module table) - from course_modules table
413 * Course ID - from course_modules table
419 * 'ID number' from course-modules table (arbitrary text set by user) - from
420 * course_modules table
426 * Time that this course-module was added (unix time) - from course_modules table
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
436 * @deprecated Do not use this variable
441 * Visible setting (0 or 1; if this is 0, students cannot see/access the activity) - from
442 * course_modules table
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
455 * Group mode (one of the constants NONE, SEPARATEGROUPS, or VISIBLEGROUPS) - from
456 * course_modules table
462 * Grouping ID (0 = all groupings)
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
473 public $groupmembersonly;
476 * Indent level on course page (0 = no indent) - from course_modules table
482 * Activity completion setting for this activity, COMPLETION_TRACKING_xx constant - from
483 * course_modules table
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
494 public $completiongradeitemnumber;
497 * 1 if 'on view' completion is enabled, 0 otherwise - from course_modules table
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
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
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
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
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.
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
548 * Name of icon to use - from cached data in modinfo field
554 * Component that contains icon - from cached data in modinfo field
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
567 * ID of module - from course_modules table
573 * Name of module instance for display on page e.g. 'General discussion forum' - from cached
574 * data in modinfo field
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
587 * Section id - from course_modules table
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
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
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)
616 * True if this course-module is available to students i.e. if all availability conditions
617 * are met - obtained dynamically
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
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)
639 * Module context - hacky shortcut
646 // New data available only via functions
647 ////////////////////////////////////////
662 private $extraclasses;
665 * @var moodle_url full external url pointing to icon image for activity
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() {
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) {
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);
776 if (!empty($this->iconcomponent
)) {
777 // Icon has specified component
778 $icon = $output->pix_url($this->icon
, $this->iconcomponent
);
780 // Icon does not have specified component, use default
781 $icon = $output->pix_url($this->icon
);
785 $icon = $output->pix_url('icon', $this->modname
);
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();
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)
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)
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
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)
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)
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)
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
873 public function set_name($name) {
874 $this->update_user_visible();
879 * Turns off the view link for this module instance.
880 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
883 public function set_no_view_link() {
884 $this->check_not_view_only();
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
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
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)
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
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) {
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
976 if ($this->modname
=== 'label' && $this->content
=== '') {
977 $this->content
= $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.
1013 if (!isset($modplurals[$this->modname
])) {
1014 $modplurals[$this->modname
] = get_string('modulenameplural', $this->modname
);
1016 $this->modplural
= $modplurals[$this->modname
];
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
))
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
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).
1042 public function obtain_dynamic_data() {
1044 if ($this->state
>= self
::STATE_DYNAMIC
) {
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
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
1065 $this->available
= false;
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()
1088 private function update_user_visible() {
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() {
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
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() {
1142 if (empty($CFG->enableavailability
)) {
1146 // If module will always be visible anyway (but greyed out), don't bother checking anything else
1147 if ($this->showavailability
== CONDITION_STUDENTVIEW_SHOW
) {
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)) {
1158 // Is the module hidden due to unmet conditions?
1159 if (!$this->available
) {
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'
1172 private function call_mod_function($type) {
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)) {
1181 $function = $this->modname
. '_' . $type;
1182 if (function_exists($function)) {
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).
1203 private function obtain_view_data() {
1204 if ($this->state
>= self
::STATE_VIEW
) {
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).
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') {
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
) {
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 if (!$clearonly && !empty($CFG->upgraderunning
)) {
1283 debugging('Function rebuild_course_cache() should not be called from upgrade script unless with argument clearonly.',
1288 // Destroy navigation caches
1289 navigation_cache
::destroy_volatile_caches();
1292 if (empty($courseid)) {
1293 $DB->set_field('course', 'modinfo', null);
1294 $DB->set_field('course', 'sectioncache', null);
1296 // Clear both fields in one update
1297 $resetobj = (object)array('id' => $courseid, 'modinfo' => null, 'sectioncache' => null);
1298 $DB->update_record('course', $resetobj);
1300 // update cached global COURSE too ;-)
1301 if ($courseid == $COURSE->id
or empty($courseid)) {
1302 $COURSE->modinfo
= null;
1303 $COURSE->sectioncache
= null;
1305 // reset the fast modinfo cache
1307 get_fast_modinfo($reset);
1311 require_once("$CFG->dirroot/course/lib.php");
1314 $select = array('id'=>$courseid);
1317 @set_time_limit
(0); // this could take a while! MDL-10954
1320 $rs = $DB->get_recordset("course", $select,'','id,fullname');
1321 foreach ($rs as $course) {
1322 $modinfo = serialize(get_array_of_activities($course->id
));
1323 $sectioncache = serialize(course_modinfo
::build_section_cache($course->id
));
1324 $updateobj = (object)array('id' => $course->id
,
1325 'modinfo' => $modinfo, 'sectioncache' => $sectioncache);
1326 $DB->update_record("course", $updateobj);
1327 // update cached global COURSE too ;-)
1328 if ($course->id
== $COURSE->id
) {
1329 $COURSE->modinfo
= $modinfo;
1330 $COURSE->sectioncache
= $sectioncache;
1334 // reset the fast modinfo cache
1336 get_fast_modinfo($reset);
1341 * Class that is the return value for the _get_coursemodule_info module API function.
1343 * Note: For backward compatibility, you can also return a stdclass object from that function.
1344 * The difference is that the stdclass object may contain an 'extra' field (deprecated because
1345 * it was crazy, except for label which uses it differently). The stdclass object may not contain
1346 * the new fields defined here (content, extraclasses, customdata).
1348 class cached_cm_info
{
1350 * Name (text of link) for this activity; Leave unset to accept default name
1356 * Name of icon for this activity. Normally, this should be used together with $iconcomponent
1357 * to define the icon, as per pix_url function.
1358 * For backward compatibility, if this value is of the form 'mod/forum/icon' then an icon
1359 * within that module will be used.
1360 * @see cm_info::get_icon_url()
1361 * @see renderer_base::pix_url()
1367 * Component for icon for this activity, as per pix_url; leave blank to use default 'moodle'
1369 * @see renderer_base::pix_url()
1372 public $iconcomponent;
1375 * HTML content to be displayed on the main page below the link (if any) for this course-module
1381 * Custom data to be stored in modinfo for this activity; useful if there are cases when
1382 * internal information for this activity type needs to be accessible from elsewhere on the
1383 * course without making database queries. May be of any type but should be short.
1389 * Extra CSS class or classes to be added when this activity is displayed on the main page;
1390 * space-separated string
1393 public $extraclasses;
1396 * External URL image to be used by activity as icon, useful for some external-tool modules
1397 * like lti. If set, takes precedence over $icon and $iconcomponent
1403 * Content of onclick JavaScript; escaped HTML to be inserted as attribute value
1411 * Data about a single section on a course. This contains the fields from the
1412 * course_sections table, plus additional data when required.
1414 class section_info
extends stdClass
{
1416 * Section ID - from course_sections table
1422 * Course ID - from course_sections table
1428 * Section number - from course_sections table
1434 * Section name if specified - from course_sections table
1440 * Section visibility (1 = visible) - from course_sections table
1446 * Section summary text if specified - from course_sections table
1452 * Section summary text format (FORMAT_xx constant) - from course_sections table
1455 public $summaryformat;
1458 * When section is unavailable, this field controls whether it is shown to students (0 =
1459 * hide completely, 1 = show greyed out with information about when it will be available) -
1460 * from course_sections table
1463 public $showavailability;
1466 * Available date for this section (0 if not set, or set to seconds since epoch; before this
1467 * date, section does not display to students) - from course_sections table
1470 public $availablefrom;
1473 * Available until date for this section (0 if not set, or set to seconds since epoch; from
1474 * this date, section does not display to students) - from course_sections table
1477 public $availableuntil;
1480 * If section is restricted to users of a particular grouping, this is its id
1481 * (0 if not set) - from course_sections table
1487 * Availability conditions for this section based on the completion of
1488 * course-modules (array from course-module id to required completion state
1489 * for that module) - from cached data in sectioncache field
1492 public $conditionscompletion;
1495 * Availability conditions for this section based on course grades (array from
1496 * grade item id to object with ->min, ->max fields) - from cached data in
1497 * sectioncache field
1500 public $conditionsgrade;
1503 * True if this section is available to students i.e. if all availability conditions
1504 * are met - obtained dynamically
1510 * If section is not available to students, this string gives information about
1511 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
1512 * January 2010') for display on main page - obtained dynamically
1515 public $availableinfo;
1518 * True if this section is available to the CURRENT user (for example, if current user
1519 * has viewhiddensections capability, they can access the section even if it is not
1520 * visible or not available, so this would be true in that case)
1523 public $uservisible;
1526 * Default values for sectioncache fields; if a field has this value, it won't
1527 * be stored in the sectioncache cache, to save space. Checks are done by ===
1528 * which means values must all be strings.
1531 private static $sectioncachedefaults = array(
1534 'summaryformat' => '1', // FORMAT_HTML, but must be a string
1536 'showavailability' => '0',
1537 'availablefrom' => '0',
1538 'availableuntil' => '0',
1539 'groupingid' => '0',
1543 * Constructs object from database information plus extra required data.
1544 * @param object $data Array entry from cached sectioncache
1545 * @param int $number Section number (array key)
1546 * @param int $courseid Course ID
1547 * @param int $sequence Sequence of course-module ids contained within
1548 * @param course_modinfo $modinfo Owner (needed for checking availability)
1549 * @param int $userid User ID
1551 public function __construct($data, $number, $courseid, $sequence, $modinfo, $userid) {
1554 // Data that is always present
1555 $this->id
= $data->id
;
1557 // Data that may use default values to save cache size
1558 foreach (self
::$sectioncachedefaults as $field => $value) {
1559 if (isset($data->{$field})) {
1560 $this->{$field} = $data->{$field};
1562 $this->{$field} = $value;
1566 // Data with array defaults
1567 $this->conditionscompletion
= isset($data->conditionscompletion
)
1568 ?
$data->conditionscompletion
: array();
1569 $this->conditionsgrade
= isset($data->conditionsgrade
)
1570 ?
$data->conditionsgrade
: array();
1572 // Other data from other places
1573 $this->course
= $courseid;
1574 $this->section
= $number;
1575 $this->sequence
= $sequence;
1577 // Availability data
1578 if (!empty($CFG->enableavailability
)) {
1579 // Get availability information
1580 $ci = new condition_info_section($this);
1581 $this->available
= $ci->is_available($this->availableinfo
, true,
1583 // Display grouping info if available & not already displaying
1584 // (it would already display if current user doesn't have access)
1585 // for people with managegroups - same logic/class as grouping label
1586 // on individual activities.
1587 $context = context_course
::instance($courseid);
1588 if ($this->availableinfo
=== '' && $this->groupingid
&&
1589 has_capability('moodle/course:managegroups', $context)) {
1590 $groupings = groups_get_all_groupings($courseid);
1591 $this->availableinfo
= html_writer
::tag('span', '(' . format_string(
1592 $groupings[$this->groupingid
]->name
, true, array('context' => $context)) .
1593 ')', array('class' => 'groupinglabel'));
1596 $this->available
= true;
1599 // Update visibility for current user
1600 $this->update_user_visible($userid);
1604 * Works out whether activity is visible *for current user* - if this is false, they
1605 * aren't allowed to access it.
1606 * @param int $userid User ID
1609 private function update_user_visible($userid) {
1611 $coursecontext = context_course
::instance($this->course
);
1612 $this->uservisible
= true;
1613 if ((!$this->visible ||
!$this->available
) &&
1614 !has_capability('moodle/course:viewhiddensections', $coursecontext, $userid)) {
1615 $this->uservisible
= false;
1620 * Prepares section data for inclusion in sectioncache cache, removing items
1621 * that are set to defaults, and adding availability data if required.
1623 * Called by build_section_cache in course_modinfo only; do not use otherwise.
1624 * @param object $section Raw section data object
1626 public static function convert_for_section_cache($section) {
1629 // Course id stored in course table
1630 unset($section->course
);
1631 // Section number stored in array key
1632 unset($section->section
);
1633 // Sequence stored implicity in modinfo $sections array
1634 unset($section->sequence
);
1636 // Add availability data if turned on
1637 if ($CFG->enableavailability
) {
1638 require_once($CFG->dirroot
. '/lib/conditionlib.php');
1639 condition_info_section
::fill_availability_conditions($section);
1640 if (count($section->conditionscompletion
) == 0) {
1641 unset($section->conditionscompletion
);
1643 if (count($section->conditionsgrade
) == 0) {
1644 unset($section->conditionsgrade
);
1648 // Remove default data
1649 foreach (self
::$sectioncachedefaults as $field => $value) {
1650 // Exact compare as strings to avoid problems if some strings are set
1652 if (isset($section->{$field}) && $section->{$field} === $value) {
1653 unset($section->{$field});