Merge branch 'MDL-37858_master' of git://github.com/dmonllao/moodle
[moodle.git] / lib / modinfolib.php
blobc40efc7ebafedaf92c03ff8cfb5c880871b62ba8
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 * 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
165 * @return array
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])) {
186 return array();
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
203 // each request.
204 $this->groups = groups_get_user_groups($this->courseid, $this->userid);
206 if (!isset($this->groups[$groupingid])) {
207 return array();
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');
230 } else {
231 return null;
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) {
245 global $CFG, $DB;
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');
272 return;
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');
286 return;
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
298 continue;
301 // Skip modules which don't exist
302 if (empty($modexists[$mod->mod])) {
303 if (!file_exists("$CFG->dirroot/mod/$mod->mod/lib.php")) {
304 continue;
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]);
332 } else {
333 $sequence = '';
335 // Expand
336 $this->sectioninfo[$number] = new section_info($data, $number, $course->id, $sequence,
337 $this, $userid);
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) {
359 global $DB;
361 // Get section data
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;
414 * Parent object
415 * @var course_modinfo
417 private $modinfo;
420 * Level of information stored inside this object (STATE_xx constant)
421 * @var int
423 private $state;
425 // Existing data fields
426 ///////////////////////
429 * Course-module ID - from course_modules table
430 * @var int
432 public $id;
435 * Module instance (ID within module table) - from course_modules table
436 * @var int
438 public $instance;
441 * Course ID - from course_modules table
442 * @var int
444 public $course;
447 * 'ID number' from course-modules table (arbitrary text set by user) - from
448 * course_modules table
449 * @var string
451 public $idnumber;
454 * Time that this course-module was added (unix time) - from course_modules table
455 * @var int
457 public $added;
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
462 * here too.
463 * @var int
464 * @deprecated Do not use this variable
466 public $score;
469 * Visible setting (0 or 1; if this is 0, students cannot see/access the activity) - from
470 * course_modules table
471 * @var int
473 public $visible;
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
478 * @var int
480 public $visibleold;
483 * Group mode (one of the constants NONE, SEPARATEGROUPS, or VISIBLEGROUPS) - from
484 * course_modules table
485 * @var int
487 public $groupmode;
490 * Grouping ID (0 = all groupings)
491 * @var int
493 public $groupingid;
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
499 * @var int
501 public $groupmembersonly;
504 * Indicates whether the course containing the module has forced the groupmode
505 * This means that cm_info::$groupmode should be ignored and cm_info::$coursegroupmode be
506 * used instead
507 * @var bool
509 public $coursegroupmodeforce;
512 * Group mode (one of the constants NONE, SEPARATEGROUPS, or VISIBLEGROUPS) - from
513 * course table - as specified for the course containing the module
514 * Effective only if cm_info::$coursegroupmodeforce is set
515 * @var int
517 public $coursegroupmode;
520 * Indent level on course page (0 = no indent) - from course_modules table
521 * @var int
523 public $indent;
526 * Activity completion setting for this activity, COMPLETION_TRACKING_xx constant - from
527 * course_modules table
528 * @var int
530 public $completion;
533 * Set to the item number (usually 0) if completion depends on a particular
534 * grade of this activity, or null if completion does not depend on a grade - from
535 * course_modules table
536 * @var mixed
538 public $completiongradeitemnumber;
541 * 1 if 'on view' completion is enabled, 0 otherwise - from course_modules table
542 * @var int
544 public $completionview;
547 * Set to a unix time if completion of this activity is expected at a
548 * particular time, 0 if no time set - from course_modules table
549 * @var int
551 public $completionexpected;
554 * Available date for this activity (0 if not set, or set to seconds since epoch; before this
555 * date, activity does not display to students) - from course_modules table
556 * @var int
558 public $availablefrom;
561 * Available until date for this activity (0 if not set, or set to seconds since epoch; from
562 * this date, activity does not display to students) - from course_modules table
563 * @var int
565 public $availableuntil;
568 * When activity is unavailable, this field controls whether it is shown to students (0 =
569 * hide completely, 1 = show greyed out with information about when it will be available) -
570 * from course_modules table
571 * @var int
573 public $showavailability;
576 * Controls whether the description of the activity displays on the course main page (in
577 * addition to anywhere it might display within the activity itself). 0 = do not show
578 * on main page, 1 = show on main page.
579 * @var int
581 public $showdescription;
584 * Extra HTML that is put in an unhelpful part of the HTML when displaying this module in
585 * course page - from cached data in modinfo field
586 * @deprecated This is crazy, don't use it. Replaced by ->extraclasses and ->onclick
587 * @var string
589 public $extra;
592 * Name of icon to use - from cached data in modinfo field
593 * @var string
595 public $icon;
598 * Component that contains icon - from cached data in modinfo field
599 * @var string
601 public $iconcomponent;
604 * Name of module e.g. 'forum' (this is the same name as the module's main database
605 * table) - from cached data in modinfo field
606 * @var string
608 public $modname;
611 * ID of module - from course_modules table
612 * @var int
614 public $module;
617 * Name of module instance for display on page e.g. 'General discussion forum' - from cached
618 * data in modinfo field
619 * @var string
621 public $name;
624 * Section number that this course-module is in (section 0 = above the calendar, section 1
625 * = week/topic 1, etc) - from cached data in modinfo field
626 * @var string
628 public $sectionnum;
631 * Section id - from course_modules table
632 * @var int
634 public $section;
637 * Availability conditions for this course-module based on the completion of other
638 * course-modules (array from other course-module id to required completion state for that
639 * module) - from cached data in modinfo field
640 * @var array
642 public $conditionscompletion;
645 * Availability conditions for this course-module based on course grades (array from
646 * grade item id to object with ->min, ->max fields) - from cached data in modinfo field
647 * @var array
649 public $conditionsgrade;
652 * Availability conditions for this course-module based on user fields
653 * @var array
655 public $conditionsfield;
658 * True if this course-module is available to students i.e. if all availability conditions
659 * are met - obtained dynamically
660 * @var bool
662 public $available;
665 * If course-module is not available to students, this string gives information about
666 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
667 * January 2010') for display on main page - obtained dynamically
668 * @var string
670 public $availableinfo;
673 * True if this course-module is available to the CURRENT user (for example, if current user
674 * has viewhiddenactivities capability, they can access the course-module even if it is not
675 * visible or not available, so this would be true in that case)
676 * @var bool
678 public $uservisible;
681 * Module context - hacky shortcut
682 * @deprecated
683 * @var stdClass
685 public $context;
688 // New data available only via functions
689 ////////////////////////////////////////
692 * @var moodle_url
694 private $url;
697 * @var string
699 private $content;
702 * @var string
704 private $extraclasses;
707 * @var moodle_url full external url pointing to icon image for activity
709 private $iconurl;
712 * @var string
714 private $onclick;
717 * @var mixed
719 private $customdata;
722 * @var string
724 private $afterlink;
727 * @var string
729 private $afterediticons;
732 * Magic method getter
734 * @param string $name
735 * @return mixed
737 public function __get($name) {
738 switch ($name) {
739 case 'modplural':
740 return $this->get_module_type_name(true);
741 case 'modfullname':
742 return $this->get_module_type_name();
743 default:
744 debugging('Invalid cm_info property accessed: '.$name);
745 return null;
750 * @return bool True if this module has a 'view' page that should be linked to in navigation
751 * etc (note: modules may still have a view.php file, but return false if this is not
752 * intended to be linked to from 'normal' parts of the interface; this is what label does).
754 public function has_view() {
755 return !is_null($this->url);
759 * @return moodle_url URL to link to for this module, or null if it doesn't have a view page
761 public function get_url() {
762 return $this->url;
766 * Obtains content to display on main (view) page.
767 * Note: Will collect view data, if not already obtained.
768 * @return string Content to display on main page below link, or empty string if none
770 public function get_content() {
771 $this->obtain_view_data();
772 return $this->content;
776 * Returns the content to display on course/overview page, formatted and passed through filters
778 * if $options['context'] is not specified, the module context is used
780 * @param array|stdClass $options formatting options, see {@link format_text()}
781 * @return string
783 public function get_formatted_content($options = array()) {
784 $this->obtain_view_data();
785 if (empty($this->content)) {
786 return '';
788 if ($this->modname === 'label') {
789 // special case, label returns already formatted content, see cm_info::__construct()
790 // and label_get_coursemodule_info()
791 return $this->content;
793 // Improve filter performance by preloading filter setttings for all
794 // activities on the course (this does nothing if called multiple
795 // times)
796 filter_preload_activities($this->get_modinfo());
798 $options = (array)$options;
799 if (!isset($options['context'])) {
800 $options['context'] = context_module::instance($this->id);
802 return format_text($this->content, FORMAT_HTML, $options);
806 * Returns the name to display on course/overview page, formatted and passed through filters
808 * if $options['context'] is not specified, the module context is used
810 * @param array|stdClass $options formatting options, see {@link format_string()}
811 * @return string
813 public function get_formatted_name($options = array()) {
814 $options = (array)$options;
815 if (!isset($options['context'])) {
816 $options['context'] = context_module::instance($this->id);
818 return format_string($this->name, true, $options);
822 * Note: Will collect view data, if not already obtained.
823 * @return string Extra CSS classes to add to html output for this activity on main page
825 public function get_extra_classes() {
826 $this->obtain_view_data();
827 return $this->extraclasses;
831 * @return string Content of HTML on-click attribute. This string will be used literally
832 * as a string so should be pre-escaped.
834 public function get_on_click() {
835 // Does not need view data; may be used by navigation
836 return $this->onclick;
839 * @return mixed Optional custom data stored in modinfo cache for this activity, or null if none
841 public function get_custom_data() {
842 return $this->customdata;
846 * Note: Will collect view data, if not already obtained.
847 * @return string Extra HTML code to display after link
849 public function get_after_link() {
850 $this->obtain_view_data();
851 return $this->afterlink;
855 * Note: Will collect view data, if not already obtained.
856 * @return string Extra HTML code to display after editing icons (e.g. more icons)
858 public function get_after_edit_icons() {
859 $this->obtain_view_data();
860 return $this->afterediticons;
864 * @param moodle_core_renderer $output Output render to use, or null for default (global)
865 * @return moodle_url Icon URL for a suitable icon to put beside this cm
867 public function get_icon_url($output = null) {
868 global $OUTPUT;
869 if (!$output) {
870 $output = $OUTPUT;
872 // Support modules setting their own, external, icon image
873 if (!empty($this->iconurl)) {
874 $icon = $this->iconurl;
876 // Fallback to normal local icon + component procesing
877 } else if (!empty($this->icon)) {
878 if (substr($this->icon, 0, 4) === 'mod/') {
879 list($modname, $iconname) = explode('/', substr($this->icon, 4), 2);
880 $icon = $output->pix_url($iconname, $modname);
881 } else {
882 if (!empty($this->iconcomponent)) {
883 // Icon has specified component
884 $icon = $output->pix_url($this->icon, $this->iconcomponent);
885 } else {
886 // Icon does not have specified component, use default
887 $icon = $output->pix_url($this->icon);
890 } else {
891 $icon = $output->pix_url('icon', $this->modname);
893 return $icon;
897 * Returns a localised human-readable name of the module type
899 * @param bool $plural return plural form
900 * @return string
902 public function get_module_type_name($plural = false) {
903 $modnames = get_module_types_names($plural);
904 if (isset($modnames[$this->modname])) {
905 return $modnames[$this->modname];
906 } else {
907 return null;
912 * @return course_modinfo Modinfo object that this came from
914 public function get_modinfo() {
915 return $this->modinfo;
919 * @return object Moodle course object that was used to construct this data
921 public function get_course() {
922 return $this->modinfo->get_course();
925 // Set functions
926 ////////////////
929 * Sets content to display on course view page below link (if present).
930 * @param string $content New content as HTML string (empty string if none)
931 * @return void
933 public function set_content($content) {
934 $this->content = $content;
938 * Sets extra classes to include in CSS.
939 * @param string $extraclasses Extra classes (empty string if none)
940 * @return void
942 public function set_extra_classes($extraclasses) {
943 $this->extraclasses = $extraclasses;
947 * Sets the external full url that points to the icon being used
948 * by the activity. Useful for external-tool modules (lti...)
949 * If set, takes precedence over $icon and $iconcomponent
951 * @param moodle_url $iconurl full external url pointing to icon image for activity
952 * @return void
954 public function set_icon_url(moodle_url $iconurl) {
955 $this->iconurl = $iconurl;
959 * Sets value of on-click attribute for JavaScript.
960 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
961 * @param string $onclick New onclick attribute which should be HTML-escaped
962 * (empty string if none)
963 * @return void
965 public function set_on_click($onclick) {
966 $this->check_not_view_only();
967 $this->onclick = $onclick;
971 * Sets HTML that displays after link on course view page.
972 * @param string $afterlink HTML string (empty string if none)
973 * @return void
975 public function set_after_link($afterlink) {
976 $this->afterlink = $afterlink;
980 * Sets HTML that displays after edit icons on course view page.
981 * @param string $afterediticons HTML string (empty string if none)
982 * @return void
984 public function set_after_edit_icons($afterediticons) {
985 $this->afterediticons = $afterediticons;
989 * Changes the name (text of link) for this module instance.
990 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
991 * @param string $name Name of activity / link text
992 * @return void
994 public function set_name($name) {
995 $this->update_user_visible();
996 $this->name = $name;
1000 * Turns off the view link for this module instance.
1001 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1002 * @return void
1004 public function set_no_view_link() {
1005 $this->check_not_view_only();
1006 $this->url = null;
1010 * Sets the 'uservisible' flag. This can be used (by setting false) to prevent access and
1011 * display of this module link for the current user.
1012 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1013 * @param bool $uservisible
1014 * @return void
1016 public function set_user_visible($uservisible) {
1017 $this->check_not_view_only();
1018 $this->uservisible = $uservisible;
1022 * Sets the 'available' flag and related details. This flag is normally used to make
1023 * course modules unavailable until a certain date or condition is met. (When a course
1024 * module is unavailable, it is still visible to users who have viewhiddenactivities
1025 * permission.)
1027 * When this is function is called, user-visible status is recalculated automatically.
1029 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1030 * @param bool $available False if this item is not 'available'
1031 * @param int $showavailability 0 = do not show this item at all if it's not available,
1032 * 1 = show this item greyed out with the following message
1033 * @param string $availableinfo Information about why this is not available which displays
1034 * to those who have viewhiddenactivities, and to everyone if showavailability is set;
1035 * note that this function replaces the existing data (if any)
1036 * @return void
1038 public function set_available($available, $showavailability=0, $availableinfo='') {
1039 $this->check_not_view_only();
1040 $this->available = $available;
1041 $this->showavailability = $showavailability;
1042 $this->availableinfo = $availableinfo;
1043 $this->update_user_visible();
1047 * Some set functions can only be called from _cm_info_dynamic and not _cm_info_view.
1048 * This is because they may affect parts of this object which are used on pages other
1049 * than the view page (e.g. in the navigation block, or when checking access on
1050 * module pages).
1051 * @return void
1053 private function check_not_view_only() {
1054 if ($this->state >= self::STATE_DYNAMIC) {
1055 throw new coding_exception('Cannot set this data from _cm_info_view because it may ' .
1056 'affect other pages as well as view');
1061 * Constructor should not be called directly; use get_fast_modinfo.
1062 * @param course_modinfo $modinfo Parent object
1063 * @param object $course Course row
1064 * @param object $mod Module object from the modinfo field of course table
1065 * @param object $info Entire object from modinfo field of course table
1067 public function __construct(course_modinfo $modinfo, $course, $mod, $info) {
1068 global $CFG;
1069 $this->modinfo = $modinfo;
1071 $this->id = $mod->cm;
1072 $this->instance = $mod->id;
1073 $this->course = $course->id;
1074 $this->modname = $mod->mod;
1075 $this->idnumber = isset($mod->idnumber) ? $mod->idnumber : '';
1076 $this->name = $mod->name;
1077 $this->visible = $mod->visible;
1078 $this->sectionnum = $mod->section; // Note weirdness with name here
1079 $this->groupmode = isset($mod->groupmode) ? $mod->groupmode : 0;
1080 $this->groupingid = isset($mod->groupingid) ? $mod->groupingid : 0;
1081 $this->groupmembersonly = isset($mod->groupmembersonly) ? $mod->groupmembersonly : 0;
1082 $this->coursegroupmodeforce = $course->groupmodeforce;
1083 $this->coursegroupmode = $course->groupmode;
1084 $this->indent = isset($mod->indent) ? $mod->indent : 0;
1085 $this->extra = isset($mod->extra) ? $mod->extra : '';
1086 $this->extraclasses = isset($mod->extraclasses) ? $mod->extraclasses : '';
1087 $this->iconurl = isset($mod->iconurl) ? $mod->iconurl : '';
1088 $this->onclick = isset($mod->onclick) ? $mod->onclick : '';
1089 $this->content = isset($mod->content) ? $mod->content : '';
1090 $this->icon = isset($mod->icon) ? $mod->icon : '';
1091 $this->iconcomponent = isset($mod->iconcomponent) ? $mod->iconcomponent : '';
1092 $this->customdata = isset($mod->customdata) ? $mod->customdata : '';
1093 $this->context = context_module::instance($mod->cm);
1094 $this->showdescription = isset($mod->showdescription) ? $mod->showdescription : 0;
1095 $this->state = self::STATE_BASIC;
1097 // This special case handles old label data. Labels used to use the 'name' field for
1098 // content
1099 if ($this->modname === 'label' && $this->content === '') {
1100 $this->content = $this->extra;
1101 $this->extra = '';
1104 // Note: These fields from $cm were not present in cm_info in Moodle
1105 // 2.0.2 and prior. They may not be available if course cache hasn't
1106 // been rebuilt since then.
1107 $this->section = isset($mod->sectionid) ? $mod->sectionid : 0;
1108 $this->module = isset($mod->module) ? $mod->module : 0;
1109 $this->added = isset($mod->added) ? $mod->added : 0;
1110 $this->score = isset($mod->score) ? $mod->score : 0;
1111 $this->visibleold = isset($mod->visibleold) ? $mod->visibleold : 0;
1113 // Note: it saves effort and database space to always include the
1114 // availability and completion fields, even if availability or completion
1115 // are actually disabled
1116 $this->completion = isset($mod->completion) ? $mod->completion : 0;
1117 $this->completiongradeitemnumber = isset($mod->completiongradeitemnumber)
1118 ? $mod->completiongradeitemnumber : null;
1119 $this->completionview = isset($mod->completionview)
1120 ? $mod->completionview : 0;
1121 $this->completionexpected = isset($mod->completionexpected)
1122 ? $mod->completionexpected : 0;
1123 $this->showavailability = isset($mod->showavailability) ? $mod->showavailability : 0;
1124 $this->availablefrom = isset($mod->availablefrom) ? $mod->availablefrom : 0;
1125 $this->availableuntil = isset($mod->availableuntil) ? $mod->availableuntil : 0;
1126 $this->conditionscompletion = isset($mod->conditionscompletion)
1127 ? $mod->conditionscompletion : array();
1128 $this->conditionsgrade = isset($mod->conditionsgrade)
1129 ? $mod->conditionsgrade : array();
1130 $this->conditionsfield = isset($mod->conditionsfield)
1131 ? $mod->conditionsfield : array();
1133 static $modviews;
1134 if (!isset($modviews[$this->modname])) {
1135 $modviews[$this->modname] = !plugin_supports('mod', $this->modname,
1136 FEATURE_NO_VIEW_LINK);
1138 $this->url = $modviews[$this->modname]
1139 ? new moodle_url('/mod/' . $this->modname . '/view.php', array('id'=>$this->id))
1140 : null;
1144 * If dynamic data for this course-module is not yet available, gets it.
1146 * This function is automatically called when constructing course_modinfo, so users don't
1147 * need to call it.
1149 * Dynamic data is data which does not come directly from the cache but is calculated at
1150 * runtime based on the current user. Primarily this concerns whether the user can access
1151 * the module or not.
1153 * As part of this function, the module's _cm_info_dynamic function from its lib.php will
1154 * be called (if it exists).
1155 * @return void
1157 public function obtain_dynamic_data() {
1158 global $CFG;
1159 if ($this->state >= self::STATE_DYNAMIC) {
1160 return;
1162 $userid = $this->modinfo->get_user_id();
1164 if (!empty($CFG->enableavailability)) {
1165 // Get availability information
1166 $ci = new condition_info($this);
1167 // Note that the modinfo currently available only includes minimal details (basic data)
1168 // so passing it to this function is a bit dangerous as it would cause infinite
1169 // recursion if it tried to get dynamic data, however we know that this function only
1170 // uses basic data.
1171 $this->available = $ci->is_available($this->availableinfo, true,
1172 $userid, $this->modinfo);
1174 // Check parent section
1175 $parentsection = $this->modinfo->get_section_info($this->sectionnum);
1176 if (!$parentsection->available) {
1177 // Do not store info from section here, as that is already
1178 // presented from the section (if appropriate) - just change
1179 // the flag
1180 $this->available = false;
1182 } else {
1183 $this->available = true;
1186 // Update visible state for current user
1187 $this->update_user_visible();
1189 // Let module make dynamic changes at this point
1190 $this->call_mod_function('cm_info_dynamic');
1191 $this->state = self::STATE_DYNAMIC;
1195 * Works out whether activity is available to the current user
1197 * If the activity is unavailable, additional checks are required to determine if its hidden or greyed out
1199 * @see is_user_access_restricted_by_group()
1200 * @see is_user_access_restricted_by_conditional_access()
1201 * @return void
1203 private function update_user_visible() {
1204 global $CFG;
1205 $modcontext = context_module::instance($this->id);
1206 $userid = $this->modinfo->get_user_id();
1207 $this->uservisible = true;
1209 // If the user cannot access the activity set the uservisible flag to false.
1210 // Additional checks are required to determine whether the activity is entirely hidden or just greyed out.
1211 if ((!$this->visible or !$this->available) and
1212 !has_capability('moodle/course:viewhiddenactivities', $modcontext, $userid)) {
1214 $this->uservisible = false;
1217 // Check group membership.
1218 if ($this->is_user_access_restricted_by_group()) {
1220 $this->uservisible = false;
1221 // Ensure activity is completely hidden from the user.
1222 $this->showavailability = 0;
1227 * Checks whether the module's group settings restrict the current user's access
1229 * @return bool True if the user access is restricted
1231 public function is_user_access_restricted_by_group() {
1232 global $CFG;
1234 if (!empty($CFG->enablegroupmembersonly) and !empty($this->groupmembersonly)) {
1235 $modcontext = context_module::instance($this->id);
1236 $userid = $this->modinfo->get_user_id();
1237 if (!has_capability('moodle/site:accessallgroups', $modcontext, $userid)) {
1238 // If the activity has 'group members only' and you don't have accessallgroups...
1239 $groups = $this->modinfo->get_groups($this->groupingid);
1240 if (empty($groups)) {
1241 // ...and you don't belong to a group, then set it so you can't see/access it
1242 return true;
1246 return false;
1250 * Checks whether the module's conditional access settings mean that the user cannot see the activity at all
1252 * @return bool True if the user cannot see the module. False if the activity is either available or should be greyed out.
1254 public function is_user_access_restricted_by_conditional_access() {
1255 global $CFG, $USER;
1257 if (empty($CFG->enableavailability)) {
1258 return false;
1261 // If module will always be visible anyway (but greyed out), don't bother checking anything else
1262 if ($this->showavailability == CONDITION_STUDENTVIEW_SHOW) {
1263 return false;
1266 // Can the user see hidden modules?
1267 $modcontext = context_module::instance($this->id);
1268 $userid = $this->modinfo->get_user_id();
1269 if (has_capability('moodle/course:viewhiddenactivities', $modcontext, $userid)) {
1270 return false;
1273 // Is the module hidden due to unmet conditions?
1274 if (!$this->available) {
1275 return true;
1278 return false;
1282 * Calls a module function (if exists), passing in one parameter: this object.
1283 * @param string $type Name of function e.g. if this is 'grooblezorb' and the modname is
1284 * 'forum' then it will try to call 'mod_forum_grooblezorb' or 'forum_grooblezorb'
1285 * @return void
1287 private function call_mod_function($type) {
1288 global $CFG;
1289 $libfile = $CFG->dirroot . '/mod/' . $this->modname . '/lib.php';
1290 if (file_exists($libfile)) {
1291 include_once($libfile);
1292 $function = 'mod_' . $this->modname . '_' . $type;
1293 if (function_exists($function)) {
1294 $function($this);
1295 } else {
1296 $function = $this->modname . '_' . $type;
1297 if (function_exists($function)) {
1298 $function($this);
1305 * If view data for this course-module is not yet available, obtains it.
1307 * This function is automatically called if any of the functions (marked) which require
1308 * view data are called.
1310 * View data is data which is needed only for displaying the course main page (& any similar
1311 * functionality on other pages) but is not needed in general. Obtaining view data may have
1312 * a performance cost.
1314 * As part of this function, the module's _cm_info_view function from its lib.php will
1315 * be called (if it exists).
1316 * @return void
1318 private function obtain_view_data() {
1319 if ($this->state >= self::STATE_VIEW) {
1320 return;
1323 // Let module make changes at this point
1324 $this->call_mod_function('cm_info_view');
1325 $this->state = self::STATE_VIEW;
1331 * Returns reference to full info about modules in course (including visibility).
1332 * Cached and as fast as possible (0 or 1 db query).
1334 * use get_fast_modinfo($courseid, 0, true) to reset the static cache for particular course
1335 * use get_fast_modinfo(0, 0, true) to reset the static cache for all courses
1337 * @uses MAX_MODINFO_CACHE_SIZE
1338 * @param int|stdClass $courseorid object from DB table 'course' or just a course id
1339 * @param int $userid User id to populate 'uservisible' attributes of modules and sections.
1340 * Set to 0 for current user (default)
1341 * @param bool $resetonly whether we want to get modinfo or just reset the cache
1342 * @return course_modinfo|null Module information for course, or null if resetting
1344 function get_fast_modinfo($courseorid, $userid = 0, $resetonly = false) {
1345 global $CFG, $USER;
1346 require_once($CFG->dirroot.'/course/lib.php');
1348 if (!empty($CFG->enableavailability)) {
1349 require_once($CFG->libdir.'/conditionlib.php');
1352 static $cache = array();
1354 // compartibility with syntax prior to 2.4:
1355 if ($courseorid === 'reset') {
1356 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);
1357 $courseorid = 0;
1358 $resetonly = true;
1361 if (is_object($courseorid)) {
1362 $course = $courseorid;
1363 } else {
1364 $course = (object)array('id' => $courseorid, 'modinfo' => null, 'sectioncache' => null);
1367 // Function is called with $reset = true
1368 if ($resetonly) {
1369 if (isset($course->id) && $course->id > 0) {
1370 $cache[$course->id] = false;
1371 } else {
1372 foreach (array_keys($cache) as $key) {
1373 $cache[$key] = false;
1376 return null;
1379 // Function is called with $reset = false, retrieve modinfo
1380 if (empty($userid)) {
1381 $userid = $USER->id;
1384 if (array_key_exists($course->id, $cache)) {
1385 if ($cache[$course->id] === false) {
1386 // this course has been recently reset, do not rely on modinfo and sectioncache in $course
1387 $course->modinfo = null;
1388 $course->sectioncache = null;
1389 } else if ($cache[$course->id]->userid == $userid) {
1390 // this course's modinfo for the same user was recently retrieved, return cached
1391 return $cache[$course->id];
1395 if (!property_exists($course, 'modinfo')) {
1396 debugging('Coding problem - missing course modinfo property in get_fast_modinfo() call');
1399 if (!property_exists($course, 'sectioncache')) {
1400 debugging('Coding problem - missing course sectioncache property in get_fast_modinfo() call');
1403 unset($cache[$course->id]); // prevent potential reference problems when switching users
1405 $cache[$course->id] = new course_modinfo($course, $userid);
1407 // Ensure cache does not use too much RAM
1408 if (count($cache) > MAX_MODINFO_CACHE_SIZE) {
1409 reset($cache);
1410 $key = key($cache);
1411 unset($cache[$key]->instances);
1412 unset($cache[$key]->cms);
1413 unset($cache[$key]);
1416 return $cache[$course->id];
1420 * Rebuilds the cached list of course activities stored in the database
1421 * @param int $courseid - id of course to rebuild, empty means all
1422 * @param boolean $clearonly - only clear the modinfo fields, gets rebuild automatically on the fly
1424 function rebuild_course_cache($courseid=0, $clearonly=false) {
1425 global $COURSE, $SITE, $DB, $CFG;
1427 // Destroy navigation caches
1428 navigation_cache::destroy_volatile_caches();
1430 if (class_exists('format_base')) {
1431 // if file containing class is not loaded, there is no cache there anyway
1432 format_base::reset_course_cache($courseid);
1435 if ($clearonly) {
1436 if (empty($courseid)) {
1437 $DB->set_field('course', 'modinfo', null);
1438 $DB->set_field('course', 'sectioncache', null);
1439 } else {
1440 // Clear both fields in one update
1441 $resetobj = (object)array('id' => $courseid, 'modinfo' => null, 'sectioncache' => null);
1442 $DB->update_record('course', $resetobj);
1444 // update cached global COURSE too ;-)
1445 if ($courseid == $COURSE->id or empty($courseid)) {
1446 $COURSE->modinfo = null;
1447 $COURSE->sectioncache = null;
1449 if ($courseid == $SITE->id) {
1450 $SITE->modinfo = null;
1451 $SITE->sectioncache = null;
1453 // reset the fast modinfo cache
1454 get_fast_modinfo($courseid, 0, true);
1455 return;
1458 require_once("$CFG->dirroot/course/lib.php");
1460 if ($courseid) {
1461 $select = array('id'=>$courseid);
1462 } else {
1463 $select = array();
1464 @set_time_limit(0); // this could take a while! MDL-10954
1467 $rs = $DB->get_recordset("course", $select,'','id,fullname');
1468 foreach ($rs as $course) {
1469 $modinfo = serialize(get_array_of_activities($course->id));
1470 $sectioncache = serialize(course_modinfo::build_section_cache($course->id));
1471 $updateobj = (object)array('id' => $course->id,
1472 'modinfo' => $modinfo, 'sectioncache' => $sectioncache);
1473 $DB->update_record("course", $updateobj);
1474 // update cached global COURSE too ;-)
1475 if ($course->id == $COURSE->id) {
1476 $COURSE->modinfo = $modinfo;
1477 $COURSE->sectioncache = $sectioncache;
1479 if ($course->id == $SITE->id) {
1480 $SITE->modinfo = $modinfo;
1481 $SITE->sectioncache = $sectioncache;
1484 $rs->close();
1485 // reset the fast modinfo cache
1486 get_fast_modinfo($courseid, 0, true);
1491 * Class that is the return value for the _get_coursemodule_info module API function.
1493 * Note: For backward compatibility, you can also return a stdclass object from that function.
1494 * The difference is that the stdclass object may contain an 'extra' field (deprecated because
1495 * it was crazy, except for label which uses it differently). The stdclass object may not contain
1496 * the new fields defined here (content, extraclasses, customdata).
1498 class cached_cm_info {
1500 * Name (text of link) for this activity; Leave unset to accept default name
1501 * @var string
1503 public $name;
1506 * Name of icon for this activity. Normally, this should be used together with $iconcomponent
1507 * to define the icon, as per pix_url function.
1508 * For backward compatibility, if this value is of the form 'mod/forum/icon' then an icon
1509 * within that module will be used.
1510 * @see cm_info::get_icon_url()
1511 * @see renderer_base::pix_url()
1512 * @var string
1514 public $icon;
1517 * Component for icon for this activity, as per pix_url; leave blank to use default 'moodle'
1518 * component
1519 * @see renderer_base::pix_url()
1520 * @var string
1522 public $iconcomponent;
1525 * HTML content to be displayed on the main page below the link (if any) for this course-module
1526 * @var string
1528 public $content;
1531 * Custom data to be stored in modinfo for this activity; useful if there are cases when
1532 * internal information for this activity type needs to be accessible from elsewhere on the
1533 * course without making database queries. May be of any type but should be short.
1534 * @var mixed
1536 public $customdata;
1539 * Extra CSS class or classes to be added when this activity is displayed on the main page;
1540 * space-separated string
1541 * @var string
1543 public $extraclasses;
1546 * External URL image to be used by activity as icon, useful for some external-tool modules
1547 * like lti. If set, takes precedence over $icon and $iconcomponent
1548 * @var $moodle_url
1550 public $iconurl;
1553 * Content of onclick JavaScript; escaped HTML to be inserted as attribute value
1554 * @var string
1556 public $onclick;
1561 * Data about a single section on a course. This contains the fields from the
1562 * course_sections table, plus additional data when required.
1564 class section_info implements IteratorAggregate {
1566 * Section ID - from course_sections table
1567 * @var int
1569 private $_id;
1572 * Course ID - from course_sections table
1573 * @var int
1575 private $_course;
1578 * Section number - from course_sections table
1579 * @var int
1581 private $_section;
1584 * Section name if specified - from course_sections table
1585 * @var string
1587 private $_name;
1590 * Section visibility (1 = visible) - from course_sections table
1591 * @var int
1593 private $_visible;
1596 * Section summary text if specified - from course_sections table
1597 * @var string
1599 private $_summary;
1602 * Section summary text format (FORMAT_xx constant) - from course_sections table
1603 * @var int
1605 private $_summaryformat;
1608 * When section is unavailable, this field controls whether it is shown to students (0 =
1609 * hide completely, 1 = show greyed out with information about when it will be available) -
1610 * from course_sections table
1611 * @var int
1613 private $_showavailability;
1616 * Available date for this section (0 if not set, or set to seconds since epoch; before this
1617 * date, section does not display to students) - from course_sections table
1618 * @var int
1620 private $_availablefrom;
1623 * Available until date for this section (0 if not set, or set to seconds since epoch; from
1624 * this date, section does not display to students) - from course_sections table
1625 * @var int
1627 private $_availableuntil;
1630 * If section is restricted to users of a particular grouping, this is its id
1631 * (0 if not set) - from course_sections table
1632 * @var int
1634 private $_groupingid;
1637 * Availability conditions for this section based on the completion of
1638 * course-modules (array from course-module id to required completion state
1639 * for that module) - from cached data in sectioncache field
1640 * @var array
1642 private $_conditionscompletion;
1645 * Availability conditions for this section based on course grades (array from
1646 * grade item id to object with ->min, ->max fields) - from cached data in
1647 * sectioncache field
1648 * @var array
1650 private $_conditionsgrade;
1653 * Availability conditions for this section based on user fields
1654 * @var array
1656 private $_conditionsfield;
1659 * True if this section is available to students i.e. if all availability conditions
1660 * are met - obtained dynamically
1661 * @var bool
1663 private $_available;
1666 * If section is not available to students, this string gives information about
1667 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
1668 * January 2010') for display on main page - obtained dynamically
1669 * @var string
1671 private $_availableinfo;
1674 * True if this section is available to the CURRENT user (for example, if current user
1675 * has viewhiddensections capability, they can access the section even if it is not
1676 * visible or not available, so this would be true in that case)
1677 * @var bool
1679 private $_uservisible;
1682 * Default values for sectioncache fields; if a field has this value, it won't
1683 * be stored in the sectioncache cache, to save space. Checks are done by ===
1684 * which means values must all be strings.
1685 * @var array
1687 private static $sectioncachedefaults = array(
1688 'name' => null,
1689 'summary' => '',
1690 'summaryformat' => '1', // FORMAT_HTML, but must be a string
1691 'visible' => '1',
1692 'showavailability' => '0',
1693 'availablefrom' => '0',
1694 'availableuntil' => '0',
1695 'groupingid' => '0',
1699 * Stores format options that have been cached when building 'coursecache'
1700 * When the format option is requested we look first if it has been cached
1701 * @var array
1703 private $cachedformatoptions = array();
1706 * Constructs object from database information plus extra required data.
1707 * @param object $data Array entry from cached sectioncache
1708 * @param int $number Section number (array key)
1709 * @param int $courseid Course ID
1710 * @param int $sequence Sequence of course-module ids contained within
1711 * @param course_modinfo $modinfo Owner (needed for checking availability)
1712 * @param int $userid User ID
1714 public function __construct($data, $number, $courseid, $sequence, $modinfo, $userid) {
1715 global $CFG;
1717 // Data that is always present
1718 $this->_id = $data->id;
1720 $defaults = self::$sectioncachedefaults +
1721 array('conditionscompletion' => array(),
1722 'conditionsgrade' => array(),
1723 'conditionsfield' => array());
1725 // Data that may use default values to save cache size
1726 foreach ($defaults as $field => $value) {
1727 if (isset($data->{$field})) {
1728 $this->{'_'.$field} = $data->{$field};
1729 } else {
1730 $this->{'_'.$field} = $value;
1734 // cached course format data
1735 $formatoptionsdef = course_get_format($courseid)->section_format_options();
1736 foreach ($formatoptionsdef as $field => $option) {
1737 if (!empty($option['cache'])) {
1738 if (isset($data->{$field})) {
1739 $this->cachedformatoptions[$field] = $data->{$field};
1740 } else if (array_key_exists('cachedefault', $option)) {
1741 $this->cachedformatoptions[$field] = $option['cachedefault'];
1746 // Other data from other places
1747 $this->_course = $courseid;
1748 $this->_section = $number;
1749 $this->_sequence = $sequence;
1751 // Availability data
1752 if (!empty($CFG->enableavailability)) {
1753 // Get availability information
1754 $ci = new condition_info_section($this);
1755 $this->_available = $ci->is_available($this->_availableinfo, true,
1756 $userid, $modinfo);
1757 // Display grouping info if available & not already displaying
1758 // (it would already display if current user doesn't have access)
1759 // for people with managegroups - same logic/class as grouping label
1760 // on individual activities.
1761 $context = context_course::instance($courseid);
1762 if ($this->_availableinfo === '' && $this->_groupingid &&
1763 has_capability('moodle/course:managegroups', $context)) {
1764 $groupings = groups_get_all_groupings($courseid);
1765 $this->_availableinfo = html_writer::tag('span', '(' . format_string(
1766 $groupings[$this->_groupingid]->name, true, array('context' => $context)) .
1767 ')', array('class' => 'groupinglabel'));
1769 } else {
1770 $this->_available = true;
1773 // Update visibility for current user
1774 $this->update_user_visible($userid);
1778 * Magic method to check if the property is set
1780 * @param string $name name of the property
1781 * @return bool
1783 public function __isset($name) {
1784 if (property_exists($this, '_'.$name)) {
1785 return isset($this->{'_'.$name});
1787 $defaultformatoptions = course_get_format($this->_course)->section_format_options();
1788 if (array_key_exists($name, $defaultformatoptions)) {
1789 $value = $this->__get($name);
1790 return isset($value);
1792 return false;
1796 * Magic method to check if the property is empty
1798 * @param string $name name of the property
1799 * @return bool
1801 public function __empty($name) {
1802 if (property_exists($this, '_'.$name)) {
1803 return empty($this->{'_'.$name});
1805 $defaultformatoptions = course_get_format($this->_course)->section_format_options();
1806 if (array_key_exists($name, $defaultformatoptions)) {
1807 $value = $this->__get($name);
1808 return empty($value);
1810 return true;
1814 * Magic method to retrieve the property, this is either basic section property
1815 * or availability information or additional properties added by course format
1817 * @param string $name name of the property
1818 * @return bool
1820 public function __get($name) {
1821 if (property_exists($this, '_'.$name)) {
1822 return $this->{'_'.$name};
1824 if (array_key_exists($name, $this->cachedformatoptions)) {
1825 return $this->cachedformatoptions[$name];
1827 $defaultformatoptions = course_get_format($this->_course)->section_format_options();
1828 // precheck if the option is defined in format to avoid unnecessary DB queries in get_format_options()
1829 if (array_key_exists($name, $defaultformatoptions)) {
1830 $formatoptions = course_get_format($this->_course)->get_format_options($this);
1831 return $formatoptions[$name];
1833 debugging('Invalid section_info property accessed! '.$name);
1834 return null;
1838 * Implementation of IteratorAggregate::getIterator(), allows to cycle through properties
1839 * and use {@link convert_to_array()}
1841 * @return ArrayIterator
1843 public function getIterator() {
1844 $ret = array();
1845 foreach (get_object_vars($this) as $key => $value) {
1846 if (substr($key, 0, 1) == '_') {
1847 $ret[substr($key, 1)] = $this->$key;
1850 $ret = array_merge($ret, course_get_format($this->_course)->get_format_options($this));
1851 return new ArrayIterator($ret);
1855 * Works out whether activity is visible *for current user* - if this is false, they
1856 * aren't allowed to access it.
1857 * @param int $userid User ID
1858 * @return void
1860 private function update_user_visible($userid) {
1861 global $CFG;
1862 $coursecontext = context_course::instance($this->_course);
1863 $this->_uservisible = true;
1864 if ((!$this->_visible || !$this->_available) &&
1865 !has_capability('moodle/course:viewhiddensections', $coursecontext, $userid)) {
1866 $this->_uservisible = false;
1871 * Prepares section data for inclusion in sectioncache cache, removing items
1872 * that are set to defaults, and adding availability data if required.
1874 * Called by build_section_cache in course_modinfo only; do not use otherwise.
1875 * @param object $section Raw section data object
1877 public static function convert_for_section_cache($section) {
1878 global $CFG;
1880 // Course id stored in course table
1881 unset($section->course);
1882 // Section number stored in array key
1883 unset($section->section);
1884 // Sequence stored implicity in modinfo $sections array
1885 unset($section->sequence);
1887 // Add availability data if turned on
1888 if ($CFG->enableavailability) {
1889 require_once($CFG->dirroot . '/lib/conditionlib.php');
1890 condition_info_section::fill_availability_conditions($section);
1891 if (count($section->conditionscompletion) == 0) {
1892 unset($section->conditionscompletion);
1894 if (count($section->conditionsgrade) == 0) {
1895 unset($section->conditionsgrade);
1899 // Remove default data
1900 foreach (self::$sectioncachedefaults as $field => $value) {
1901 // Exact compare as strings to avoid problems if some strings are set
1902 // to "0" etc.
1903 if (isset($section->{$field}) && $section->{$field} === $value) {
1904 unset($section->{$field});