MDL-33399 files: Fixed up handling of empty sort in File API methods.
[moodle.git] / lib / modinfolib.php
blobbcbb7ecff22abcf426d4d1e044e3f82054df56e7
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * modinfolib.php - Functions/classes relating to cached information about module instances on
19 * a course.
20 * @package core
21 * @subpackage lib
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 * @author sam marshall
27 // Maximum number of modinfo items to keep in memory cache. Do not increase this to a large
28 // number because:
29 // a) modinfo can be big (megabyte range) for some courses
30 // b) performance of cache will deteriorate if there are very many items in it
31 if (!defined('MAX_MODINFO_CACHE_SIZE')) {
32 define('MAX_MODINFO_CACHE_SIZE', 10);
36 /**
37 * Information about a course that is cached in the course table 'modinfo' field (and then in
38 * memory) in order to reduce the need for other database queries.
40 * This includes information about the course-modules and the sections on the course. It can also
41 * include dynamic data that has been updated for the current user.
43 class course_modinfo extends stdClass {
44 // For convenience we store the course object here as it is needed in other parts of code
45 private $course;
46 // Array of section data from cache
47 private $sectioninfo;
49 // Existing data fields
50 ///////////////////////
52 // These are public for backward compatibility. Note: it is not possible to retain BC
53 // using PHP magic get methods because behaviour is different with regard to empty().
55 /**
56 * Course ID
57 * @var int
58 * @deprecated For new code, use get_course_id instead.
60 public $courseid;
62 /**
63 * User ID
64 * @var int
65 * @deprecated For new code, use get_user_id instead.
67 public $userid;
69 /**
70 * Array from int (section num, e.g. 0) => array of int (course-module id); this list only
71 * includes sections that actually contain at least one course-module
72 * @var array
73 * @deprecated For new code, use get_sections instead
75 public $sections;
77 /**
78 * Array from int (cm id) => cm_info object
79 * @var array
80 * @deprecated For new code, use get_cms or get_cm instead.
82 public $cms;
84 /**
85 * Array from string (modname) => int (instance id) => cm_info object
86 * @var array
87 * @deprecated For new code, use get_instances or get_instances_of instead.
89 public $instances;
91 /**
92 * Groups that the current user belongs to. This value is usually not available (set to null)
93 * unless the course has activities set to groupmembersonly. When set, it is an array of
94 * grouping id => array of group id => group id. Includes grouping id 0 for 'all groups'.
95 * @var array
96 * @deprecated Don't use this! For new code, use get_groups.
98 public $groups;
100 // Get methods for data
101 ///////////////////////
104 * @return object Moodle course object that was used to construct this data
106 public function get_course() {
107 return $this->course;
111 * @return int Course ID
113 public function get_course_id() {
114 return $this->courseid;
118 * @return int User ID
120 public function get_user_id() {
121 return $this->userid;
125 * @return array Array from section number (e.g. 0) to array of course-module IDs in that
126 * section; this only includes sections that contain at least one course-module
128 public function get_sections() {
129 return $this->sections;
133 * @return array Array from course-module instance to cm_info object within this course, in
134 * order of appearance
136 public function get_cms() {
137 return $this->cms;
141 * Obtains a single course-module object (for a course-module that is on this course).
142 * @param int $cmid Course-module ID
143 * @return cm_info Information about that course-module
144 * @throws moodle_exception If the course-module does not exist
146 public function get_cm($cmid) {
147 if (empty($this->cms[$cmid])) {
148 throw new moodle_exception('invalidcoursemodule', 'error');
150 return $this->cms[$cmid];
154 * Obtains all module instances on this course.
155 * @return array Array from module name => array from instance id => cm_info
157 public function get_instances() {
158 return $this->instances;
162 * Obtains all instances of a particular module on this course.
163 * @param $modname Name of module (not full frankenstyle) e.g. 'label'
164 * @return array Array from instance id => cm_info for modules on this course; empty if none
166 public function get_instances_of($modname) {
167 if (empty($this->instances[$modname])) {
168 return array();
170 return $this->instances[$modname];
174 * Returns groups that the current user belongs to on the course. Note: If not already
175 * available, this may make a database query.
176 * @param int $groupingid Grouping ID or 0 (default) for all groups
177 * @return array Array of int (group id) => int (same group id again); empty array if none
179 public function get_groups($groupingid=0) {
180 if (is_null($this->groups)) {
181 // NOTE: Performance could be improved here. The system caches user groups
182 // in $USER->groupmember[$courseid] => array of groupid=>groupid. Unfortunately this
183 // structure does not include grouping information. It probably could be changed to
184 // do so, without a significant performance hit on login, thus saving this one query
185 // each request.
186 $this->groups = groups_get_user_groups($this->courseid, $this->userid);
188 if (!isset($this->groups[$groupingid])) {
189 return array();
191 return $this->groups[$groupingid];
195 * Gets all sections as array from section number => data about section.
196 * @return array Array of section_info objects organised by section number
198 public function get_section_info_all() {
199 return $this->sectioninfo;
203 * Gets data about specific numbered section.
204 * @param int $sectionnumber Number (not id) of section
205 * @return section_info Information for numbered section
207 public function get_section_info($sectionnumber) {
208 return $this->sectioninfo[$sectionnumber];
212 * Constructs based on course.
213 * Note: This constructor should not usually be called directly.
214 * Use get_fast_modinfo($course) instead as this maintains a cache.
215 * @param object $course Moodle course object, which may include modinfo
216 * @param int $userid User ID
218 public function __construct($course, $userid) {
219 global $CFG, $DB;
221 // Check modinfo field is set. If not, build and load it.
222 if (empty($course->modinfo) || empty($course->sectioncache)) {
223 rebuild_course_cache($course->id);
224 $course = $DB->get_record('course', array('id'=>$course->id), '*', MUST_EXIST);
227 // Set initial values
228 $this->courseid = $course->id;
229 $this->userid = $userid;
230 $this->sections = array();
231 $this->cms = array();
232 $this->instances = array();
233 $this->groups = null;
234 $this->course = $course;
236 // Load modinfo field into memory as PHP object and check it's valid
237 $info = unserialize($course->modinfo);
238 if (!is_array($info)) {
239 // hmm, something is wrong - lets try to fix it
240 rebuild_course_cache($course->id);
241 $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
242 $info = unserialize($course->modinfo);
243 if (!is_array($info)) {
244 // If it still fails, abort
245 debugging('Problem with "modinfo" data for this course');
246 return;
250 // Load sectioncache field into memory as PHP object and check it's valid
251 $sectioncache = unserialize($course->sectioncache);
252 if (!is_array($sectioncache) || empty($sectioncache)) {
253 // hmm, something is wrong - let's fix it
254 rebuild_course_cache($course->id);
255 $course->sectioncache = $DB->get_field('course', 'sectioncache', array('id'=>$course->id));
256 $sectioncache = unserialize($course->sectioncache);
257 if (!is_array($sectioncache)) {
258 // If it still fails, abort
259 debugging('Problem with "sectioncache" data for this course');
260 return;
264 // If we haven't already preloaded contexts for the course, do it now
265 preload_course_contexts($course->id);
267 // Loop through each piece of module data, constructing it
268 $modexists = array();
269 foreach ($info as $mod) {
270 if (empty($mod->name)) {
271 // something is wrong here
272 continue;
275 // Skip modules which don't exist
276 if (empty($modexists[$mod->mod])) {
277 if (!file_exists("$CFG->dirroot/mod/$mod->mod/lib.php")) {
278 continue;
280 $modexists[$mod->mod] = true;
283 // Construct info for this module
284 $cm = new cm_info($this, $course, $mod, $info);
286 // Store module in instances and cms array
287 if (!isset($this->instances[$cm->modname])) {
288 $this->instances[$cm->modname] = array();
290 $this->instances[$cm->modname][$cm->instance] = $cm;
291 $this->cms[$cm->id] = $cm;
293 // Reconstruct sections. This works because modules are stored in order
294 if (!isset($this->sections[$cm->sectionnum])) {
295 $this->sections[$cm->sectionnum] = array();
297 $this->sections[$cm->sectionnum][] = $cm->id;
300 // Expand section objects
301 $this->sectioninfo = array();
302 foreach ($sectioncache as $number => $data) {
303 // Calculate sequence
304 if (isset($this->sections[$number])) {
305 $sequence = implode(',', $this->sections[$number]);
306 } else {
307 $sequence = '';
309 // Expand
310 $this->sectioninfo[$number] = new section_info($data, $number, $course->id, $sequence,
311 $this, $userid);
314 // We need at least 'dynamic' data from each course-module (this is basically the remaining
315 // data which was always present in previous version of get_fast_modinfo, so it's required
316 // for BC). Creating it in a second pass is necessary because obtain_dynamic_data sometimes
317 // needs to be able to refer to a 'complete' (with basic data) modinfo.
318 foreach ($this->cms as $cm) {
319 $cm->obtain_dynamic_data();
324 * Builds a list of information about sections on a course to be stored in
325 * the course cache. (Does not include information that is already cached
326 * in some other way.)
328 * Used internally by rebuild_course_cache function; do not use otherwise.
329 * @param int $courseid Course ID
330 * @return array Information about sections, indexed by section number (not id)
332 public static function build_section_cache($courseid) {
333 global $DB;
335 // Get section data
336 $sections = $DB->get_records('course_sections', array('course' => $courseid), 'section',
337 'section, id, course, name, summary, summaryformat, sequence, visible, ' .
338 'availablefrom, availableuntil, showavailability, groupingid');
339 $compressedsections = array();
341 // Remove unnecessary data and add availability
342 foreach ($sections as $number => $section) {
343 // Clone just in case it is reused elsewhere (get_all_sections cache)
344 $compressedsections[$number] = clone($section);
345 section_info::convert_for_section_cache($compressedsections[$number]);
348 return $compressedsections;
354 * Data about a single module on a course. This contains most of the fields in the course_modules
355 * table, plus additional data when required.
357 * This object has many public fields; code should treat all these fields as read-only and set
358 * data only using the supplied set functions. Setting the fields directly is not supported
359 * and may cause problems later.
361 class cm_info extends stdClass {
363 * State: Only basic data from modinfo cache is available.
365 const STATE_BASIC = 0;
368 * State: Dynamic data is available too.
370 const STATE_DYNAMIC = 1;
373 * State: View data (for course page) is available.
375 const STATE_VIEW = 2;
378 * Parent object
379 * @var course_modinfo
381 private $modinfo;
384 * Level of information stored inside this object (STATE_xx constant)
385 * @var int
387 private $state;
389 // Existing data fields
390 ///////////////////////
393 * Course-module ID - from course_modules table
394 * @var int
396 public $id;
399 * Module instance (ID within module table) - from course_modules table
400 * @var int
402 public $instance;
405 * Course ID - from course_modules table
406 * @var int
408 public $course;
411 * 'ID number' from course-modules table (arbitrary text set by user) - from
412 * course_modules table
413 * @var string
415 public $idnumber;
418 * Time that this course-module was added (unix time) - from course_modules table
419 * @var int
421 public $added;
424 * This variable is not used and is included here only so it can be documented.
425 * Once the database entry is removed from course_modules, it should be deleted
426 * here too.
427 * @var int
428 * @deprecated Do not use this variable
430 public $score;
433 * Visible setting (0 or 1; if this is 0, students cannot see/access the activity) - from
434 * course_modules table
435 * @var int
437 public $visible;
440 * Old visible setting (if the entire section is hidden, the previous value for
441 * visible is stored in this field) - from course_modules table
442 * @var int
444 public $visibleold;
447 * Group mode (one of the constants NONE, SEPARATEGROUPS, or VISIBLEGROUPS) - from
448 * course_modules table
449 * @var int
451 public $groupmode;
454 * Grouping ID (0 = all groupings)
455 * @var int
457 public $groupingid;
460 * Group members only (if set to 1, only members of a suitable group see this link on the
461 * course page; 0 = everyone sees it even if they don't belong to a suitable group) - from
462 * course_modules table
463 * @var int
465 public $groupmembersonly;
468 * Indent level on course page (0 = no indent) - from course_modules table
469 * @var int
471 public $indent;
474 * Activity completion setting for this activity, COMPLETION_TRACKING_xx constant - from
475 * course_modules table
476 * @var int
478 public $completion;
481 * Set to the item number (usually 0) if completion depends on a particular
482 * grade of this activity, or null if completion does not depend on a grade - from
483 * course_modules table
484 * @var mixed
486 public $completiongradeitemnumber;
489 * 1 if 'on view' completion is enabled, 0 otherwise - from course_modules table
490 * @var int
492 public $completionview;
495 * Set to a unix time if completion of this activity is expected at a
496 * particular time, 0 if no time set - from course_modules table
497 * @var int
499 public $completionexpected;
502 * Available date for this activity (0 if not set, or set to seconds since epoch; before this
503 * date, activity does not display to students) - from course_modules table
504 * @var int
506 public $availablefrom;
509 * Available until date for this activity (0 if not set, or set to seconds since epoch; from
510 * this date, activity does not display to students) - from course_modules table
511 * @var int
513 public $availableuntil;
516 * When activity is unavailable, this field controls whether it is shown to students (0 =
517 * hide completely, 1 = show greyed out with information about when it will be available) -
518 * from course_modules table
519 * @var int
521 public $showavailability;
524 * Controls whether the description of the activity displays on the course main page (in
525 * addition to anywhere it might display within the activity itself). 0 = do not show
526 * on main page, 1 = show on main page.
527 * @var int
529 public $showdescription;
532 * Extra HTML that is put in an unhelpful part of the HTML when displaying this module in
533 * course page - from cached data in modinfo field
534 * @deprecated This is crazy, don't use it. Replaced by ->extraclasses and ->onclick
535 * @var string
537 public $extra;
540 * Name of icon to use - from cached data in modinfo field
541 * @var string
543 public $icon;
546 * Component that contains icon - from cached data in modinfo field
547 * @var string
549 public $iconcomponent;
552 * Name of module e.g. 'forum' (this is the same name as the module's main database
553 * table) - from cached data in modinfo field
554 * @var string
556 public $modname;
559 * ID of module - from course_modules table
560 * @var int
562 public $module;
565 * Name of module instance for display on page e.g. 'General discussion forum' - from cached
566 * data in modinfo field
567 * @var string
569 public $name;
572 * Section number that this course-module is in (section 0 = above the calendar, section 1
573 * = week/topic 1, etc) - from cached data in modinfo field
574 * @var string
576 public $sectionnum;
579 * Section id - from course_modules table
580 * @var int
582 public $section;
585 * Availability conditions for this course-module based on the completion of other
586 * course-modules (array from other course-module id to required completion state for that
587 * module) - from cached data in modinfo field
588 * @var array
590 public $conditionscompletion;
593 * Availability conditions for this course-module based on course grades (array from
594 * grade item id to object with ->min, ->max fields) - from cached data in modinfo field
595 * @var array
597 public $conditionsgrade;
600 * Plural name of module type, e.g. 'Forums' - from lang file
601 * @deprecated Do not use this value (you can obtain it by calling get_string instead); it
602 * will be removed in a future version (see later TODO in this file)
603 * @var string
605 public $modplural;
608 * True if this course-module is available to students i.e. if all availability conditions
609 * are met - obtained dynamically
610 * @var bool
612 public $available;
615 * If course-module is not available to students, this string gives information about
616 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
617 * January 2010') for display on main page - obtained dynamically
618 * @var string
620 public $availableinfo;
623 * True if this course-module is available to the CURRENT user (for example, if current user
624 * has viewhiddenactivities capability, they can access the course-module even if it is not
625 * visible or not available, so this would be true in that case)
626 * @var bool
628 public $uservisible;
631 * Module context - hacky shortcut
632 * @deprecated
633 * @var stdClass
635 public $context;
638 // New data available only via functions
639 ////////////////////////////////////////
642 * @var moodle_url
644 private $url;
647 * @var string
649 private $content;
652 * @var string
654 private $extraclasses;
657 * @var moodle_url full external url pointing to icon image for activity
659 private $iconurl;
662 * @var string
664 private $onclick;
667 * @var mixed
669 private $customdata;
672 * @var string
674 private $afterlink;
677 * @var string
679 private $afterediticons;
682 * @return bool True if this module has a 'view' page that should be linked to in navigation
683 * etc (note: modules may still have a view.php file, but return false if this is not
684 * intended to be linked to from 'normal' parts of the interface; this is what label does).
686 public function has_view() {
687 return !is_null($this->url);
691 * @return moodle_url URL to link to for this module, or null if it doesn't have a view page
693 public function get_url() {
694 return $this->url;
698 * Obtains content to display on main (view) page.
699 * Note: Will collect view data, if not already obtained.
700 * @return string Content to display on main page below link, or empty string if none
702 public function get_content() {
703 $this->obtain_view_data();
704 return $this->content;
708 * Note: Will collect view data, if not already obtained.
709 * @return string Extra CSS classes to add to html output for this activity on main page
711 public function get_extra_classes() {
712 $this->obtain_view_data();
713 return $this->extraclasses;
717 * @return string Content of HTML on-click attribute. This string will be used literally
718 * as a string so should be pre-escaped.
720 public function get_on_click() {
721 // Does not need view data; may be used by navigation
722 return $this->onclick;
725 * @return mixed Optional custom data stored in modinfo cache for this activity, or null if none
727 public function get_custom_data() {
728 return $this->customdata;
732 * Note: Will collect view data, if not already obtained.
733 * @return string Extra HTML code to display after link
735 public function get_after_link() {
736 $this->obtain_view_data();
737 return $this->afterlink;
741 * Note: Will collect view data, if not already obtained.
742 * @return string Extra HTML code to display after editing icons (e.g. more icons)
744 public function get_after_edit_icons() {
745 $this->obtain_view_data();
746 return $this->afterediticons;
750 * @param moodle_core_renderer $output Output render to use, or null for default (global)
751 * @return moodle_url Icon URL for a suitable icon to put beside this cm
753 public function get_icon_url($output = null) {
754 global $OUTPUT;
755 if (!$output) {
756 $output = $OUTPUT;
758 // Support modules setting their own, external, icon image
759 if (!empty($this->iconurl)) {
760 $icon = $this->iconurl;
762 // Fallback to normal local icon + component procesing
763 } else if (!empty($this->icon)) {
764 if (substr($this->icon, 0, 4) === 'mod/') {
765 list($modname, $iconname) = explode('/', substr($this->icon, 4), 2);
766 $icon = $output->pix_url($iconname, $modname);
767 } else {
768 if (!empty($this->iconcomponent)) {
769 // Icon has specified component
770 $icon = $output->pix_url($this->icon, $this->iconcomponent);
771 } else {
772 // Icon does not have specified component, use default
773 $icon = $output->pix_url($this->icon);
776 } else {
777 $icon = $output->pix_url('icon', $this->modname);
779 return $icon;
783 * @return course_modinfo Modinfo object that this came from
785 public function get_modinfo() {
786 return $this->modinfo;
790 * @return object Moodle course object that was used to construct this data
792 public function get_course() {
793 return $this->modinfo->get_course();
796 // Set functions
797 ////////////////
800 * Sets content to display on course view page below link (if present).
801 * @param string $content New content as HTML string (empty string if none)
802 * @return void
804 public function set_content($content) {
805 $this->content = $content;
809 * Sets extra classes to include in CSS.
810 * @param string $extraclasses Extra classes (empty string if none)
811 * @return void
813 public function set_extra_classes($extraclasses) {
814 $this->extraclasses = $extraclasses;
818 * Sets the external full url that points to the icon being used
819 * by the activity. Useful for external-tool modules (lti...)
820 * If set, takes precedence over $icon and $iconcomponent
822 * @param moodle_url $iconurl full external url pointing to icon image for activity
823 * @return void
825 public function set_icon_url(moodle_url $iconurl) {
826 $this->iconurl = $iconurl;
830 * Sets value of on-click attribute for JavaScript.
831 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
832 * @param string $onclick New onclick attribute which should be HTML-escaped
833 * (empty string if none)
834 * @return void
836 public function set_on_click($onclick) {
837 $this->check_not_view_only();
838 $this->onclick = $onclick;
842 * Sets HTML that displays after link on course view page.
843 * @param string $afterlink HTML string (empty string if none)
844 * @return void
846 public function set_after_link($afterlink) {
847 $this->afterlink = $afterlink;
851 * Sets HTML that displays after edit icons on course view page.
852 * @param string $afterediticons HTML string (empty string if none)
853 * @return void
855 public function set_after_edit_icons($afterediticons) {
856 $this->afterediticons = $afterediticons;
860 * Changes the name (text of link) for this module instance.
861 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
862 * @param string $name Name of activity / link text
863 * @return void
865 public function set_name($name) {
866 $this->update_user_visible();
867 $this->name = $name;
871 * Turns off the view link for this module instance.
872 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
873 * @return void
875 public function set_no_view_link() {
876 $this->check_not_view_only();
877 $this->url = null;
881 * Sets the 'uservisible' flag. This can be used (by setting false) to prevent access and
882 * display of this module link for the current user.
883 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
884 * @param bool $uservisible
885 * @return void
887 public function set_user_visible($uservisible) {
888 $this->check_not_view_only();
889 $this->uservisible = $uservisible;
893 * Sets the 'available' flag and related details. This flag is normally used to make
894 * course modules unavailable until a certain date or condition is met. (When a course
895 * module is unavailable, it is still visible to users who have viewhiddenactivities
896 * permission.)
898 * When this is function is called, user-visible status is recalculated automatically.
900 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
901 * @param bool $available False if this item is not 'available'
902 * @param int $showavailability 0 = do not show this item at all if it's not available,
903 * 1 = show this item greyed out with the following message
904 * @param string $availableinfo Information about why this is not available which displays
905 * to those who have viewhiddenactivities, and to everyone if showavailability is set;
906 * note that this function replaces the existing data (if any)
907 * @return void
909 public function set_available($available, $showavailability=0, $availableinfo='') {
910 $this->check_not_view_only();
911 $this->available = $available;
912 $this->showavailability = $showavailability;
913 $this->availableinfo = $availableinfo;
914 $this->update_user_visible();
918 * Some set functions can only be called from _cm_info_dynamic and not _cm_info_view.
919 * This is because they may affect parts of this object which are used on pages other
920 * than the view page (e.g. in the navigation block, or when checking access on
921 * module pages).
922 * @return void
924 private function check_not_view_only() {
925 if ($this->state >= self::STATE_DYNAMIC) {
926 throw new coding_exception('Cannot set this data from _cm_info_view because it may ' .
927 'affect other pages as well as view');
932 * Constructor should not be called directly; use get_fast_modinfo.
933 * @param course_modinfo $modinfo Parent object
934 * @param object $course Course row
935 * @param object $mod Module object from the modinfo field of course table
936 * @param object $info Entire object from modinfo field of course table
938 public function __construct(course_modinfo $modinfo, $course, $mod, $info) {
939 global $CFG;
940 $this->modinfo = $modinfo;
942 $this->id = $mod->cm;
943 $this->instance = $mod->id;
944 $this->course = $course->id;
945 $this->modname = $mod->mod;
946 $this->idnumber = isset($mod->idnumber) ? $mod->idnumber : '';
947 $this->name = $mod->name;
948 $this->visible = $mod->visible;
949 $this->sectionnum = $mod->section; // Note weirdness with name here
950 $this->groupmode = isset($mod->groupmode) ? $mod->groupmode : 0;
951 $this->groupingid = isset($mod->groupingid) ? $mod->groupingid : 0;
952 $this->groupmembersonly = isset($mod->groupmembersonly) ? $mod->groupmembersonly : 0;
953 $this->indent = isset($mod->indent) ? $mod->indent : 0;
954 $this->extra = isset($mod->extra) ? $mod->extra : '';
955 $this->extraclasses = isset($mod->extraclasses) ? $mod->extraclasses : '';
956 $this->iconurl = isset($mod->iconurl) ? $mod->iconurl : '';
957 $this->onclick = isset($mod->onclick) ? $mod->onclick : '';
958 $this->content = isset($mod->content) ? $mod->content : '';
959 $this->icon = isset($mod->icon) ? $mod->icon : '';
960 $this->iconcomponent = isset($mod->iconcomponent) ? $mod->iconcomponent : '';
961 $this->customdata = isset($mod->customdata) ? $mod->customdata : '';
962 $this->context = get_context_instance(CONTEXT_MODULE, $mod->cm);
963 $this->showdescription = isset($mod->showdescription) ? $mod->showdescription : 0;
964 $this->state = self::STATE_BASIC;
966 // This special case handles old label data. Labels used to use the 'name' field for
967 // content
968 if ($this->modname === 'label' && $this->content === '') {
969 $this->content = $this->extra;
970 $this->extra = '';
973 // Note: These fields from $cm were not present in cm_info in Moodle
974 // 2.0.2 and prior. They may not be available if course cache hasn't
975 // been rebuilt since then.
976 $this->section = isset($mod->sectionid) ? $mod->sectionid : 0;
977 $this->module = isset($mod->module) ? $mod->module : 0;
978 $this->added = isset($mod->added) ? $mod->added : 0;
979 $this->score = isset($mod->score) ? $mod->score : 0;
980 $this->visibleold = isset($mod->visibleold) ? $mod->visibleold : 0;
982 // Note: it saves effort and database space to always include the
983 // availability and completion fields, even if availability or completion
984 // are actually disabled
985 $this->completion = isset($mod->completion) ? $mod->completion : 0;
986 $this->completiongradeitemnumber = isset($mod->completiongradeitemnumber)
987 ? $mod->completiongradeitemnumber : null;
988 $this->completionview = isset($mod->completionview)
989 ? $mod->completionview : 0;
990 $this->completionexpected = isset($mod->completionexpected)
991 ? $mod->completionexpected : 0;
992 $this->showavailability = isset($mod->showavailability) ? $mod->showavailability : 0;
993 $this->availablefrom = isset($mod->availablefrom) ? $mod->availablefrom : 0;
994 $this->availableuntil = isset($mod->availableuntil) ? $mod->availableuntil : 0;
995 $this->conditionscompletion = isset($mod->conditionscompletion)
996 ? $mod->conditionscompletion : array();
997 $this->conditionsgrade = isset($mod->conditionsgrade)
998 ? $mod->conditionsgrade : array();
1000 // Get module plural name.
1001 // TODO This was a very old performance hack and should now be removed as the information
1002 // certainly doesn't belong in modinfo. On a 'normal' page this is only used in the
1003 // activity_modules block, so if it needs caching, it should be cached there.
1004 static $modplurals;
1005 if (!isset($modplurals[$this->modname])) {
1006 $modplurals[$this->modname] = get_string('modulenameplural', $this->modname);
1008 $this->modplural = $modplurals[$this->modname];
1010 static $modviews;
1011 if (!isset($modviews[$this->modname])) {
1012 $modviews[$this->modname] = !plugin_supports('mod', $this->modname,
1013 FEATURE_NO_VIEW_LINK);
1015 $this->url = $modviews[$this->modname]
1016 ? new moodle_url('/mod/' . $this->modname . '/view.php', array('id'=>$this->id))
1017 : null;
1021 * If dynamic data for this course-module is not yet available, gets it.
1023 * This function is automatically called when constructing course_modinfo, so users don't
1024 * need to call it.
1026 * Dynamic data is data which does not come directly from the cache but is calculated at
1027 * runtime based on the current user. Primarily this concerns whether the user can access
1028 * the module or not.
1030 * As part of this function, the module's _cm_info_dynamic function from its lib.php will
1031 * be called (if it exists).
1032 * @return void
1034 public function obtain_dynamic_data() {
1035 global $CFG;
1036 if ($this->state >= self::STATE_DYNAMIC) {
1037 return;
1039 $userid = $this->modinfo->get_user_id();
1041 if (!empty($CFG->enableavailability)) {
1042 // Get availability information
1043 $ci = new condition_info($this);
1044 // Note that the modinfo currently available only includes minimal details (basic data)
1045 // so passing it to this function is a bit dangerous as it would cause infinite
1046 // recursion if it tried to get dynamic data, however we know that this function only
1047 // uses basic data.
1048 $this->available = $ci->is_available($this->availableinfo, true,
1049 $userid, $this->modinfo);
1051 // Check parent section
1052 $parentsection = $this->modinfo->get_section_info($this->sectionnum);
1053 if (!$parentsection->available) {
1054 // Do not store info from section here, as that is already
1055 // presented from the section (if appropriate) - just change
1056 // the flag
1057 $this->available = false;
1059 } else {
1060 $this->available = true;
1063 // Update visible state for current user
1064 $this->update_user_visible();
1066 // Let module make dynamic changes at this point
1067 $this->call_mod_function('cm_info_dynamic');
1068 $this->state = self::STATE_DYNAMIC;
1072 * Works out whether activity is visible *for current user* - if this is false, they
1073 * aren't allowed to access it.
1074 * @return void
1076 private function update_user_visible() {
1077 global $CFG;
1078 $modcontext = get_context_instance(CONTEXT_MODULE, $this->id);
1079 $userid = $this->modinfo->get_user_id();
1080 $this->uservisible = true;
1081 if ((!$this->visible or !$this->available) and
1082 !has_capability('moodle/course:viewhiddenactivities', $modcontext, $userid)) {
1083 // If the activity is hidden or unavailable, and you don't have viewhiddenactivities,
1084 // set it so that user can't see or access it
1085 $this->uservisible = false;
1086 } else if (!empty($CFG->enablegroupmembersonly) and !empty($this->groupmembersonly)
1087 and !has_capability('moodle/site:accessallgroups', $modcontext, $userid)) {
1088 // If the activity has 'group members only' and you don't have accessallgroups...
1089 $groups = $this->modinfo->get_groups($this->groupingid);
1090 if (empty($groups)) {
1091 // ...and you don't belong to a group, then set it so you can't see/access it
1092 $this->uservisible = false;
1098 * Calls a module function (if exists), passing in one parameter: this object.
1099 * @param string $type Name of function e.g. if this is 'grooblezorb' and the modname is
1100 * 'forum' then it will try to call 'mod_forum_grooblezorb' or 'forum_grooblezorb'
1101 * @return void
1103 private function call_mod_function($type) {
1104 global $CFG;
1105 $libfile = $CFG->dirroot . '/mod/' . $this->modname . '/lib.php';
1106 if (file_exists($libfile)) {
1107 include_once($libfile);
1108 $function = 'mod_' . $this->modname . '_' . $type;
1109 if (function_exists($function)) {
1110 $function($this);
1111 } else {
1112 $function = $this->modname . '_' . $type;
1113 if (function_exists($function)) {
1114 $function($this);
1121 * If view data for this course-module is not yet available, obtains it.
1123 * This function is automatically called if any of the functions (marked) which require
1124 * view data are called.
1126 * View data is data which is needed only for displaying the course main page (& any similar
1127 * functionality on other pages) but is not needed in general. Obtaining view data may have
1128 * a performance cost.
1130 * As part of this function, the module's _cm_info_view function from its lib.php will
1131 * be called (if it exists).
1132 * @return void
1134 private function obtain_view_data() {
1135 if ($this->state >= self::STATE_VIEW) {
1136 return;
1139 // Let module make changes at this point
1140 $this->call_mod_function('cm_info_view');
1141 $this->state = self::STATE_VIEW;
1147 * Returns reference to full info about modules in course (including visibility).
1148 * Cached and as fast as possible (0 or 1 db query).
1150 * @global object
1151 * @global object
1152 * @global moodle_database
1153 * @uses MAX_MODINFO_CACHE_SIZE
1154 * @param mixed $course object or 'reset' string to reset caches, modinfo may be updated in db
1155 * @param int $userid Defaults to current user id
1156 * @return course_modinfo Module information for course, or null if resetting
1158 function get_fast_modinfo(&$course, $userid=0) {
1159 global $CFG, $USER, $DB;
1160 require_once($CFG->dirroot.'/course/lib.php');
1162 if (!empty($CFG->enableavailability)) {
1163 require_once($CFG->libdir.'/conditionlib.php');
1166 static $cache = array();
1168 if ($course === 'reset') {
1169 $cache = array();
1170 return null;
1173 if (empty($userid)) {
1174 $userid = $USER->id;
1177 if (array_key_exists($course->id, $cache) and $cache[$course->id]->userid == $userid) {
1178 return $cache[$course->id];
1181 if (!property_exists($course, 'modinfo')) {
1182 debugging('Coding problem - missing course modinfo property in get_fast_modinfo() call');
1185 unset($cache[$course->id]); // prevent potential reference problems when switching users
1187 $cache[$course->id] = new course_modinfo($course, $userid);
1189 // Ensure cache does not use too much RAM
1190 if (count($cache) > MAX_MODINFO_CACHE_SIZE) {
1191 reset($cache);
1192 $key = key($cache);
1193 unset($cache[$key]->instances);
1194 unset($cache[$key]->cms);
1195 unset($cache[$key]);
1198 return $cache[$course->id];
1202 * Rebuilds the cached list of course activities stored in the database
1203 * @param int $courseid - id of course to rebuild, empty means all
1204 * @param boolean $clearonly - only clear the modinfo fields, gets rebuild automatically on the fly
1206 function rebuild_course_cache($courseid=0, $clearonly=false) {
1207 global $COURSE, $DB, $CFG;
1209 // Destroy navigation caches
1210 navigation_cache::destroy_volatile_caches();
1212 if ($clearonly) {
1213 if (empty($courseid)) {
1214 $DB->set_field('course', 'modinfo', null);
1215 $DB->set_field('course', 'sectioncache', null);
1216 } else {
1217 // Clear both fields in one update
1218 $resetobj = (object)array('id' => $courseid, 'modinfo' => null, 'sectioncache' => null);
1219 $DB->update_record('course', $resetobj);
1221 // update cached global COURSE too ;-)
1222 if ($courseid == $COURSE->id or empty($courseid)) {
1223 $COURSE->modinfo = null;
1224 $COURSE->sectioncache = null;
1226 // reset the fast modinfo cache
1227 $reset = 'reset';
1228 get_fast_modinfo($reset);
1229 return;
1232 require_once("$CFG->dirroot/course/lib.php");
1234 if ($courseid) {
1235 $select = array('id'=>$courseid);
1236 } else {
1237 $select = array();
1238 @set_time_limit(0); // this could take a while! MDL-10954
1241 $rs = $DB->get_recordset("course", $select,'','id,fullname');
1242 foreach ($rs as $course) {
1243 $modinfo = serialize(get_array_of_activities($course->id));
1244 $sectioncache = serialize(course_modinfo::build_section_cache($course->id));
1245 $updateobj = (object)array('id' => $course->id,
1246 'modinfo' => $modinfo, 'sectioncache' => $sectioncache);
1247 $DB->update_record("course", $updateobj);
1248 // update cached global COURSE too ;-)
1249 if ($course->id == $COURSE->id) {
1250 $COURSE->modinfo = $modinfo;
1251 $COURSE->sectioncache = $sectioncache;
1254 $rs->close();
1255 // reset the fast modinfo cache
1256 $reset = 'reset';
1257 get_fast_modinfo($reset);
1262 * Class that is the return value for the _get_coursemodule_info module API function.
1264 * Note: For backward compatibility, you can also return a stdclass object from that function.
1265 * The difference is that the stdclass object may contain an 'extra' field (deprecated because
1266 * it was crazy, except for label which uses it differently). The stdclass object may not contain
1267 * the new fields defined here (content, extraclasses, customdata).
1269 class cached_cm_info {
1271 * Name (text of link) for this activity; Leave unset to accept default name
1272 * @var string
1274 public $name;
1277 * Name of icon for this activity. Normally, this should be used together with $iconcomponent
1278 * to define the icon, as per pix_url function.
1279 * For backward compatibility, if this value is of the form 'mod/forum/icon' then an icon
1280 * within that module will be used.
1281 * @see cm_info::get_icon_url()
1282 * @see renderer_base::pix_url()
1283 * @var string
1285 public $icon;
1288 * Component for icon for this activity, as per pix_url; leave blank to use default 'moodle'
1289 * component
1290 * @see renderer_base::pix_url()
1291 * @var string
1293 public $iconcomponent;
1296 * HTML content to be displayed on the main page below the link (if any) for this course-module
1297 * @var string
1299 public $content;
1302 * Custom data to be stored in modinfo for this activity; useful if there are cases when
1303 * internal information for this activity type needs to be accessible from elsewhere on the
1304 * course without making database queries. May be of any type but should be short.
1305 * @var mixed
1307 public $customdata;
1310 * Extra CSS class or classes to be added when this activity is displayed on the main page;
1311 * space-separated string
1312 * @var string
1314 public $extraclasses;
1317 * External URL image to be used by activity as icon, useful for some external-tool modules
1318 * like lti. If set, takes precedence over $icon and $iconcomponent
1319 * @var $moodle_url
1321 public $iconurl;
1324 * Content of onclick JavaScript; escaped HTML to be inserted as attribute value
1325 * @var string
1327 public $onclick;
1332 * Data about a single section on a course. This contains the fields from the
1333 * course_sections table, plus additional data when required.
1335 class section_info extends stdClass {
1337 * Section ID - from course_sections table
1338 * @var int
1340 public $id;
1343 * Course ID - from course_sections table
1344 * @var int
1346 public $course;
1349 * Section number - from course_sections table
1350 * @var int
1352 public $section;
1355 * Section name if specified - from course_sections table
1356 * @var string
1358 public $name;
1361 * Section visibility (1 = visible) - from course_sections table
1362 * @var int
1364 public $visible;
1367 * Section summary text if specified - from course_sections table
1368 * @var string
1370 public $summary;
1373 * Section summary text format (FORMAT_xx constant) - from course_sections table
1374 * @var int
1376 public $summaryformat;
1379 * When section is unavailable, this field controls whether it is shown to students (0 =
1380 * hide completely, 1 = show greyed out with information about when it will be available) -
1381 * from course_sections table
1382 * @var int
1384 public $showavailability;
1387 * Available date for this section (0 if not set, or set to seconds since epoch; before this
1388 * date, section does not display to students) - from course_sections table
1389 * @var int
1391 public $availablefrom;
1394 * Available until date for this section (0 if not set, or set to seconds since epoch; from
1395 * this date, section does not display to students) - from course_sections table
1396 * @var int
1398 public $availableuntil;
1401 * If section is restricted to users of a particular grouping, this is its id
1402 * (0 if not set) - from course_sections table
1403 * @var int
1405 public $groupingid;
1408 * Availability conditions for this section based on the completion of
1409 * course-modules (array from course-module id to required completion state
1410 * for that module) - from cached data in sectioncache field
1411 * @var array
1413 public $conditionscompletion;
1416 * Availability conditions for this section based on course grades (array from
1417 * grade item id to object with ->min, ->max fields) - from cached data in
1418 * sectioncache field
1419 * @var array
1421 public $conditionsgrade;
1424 * True if this section is available to students i.e. if all availability conditions
1425 * are met - obtained dynamically
1426 * @var bool
1428 public $available;
1431 * If section is not available to students, this string gives information about
1432 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
1433 * January 2010') for display on main page - obtained dynamically
1434 * @var string
1436 public $availableinfo;
1439 * True if this section is available to the CURRENT user (for example, if current user
1440 * has viewhiddensections capability, they can access the section even if it is not
1441 * visible or not available, so this would be true in that case)
1442 * @var bool
1444 public $uservisible;
1447 * Default values for sectioncache fields; if a field has this value, it won't
1448 * be stored in the sectioncache cache, to save space. Checks are done by ===
1449 * which means values must all be strings.
1450 * @var array
1452 private static $sectioncachedefaults = array(
1453 'name' => null,
1454 'summary' => '',
1455 'summaryformat' => '1', // FORMAT_HTML, but must be a string
1456 'visible' => '1',
1457 'showavailability' => '0',
1458 'availablefrom' => '0',
1459 'availableuntil' => '0',
1460 'groupingid' => '0',
1464 * Constructs object from database information plus extra required data.
1465 * @param object $data Array entry from cached sectioncache
1466 * @param int $number Section number (array key)
1467 * @param int $courseid Course ID
1468 * @param int $sequence Sequence of course-module ids contained within
1469 * @param course_modinfo $modinfo Owner (needed for checking availability)
1470 * @param int $userid User ID
1472 public function __construct($data, $number, $courseid, $sequence, $modinfo, $userid) {
1473 global $CFG;
1475 // Data that is always present
1476 $this->id = $data->id;
1478 // Data that may use default values to save cache size
1479 foreach (self::$sectioncachedefaults as $field => $value) {
1480 if (isset($data->{$field})) {
1481 $this->{$field} = $data->{$field};
1482 } else {
1483 $this->{$field} = $value;
1487 // Data with array defaults
1488 $this->conditionscompletion = isset($data->conditionscompletion)
1489 ? $data->conditionscompletion : array();
1490 $this->conditionsgrade = isset($data->conditionsgrade)
1491 ? $data->conditionsgrade : array();
1493 // Other data from other places
1494 $this->course = $courseid;
1495 $this->section = $number;
1496 $this->sequence = $sequence;
1498 // Availability data
1499 if (!empty($CFG->enableavailability)) {
1500 // Get availability information
1501 $ci = new condition_info_section($this);
1502 $this->available = $ci->is_available($this->availableinfo, true,
1503 $userid, $modinfo);
1504 // Display grouping info if available & not already displaying
1505 // (it would already display if current user doesn't have access)
1506 // for people with managegroups - same logic/class as grouping label
1507 // on individual activities.
1508 $context = context_course::instance($courseid);
1509 if ($this->availableinfo === '' && $this->groupingid &&
1510 has_capability('moodle/course:managegroups', $context)) {
1511 $groupings = groups_get_all_groupings($courseid);
1512 $this->availableinfo = html_writer::tag('span', '(' . format_string(
1513 $groupings[$this->groupingid]->name, true, array('context' => $context)) .
1514 ')', array('class' => 'groupinglabel'));
1516 } else {
1517 $this->available = true;
1520 // Update visibility for current user
1521 $this->update_user_visible($userid);
1525 * Works out whether activity is visible *for current user* - if this is false, they
1526 * aren't allowed to access it.
1527 * @param int $userid User ID
1528 * @return void
1530 private function update_user_visible($userid) {
1531 global $CFG;
1532 $coursecontext = context_course::instance($this->course);
1533 $this->uservisible = true;
1534 if ((!$this->visible || !$this->available) &&
1535 !has_capability('moodle/course:viewhiddensections', $coursecontext, $userid)) {
1536 $this->uservisible = false;
1541 * Prepares section data for inclusion in sectioncache cache, removing items
1542 * that are set to defaults, and adding availability data if required.
1544 * Called by build_section_cache in course_modinfo only; do not use otherwise.
1545 * @param object $section Raw section data object
1547 public static function convert_for_section_cache($section) {
1548 global $CFG;
1550 // Course id stored in course table
1551 unset($section->course);
1552 // Section number stored in array key
1553 unset($section->section);
1554 // Sequence stored implicity in modinfo $sections array
1555 unset($section->sequence);
1557 // Add availability data if turned on
1558 if ($CFG->enableavailability) {
1559 require_once($CFG->dirroot . '/lib/conditionlib.php');
1560 condition_info_section::fill_availability_conditions($section);
1561 if (count($section->conditionscompletion) == 0) {
1562 unset($section->conditionscompletion);
1564 if (count($section->conditionsgrade) == 0) {
1565 unset($section->conditionsgrade);
1569 // Remove default data
1570 foreach (self::$sectioncachedefaults as $field => $value) {
1571 // Exact compare as strings to avoid problems if some strings are set
1572 // to "0" etc.
1573 if (isset($section->{$field}) && $section->{$field} === $value) {
1574 unset($section->{$field});