MDL-40531 mod_lti: Various 1.1/1.1.1 fixes.
[moodle.git] / lib / modinfolib.php
blob8ff69fb08a545d910043392e95fcad85b079a293
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, $COURSE, $SITE;
247 if (!isset($course->modinfo) || !isset($course->sectioncache)) {
248 $course = get_course($course->id, false);
251 // Check modinfo field is set. If not, build and load it.
252 if (empty($course->modinfo) || empty($course->sectioncache)) {
253 rebuild_course_cache($course->id);
254 $course = $DB->get_record('course', array('id'=>$course->id), '*', MUST_EXIST);
257 // Set initial values
258 $this->courseid = $course->id;
259 $this->userid = $userid;
260 $this->sections = array();
261 $this->cms = array();
262 $this->instances = array();
263 $this->groups = null;
264 $this->course = $course;
266 // Load modinfo field into memory as PHP object and check it's valid
267 $info = unserialize($course->modinfo);
268 if (!is_array($info)) {
269 // hmm, something is wrong - lets try to fix it
270 rebuild_course_cache($course->id);
271 $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
272 $info = unserialize($course->modinfo);
273 if (!is_array($info)) {
274 // If it still fails, abort
275 debugging('Problem with "modinfo" data for this course');
276 return;
280 // Load sectioncache field into memory as PHP object and check it's valid
281 $sectioncache = unserialize($course->sectioncache);
282 if (!is_array($sectioncache)) {
283 // hmm, something is wrong - let's fix it
284 rebuild_course_cache($course->id);
285 $course->sectioncache = $DB->get_field('course', 'sectioncache', array('id'=>$course->id));
286 $sectioncache = unserialize($course->sectioncache);
287 if (!is_array($sectioncache)) {
288 // If it still fails, abort
289 debugging('Problem with "sectioncache" data for this course');
290 return;
294 // If we haven't already preloaded contexts for the course, do it now.
295 // Modules are also cached here as long as it's the first time this course has been preloaded.
296 preload_course_contexts($course->id);
298 // Quick integrity check: as a result of race conditions modinfo may not be regenerated after the change.
299 // It is especially dangerous if modinfo contains the deleted course module, as it results in fatal error.
300 // We can check it very cheap by validating the existence of module context.
301 if ($course->id == $COURSE->id || $course->id == $SITE->id) {
302 // Only verify current course (or frontpage) as pages with many courses may not have module contexts cached.
303 // (Uncached modules will result in a very slow verification).
304 foreach ($info as $mod) {
305 if (!context_module::instance($mod->cm, IGNORE_MISSING)) {
306 debugging('Course cache integrity check failed: course module with id '. $mod->cm.
307 ' does not have context. Rebuilding cache for course '. $course->id);
308 rebuild_course_cache($course->id);
309 $this->course = $DB->get_record('course', array('id' => $course->id), '*', MUST_EXIST);
310 $info = unserialize($this->course->modinfo);
311 $sectioncache = unserialize($this->course->sectioncache);
312 break;
317 // Loop through each piece of module data, constructing it
318 $modexists = array();
319 foreach ($info as $mod) {
320 if (empty($mod->name)) {
321 // something is wrong here
322 continue;
325 // Skip modules which don't exist
326 if (empty($modexists[$mod->mod])) {
327 if (!file_exists("$CFG->dirroot/mod/$mod->mod/lib.php")) {
328 continue;
330 $modexists[$mod->mod] = true;
333 // Construct info for this module
334 $cm = new cm_info($this, $course, $mod, $info);
336 // Store module in instances and cms array
337 if (!isset($this->instances[$cm->modname])) {
338 $this->instances[$cm->modname] = array();
340 $this->instances[$cm->modname][$cm->instance] = $cm;
341 $this->cms[$cm->id] = $cm;
343 // Reconstruct sections. This works because modules are stored in order
344 if (!isset($this->sections[$cm->sectionnum])) {
345 $this->sections[$cm->sectionnum] = array();
347 $this->sections[$cm->sectionnum][] = $cm->id;
350 // Expand section objects
351 $this->sectioninfo = array();
352 foreach ($sectioncache as $number => $data) {
353 // Calculate sequence
354 if (isset($this->sections[$number])) {
355 $sequence = implode(',', $this->sections[$number]);
356 } else {
357 $sequence = '';
359 // Expand
360 $this->sectioninfo[$number] = new section_info($data, $number, $course->id, $sequence,
361 $this, $userid);
364 // We need at least 'dynamic' data from each course-module (this is basically the remaining
365 // data which was always present in previous version of get_fast_modinfo, so it's required
366 // for BC). Creating it in a second pass is necessary because obtain_dynamic_data sometimes
367 // needs to be able to refer to a 'complete' (with basic data) modinfo.
368 foreach ($this->cms as $cm) {
369 $cm->obtain_dynamic_data();
374 * Builds a list of information about sections on a course to be stored in
375 * the course cache. (Does not include information that is already cached
376 * in some other way.)
378 * Used internally by rebuild_course_cache function; do not use otherwise.
379 * @param int $courseid Course ID
380 * @return array Information about sections, indexed by section number (not id)
382 public static function build_section_cache($courseid) {
383 global $DB;
385 // Get section data
386 $sections = $DB->get_records('course_sections', array('course' => $courseid), 'section',
387 'section, id, course, name, summary, summaryformat, sequence, visible, ' .
388 'availablefrom, availableuntil, showavailability, groupingid');
389 $compressedsections = array();
391 $formatoptionsdef = course_get_format($courseid)->section_format_options();
392 // Remove unnecessary data and add availability
393 foreach ($sections as $number => $section) {
394 // Add cached options from course format to $section object
395 foreach ($formatoptionsdef as $key => $option) {
396 if (!empty($option['cache'])) {
397 $formatoptions = course_get_format($courseid)->get_format_options($section);
398 if (!array_key_exists('cachedefault', $option) || $option['cachedefault'] !== $formatoptions[$key]) {
399 $section->$key = $formatoptions[$key];
403 // Clone just in case it is reused elsewhere
404 $compressedsections[$number] = clone($section);
405 section_info::convert_for_section_cache($compressedsections[$number]);
408 return $compressedsections;
414 * Data about a single module on a course. This contains most of the fields in the course_modules
415 * table, plus additional data when required.
417 * This object has many public fields; code should treat all these fields as read-only and set
418 * data only using the supplied set functions. Setting the fields directly is not supported
419 * and may cause problems later.
421 class cm_info extends stdClass {
423 * State: Only basic data from modinfo cache is available.
425 const STATE_BASIC = 0;
428 * State: Dynamic data is available too.
430 const STATE_DYNAMIC = 1;
433 * State: View data (for course page) is available.
435 const STATE_VIEW = 2;
438 * Parent object
439 * @var course_modinfo
441 private $modinfo;
444 * Level of information stored inside this object (STATE_xx constant)
445 * @var int
447 private $state;
449 // Existing data fields
450 ///////////////////////
453 * Course-module ID - from course_modules table
454 * @var int
456 public $id;
459 * Module instance (ID within module table) - from course_modules table
460 * @var int
462 public $instance;
465 * Course ID - from course_modules table
466 * @var int
468 public $course;
471 * 'ID number' from course-modules table (arbitrary text set by user) - from
472 * course_modules table
473 * @var string
475 public $idnumber;
478 * Time that this course-module was added (unix time) - from course_modules table
479 * @var int
481 public $added;
484 * This variable is not used and is included here only so it can be documented.
485 * Once the database entry is removed from course_modules, it should be deleted
486 * here too.
487 * @var int
488 * @deprecated Do not use this variable
490 public $score;
493 * Visible setting (0 or 1; if this is 0, students cannot see/access the activity) - from
494 * course_modules table
495 * @var int
497 public $visible;
500 * Old visible setting (if the entire section is hidden, the previous value for
501 * visible is stored in this field) - from course_modules table
502 * @var int
504 public $visibleold;
507 * Group mode (one of the constants NONE, SEPARATEGROUPS, or VISIBLEGROUPS) - from
508 * course_modules table
509 * @var int
511 public $groupmode;
514 * Grouping ID (0 = all groupings)
515 * @var int
517 public $groupingid;
520 * Group members only (if set to 1, only members of a suitable group see this link on the
521 * course page; 0 = everyone sees it even if they don't belong to a suitable group) - from
522 * course_modules table
523 * @var int
525 public $groupmembersonly;
528 * Indicates whether the course containing the module has forced the groupmode
529 * This means that cm_info::$groupmode should be ignored and cm_info::$coursegroupmode be
530 * used instead
531 * @var bool
533 public $coursegroupmodeforce;
536 * Group mode (one of the constants NONE, SEPARATEGROUPS, or VISIBLEGROUPS) - from
537 * course table - as specified for the course containing the module
538 * Effective only if cm_info::$coursegroupmodeforce is set
539 * @var int
541 public $coursegroupmode;
544 * Indent level on course page (0 = no indent) - from course_modules table
545 * @var int
547 public $indent;
550 * Activity completion setting for this activity, COMPLETION_TRACKING_xx constant - from
551 * course_modules table
552 * @var int
554 public $completion;
557 * Set to the item number (usually 0) if completion depends on a particular
558 * grade of this activity, or null if completion does not depend on a grade - from
559 * course_modules table
560 * @var mixed
562 public $completiongradeitemnumber;
565 * 1 if 'on view' completion is enabled, 0 otherwise - from course_modules table
566 * @var int
568 public $completionview;
571 * Set to a unix time if completion of this activity is expected at a
572 * particular time, 0 if no time set - from course_modules table
573 * @var int
575 public $completionexpected;
578 * Available date for this activity (0 if not set, or set to seconds since epoch; before this
579 * date, activity does not display to students) - from course_modules table
580 * @var int
582 public $availablefrom;
585 * Available until date for this activity (0 if not set, or set to seconds since epoch; from
586 * this date, activity does not display to students) - from course_modules table
587 * @var int
589 public $availableuntil;
592 * When activity is unavailable, this field controls whether it is shown to students (0 =
593 * hide completely, 1 = show greyed out with information about when it will be available) -
594 * from course_modules table
595 * @var int
597 public $showavailability;
600 * Controls whether the description of the activity displays on the course main page (in
601 * addition to anywhere it might display within the activity itself). 0 = do not show
602 * on main page, 1 = show on main page.
603 * @var int
605 public $showdescription;
608 * Extra HTML that is put in an unhelpful part of the HTML when displaying this module in
609 * course page - from cached data in modinfo field
610 * @deprecated This is crazy, don't use it. Replaced by ->extraclasses and ->onclick
611 * @var string
613 public $extra;
616 * Name of icon to use - from cached data in modinfo field
617 * @var string
619 public $icon;
622 * Component that contains icon - from cached data in modinfo field
623 * @var string
625 public $iconcomponent;
628 * Name of module e.g. 'forum' (this is the same name as the module's main database
629 * table) - from cached data in modinfo field
630 * @var string
632 public $modname;
635 * ID of module - from course_modules table
636 * @var int
638 public $module;
641 * Name of module instance for display on page e.g. 'General discussion forum' - from cached
642 * data in modinfo field
643 * @var string
645 public $name;
648 * Section number that this course-module is in (section 0 = above the calendar, section 1
649 * = week/topic 1, etc) - from cached data in modinfo field
650 * @var string
652 public $sectionnum;
655 * Section id - from course_modules table
656 * @var int
658 public $section;
661 * Availability conditions for this course-module based on the completion of other
662 * course-modules (array from other course-module id to required completion state for that
663 * module) - from cached data in modinfo field
664 * @var array
666 public $conditionscompletion;
669 * Availability conditions for this course-module based on course grades (array from
670 * grade item id to object with ->min, ->max fields) - from cached data in modinfo field
671 * @var array
673 public $conditionsgrade;
676 * Availability conditions for this course-module based on user fields
677 * @var array
679 public $conditionsfield;
682 * True if this course-module is available to students i.e. if all availability conditions
683 * are met - obtained dynamically
684 * @var bool
686 public $available;
689 * If course-module is not available to students, this string gives information about
690 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
691 * January 2010') for display on main page - obtained dynamically
692 * @var string
694 public $availableinfo;
697 * True if this course-module is available to the CURRENT user (for example, if current user
698 * has viewhiddenactivities capability, they can access the course-module even if it is not
699 * visible or not available, so this would be true in that case)
700 * @var bool
702 public $uservisible;
705 * Module context - hacky shortcut
706 * @deprecated
707 * @var stdClass
709 public $context;
712 // New data available only via functions
713 ////////////////////////////////////////
716 * @var moodle_url
718 private $url;
721 * @var string
723 private $content;
726 * @var string
728 private $extraclasses;
731 * @var moodle_url full external url pointing to icon image for activity
733 private $iconurl;
736 * @var string
738 private $onclick;
741 * @var mixed
743 private $customdata;
746 * @var string
748 private $afterlink;
751 * @var string
753 private $afterediticons;
756 * Magic method getter
758 * @param string $name
759 * @return mixed
761 public function __get($name) {
762 switch ($name) {
763 case 'modplural':
764 return $this->get_module_type_name(true);
765 case 'modfullname':
766 return $this->get_module_type_name();
767 default:
768 debugging('Invalid cm_info property accessed: '.$name);
769 return null;
774 * @return bool True if this module has a 'view' page that should be linked to in navigation
775 * etc (note: modules may still have a view.php file, but return false if this is not
776 * intended to be linked to from 'normal' parts of the interface; this is what label does).
778 public function has_view() {
779 return !is_null($this->url);
783 * @return moodle_url URL to link to for this module, or null if it doesn't have a view page
785 public function get_url() {
786 return $this->url;
790 * Obtains content to display on main (view) page.
791 * Note: Will collect view data, if not already obtained.
792 * @return string Content to display on main page below link, or empty string if none
794 public function get_content() {
795 $this->obtain_view_data();
796 return $this->content;
800 * Returns the content to display on course/overview page, formatted and passed through filters
802 * if $options['context'] is not specified, the module context is used
804 * @param array|stdClass $options formatting options, see {@link format_text()}
805 * @return string
807 public function get_formatted_content($options = array()) {
808 $this->obtain_view_data();
809 if (empty($this->content)) {
810 return '';
812 // Improve filter performance by preloading filter setttings for all
813 // activities on the course (this does nothing if called multiple
814 // times)
815 filter_preload_activities($this->get_modinfo());
817 $options = (array)$options;
818 if (!isset($options['context'])) {
819 $options['context'] = context_module::instance($this->id);
821 return format_text($this->content, FORMAT_HTML, $options);
825 * Returns the name to display on course/overview page, formatted and passed through filters
827 * if $options['context'] is not specified, the module context is used
829 * @param array|stdClass $options formatting options, see {@link format_string()}
830 * @return string
832 public function get_formatted_name($options = array()) {
833 $options = (array)$options;
834 if (!isset($options['context'])) {
835 $options['context'] = context_module::instance($this->id);
837 return format_string($this->name, true, $options);
841 * Note: Will collect view data, if not already obtained.
842 * @return string Extra CSS classes to add to html output for this activity on main page
844 public function get_extra_classes() {
845 $this->obtain_view_data();
846 return $this->extraclasses;
850 * @return string Content of HTML on-click attribute. This string will be used literally
851 * as a string so should be pre-escaped.
853 public function get_on_click() {
854 // Does not need view data; may be used by navigation
855 return $this->onclick;
858 * @return mixed Optional custom data stored in modinfo cache for this activity, or null if none
860 public function get_custom_data() {
861 return $this->customdata;
865 * Note: Will collect view data, if not already obtained.
866 * @return string Extra HTML code to display after link
868 public function get_after_link() {
869 $this->obtain_view_data();
870 return $this->afterlink;
874 * Note: Will collect view data, if not already obtained.
875 * @return string Extra HTML code to display after editing icons (e.g. more icons)
877 public function get_after_edit_icons() {
878 $this->obtain_view_data();
879 return $this->afterediticons;
883 * @param moodle_core_renderer $output Output render to use, or null for default (global)
884 * @return moodle_url Icon URL for a suitable icon to put beside this cm
886 public function get_icon_url($output = null) {
887 global $OUTPUT;
888 if (!$output) {
889 $output = $OUTPUT;
891 // Support modules setting their own, external, icon image
892 if (!empty($this->iconurl)) {
893 $icon = $this->iconurl;
895 // Fallback to normal local icon + component procesing
896 } else if (!empty($this->icon)) {
897 if (substr($this->icon, 0, 4) === 'mod/') {
898 list($modname, $iconname) = explode('/', substr($this->icon, 4), 2);
899 $icon = $output->pix_url($iconname, $modname);
900 } else {
901 if (!empty($this->iconcomponent)) {
902 // Icon has specified component
903 $icon = $output->pix_url($this->icon, $this->iconcomponent);
904 } else {
905 // Icon does not have specified component, use default
906 $icon = $output->pix_url($this->icon);
909 } else {
910 $icon = $output->pix_url('icon', $this->modname);
912 return $icon;
916 * Returns a localised human-readable name of the module type
918 * @param bool $plural return plural form
919 * @return string
921 public function get_module_type_name($plural = false) {
922 $modnames = get_module_types_names($plural);
923 if (isset($modnames[$this->modname])) {
924 return $modnames[$this->modname];
925 } else {
926 return null;
931 * @return course_modinfo Modinfo object that this came from
933 public function get_modinfo() {
934 return $this->modinfo;
938 * @return object Moodle course object that was used to construct this data
940 public function get_course() {
941 return $this->modinfo->get_course();
944 // Set functions
945 ////////////////
948 * Sets content to display on course view page below link (if present).
949 * @param string $content New content as HTML string (empty string if none)
950 * @return void
952 public function set_content($content) {
953 $this->content = $content;
957 * Sets extra classes to include in CSS.
958 * @param string $extraclasses Extra classes (empty string if none)
959 * @return void
961 public function set_extra_classes($extraclasses) {
962 $this->extraclasses = $extraclasses;
966 * Sets the external full url that points to the icon being used
967 * by the activity. Useful for external-tool modules (lti...)
968 * If set, takes precedence over $icon and $iconcomponent
970 * @param moodle_url $iconurl full external url pointing to icon image for activity
971 * @return void
973 public function set_icon_url(moodle_url $iconurl) {
974 $this->iconurl = $iconurl;
978 * Sets value of on-click attribute for JavaScript.
979 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
980 * @param string $onclick New onclick attribute which should be HTML-escaped
981 * (empty string if none)
982 * @return void
984 public function set_on_click($onclick) {
985 $this->check_not_view_only();
986 $this->onclick = $onclick;
990 * Sets HTML that displays after link on course view page.
991 * @param string $afterlink HTML string (empty string if none)
992 * @return void
994 public function set_after_link($afterlink) {
995 $this->afterlink = $afterlink;
999 * Sets HTML that displays after edit icons on course view page.
1000 * @param string $afterediticons HTML string (empty string if none)
1001 * @return void
1003 public function set_after_edit_icons($afterediticons) {
1004 $this->afterediticons = $afterediticons;
1008 * Changes the name (text of link) for this module instance.
1009 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1010 * @param string $name Name of activity / link text
1011 * @return void
1013 public function set_name($name) {
1014 $this->update_user_visible();
1015 $this->name = $name;
1019 * Turns off the view link for this module instance.
1020 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1021 * @return void
1023 public function set_no_view_link() {
1024 $this->check_not_view_only();
1025 $this->url = null;
1029 * Sets the 'uservisible' flag. This can be used (by setting false) to prevent access and
1030 * display of this module link for the current user.
1031 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1032 * @param bool $uservisible
1033 * @return void
1035 public function set_user_visible($uservisible) {
1036 $this->check_not_view_only();
1037 $this->uservisible = $uservisible;
1041 * Sets the 'available' flag and related details. This flag is normally used to make
1042 * course modules unavailable until a certain date or condition is met. (When a course
1043 * module is unavailable, it is still visible to users who have viewhiddenactivities
1044 * permission.)
1046 * When this is function is called, user-visible status is recalculated automatically.
1048 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1049 * @param bool $available False if this item is not 'available'
1050 * @param int $showavailability 0 = do not show this item at all if it's not available,
1051 * 1 = show this item greyed out with the following message
1052 * @param string $availableinfo Information about why this is not available which displays
1053 * to those who have viewhiddenactivities, and to everyone if showavailability is set;
1054 * note that this function replaces the existing data (if any)
1055 * @return void
1057 public function set_available($available, $showavailability=0, $availableinfo='') {
1058 $this->check_not_view_only();
1059 $this->available = $available;
1060 $this->showavailability = $showavailability;
1061 $this->availableinfo = $availableinfo;
1062 $this->update_user_visible();
1066 * Some set functions can only be called from _cm_info_dynamic and not _cm_info_view.
1067 * This is because they may affect parts of this object which are used on pages other
1068 * than the view page (e.g. in the navigation block, or when checking access on
1069 * module pages).
1070 * @return void
1072 private function check_not_view_only() {
1073 if ($this->state >= self::STATE_DYNAMIC) {
1074 throw new coding_exception('Cannot set this data from _cm_info_view because it may ' .
1075 'affect other pages as well as view');
1080 * Constructor should not be called directly; use get_fast_modinfo.
1081 * @param course_modinfo $modinfo Parent object
1082 * @param object $course Course row
1083 * @param object $mod Module object from the modinfo field of course table
1084 * @param object $info Entire object from modinfo field of course table
1086 public function __construct(course_modinfo $modinfo, $course, $mod, $info) {
1087 global $CFG;
1088 $this->modinfo = $modinfo;
1090 $this->id = $mod->cm;
1091 $this->instance = $mod->id;
1092 $this->course = $course->id;
1093 $this->modname = $mod->mod;
1094 $this->idnumber = isset($mod->idnumber) ? $mod->idnumber : '';
1095 $this->name = $mod->name;
1096 $this->visible = $mod->visible;
1097 $this->sectionnum = $mod->section; // Note weirdness with name here
1098 $this->groupmode = isset($mod->groupmode) ? $mod->groupmode : 0;
1099 $this->groupingid = isset($mod->groupingid) ? $mod->groupingid : 0;
1100 $this->groupmembersonly = isset($mod->groupmembersonly) ? $mod->groupmembersonly : 0;
1101 $this->coursegroupmodeforce = $course->groupmodeforce;
1102 $this->coursegroupmode = $course->groupmode;
1103 $this->indent = isset($mod->indent) ? $mod->indent : 0;
1104 $this->extra = isset($mod->extra) ? $mod->extra : '';
1105 $this->extraclasses = isset($mod->extraclasses) ? $mod->extraclasses : '';
1106 // iconurl may be stored as either string or instance of moodle_url.
1107 $this->iconurl = isset($mod->iconurl) ? new moodle_url($mod->iconurl) : '';
1108 $this->onclick = isset($mod->onclick) ? $mod->onclick : '';
1109 $this->content = isset($mod->content) ? $mod->content : '';
1110 $this->icon = isset($mod->icon) ? $mod->icon : '';
1111 $this->iconcomponent = isset($mod->iconcomponent) ? $mod->iconcomponent : '';
1112 $this->customdata = isset($mod->customdata) ? $mod->customdata : '';
1113 $this->context = context_module::instance($mod->cm);
1114 $this->showdescription = isset($mod->showdescription) ? $mod->showdescription : 0;
1115 $this->state = self::STATE_BASIC;
1117 // Note: These fields from $cm were not present in cm_info in Moodle
1118 // 2.0.2 and prior. They may not be available if course cache hasn't
1119 // been rebuilt since then.
1120 $this->section = isset($mod->sectionid) ? $mod->sectionid : 0;
1121 $this->module = isset($mod->module) ? $mod->module : 0;
1122 $this->added = isset($mod->added) ? $mod->added : 0;
1123 $this->score = isset($mod->score) ? $mod->score : 0;
1124 $this->visibleold = isset($mod->visibleold) ? $mod->visibleold : 0;
1126 // Note: it saves effort and database space to always include the
1127 // availability and completion fields, even if availability or completion
1128 // are actually disabled
1129 $this->completion = isset($mod->completion) ? $mod->completion : 0;
1130 $this->completiongradeitemnumber = isset($mod->completiongradeitemnumber)
1131 ? $mod->completiongradeitemnumber : null;
1132 $this->completionview = isset($mod->completionview)
1133 ? $mod->completionview : 0;
1134 $this->completionexpected = isset($mod->completionexpected)
1135 ? $mod->completionexpected : 0;
1136 $this->showavailability = isset($mod->showavailability) ? $mod->showavailability : 0;
1137 $this->availablefrom = isset($mod->availablefrom) ? $mod->availablefrom : 0;
1138 $this->availableuntil = isset($mod->availableuntil) ? $mod->availableuntil : 0;
1139 $this->conditionscompletion = isset($mod->conditionscompletion)
1140 ? $mod->conditionscompletion : array();
1141 $this->conditionsgrade = isset($mod->conditionsgrade)
1142 ? $mod->conditionsgrade : array();
1143 $this->conditionsfield = isset($mod->conditionsfield)
1144 ? $mod->conditionsfield : array();
1146 static $modviews;
1147 if (!isset($modviews[$this->modname])) {
1148 $modviews[$this->modname] = !plugin_supports('mod', $this->modname,
1149 FEATURE_NO_VIEW_LINK);
1151 $this->url = $modviews[$this->modname]
1152 ? new moodle_url('/mod/' . $this->modname . '/view.php', array('id'=>$this->id))
1153 : null;
1157 * If dynamic data for this course-module is not yet available, gets it.
1159 * This function is automatically called when constructing course_modinfo, so users don't
1160 * need to call it.
1162 * Dynamic data is data which does not come directly from the cache but is calculated at
1163 * runtime based on the current user. Primarily this concerns whether the user can access
1164 * the module or not.
1166 * As part of this function, the module's _cm_info_dynamic function from its lib.php will
1167 * be called (if it exists).
1168 * @return void
1170 public function obtain_dynamic_data() {
1171 global $CFG;
1172 if ($this->state >= self::STATE_DYNAMIC) {
1173 return;
1175 $userid = $this->modinfo->get_user_id();
1177 if (!empty($CFG->enableavailability)) {
1178 // Get availability information
1179 $ci = new condition_info($this);
1180 // Note that the modinfo currently available only includes minimal details (basic data)
1181 // so passing it to this function is a bit dangerous as it would cause infinite
1182 // recursion if it tried to get dynamic data, however we know that this function only
1183 // uses basic data.
1184 $this->available = $ci->is_available($this->availableinfo, true,
1185 $userid, $this->modinfo);
1187 // Check parent section
1188 $parentsection = $this->modinfo->get_section_info($this->sectionnum);
1189 if (!$parentsection->available) {
1190 // Do not store info from section here, as that is already
1191 // presented from the section (if appropriate) - just change
1192 // the flag
1193 $this->available = false;
1195 } else {
1196 $this->available = true;
1199 // Update visible state for current user
1200 $this->update_user_visible();
1202 // Let module make dynamic changes at this point
1203 $this->call_mod_function('cm_info_dynamic');
1204 $this->state = self::STATE_DYNAMIC;
1208 * Works out whether activity is available to the current user
1210 * If the activity is unavailable, additional checks are required to determine if its hidden or greyed out
1212 * @see is_user_access_restricted_by_group()
1213 * @see is_user_access_restricted_by_conditional_access()
1214 * @return void
1216 private function update_user_visible() {
1217 global $CFG;
1218 $modcontext = context_module::instance($this->id);
1219 $userid = $this->modinfo->get_user_id();
1220 $this->uservisible = true;
1222 // If the user cannot access the activity set the uservisible flag to false.
1223 // Additional checks are required to determine whether the activity is entirely hidden or just greyed out.
1224 if ((!$this->visible or !$this->available) and
1225 !has_capability('moodle/course:viewhiddenactivities', $modcontext, $userid)) {
1227 $this->uservisible = false;
1230 // Check group membership.
1231 if ($this->is_user_access_restricted_by_group() ||
1232 $this->is_user_access_restricted_by_capability()) {
1234 $this->uservisible = false;
1235 // Ensure activity is completely hidden from the user.
1236 $this->showavailability = 0;
1241 * Checks whether the module's group settings restrict the current user's access
1243 * @return bool True if the user access is restricted
1245 public function is_user_access_restricted_by_group() {
1246 global $CFG;
1248 if (!empty($CFG->enablegroupmembersonly) and !empty($this->groupmembersonly)) {
1249 $modcontext = context_module::instance($this->id);
1250 $userid = $this->modinfo->get_user_id();
1251 if (!has_capability('moodle/site:accessallgroups', $modcontext, $userid)) {
1252 // If the activity has 'group members only' and you don't have accessallgroups...
1253 $groups = $this->modinfo->get_groups($this->groupingid);
1254 if (empty($groups)) {
1255 // ...and you don't belong to a group, then set it so you can't see/access it
1256 return true;
1260 return false;
1264 * Checks whether mod/...:view capability restricts the current user's access.
1266 * @return bool True if the user access is restricted.
1268 public function is_user_access_restricted_by_capability() {
1269 $capability = 'mod/' . $this->modname . ':view';
1270 $capabilityinfo = get_capability_info($capability);
1271 if (!$capabilityinfo) {
1272 // Capability does not exist, no one is prevented from seeing the activity.
1273 return false;
1276 // You are blocked if you don't have the capability.
1277 $userid = $this->modinfo->get_user_id();
1278 return !has_capability($capability, context_module::instance($this->id), $userid);
1282 * Checks whether the module's conditional access settings mean that the user cannot see the activity at all
1284 * @return bool True if the user cannot see the module. False if the activity is either available or should be greyed out.
1286 public function is_user_access_restricted_by_conditional_access() {
1287 global $CFG;
1289 if (empty($CFG->enableavailability)) {
1290 return false;
1293 // If module will always be visible anyway (but greyed out), don't bother checking anything else
1294 if ($this->showavailability == CONDITION_STUDENTVIEW_SHOW) {
1295 return false;
1298 // Can the user see hidden modules?
1299 $modcontext = context_module::instance($this->id);
1300 $userid = $this->modinfo->get_user_id();
1301 if (has_capability('moodle/course:viewhiddenactivities', $modcontext, $userid)) {
1302 return false;
1305 // Is the module hidden due to unmet conditions?
1306 if (!$this->available) {
1307 return true;
1310 return false;
1314 * Calls a module function (if exists), passing in one parameter: this object.
1315 * @param string $type Name of function e.g. if this is 'grooblezorb' and the modname is
1316 * 'forum' then it will try to call 'mod_forum_grooblezorb' or 'forum_grooblezorb'
1317 * @return void
1319 private function call_mod_function($type) {
1320 global $CFG;
1321 $libfile = $CFG->dirroot . '/mod/' . $this->modname . '/lib.php';
1322 if (file_exists($libfile)) {
1323 include_once($libfile);
1324 $function = 'mod_' . $this->modname . '_' . $type;
1325 if (function_exists($function)) {
1326 $function($this);
1327 } else {
1328 $function = $this->modname . '_' . $type;
1329 if (function_exists($function)) {
1330 $function($this);
1337 * If view data for this course-module is not yet available, obtains it.
1339 * This function is automatically called if any of the functions (marked) which require
1340 * view data are called.
1342 * View data is data which is needed only for displaying the course main page (& any similar
1343 * functionality on other pages) but is not needed in general. Obtaining view data may have
1344 * a performance cost.
1346 * As part of this function, the module's _cm_info_view function from its lib.php will
1347 * be called (if it exists).
1348 * @return void
1350 private function obtain_view_data() {
1351 if ($this->state >= self::STATE_VIEW) {
1352 return;
1355 // Let module make changes at this point
1356 $this->call_mod_function('cm_info_view');
1357 $this->state = self::STATE_VIEW;
1363 * Returns reference to full info about modules in course (including visibility).
1364 * Cached and as fast as possible (0 or 1 db query).
1366 * use get_fast_modinfo($courseid, 0, true) to reset the static cache for particular course
1367 * use get_fast_modinfo(0, 0, true) to reset the static cache for all courses
1369 * @uses MAX_MODINFO_CACHE_SIZE
1370 * @param int|stdClass $courseorid object from DB table 'course' or just a course id
1371 * @param int $userid User id to populate 'uservisible' attributes of modules and sections.
1372 * Set to 0 for current user (default)
1373 * @param bool $resetonly whether we want to get modinfo or just reset the cache
1374 * @return course_modinfo|null Module information for course, or null if resetting
1376 function get_fast_modinfo($courseorid, $userid = 0, $resetonly = false) {
1377 global $CFG, $USER;
1379 static $cache = array();
1381 // compartibility with syntax prior to 2.4:
1382 if ($courseorid === 'reset') {
1383 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);
1384 $courseorid = 0;
1385 $resetonly = true;
1388 // Function get_fast_modinfo() can never be called during upgrade unless it is used for clearing cache only.
1389 if (!$resetonly) {
1390 upgrade_ensure_not_running();
1393 if (is_object($courseorid)) {
1394 $course = $courseorid;
1395 } else {
1396 $course = (object)array('id' => $courseorid);
1399 // Function is called with $reset = true
1400 if ($resetonly) {
1401 if (isset($course->id) && $course->id > 0) {
1402 $cache[$course->id] = false;
1403 } else {
1404 foreach (array_keys($cache) as $key) {
1405 $cache[$key] = false;
1408 return null;
1411 // Function is called with $reset = false, retrieve modinfo
1412 if (empty($userid)) {
1413 $userid = $USER->id;
1416 if (array_key_exists($course->id, $cache)) {
1417 if ($cache[$course->id] === false) {
1418 // this course has been recently reset, do not rely on modinfo and sectioncache in $course
1419 $course->modinfo = null;
1420 $course->sectioncache = null;
1421 } else if ($cache[$course->id]->userid == $userid) {
1422 // this course's modinfo for the same user was recently retrieved, return cached
1423 return $cache[$course->id];
1427 unset($cache[$course->id]); // prevent potential reference problems when switching users
1429 $cache[$course->id] = new course_modinfo($course, $userid);
1431 // Ensure cache does not use too much RAM
1432 if (count($cache) > MAX_MODINFO_CACHE_SIZE) {
1433 reset($cache);
1434 $key = key($cache);
1435 // Unsetting static variable in PHP is percular, it removes the reference,
1436 // but data remain in memory. Prior to unsetting, the varable needs to be
1437 // set to empty to remove its remains from memory.
1438 $cache[$key] = '';
1439 unset($cache[$key]);
1442 return $cache[$course->id];
1446 * Rebuilds the cached list of course activities stored in the database
1447 * @param int $courseid - id of course to rebuild, empty means all
1448 * @param boolean $clearonly - only clear the modinfo fields, gets rebuild automatically on the fly
1450 function rebuild_course_cache($courseid=0, $clearonly=false) {
1451 global $COURSE, $SITE, $DB, $CFG;
1453 // Function rebuild_course_cache() can not be called during upgrade unless it's clear only.
1454 if (!$clearonly && !upgrade_ensure_not_running(true)) {
1455 $clearonly = true;
1458 // Destroy navigation caches
1459 navigation_cache::destroy_volatile_caches();
1461 if (class_exists('format_base')) {
1462 // if file containing class is not loaded, there is no cache there anyway
1463 format_base::reset_course_cache($courseid);
1466 if ($clearonly) {
1467 if (empty($courseid)) {
1468 $DB->execute('UPDATE {course} set modinfo = ?, sectioncache = ?', array(null, null));
1469 } else {
1470 // Clear both fields in one update
1471 $resetobj = (object)array('id' => $courseid, 'modinfo' => null, 'sectioncache' => null);
1472 $DB->update_record('course', $resetobj);
1474 // update cached global COURSE too ;-)
1475 if ($courseid == $COURSE->id or empty($courseid)) {
1476 $COURSE->modinfo = null;
1477 $COURSE->sectioncache = null;
1479 if ($courseid == $SITE->id) {
1480 $SITE->modinfo = null;
1481 $SITE->sectioncache = null;
1483 // reset the fast modinfo cache
1484 get_fast_modinfo($courseid, 0, true);
1485 return;
1488 require_once("$CFG->dirroot/course/lib.php");
1490 if ($courseid) {
1491 $select = array('id'=>$courseid);
1492 } else {
1493 $select = array();
1494 @set_time_limit(0); // this could take a while! MDL-10954
1497 $rs = $DB->get_recordset("course", $select,'','id,fullname');
1498 foreach ($rs as $course) {
1499 $modinfo = serialize(get_array_of_activities($course->id));
1500 $sectioncache = serialize(course_modinfo::build_section_cache($course->id));
1501 $updateobj = (object)array('id' => $course->id,
1502 'modinfo' => $modinfo, 'sectioncache' => $sectioncache);
1503 $DB->update_record("course", $updateobj);
1504 // update cached global COURSE too ;-)
1505 if ($course->id == $COURSE->id) {
1506 $COURSE->modinfo = $modinfo;
1507 $COURSE->sectioncache = $sectioncache;
1509 if ($course->id == $SITE->id) {
1510 $SITE->modinfo = $modinfo;
1511 $SITE->sectioncache = $sectioncache;
1514 $rs->close();
1515 // reset the fast modinfo cache
1516 get_fast_modinfo($courseid, 0, true);
1521 * Class that is the return value for the _get_coursemodule_info module API function.
1523 * Note: For backward compatibility, you can also return a stdclass object from that function.
1524 * The difference is that the stdclass object may contain an 'extra' field (deprecated,
1525 * use extraclasses and onclick instead). The stdclass object may not contain
1526 * the new fields defined here (content, extraclasses, customdata).
1528 class cached_cm_info {
1530 * Name (text of link) for this activity; Leave unset to accept default name
1531 * @var string
1533 public $name;
1536 * Name of icon for this activity. Normally, this should be used together with $iconcomponent
1537 * to define the icon, as per pix_url function.
1538 * For backward compatibility, if this value is of the form 'mod/forum/icon' then an icon
1539 * within that module will be used.
1540 * @see cm_info::get_icon_url()
1541 * @see renderer_base::pix_url()
1542 * @var string
1544 public $icon;
1547 * Component for icon for this activity, as per pix_url; leave blank to use default 'moodle'
1548 * component
1549 * @see renderer_base::pix_url()
1550 * @var string
1552 public $iconcomponent;
1555 * HTML content to be displayed on the main page below the link (if any) for this course-module
1556 * @var string
1558 public $content;
1561 * Custom data to be stored in modinfo for this activity; useful if there are cases when
1562 * internal information for this activity type needs to be accessible from elsewhere on the
1563 * course without making database queries. May be of any type but should be short.
1564 * @var mixed
1566 public $customdata;
1569 * Extra CSS class or classes to be added when this activity is displayed on the main page;
1570 * space-separated string
1571 * @var string
1573 public $extraclasses;
1576 * External URL image to be used by activity as icon, useful for some external-tool modules
1577 * like lti. If set, takes precedence over $icon and $iconcomponent
1578 * @var $moodle_url
1580 public $iconurl;
1583 * Content of onclick JavaScript; escaped HTML to be inserted as attribute value
1584 * @var string
1586 public $onclick;
1591 * Data about a single section on a course. This contains the fields from the
1592 * course_sections table, plus additional data when required.
1594 class section_info implements IteratorAggregate {
1596 * Section ID - from course_sections table
1597 * @var int
1599 private $_id;
1602 * Course ID - from course_sections table
1603 * @var int
1605 private $_course;
1608 * Section number - from course_sections table
1609 * @var int
1611 private $_section;
1614 * Section name if specified - from course_sections table
1615 * @var string
1617 private $_name;
1620 * Section visibility (1 = visible) - from course_sections table
1621 * @var int
1623 private $_visible;
1626 * Section summary text if specified - from course_sections table
1627 * @var string
1629 private $_summary;
1632 * Section summary text format (FORMAT_xx constant) - from course_sections table
1633 * @var int
1635 private $_summaryformat;
1638 * When section is unavailable, this field controls whether it is shown to students (0 =
1639 * hide completely, 1 = show greyed out with information about when it will be available) -
1640 * from course_sections table
1641 * @var int
1643 private $_showavailability;
1646 * Available date for this section (0 if not set, or set to seconds since epoch; before this
1647 * date, section does not display to students) - from course_sections table
1648 * @var int
1650 private $_availablefrom;
1653 * Available until date for this section (0 if not set, or set to seconds since epoch; from
1654 * this date, section does not display to students) - from course_sections table
1655 * @var int
1657 private $_availableuntil;
1660 * If section is restricted to users of a particular grouping, this is its id
1661 * (0 if not set) - from course_sections table
1662 * @var int
1664 private $_groupingid;
1667 * Availability conditions for this section based on the completion of
1668 * course-modules (array from course-module id to required completion state
1669 * for that module) - from cached data in sectioncache field
1670 * @var array
1672 private $_conditionscompletion;
1675 * Availability conditions for this section based on course grades (array from
1676 * grade item id to object with ->min, ->max fields) - from cached data in
1677 * sectioncache field
1678 * @var array
1680 private $_conditionsgrade;
1683 * Availability conditions for this section based on user fields
1684 * @var array
1686 private $_conditionsfield;
1689 * True if this section is available to students i.e. if all availability conditions
1690 * are met - obtained dynamically
1691 * @var bool
1693 private $_available;
1696 * If section is not available to students, this string gives information about
1697 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
1698 * January 2010') for display on main page - obtained dynamically
1699 * @var string
1701 private $_availableinfo;
1704 * True if this section is available to the CURRENT user (for example, if current user
1705 * has viewhiddensections capability, they can access the section even if it is not
1706 * visible or not available, so this would be true in that case)
1707 * @var bool
1709 private $_uservisible;
1712 * Default values for sectioncache fields; if a field has this value, it won't
1713 * be stored in the sectioncache cache, to save space. Checks are done by ===
1714 * which means values must all be strings.
1715 * @var array
1717 private static $sectioncachedefaults = array(
1718 'name' => null,
1719 'summary' => '',
1720 'summaryformat' => '1', // FORMAT_HTML, but must be a string
1721 'visible' => '1',
1722 'showavailability' => '0',
1723 'availablefrom' => '0',
1724 'availableuntil' => '0',
1725 'groupingid' => '0',
1729 * Stores format options that have been cached when building 'coursecache'
1730 * When the format option is requested we look first if it has been cached
1731 * @var array
1733 private $cachedformatoptions = array();
1736 * Constructs object from database information plus extra required data.
1737 * @param object $data Array entry from cached sectioncache
1738 * @param int $number Section number (array key)
1739 * @param int $courseid Course ID
1740 * @param int $sequence Sequence of course-module ids contained within
1741 * @param course_modinfo $modinfo Owner (needed for checking availability)
1742 * @param int $userid User ID
1744 public function __construct($data, $number, $courseid, $sequence, $modinfo, $userid) {
1745 global $CFG;
1746 require_once($CFG->dirroot.'/course/lib.php');
1748 // Data that is always present
1749 $this->_id = $data->id;
1751 $defaults = self::$sectioncachedefaults +
1752 array('conditionscompletion' => array(),
1753 'conditionsgrade' => array(),
1754 'conditionsfield' => array());
1756 // Data that may use default values to save cache size
1757 foreach ($defaults as $field => $value) {
1758 if (isset($data->{$field})) {
1759 $this->{'_'.$field} = $data->{$field};
1760 } else {
1761 $this->{'_'.$field} = $value;
1765 // cached course format data
1766 $formatoptionsdef = course_get_format($courseid)->section_format_options();
1767 foreach ($formatoptionsdef as $field => $option) {
1768 if (!empty($option['cache'])) {
1769 if (isset($data->{$field})) {
1770 $this->cachedformatoptions[$field] = $data->{$field};
1771 } else if (array_key_exists('cachedefault', $option)) {
1772 $this->cachedformatoptions[$field] = $option['cachedefault'];
1777 // Other data from other places
1778 $this->_course = $courseid;
1779 $this->_section = $number;
1780 $this->_sequence = $sequence;
1782 // Availability data
1783 if (!empty($CFG->enableavailability)) {
1784 require_once($CFG->libdir. '/conditionlib.php');
1785 // Get availability information
1786 $ci = new condition_info_section($this);
1787 $this->_available = $ci->is_available($this->_availableinfo, true,
1788 $userid, $modinfo);
1789 // Display grouping info if available & not already displaying
1790 // (it would already display if current user doesn't have access)
1791 // for people with managegroups - same logic/class as grouping label
1792 // on individual activities.
1793 $context = context_course::instance($courseid);
1794 if ($this->_availableinfo === '' && $this->_groupingid &&
1795 has_capability('moodle/course:managegroups', $context)) {
1796 $groupings = groups_get_all_groupings($courseid);
1797 $this->_availableinfo = html_writer::tag('span', '(' . format_string(
1798 $groupings[$this->_groupingid]->name, true, array('context' => $context)) .
1799 ')', array('class' => 'groupinglabel'));
1801 } else {
1802 $this->_available = true;
1805 // Update visibility for current user
1806 $this->update_user_visible($userid);
1810 * Magic method to check if the property is set
1812 * @param string $name name of the property
1813 * @return bool
1815 public function __isset($name) {
1816 if (property_exists($this, '_'.$name)) {
1817 return isset($this->{'_'.$name});
1819 $defaultformatoptions = course_get_format($this->_course)->section_format_options();
1820 if (array_key_exists($name, $defaultformatoptions)) {
1821 $value = $this->__get($name);
1822 return isset($value);
1824 return false;
1828 * Magic method to check if the property is empty
1830 * @param string $name name of the property
1831 * @return bool
1833 public function __empty($name) {
1834 if (property_exists($this, '_'.$name)) {
1835 return empty($this->{'_'.$name});
1837 $defaultformatoptions = course_get_format($this->_course)->section_format_options();
1838 if (array_key_exists($name, $defaultformatoptions)) {
1839 $value = $this->__get($name);
1840 return empty($value);
1842 return true;
1846 * Magic method to retrieve the property, this is either basic section property
1847 * or availability information or additional properties added by course format
1849 * @param string $name name of the property
1850 * @return bool
1852 public function __get($name) {
1853 if (property_exists($this, '_'.$name)) {
1854 return $this->{'_'.$name};
1856 if (array_key_exists($name, $this->cachedformatoptions)) {
1857 return $this->cachedformatoptions[$name];
1859 $defaultformatoptions = course_get_format($this->_course)->section_format_options();
1860 // precheck if the option is defined in format to avoid unnecessary DB queries in get_format_options()
1861 if (array_key_exists($name, $defaultformatoptions)) {
1862 $formatoptions = course_get_format($this->_course)->get_format_options($this);
1863 return $formatoptions[$name];
1865 debugging('Invalid section_info property accessed! '.$name);
1866 return null;
1870 * Implementation of IteratorAggregate::getIterator(), allows to cycle through properties
1871 * and use {@link convert_to_array()}
1873 * @return ArrayIterator
1875 public function getIterator() {
1876 $ret = array();
1877 foreach (get_object_vars($this) as $key => $value) {
1878 if (substr($key, 0, 1) == '_') {
1879 $ret[substr($key, 1)] = $this->$key;
1882 $ret = array_merge($ret, course_get_format($this->_course)->get_format_options($this));
1883 return new ArrayIterator($ret);
1887 * Works out whether activity is visible *for current user* - if this is false, they
1888 * aren't allowed to access it.
1889 * @param int $userid User ID
1890 * @return void
1892 private function update_user_visible($userid) {
1893 global $CFG;
1894 $coursecontext = context_course::instance($this->_course);
1895 $this->_uservisible = true;
1896 if ((!$this->_visible || !$this->_available) &&
1897 !has_capability('moodle/course:viewhiddensections', $coursecontext, $userid)) {
1898 $this->_uservisible = false;
1903 * Prepares section data for inclusion in sectioncache cache, removing items
1904 * that are set to defaults, and adding availability data if required.
1906 * Called by build_section_cache in course_modinfo only; do not use otherwise.
1907 * @param object $section Raw section data object
1909 public static function convert_for_section_cache($section) {
1910 global $CFG;
1912 // Course id stored in course table
1913 unset($section->course);
1914 // Section number stored in array key
1915 unset($section->section);
1916 // Sequence stored implicity in modinfo $sections array
1917 unset($section->sequence);
1919 // Add availability data if turned on
1920 if ($CFG->enableavailability) {
1921 require_once($CFG->dirroot . '/lib/conditionlib.php');
1922 condition_info_section::fill_availability_conditions($section);
1923 if (count($section->conditionscompletion) == 0) {
1924 unset($section->conditionscompletion);
1926 if (count($section->conditionsgrade) == 0) {
1927 unset($section->conditionsgrade);
1931 // Remove default data
1932 foreach (self::$sectioncachedefaults as $field => $value) {
1933 // Exact compare as strings to avoid problems if some strings are set
1934 // to "0" etc.
1935 if (isset($section->{$field}) && $section->{$field} === $value) {
1936 unset($section->{$field});