2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * modinfolib.php - Functions/classes relating to cached information about module instances on
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 * @author sam marshall
27 // Maximum number of modinfo items to keep in memory cache. Do not increase this to a large
29 // a) modinfo can be big (megabyte range) for some courses
30 // b) performance of cache will deteriorate if there are very many items in it
31 if (!defined('MAX_MODINFO_CACHE_SIZE')) {
32 define('MAX_MODINFO_CACHE_SIZE', 10);
37 * Information about a course that is cached in the course table 'modinfo' field (and then in
38 * memory) in order to reduce the need for other database queries.
40 * This includes information about the course-modules and the sections on the course. It can also
41 * include dynamic data that has been updated for the current user.
43 class course_modinfo
extends stdClass
{
44 // For convenience we store the course object here as it is needed in other parts of code
46 // Array of section data from cache
49 // Existing data fields
50 ///////////////////////
52 // These are public for backward compatibility. Note: it is not possible to retain BC
53 // using PHP magic get methods because behaviour is different with regard to empty().
58 * @deprecated For new code, use get_course_id instead.
65 * @deprecated For new code, use get_user_id instead.
70 * Array from int (section num, e.g. 0) => array of int (course-module id); this list only
71 * includes sections that actually contain at least one course-module
73 * @deprecated For new code, use get_sections instead
78 * Array from int (cm id) => cm_info object
80 * @deprecated For new code, use get_cms or get_cm instead.
85 * Array from string (modname) => int (instance id) => cm_info object
87 * @deprecated For new code, use get_instances or get_instances_of instead.
92 * Groups that the current user belongs to. This value is usually not available (set to null)
93 * unless the course has activities set to groupmembersonly. When set, it is an array of
94 * grouping id => array of group id => group id. Includes grouping id 0 for 'all groups'.
96 * @deprecated Don't use this! For new code, use get_groups.
100 // Get methods for data
101 ///////////////////////
104 * @return object Moodle course object that was used to construct this data
106 public function get_course() {
107 return $this->course
;
111 * @return int Course ID
113 public function get_course_id() {
114 return $this->courseid
;
118 * @return int User ID
120 public function get_user_id() {
121 return $this->userid
;
125 * @return array Array from section number (e.g. 0) to array of course-module IDs in that
126 * section; this only includes sections that contain at least one course-module
128 public function get_sections() {
129 return $this->sections
;
133 * @return array Array from course-module instance to cm_info object within this course, in
134 * order of appearance
136 public function get_cms() {
141 * Obtains a single course-module object (for a course-module that is on this course).
142 * @param int $cmid Course-module ID
143 * @return cm_info Information about that course-module
144 * @throws moodle_exception If the course-module does not exist
146 public function get_cm($cmid) {
147 if (empty($this->cms
[$cmid])) {
148 throw new moodle_exception('invalidcoursemodule', 'error');
150 return $this->cms
[$cmid];
154 * Obtains all module instances on this course.
155 * @return array Array from module name => array from instance id => cm_info
157 public function get_instances() {
158 return $this->instances
;
162 * Returns array of localised human-readable module names used in this course
164 * @param bool $plural if true returns the plural form of modules names
167 public function get_used_module_names($plural = false) {
168 $modnames = get_module_types_names($plural);
169 $modnamesused = array();
170 foreach ($this->get_cms() as $cmid => $mod) {
171 if (isset($modnames[$mod->modname
]) && $mod->uservisible
) {
172 $modnamesused[$mod->modname
] = $modnames[$mod->modname
];
175 collatorlib
::asort($modnamesused);
176 return $modnamesused;
180 * Obtains all instances of a particular module on this course.
181 * @param $modname Name of module (not full frankenstyle) e.g. 'label'
182 * @return array Array from instance id => cm_info for modules on this course; empty if none
184 public function get_instances_of($modname) {
185 if (empty($this->instances
[$modname])) {
188 return $this->instances
[$modname];
192 * Returns groups that the current user belongs to on the course. Note: If not already
193 * available, this may make a database query.
194 * @param int $groupingid Grouping ID or 0 (default) for all groups
195 * @return array Array of int (group id) => int (same group id again); empty array if none
197 public function get_groups($groupingid=0) {
198 if (is_null($this->groups
)) {
199 // NOTE: Performance could be improved here. The system caches user groups
200 // in $USER->groupmember[$courseid] => array of groupid=>groupid. Unfortunately this
201 // structure does not include grouping information. It probably could be changed to
202 // do so, without a significant performance hit on login, thus saving this one query
204 $this->groups
= groups_get_user_groups($this->courseid
, $this->userid
);
206 if (!isset($this->groups
[$groupingid])) {
209 return $this->groups
[$groupingid];
213 * Gets all sections as array from section number => data about section.
214 * @return array Array of section_info objects organised by section number
216 public function get_section_info_all() {
217 return $this->sectioninfo
;
221 * Gets data about specific numbered section.
222 * @param int $sectionnumber Number (not id) of section
223 * @param int $strictness Use MUST_EXIST to throw exception if it doesn't
224 * @return section_info Information for numbered section or null if not found
226 public function get_section_info($sectionnumber, $strictness = IGNORE_MISSING
) {
227 if (!array_key_exists($sectionnumber, $this->sectioninfo
)) {
228 if ($strictness === MUST_EXIST
) {
229 throw new moodle_exception('sectionnotexist');
234 return $this->sectioninfo
[$sectionnumber];
238 * Constructs based on course.
239 * Note: This constructor should not usually be called directly.
240 * Use get_fast_modinfo($course) instead as this maintains a cache.
241 * @param object $course Moodle course object, which may include modinfo
242 * @param int $userid User ID
244 public function __construct($course, $userid) {
247 // Check modinfo field is set. If not, build and load it.
248 if (empty($course->modinfo
) ||
empty($course->sectioncache
)) {
249 rebuild_course_cache($course->id
);
250 $course = $DB->get_record('course', array('id'=>$course->id
), '*', MUST_EXIST
);
253 // Set initial values
254 $this->courseid
= $course->id
;
255 $this->userid
= $userid;
256 $this->sections
= array();
257 $this->cms
= array();
258 $this->instances
= array();
259 $this->groups
= null;
260 $this->course
= $course;
262 // Load modinfo field into memory as PHP object and check it's valid
263 $info = unserialize($course->modinfo
);
264 if (!is_array($info)) {
265 // hmm, something is wrong - lets try to fix it
266 rebuild_course_cache($course->id
);
267 $course->modinfo
= $DB->get_field('course', 'modinfo', array('id'=>$course->id
));
268 $info = unserialize($course->modinfo
);
269 if (!is_array($info)) {
270 // If it still fails, abort
271 debugging('Problem with "modinfo" data for this course');
276 // Load sectioncache field into memory as PHP object and check it's valid
277 $sectioncache = unserialize($course->sectioncache
);
278 if (!is_array($sectioncache) ||
empty($sectioncache)) {
279 // hmm, something is wrong - let's fix it
280 rebuild_course_cache($course->id
);
281 $course->sectioncache
= $DB->get_field('course', 'sectioncache', array('id'=>$course->id
));
282 $sectioncache = unserialize($course->sectioncache
);
283 if (!is_array($sectioncache)) {
284 // If it still fails, abort
285 debugging('Problem with "sectioncache" data for this course');
290 // If we haven't already preloaded contexts for the course, do it now
291 preload_course_contexts($course->id
);
293 // Loop through each piece of module data, constructing it
294 $modexists = array();
295 foreach ($info as $mod) {
296 if (empty($mod->name
)) {
297 // something is wrong here
301 // Skip modules which don't exist
302 if (empty($modexists[$mod->mod
])) {
303 if (!file_exists("$CFG->dirroot/mod/$mod->mod/lib.php")) {
306 $modexists[$mod->mod
] = true;
309 // Construct info for this module
310 $cm = new cm_info($this, $course, $mod, $info);
312 // Store module in instances and cms array
313 if (!isset($this->instances
[$cm->modname
])) {
314 $this->instances
[$cm->modname
] = array();
316 $this->instances
[$cm->modname
][$cm->instance
] = $cm;
317 $this->cms
[$cm->id
] = $cm;
319 // Reconstruct sections. This works because modules are stored in order
320 if (!isset($this->sections
[$cm->sectionnum
])) {
321 $this->sections
[$cm->sectionnum
] = array();
323 $this->sections
[$cm->sectionnum
][] = $cm->id
;
326 // Expand section objects
327 $this->sectioninfo
= array();
328 foreach ($sectioncache as $number => $data) {
329 // Calculate sequence
330 if (isset($this->sections
[$number])) {
331 $sequence = implode(',', $this->sections
[$number]);
336 $this->sectioninfo
[$number] = new section_info($data, $number, $course->id
, $sequence,
340 // We need at least 'dynamic' data from each course-module (this is basically the remaining
341 // data which was always present in previous version of get_fast_modinfo, so it's required
342 // for BC). Creating it in a second pass is necessary because obtain_dynamic_data sometimes
343 // needs to be able to refer to a 'complete' (with basic data) modinfo.
344 foreach ($this->cms
as $cm) {
345 $cm->obtain_dynamic_data();
350 * Builds a list of information about sections on a course to be stored in
351 * the course cache. (Does not include information that is already cached
352 * in some other way.)
354 * Used internally by rebuild_course_cache function; do not use otherwise.
355 * @param int $courseid Course ID
356 * @return array Information about sections, indexed by section number (not id)
358 public static function build_section_cache($courseid) {
362 $sections = $DB->get_records('course_sections', array('course' => $courseid), 'section',
363 'section, id, course, name, summary, summaryformat, sequence, visible, ' .
364 'availablefrom, availableuntil, showavailability, groupingid');
365 $compressedsections = array();
367 $formatoptionsdef = course_get_format($courseid)->section_format_options();
368 // Remove unnecessary data and add availability
369 foreach ($sections as $number => $section) {
370 // Add cached options from course format to $section object
371 foreach ($formatoptionsdef as $key => $option) {
372 if (!empty($option['cache'])) {
373 $formatoptions = course_get_format($courseid)->get_format_options($section);
374 if (!array_key_exists('cachedefault', $option) ||
$option['cachedefault'] !== $formatoptions[$key]) {
375 $section->$key = $formatoptions[$key];
379 // Clone just in case it is reused elsewhere
380 $compressedsections[$number] = clone($section);
381 section_info
::convert_for_section_cache($compressedsections[$number]);
384 return $compressedsections;
390 * Data about a single module on a course. This contains most of the fields in the course_modules
391 * table, plus additional data when required.
393 * This object has many public fields; code should treat all these fields as read-only and set
394 * data only using the supplied set functions. Setting the fields directly is not supported
395 * and may cause problems later.
397 class cm_info
extends stdClass
{
399 * State: Only basic data from modinfo cache is available.
401 const STATE_BASIC
= 0;
404 * State: Dynamic data is available too.
406 const STATE_DYNAMIC
= 1;
409 * State: View data (for course page) is available.
411 const STATE_VIEW
= 2;
415 * @var course_modinfo
420 * Level of information stored inside this object (STATE_xx constant)
425 // Existing data fields
426 ///////////////////////
429 * Course-module ID - from course_modules table
435 * Module instance (ID within module table) - from course_modules table
441 * Course ID - from course_modules table
447 * 'ID number' from course-modules table (arbitrary text set by user) - from
448 * course_modules table
454 * Time that this course-module was added (unix time) - from course_modules table
460 * This variable is not used and is included here only so it can be documented.
461 * Once the database entry is removed from course_modules, it should be deleted
464 * @deprecated Do not use this variable
469 * Visible setting (0 or 1; if this is 0, students cannot see/access the activity) - from
470 * course_modules table
476 * Old visible setting (if the entire section is hidden, the previous value for
477 * visible is stored in this field) - from course_modules table
483 * Group mode (one of the constants NONE, SEPARATEGROUPS, or VISIBLEGROUPS) - from
484 * course_modules table
490 * Grouping ID (0 = all groupings)
496 * Group members only (if set to 1, only members of a suitable group see this link on the
497 * course page; 0 = everyone sees it even if they don't belong to a suitable group) - from
498 * course_modules table
501 public $groupmembersonly;
504 * Indent level on course page (0 = no indent) - from course_modules table
510 * Activity completion setting for this activity, COMPLETION_TRACKING_xx constant - from
511 * course_modules table
517 * Set to the item number (usually 0) if completion depends on a particular
518 * grade of this activity, or null if completion does not depend on a grade - from
519 * course_modules table
522 public $completiongradeitemnumber;
525 * 1 if 'on view' completion is enabled, 0 otherwise - from course_modules table
528 public $completionview;
531 * Set to a unix time if completion of this activity is expected at a
532 * particular time, 0 if no time set - from course_modules table
535 public $completionexpected;
538 * Available date for this activity (0 if not set, or set to seconds since epoch; before this
539 * date, activity does not display to students) - from course_modules table
542 public $availablefrom;
545 * Available until date for this activity (0 if not set, or set to seconds since epoch; from
546 * this date, activity does not display to students) - from course_modules table
549 public $availableuntil;
552 * When activity is unavailable, this field controls whether it is shown to students (0 =
553 * hide completely, 1 = show greyed out with information about when it will be available) -
554 * from course_modules table
557 public $showavailability;
560 * Controls whether the description of the activity displays on the course main page (in
561 * addition to anywhere it might display within the activity itself). 0 = do not show
562 * on main page, 1 = show on main page.
565 public $showdescription;
568 * Extra HTML that is put in an unhelpful part of the HTML when displaying this module in
569 * course page - from cached data in modinfo field
570 * @deprecated This is crazy, don't use it. Replaced by ->extraclasses and ->onclick
576 * Name of icon to use - from cached data in modinfo field
582 * Component that contains icon - from cached data in modinfo field
585 public $iconcomponent;
588 * Name of module e.g. 'forum' (this is the same name as the module's main database
589 * table) - from cached data in modinfo field
595 * ID of module - from course_modules table
601 * Name of module instance for display on page e.g. 'General discussion forum' - from cached
602 * data in modinfo field
608 * Section number that this course-module is in (section 0 = above the calendar, section 1
609 * = week/topic 1, etc) - from cached data in modinfo field
615 * Section id - from course_modules table
621 * Availability conditions for this course-module based on the completion of other
622 * course-modules (array from other course-module id to required completion state for that
623 * module) - from cached data in modinfo field
626 public $conditionscompletion;
629 * Availability conditions for this course-module based on course grades (array from
630 * grade item id to object with ->min, ->max fields) - from cached data in modinfo field
633 public $conditionsgrade;
636 * Availability conditions for this course-module based on user fields
639 public $conditionsfield;
642 * True if this course-module is available to students i.e. if all availability conditions
643 * are met - obtained dynamically
649 * If course-module is not available to students, this string gives information about
650 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
651 * January 2010') for display on main page - obtained dynamically
654 public $availableinfo;
657 * True if this course-module is available to the CURRENT user (for example, if current user
658 * has viewhiddenactivities capability, they can access the course-module even if it is not
659 * visible or not available, so this would be true in that case)
665 * Module context - hacky shortcut
672 // New data available only via functions
673 ////////////////////////////////////////
688 private $extraclasses;
691 * @var moodle_url full external url pointing to icon image for activity
713 private $afterediticons;
716 * Magic method getter
718 * @param string $name
721 public function __get($name) {
724 return $this->get_module_type_name(true);
726 return $this->get_module_type_name();
728 debugging('Invalid cm_info property accessed: '.$name);
734 * @return bool True if this module has a 'view' page that should be linked to in navigation
735 * etc (note: modules may still have a view.php file, but return false if this is not
736 * intended to be linked to from 'normal' parts of the interface; this is what label does).
738 public function has_view() {
739 return !is_null($this->url
);
743 * @return moodle_url URL to link to for this module, or null if it doesn't have a view page
745 public function get_url() {
750 * Obtains content to display on main (view) page.
751 * Note: Will collect view data, if not already obtained.
752 * @return string Content to display on main page below link, or empty string if none
754 public function get_content() {
755 $this->obtain_view_data();
756 return $this->content
;
760 * Note: Will collect view data, if not already obtained.
761 * @return string Extra CSS classes to add to html output for this activity on main page
763 public function get_extra_classes() {
764 $this->obtain_view_data();
765 return $this->extraclasses
;
769 * @return string Content of HTML on-click attribute. This string will be used literally
770 * as a string so should be pre-escaped.
772 public function get_on_click() {
773 // Does not need view data; may be used by navigation
774 return $this->onclick
;
777 * @return mixed Optional custom data stored in modinfo cache for this activity, or null if none
779 public function get_custom_data() {
780 return $this->customdata
;
784 * Note: Will collect view data, if not already obtained.
785 * @return string Extra HTML code to display after link
787 public function get_after_link() {
788 $this->obtain_view_data();
789 return $this->afterlink
;
793 * Note: Will collect view data, if not already obtained.
794 * @return string Extra HTML code to display after editing icons (e.g. more icons)
796 public function get_after_edit_icons() {
797 $this->obtain_view_data();
798 return $this->afterediticons
;
802 * @param moodle_core_renderer $output Output render to use, or null for default (global)
803 * @return moodle_url Icon URL for a suitable icon to put beside this cm
805 public function get_icon_url($output = null) {
810 // Support modules setting their own, external, icon image
811 if (!empty($this->iconurl
)) {
812 $icon = $this->iconurl
;
814 // Fallback to normal local icon + component procesing
815 } else if (!empty($this->icon
)) {
816 if (substr($this->icon
, 0, 4) === 'mod/') {
817 list($modname, $iconname) = explode('/', substr($this->icon
, 4), 2);
818 $icon = $output->pix_url($iconname, $modname);
820 if (!empty($this->iconcomponent
)) {
821 // Icon has specified component
822 $icon = $output->pix_url($this->icon
, $this->iconcomponent
);
824 // Icon does not have specified component, use default
825 $icon = $output->pix_url($this->icon
);
829 $icon = $output->pix_url('icon', $this->modname
);
835 * Returns a localised human-readable name of the module type
837 * @param bool $plural return plural form
840 public function get_module_type_name($plural = false) {
841 $modnames = get_module_types_names($plural);
842 if (isset($modnames[$this->modname
])) {
843 return $modnames[$this->modname
];
850 * @return course_modinfo Modinfo object that this came from
852 public function get_modinfo() {
853 return $this->modinfo
;
857 * @return object Moodle course object that was used to construct this data
859 public function get_course() {
860 return $this->modinfo
->get_course();
867 * Sets content to display on course view page below link (if present).
868 * @param string $content New content as HTML string (empty string if none)
871 public function set_content($content) {
872 $this->content
= $content;
876 * Sets extra classes to include in CSS.
877 * @param string $extraclasses Extra classes (empty string if none)
880 public function set_extra_classes($extraclasses) {
881 $this->extraclasses
= $extraclasses;
885 * Sets the external full url that points to the icon being used
886 * by the activity. Useful for external-tool modules (lti...)
887 * If set, takes precedence over $icon and $iconcomponent
889 * @param moodle_url $iconurl full external url pointing to icon image for activity
892 public function set_icon_url(moodle_url
$iconurl) {
893 $this->iconurl
= $iconurl;
897 * Sets value of on-click attribute for JavaScript.
898 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
899 * @param string $onclick New onclick attribute which should be HTML-escaped
900 * (empty string if none)
903 public function set_on_click($onclick) {
904 $this->check_not_view_only();
905 $this->onclick
= $onclick;
909 * Sets HTML that displays after link on course view page.
910 * @param string $afterlink HTML string (empty string if none)
913 public function set_after_link($afterlink) {
914 $this->afterlink
= $afterlink;
918 * Sets HTML that displays after edit icons on course view page.
919 * @param string $afterediticons HTML string (empty string if none)
922 public function set_after_edit_icons($afterediticons) {
923 $this->afterediticons
= $afterediticons;
927 * Changes the name (text of link) for this module instance.
928 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
929 * @param string $name Name of activity / link text
932 public function set_name($name) {
933 $this->update_user_visible();
938 * Turns off the view link for this module instance.
939 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
942 public function set_no_view_link() {
943 $this->check_not_view_only();
948 * Sets the 'uservisible' flag. This can be used (by setting false) to prevent access and
949 * display of this module link for the current user.
950 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
951 * @param bool $uservisible
954 public function set_user_visible($uservisible) {
955 $this->check_not_view_only();
956 $this->uservisible
= $uservisible;
960 * Sets the 'available' flag and related details. This flag is normally used to make
961 * course modules unavailable until a certain date or condition is met. (When a course
962 * module is unavailable, it is still visible to users who have viewhiddenactivities
965 * When this is function is called, user-visible status is recalculated automatically.
967 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
968 * @param bool $available False if this item is not 'available'
969 * @param int $showavailability 0 = do not show this item at all if it's not available,
970 * 1 = show this item greyed out with the following message
971 * @param string $availableinfo Information about why this is not available which displays
972 * to those who have viewhiddenactivities, and to everyone if showavailability is set;
973 * note that this function replaces the existing data (if any)
976 public function set_available($available, $showavailability=0, $availableinfo='') {
977 $this->check_not_view_only();
978 $this->available
= $available;
979 $this->showavailability
= $showavailability;
980 $this->availableinfo
= $availableinfo;
981 $this->update_user_visible();
985 * Some set functions can only be called from _cm_info_dynamic and not _cm_info_view.
986 * This is because they may affect parts of this object which are used on pages other
987 * than the view page (e.g. in the navigation block, or when checking access on
991 private function check_not_view_only() {
992 if ($this->state
>= self
::STATE_DYNAMIC
) {
993 throw new coding_exception('Cannot set this data from _cm_info_view because it may ' .
994 'affect other pages as well as view');
999 * Constructor should not be called directly; use get_fast_modinfo.
1000 * @param course_modinfo $modinfo Parent object
1001 * @param object $course Course row
1002 * @param object $mod Module object from the modinfo field of course table
1003 * @param object $info Entire object from modinfo field of course table
1005 public function __construct(course_modinfo
$modinfo, $course, $mod, $info) {
1007 $this->modinfo
= $modinfo;
1009 $this->id
= $mod->cm
;
1010 $this->instance
= $mod->id
;
1011 $this->course
= $course->id
;
1012 $this->modname
= $mod->mod
;
1013 $this->idnumber
= isset($mod->idnumber
) ?
$mod->idnumber
: '';
1014 $this->name
= $mod->name
;
1015 $this->visible
= $mod->visible
;
1016 $this->sectionnum
= $mod->section
; // Note weirdness with name here
1017 $this->groupmode
= isset($mod->groupmode
) ?
$mod->groupmode
: 0;
1018 $this->groupingid
= isset($mod->groupingid
) ?
$mod->groupingid
: 0;
1019 $this->groupmembersonly
= isset($mod->groupmembersonly
) ?
$mod->groupmembersonly
: 0;
1020 $this->indent
= isset($mod->indent
) ?
$mod->indent
: 0;
1021 $this->extra
= isset($mod->extra
) ?
$mod->extra
: '';
1022 $this->extraclasses
= isset($mod->extraclasses
) ?
$mod->extraclasses
: '';
1023 $this->iconurl
= isset($mod->iconurl
) ?
$mod->iconurl
: '';
1024 $this->onclick
= isset($mod->onclick
) ?
$mod->onclick
: '';
1025 $this->content
= isset($mod->content
) ?
$mod->content
: '';
1026 $this->icon
= isset($mod->icon
) ?
$mod->icon
: '';
1027 $this->iconcomponent
= isset($mod->iconcomponent
) ?
$mod->iconcomponent
: '';
1028 $this->customdata
= isset($mod->customdata
) ?
$mod->customdata
: '';
1029 $this->context
= context_module
::instance($mod->cm
);
1030 $this->showdescription
= isset($mod->showdescription
) ?
$mod->showdescription
: 0;
1031 $this->state
= self
::STATE_BASIC
;
1033 // This special case handles old label data. Labels used to use the 'name' field for
1035 if ($this->modname
=== 'label' && $this->content
=== '') {
1036 $this->content
= $this->extra
;
1040 // Note: These fields from $cm were not present in cm_info in Moodle
1041 // 2.0.2 and prior. They may not be available if course cache hasn't
1042 // been rebuilt since then.
1043 $this->section
= isset($mod->sectionid
) ?
$mod->sectionid
: 0;
1044 $this->module
= isset($mod->module
) ?
$mod->module
: 0;
1045 $this->added
= isset($mod->added
) ?
$mod->added
: 0;
1046 $this->score
= isset($mod->score
) ?
$mod->score
: 0;
1047 $this->visibleold
= isset($mod->visibleold
) ?
$mod->visibleold
: 0;
1049 // Note: it saves effort and database space to always include the
1050 // availability and completion fields, even if availability or completion
1051 // are actually disabled
1052 $this->completion
= isset($mod->completion
) ?
$mod->completion
: 0;
1053 $this->completiongradeitemnumber
= isset($mod->completiongradeitemnumber
)
1054 ?
$mod->completiongradeitemnumber
: null;
1055 $this->completionview
= isset($mod->completionview
)
1056 ?
$mod->completionview
: 0;
1057 $this->completionexpected
= isset($mod->completionexpected
)
1058 ?
$mod->completionexpected
: 0;
1059 $this->showavailability
= isset($mod->showavailability
) ?
$mod->showavailability
: 0;
1060 $this->availablefrom
= isset($mod->availablefrom
) ?
$mod->availablefrom
: 0;
1061 $this->availableuntil
= isset($mod->availableuntil
) ?
$mod->availableuntil
: 0;
1062 $this->conditionscompletion
= isset($mod->conditionscompletion
)
1063 ?
$mod->conditionscompletion
: array();
1064 $this->conditionsgrade
= isset($mod->conditionsgrade
)
1065 ?
$mod->conditionsgrade
: array();
1066 $this->conditionsfield
= isset($mod->conditionsfield
)
1067 ?
$mod->conditionsfield
: array();
1070 if (!isset($modviews[$this->modname
])) {
1071 $modviews[$this->modname
] = !plugin_supports('mod', $this->modname
,
1072 FEATURE_NO_VIEW_LINK
);
1074 $this->url
= $modviews[$this->modname
]
1075 ?
new moodle_url('/mod/' . $this->modname
. '/view.php', array('id'=>$this->id
))
1080 * If dynamic data for this course-module is not yet available, gets it.
1082 * This function is automatically called when constructing course_modinfo, so users don't
1085 * Dynamic data is data which does not come directly from the cache but is calculated at
1086 * runtime based on the current user. Primarily this concerns whether the user can access
1087 * the module or not.
1089 * As part of this function, the module's _cm_info_dynamic function from its lib.php will
1090 * be called (if it exists).
1093 public function obtain_dynamic_data() {
1095 if ($this->state
>= self
::STATE_DYNAMIC
) {
1098 $userid = $this->modinfo
->get_user_id();
1100 if (!empty($CFG->enableavailability
)) {
1101 // Get availability information
1102 $ci = new condition_info($this);
1103 // Note that the modinfo currently available only includes minimal details (basic data)
1104 // so passing it to this function is a bit dangerous as it would cause infinite
1105 // recursion if it tried to get dynamic data, however we know that this function only
1107 $this->available
= $ci->is_available($this->availableinfo
, true,
1108 $userid, $this->modinfo
);
1110 // Check parent section
1111 $parentsection = $this->modinfo
->get_section_info($this->sectionnum
);
1112 if (!$parentsection->available
) {
1113 // Do not store info from section here, as that is already
1114 // presented from the section (if appropriate) - just change
1116 $this->available
= false;
1119 $this->available
= true;
1122 // Update visible state for current user
1123 $this->update_user_visible();
1125 // Let module make dynamic changes at this point
1126 $this->call_mod_function('cm_info_dynamic');
1127 $this->state
= self
::STATE_DYNAMIC
;
1131 * Works out whether activity is available to the current user
1133 * If the activity is unavailable, additional checks are required to determine if its hidden or greyed out
1135 * @see is_user_access_restricted_by_group()
1136 * @see is_user_access_restricted_by_conditional_access()
1139 private function update_user_visible() {
1141 $modcontext = context_module
::instance($this->id
);
1142 $userid = $this->modinfo
->get_user_id();
1143 $this->uservisible
= true;
1145 // If the user cannot access the activity set the uservisible flag to false.
1146 // Additional checks are required to determine whether the activity is entirely hidden or just greyed out.
1147 if ((!$this->visible
or !$this->available
) and
1148 !has_capability('moodle/course:viewhiddenactivities', $modcontext, $userid)) {
1150 $this->uservisible
= false;
1153 // Check group membership.
1154 if ($this->is_user_access_restricted_by_group()) {
1156 $this->uservisible
= false;
1157 // Ensure activity is completely hidden from the user.
1158 $this->showavailability
= 0;
1163 * Checks whether the module's group settings restrict the current user's access
1165 * @return bool True if the user access is restricted
1167 public function is_user_access_restricted_by_group() {
1170 if (!empty($CFG->enablegroupmembersonly
) and !empty($this->groupmembersonly
)) {
1171 $modcontext = context_module
::instance($this->id
);
1172 $userid = $this->modinfo
->get_user_id();
1173 if (!has_capability('moodle/site:accessallgroups', $modcontext, $userid)) {
1174 // If the activity has 'group members only' and you don't have accessallgroups...
1175 $groups = $this->modinfo
->get_groups($this->groupingid
);
1176 if (empty($groups)) {
1177 // ...and you don't belong to a group, then set it so you can't see/access it
1186 * Checks whether the module's conditional access settings mean that the user cannot see the activity at all
1188 * @return bool True if the user cannot see the module. False if the activity is either available or should be greyed out.
1190 public function is_user_access_restricted_by_conditional_access() {
1193 if (empty($CFG->enableavailability
)) {
1197 // If module will always be visible anyway (but greyed out), don't bother checking anything else
1198 if ($this->showavailability
== CONDITION_STUDENTVIEW_SHOW
) {
1202 // Can the user see hidden modules?
1203 $modcontext = context_module
::instance($this->id
);
1204 $userid = $this->modinfo
->get_user_id();
1205 if (has_capability('moodle/course:viewhiddenactivities', $modcontext, $userid)) {
1209 // Is the module hidden due to unmet conditions?
1210 if (!$this->available
) {
1218 * Calls a module function (if exists), passing in one parameter: this object.
1219 * @param string $type Name of function e.g. if this is 'grooblezorb' and the modname is
1220 * 'forum' then it will try to call 'mod_forum_grooblezorb' or 'forum_grooblezorb'
1223 private function call_mod_function($type) {
1225 $libfile = $CFG->dirroot
. '/mod/' . $this->modname
. '/lib.php';
1226 if (file_exists($libfile)) {
1227 include_once($libfile);
1228 $function = 'mod_' . $this->modname
. '_' . $type;
1229 if (function_exists($function)) {
1232 $function = $this->modname
. '_' . $type;
1233 if (function_exists($function)) {
1241 * If view data for this course-module is not yet available, obtains it.
1243 * This function is automatically called if any of the functions (marked) which require
1244 * view data are called.
1246 * View data is data which is needed only for displaying the course main page (& any similar
1247 * functionality on other pages) but is not needed in general. Obtaining view data may have
1248 * a performance cost.
1250 * As part of this function, the module's _cm_info_view function from its lib.php will
1251 * be called (if it exists).
1254 private function obtain_view_data() {
1255 if ($this->state
>= self
::STATE_VIEW
) {
1259 // Let module make changes at this point
1260 $this->call_mod_function('cm_info_view');
1261 $this->state
= self
::STATE_VIEW
;
1267 * Returns reference to full info about modules in course (including visibility).
1268 * Cached and as fast as possible (0 or 1 db query).
1270 * use get_fast_modinfo($courseid, 0, true) to reset the static cache for particular course
1271 * use get_fast_modinfo(0, 0, true) to reset the static cache for all courses
1273 * @uses MAX_MODINFO_CACHE_SIZE
1274 * @param int|stdClass $courseorid object from DB table 'course' or just a course id
1275 * @param int $userid User id to populate 'uservisible' attributes of modules and sections.
1276 * Set to 0 for current user (default)
1277 * @param bool $resetonly whether we want to get modinfo or just reset the cache
1278 * @return course_modinfo|null Module information for course, or null if resetting
1280 function get_fast_modinfo($courseorid, $userid = 0, $resetonly = false) {
1282 require_once($CFG->dirroot
.'/course/lib.php');
1284 if (!empty($CFG->enableavailability
)) {
1285 require_once($CFG->libdir
.'/conditionlib.php');
1288 static $cache = array();
1290 // compartibility with syntax prior to 2.4:
1291 if ($courseorid === 'reset') {
1292 debugging("Using the string 'reset' as the first argument of get_fast_modinfo() is deprecated. Use get_fast_modinfo(0,0,true) instead.", DEBUG_DEVELOPER
);
1297 if (is_object($courseorid)) {
1298 $course = $courseorid;
1300 $course = (object)array('id' => $courseorid, 'modinfo' => null, 'sectioncache' => null);
1303 // Function is called with $reset = true
1305 if (isset($course->id
) && $course->id
> 0) {
1306 $cache[$course->id
] = false;
1308 foreach (array_keys($cache) as $key) {
1309 $cache[$key] = false;
1315 // Function is called with $reset = false, retrieve modinfo
1316 if (empty($userid)) {
1317 $userid = $USER->id
;
1320 if (array_key_exists($course->id
, $cache)) {
1321 if ($cache[$course->id
] === false) {
1322 // this course has been recently reset, do not rely on modinfo and sectioncache in $course
1323 $course->modinfo
= null;
1324 $course->sectioncache
= null;
1325 } else if ($cache[$course->id
]->userid
== $userid) {
1326 // this course's modinfo for the same user was recently retrieved, return cached
1327 return $cache[$course->id
];
1331 if (!property_exists($course, 'modinfo')) {
1332 debugging('Coding problem - missing course modinfo property in get_fast_modinfo() call');
1335 if (!property_exists($course, 'sectioncache')) {
1336 debugging('Coding problem - missing course sectioncache property in get_fast_modinfo() call');
1339 unset($cache[$course->id
]); // prevent potential reference problems when switching users
1341 $cache[$course->id
] = new course_modinfo($course, $userid);
1343 // Ensure cache does not use too much RAM
1344 if (count($cache) > MAX_MODINFO_CACHE_SIZE
) {
1347 unset($cache[$key]->instances
);
1348 unset($cache[$key]->cms
);
1349 unset($cache[$key]);
1352 return $cache[$course->id
];
1356 * Rebuilds the cached list of course activities stored in the database
1357 * @param int $courseid - id of course to rebuild, empty means all
1358 * @param boolean $clearonly - only clear the modinfo fields, gets rebuild automatically on the fly
1360 function rebuild_course_cache($courseid=0, $clearonly=false) {
1361 global $COURSE, $SITE, $DB, $CFG;
1363 if (!$clearonly && !empty($CFG->upgraderunning
)) {
1364 debugging('Function rebuild_course_cache() should not be called from upgrade script unless with argument clearonly.',
1369 // Destroy navigation caches
1370 navigation_cache
::destroy_volatile_caches();
1372 if (class_exists('format_base')) {
1373 // if file containing class is not loaded, there is no cache there anyway
1374 format_base
::reset_course_cache($courseid);
1378 if (empty($courseid)) {
1379 $DB->set_field('course', 'modinfo', null);
1380 $DB->set_field('course', 'sectioncache', null);
1382 // Clear both fields in one update
1383 $resetobj = (object)array('id' => $courseid, 'modinfo' => null, 'sectioncache' => null);
1384 $DB->update_record('course', $resetobj);
1386 // update cached global COURSE too ;-)
1387 if ($courseid == $COURSE->id
or empty($courseid)) {
1388 $COURSE->modinfo
= null;
1389 $COURSE->sectioncache
= null;
1391 if ($courseid == $SITE->id
) {
1392 $SITE->modinfo
= null;
1393 $SITE->sectioncache
= null;
1395 // reset the fast modinfo cache
1396 get_fast_modinfo($courseid, 0, true);
1400 require_once("$CFG->dirroot/course/lib.php");
1403 $select = array('id'=>$courseid);
1406 @set_time_limit
(0); // this could take a while! MDL-10954
1409 $rs = $DB->get_recordset("course", $select,'','id,fullname');
1410 foreach ($rs as $course) {
1411 $modinfo = serialize(get_array_of_activities($course->id
));
1412 $sectioncache = serialize(course_modinfo
::build_section_cache($course->id
));
1413 $updateobj = (object)array('id' => $course->id
,
1414 'modinfo' => $modinfo, 'sectioncache' => $sectioncache);
1415 $DB->update_record("course", $updateobj);
1416 // update cached global COURSE too ;-)
1417 if ($course->id
== $COURSE->id
) {
1418 $COURSE->modinfo
= $modinfo;
1419 $COURSE->sectioncache
= $sectioncache;
1421 if ($course->id
== $SITE->id
) {
1422 $SITE->modinfo
= $modinfo;
1423 $SITE->sectioncache
= $sectioncache;
1427 // reset the fast modinfo cache
1428 get_fast_modinfo($courseid, 0, true);
1433 * Class that is the return value for the _get_coursemodule_info module API function.
1435 * Note: For backward compatibility, you can also return a stdclass object from that function.
1436 * The difference is that the stdclass object may contain an 'extra' field (deprecated because
1437 * it was crazy, except for label which uses it differently). The stdclass object may not contain
1438 * the new fields defined here (content, extraclasses, customdata).
1440 class cached_cm_info
{
1442 * Name (text of link) for this activity; Leave unset to accept default name
1448 * Name of icon for this activity. Normally, this should be used together with $iconcomponent
1449 * to define the icon, as per pix_url function.
1450 * For backward compatibility, if this value is of the form 'mod/forum/icon' then an icon
1451 * within that module will be used.
1452 * @see cm_info::get_icon_url()
1453 * @see renderer_base::pix_url()
1459 * Component for icon for this activity, as per pix_url; leave blank to use default 'moodle'
1461 * @see renderer_base::pix_url()
1464 public $iconcomponent;
1467 * HTML content to be displayed on the main page below the link (if any) for this course-module
1473 * Custom data to be stored in modinfo for this activity; useful if there are cases when
1474 * internal information for this activity type needs to be accessible from elsewhere on the
1475 * course without making database queries. May be of any type but should be short.
1481 * Extra CSS class or classes to be added when this activity is displayed on the main page;
1482 * space-separated string
1485 public $extraclasses;
1488 * External URL image to be used by activity as icon, useful for some external-tool modules
1489 * like lti. If set, takes precedence over $icon and $iconcomponent
1495 * Content of onclick JavaScript; escaped HTML to be inserted as attribute value
1503 * Data about a single section on a course. This contains the fields from the
1504 * course_sections table, plus additional data when required.
1506 class section_info
implements IteratorAggregate
{
1508 * Section ID - from course_sections table
1514 * Course ID - from course_sections table
1520 * Section number - from course_sections table
1526 * Section name if specified - from course_sections table
1532 * Section visibility (1 = visible) - from course_sections table
1538 * Section summary text if specified - from course_sections table
1544 * Section summary text format (FORMAT_xx constant) - from course_sections table
1547 private $_summaryformat;
1550 * When section is unavailable, this field controls whether it is shown to students (0 =
1551 * hide completely, 1 = show greyed out with information about when it will be available) -
1552 * from course_sections table
1555 private $_showavailability;
1558 * Available date for this section (0 if not set, or set to seconds since epoch; before this
1559 * date, section does not display to students) - from course_sections table
1562 private $_availablefrom;
1565 * Available until date for this section (0 if not set, or set to seconds since epoch; from
1566 * this date, section does not display to students) - from course_sections table
1569 private $_availableuntil;
1572 * If section is restricted to users of a particular grouping, this is its id
1573 * (0 if not set) - from course_sections table
1576 private $_groupingid;
1579 * Availability conditions for this section based on the completion of
1580 * course-modules (array from course-module id to required completion state
1581 * for that module) - from cached data in sectioncache field
1584 private $_conditionscompletion;
1587 * Availability conditions for this section based on course grades (array from
1588 * grade item id to object with ->min, ->max fields) - from cached data in
1589 * sectioncache field
1592 private $_conditionsgrade;
1595 * Availability conditions for this section based on user fields
1598 private $_conditionsfield;
1601 * True if this section is available to students i.e. if all availability conditions
1602 * are met - obtained dynamically
1605 private $_available;
1608 * If section is not available to students, this string gives information about
1609 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
1610 * January 2010') for display on main page - obtained dynamically
1613 private $_availableinfo;
1616 * True if this section is available to the CURRENT user (for example, if current user
1617 * has viewhiddensections capability, they can access the section even if it is not
1618 * visible or not available, so this would be true in that case)
1621 private $_uservisible;
1624 * Default values for sectioncache fields; if a field has this value, it won't
1625 * be stored in the sectioncache cache, to save space. Checks are done by ===
1626 * which means values must all be strings.
1629 private static $sectioncachedefaults = array(
1632 'summaryformat' => '1', // FORMAT_HTML, but must be a string
1634 'showavailability' => '0',
1635 'availablefrom' => '0',
1636 'availableuntil' => '0',
1637 'groupingid' => '0',
1641 * Stores format options that have been cached when building 'coursecache'
1642 * When the format option is requested we look first if it has been cached
1645 private $cachedformatoptions = array();
1648 * Constructs object from database information plus extra required data.
1649 * @param object $data Array entry from cached sectioncache
1650 * @param int $number Section number (array key)
1651 * @param int $courseid Course ID
1652 * @param int $sequence Sequence of course-module ids contained within
1653 * @param course_modinfo $modinfo Owner (needed for checking availability)
1654 * @param int $userid User ID
1656 public function __construct($data, $number, $courseid, $sequence, $modinfo, $userid) {
1659 // Data that is always present
1660 $this->_id
= $data->id
;
1662 $defaults = self
::$sectioncachedefaults +
1663 array('conditionscompletion' => array(),
1664 'conditionsgrade' => array(),
1665 'conditionsfield' => array());
1667 // Data that may use default values to save cache size
1668 foreach ($defaults as $field => $value) {
1669 if (isset($data->{$field})) {
1670 $this->{'_'.$field} = $data->{$field};
1672 $this->{'_'.$field} = $value;
1676 // cached course format data
1677 $formatoptionsdef = course_get_format($courseid)->section_format_options();
1678 foreach ($formatoptionsdef as $field => $option) {
1679 if (!empty($option['cache'])) {
1680 if (isset($data->{$field})) {
1681 $this->cachedformatoptions
[$field] = $data->{$field};
1682 } else if (array_key_exists('cachedefault', $option)) {
1683 $this->cachedformatoptions
[$field] = $option['cachedefault'];
1688 // Other data from other places
1689 $this->_course
= $courseid;
1690 $this->_section
= $number;
1691 $this->_sequence
= $sequence;
1693 // Availability data
1694 if (!empty($CFG->enableavailability
)) {
1695 // Get availability information
1696 $ci = new condition_info_section($this);
1697 $this->_available
= $ci->is_available($this->_availableinfo
, true,
1699 // Display grouping info if available & not already displaying
1700 // (it would already display if current user doesn't have access)
1701 // for people with managegroups - same logic/class as grouping label
1702 // on individual activities.
1703 $context = context_course
::instance($courseid);
1704 if ($this->_availableinfo
=== '' && $this->_groupingid
&&
1705 has_capability('moodle/course:managegroups', $context)) {
1706 $groupings = groups_get_all_groupings($courseid);
1707 $this->_availableinfo
= html_writer
::tag('span', '(' . format_string(
1708 $groupings[$this->_groupingid
]->name
, true, array('context' => $context)) .
1709 ')', array('class' => 'groupinglabel'));
1712 $this->_available
= true;
1715 // Update visibility for current user
1716 $this->update_user_visible($userid);
1720 * Magic method to check if the property is set
1722 * @param string $name name of the property
1725 public function __isset($name) {
1726 if (property_exists($this, '_'.$name)) {
1727 return isset($this->{'_'.$name});
1729 $defaultformatoptions = course_get_format($this->_course
)->section_format_options();
1730 if (array_key_exists($name, $defaultformatoptions)) {
1731 $value = $this->__get($name);
1732 return isset($value);
1738 * Magic method to check if the property is empty
1740 * @param string $name name of the property
1743 public function __empty($name) {
1744 if (property_exists($this, '_'.$name)) {
1745 return empty($this->{'_'.$name});
1747 $defaultformatoptions = course_get_format($this->_course
)->section_format_options();
1748 if (array_key_exists($name, $defaultformatoptions)) {
1749 $value = $this->__get($name);
1750 return empty($value);
1756 * Magic method to retrieve the property, this is either basic section property
1757 * or availability information or additional properties added by course format
1759 * @param string $name name of the property
1762 public function __get($name) {
1763 if (property_exists($this, '_'.$name)) {
1764 return $this->{'_'.$name};
1766 if (array_key_exists($name, $this->cachedformatoptions
)) {
1767 return $this->cachedformatoptions
[$name];
1769 $defaultformatoptions = course_get_format($this->_course
)->section_format_options();
1770 // precheck if the option is defined in format to avoid unnecessary DB queries in get_format_options()
1771 if (array_key_exists($name, $defaultformatoptions)) {
1772 $formatoptions = course_get_format($this->_course
)->get_format_options($this);
1773 return $formatoptions[$name];
1775 debugging('Invalid section_info property accessed! '.$name);
1780 * Implementation of IteratorAggregate::getIterator(), allows to cycle through properties
1781 * and use {@link convert_to_array()}
1783 * @return ArrayIterator
1785 public function getIterator() {
1787 foreach (get_object_vars($this) as $key => $value) {
1788 if (substr($key, 0, 1) == '_') {
1789 $ret[substr($key, 1)] = $this->$key;
1792 $ret = array_merge($ret, course_get_format($this->_course
)->get_format_options($this));
1793 return new ArrayIterator($ret);
1797 * Works out whether activity is visible *for current user* - if this is false, they
1798 * aren't allowed to access it.
1799 * @param int $userid User ID
1802 private function update_user_visible($userid) {
1804 $coursecontext = context_course
::instance($this->_course
);
1805 $this->_uservisible
= true;
1806 if ((!$this->_visible ||
!$this->_available
) &&
1807 !has_capability('moodle/course:viewhiddensections', $coursecontext, $userid)) {
1808 $this->_uservisible
= false;
1813 * Prepares section data for inclusion in sectioncache cache, removing items
1814 * that are set to defaults, and adding availability data if required.
1816 * Called by build_section_cache in course_modinfo only; do not use otherwise.
1817 * @param object $section Raw section data object
1819 public static function convert_for_section_cache($section) {
1822 // Course id stored in course table
1823 unset($section->course
);
1824 // Section number stored in array key
1825 unset($section->section
);
1826 // Sequence stored implicity in modinfo $sections array
1827 unset($section->sequence
);
1829 // Add availability data if turned on
1830 if ($CFG->enableavailability
) {
1831 require_once($CFG->dirroot
. '/lib/conditionlib.php');
1832 condition_info_section
::fill_availability_conditions($section);
1833 if (count($section->conditionscompletion
) == 0) {
1834 unset($section->conditionscompletion
);
1836 if (count($section->conditionsgrade
) == 0) {
1837 unset($section->conditionsgrade
);
1841 // Remove default data
1842 foreach (self
::$sectioncachedefaults as $field => $value) {
1843 // Exact compare as strings to avoid problems if some strings are set
1845 if (isset($section->{$field}) && $section->{$field} === $value) {
1846 unset($section->{$field});