MDL-35339 call rebuild_course_cache() always (and only) after changing course modules...
[moodle.git] / lib / modinfolib.php
CommitLineData
0d8b6a69 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.
13//
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/>.
16
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
24 */
25
26
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
31if (!defined('MAX_MODINFO_CACHE_SIZE')) {
32 define('MAX_MODINFO_CACHE_SIZE', 10);
33}
34
35
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.
39 *
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.
42 */
1e4cb189 43class course_modinfo extends stdClass {
0d8b6a69 44 // For convenience we store the course object here as it is needed in other parts of code
45 private $course;
ce4dfd27 46 // Array of section data from cache
47 private $sectioninfo;
0d8b6a69 48
49 // Existing data fields
50 ///////////////////////
51
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().
54
55 /**
56 * Course ID
57 * @var int
58 * @deprecated For new code, use get_course_id instead.
59 */
60 public $courseid;
61
62 /**
63 * User ID
64 * @var int
65 * @deprecated For new code, use get_user_id instead.
66 */
67 public $userid;
68
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
74 */
75 public $sections;
76
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.
81 */
82 public $cms;
83
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.
88 */
89 public $instances;
90
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.
97 */
98 public $groups;
99
100 // Get methods for data
101 ///////////////////////
102
103 /**
104 * @return object Moodle course object that was used to construct this data
105 */
106 public function get_course() {
107 return $this->course;
108 }
109
110 /**
111 * @return int Course ID
112 */
113 public function get_course_id() {
114 return $this->courseid;
115 }
116
117 /**
118 * @return int User ID
119 */
120 public function get_user_id() {
121 return $this->userid;
122 }
123
124 /**
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
127 */
128 public function get_sections() {
129 return $this->sections;
130 }
131
132 /**
133 * @return array Array from course-module instance to cm_info object within this course, in
134 * order of appearance
135 */
136 public function get_cms() {
137 return $this->cms;
138 }
139
140 /**
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
145 */
146 public function get_cm($cmid) {
147 if (empty($this->cms[$cmid])) {
148 throw new moodle_exception('invalidcoursemodule', 'error');
149 }
150 return $this->cms[$cmid];
151 }
152
153 /**
154 * Obtains all module instances on this course.
155 * @return array Array from module name => array from instance id => cm_info
156 */
157 public function get_instances() {
158 return $this->instances;
159 }
160
d57aa283
MG
161 /**
162 * Returns array of localised human-readable module names used in this course
163 *
164 * @param bool $plural if true returns the plural form of modules names
165 * @return array
166 */
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];
173 }
174 }
175 collatorlib::asort($modnamesused);
176 return $modnamesused;
177 }
178
0d8b6a69 179 /**
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
183 */
184 public function get_instances_of($modname) {
185 if (empty($this->instances[$modname])) {
186 return array();
187 }
188 return $this->instances[$modname];
189 }
190
191 /**
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
196 */
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);
205 }
206 if (!isset($this->groups[$groupingid])) {
207 return array();
208 }
209 return $this->groups[$groupingid];
210 }
211
ce4dfd27 212 /**
213 * Gets all sections as array from section number => data about section.
214 * @return array Array of section_info objects organised by section number
215 */
216 public function get_section_info_all() {
217 return $this->sectioninfo;
218 }
219
220 /**
94dc3c7d
EL
221 * Gets data about specific numbered section.
222 * @param int $sectionnumber Number (not id) of section
c069dacf 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
225 */
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;
232 }
233 }
ce4dfd27 234 return $this->sectioninfo[$sectionnumber];
235 }
236
0d8b6a69 237 /**
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
243 */
244 public function __construct($course, $userid) {
d6f4508c 245 global $CFG, $DB;
0d8b6a69 246
ce4dfd27 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);
251 }
252
0d8b6a69 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;
261
0d8b6a69 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;
273 }
274 }
275
ce4dfd27 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;
287 }
288 }
289
0d8b6a69 290 // If we haven't already preloaded contexts for the course, do it now
291 preload_course_contexts($course->id);
292
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;
299 }
300
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;
305 }
306 $modexists[$mod->mod] = true;
307 }
308
309 // Construct info for this module
310 $cm = new cm_info($this, $course, $mod, $info);
311
312 // Store module in instances and cms array
313 if (!isset($this->instances[$cm->modname])) {
314 $this->instances[$cm->modname] = array();
315 }
316 $this->instances[$cm->modname][$cm->instance] = $cm;
317 $this->cms[$cm->id] = $cm;
318
319 // Reconstruct sections. This works because modules are stored in order
320 if (!isset($this->sections[$cm->sectionnum])) {
321 $this->sections[$cm->sectionnum] = array();
322 }
323 $this->sections[$cm->sectionnum][] = $cm->id;
324 }
325
ce4dfd27 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 = '';
334 }
335 // Expand
336 $this->sectioninfo[$number] = new section_info($data, $number, $course->id, $sequence,
337 $this, $userid);
338 }
339
0d8b6a69 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();
346 }
347 }
ce4dfd27 348
349 /**
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.)
353 *
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)
357 */
358 public static function build_section_cache($courseid) {
359 global $DB;
360
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();
366
367 // Remove unnecessary data and add availability
368 foreach ($sections as $number => $section) {
99e9f9a6 369 // Clone just in case it is reused elsewhere
ce4dfd27 370 $compressedsections[$number] = clone($section);
371 section_info::convert_for_section_cache($compressedsections[$number]);
372 }
373
374 return $compressedsections;
375 }
0d8b6a69 376}
377
378
379/**
380 * Data about a single module on a course. This contains most of the fields in the course_modules
381 * table, plus additional data when required.
382 *
383 * This object has many public fields; code should treat all these fields as read-only and set
384 * data only using the supplied set functions. Setting the fields directly is not supported
385 * and may cause problems later.
386 */
ce4dfd27 387class cm_info extends stdClass {
0d8b6a69 388 /**
389 * State: Only basic data from modinfo cache is available.
390 */
391 const STATE_BASIC = 0;
392
393 /**
394 * State: Dynamic data is available too.
395 */
396 const STATE_DYNAMIC = 1;
397
398 /**
399 * State: View data (for course page) is available.
400 */
401 const STATE_VIEW = 2;
402
403 /**
404 * Parent object
405 * @var course_modinfo
406 */
407 private $modinfo;
408
409 /**
410 * Level of information stored inside this object (STATE_xx constant)
411 * @var int
412 */
413 private $state;
414
415 // Existing data fields
416 ///////////////////////
417
418 /**
419 * Course-module ID - from course_modules table
420 * @var int
421 */
422 public $id;
423
424 /**
425 * Module instance (ID within module table) - from course_modules table
426 * @var int
427 */
428 public $instance;
429
430 /**
431 * Course ID - from course_modules table
432 * @var int
433 */
434 public $course;
435
436 /**
437 * 'ID number' from course-modules table (arbitrary text set by user) - from
438 * course_modules table
439 * @var string
440 */
441 public $idnumber;
442
443 /**
adaeccb6 444 * Time that this course-module was added (unix time) - from course_modules table
445 * @var int
446 */
447 public $added;
448
449 /**
450 * This variable is not used and is included here only so it can be documented.
451 * Once the database entry is removed from course_modules, it should be deleted
452 * here too.
453 * @var int
454 * @deprecated Do not use this variable
455 */
456 public $score;
457
458 /**
459 * Visible setting (0 or 1; if this is 0, students cannot see/access the activity) - from
0d8b6a69 460 * course_modules table
461 * @var int
462 */
463 public $visible;
464
adaeccb6 465 /**
466 * Old visible setting (if the entire section is hidden, the previous value for
467 * visible is stored in this field) - from course_modules table
468 * @var int
469 */
470 public $visibleold;
471
0d8b6a69 472 /**
473 * Group mode (one of the constants NONE, SEPARATEGROUPS, or VISIBLEGROUPS) - from
474 * course_modules table
475 * @var int
476 */
477 public $groupmode;
478
479 /**
480 * Grouping ID (0 = all groupings)
481 * @var int
482 */
483 public $groupingid;
484
485 /**
486 * Group members only (if set to 1, only members of a suitable group see this link on the
487 * course page; 0 = everyone sees it even if they don't belong to a suitable group) - from
488 * course_modules table
489 * @var int
490 */
491 public $groupmembersonly;
492
493 /**
494 * Indent level on course page (0 = no indent) - from course_modules table
495 * @var int
496 */
497 public $indent;
498
499 /**
500 * Activity completion setting for this activity, COMPLETION_TRACKING_xx constant - from
501 * course_modules table
502 * @var int
503 */
504 public $completion;
505
adaeccb6 506 /**
507 * Set to the item number (usually 0) if completion depends on a particular
508 * grade of this activity, or null if completion does not depend on a grade - from
509 * course_modules table
510 * @var mixed
511 */
512 public $completiongradeitemnumber;
513
514 /**
515 * 1 if 'on view' completion is enabled, 0 otherwise - from course_modules table
516 * @var int
517 */
518 public $completionview;
519
520 /**
521 * Set to a unix time if completion of this activity is expected at a
522 * particular time, 0 if no time set - from course_modules table
523 * @var int
524 */
525 public $completionexpected;
526
0d8b6a69 527 /**
528 * Available date for this activity (0 if not set, or set to seconds since epoch; before this
529 * date, activity does not display to students) - from course_modules table
530 * @var int
531 */
532 public $availablefrom;
533
534 /**
535 * Available until date for this activity (0 if not set, or set to seconds since epoch; from
536 * this date, activity does not display to students) - from course_modules table
537 * @var int
538 */
539 public $availableuntil;
540
541 /**
542 * When activity is unavailable, this field controls whether it is shown to students (0 =
543 * hide completely, 1 = show greyed out with information about when it will be available) -
544 * from course_modules table
545 * @var int
546 */
547 public $showavailability;
548
8c40662e 549 /**
550 * Controls whether the description of the activity displays on the course main page (in
551 * addition to anywhere it might display within the activity itself). 0 = do not show
552 * on main page, 1 = show on main page.
553 * @var int
554 */
555 public $showdescription;
556
0d8b6a69 557 /**
558 * Extra HTML that is put in an unhelpful part of the HTML when displaying this module in
559 * course page - from cached data in modinfo field
560 * @deprecated This is crazy, don't use it. Replaced by ->extraclasses and ->onclick
561 * @var string
562 */
563 public $extra;
564
565 /**
566 * Name of icon to use - from cached data in modinfo field
567 * @var string
568 */
569 public $icon;
570
571 /**
572 * Component that contains icon - from cached data in modinfo field
573 * @var string
574 */
575 public $iconcomponent;
576
577 /**
578 * Name of module e.g. 'forum' (this is the same name as the module's main database
579 * table) - from cached data in modinfo field
580 * @var string
581 */
582 public $modname;
583
adaeccb6 584 /**
585 * ID of module - from course_modules table
586 * @var int
587 */
588 public $module;
589
0d8b6a69 590 /**
591 * Name of module instance for display on page e.g. 'General discussion forum' - from cached
592 * data in modinfo field
593 * @var string
594 */
595 public $name;
596
597 /**
598 * Section number that this course-module is in (section 0 = above the calendar, section 1
599 * = week/topic 1, etc) - from cached data in modinfo field
600 * @var string
601 */
602 public $sectionnum;
603
adaeccb6 604 /**
605 * Section id - from course_modules table
606 * @var int
607 */
608 public $section;
609
0d8b6a69 610 /**
611 * Availability conditions for this course-module based on the completion of other
612 * course-modules (array from other course-module id to required completion state for that
613 * module) - from cached data in modinfo field
614 * @var array
615 */
616 public $conditionscompletion;
617
618 /**
619 * Availability conditions for this course-module based on course grades (array from
620 * grade item id to object with ->min, ->max fields) - from cached data in modinfo field
621 * @var array
622 */
623 public $conditionsgrade;
624
76af15bb
MN
625 /**
626 * Availability conditions for this course-module based on user fields
627 * @var array
628 */
629 public $conditionsfield;
630
0d8b6a69 631 /**
632 * True if this course-module is available to students i.e. if all availability conditions
633 * are met - obtained dynamically
634 * @var bool
635 */
636 public $available;
637
638 /**
639 * If course-module is not available to students, this string gives information about
640 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
641 * January 2010') for display on main page - obtained dynamically
642 * @var string
643 */
644 public $availableinfo;
645
646 /**
647 * True if this course-module is available to the CURRENT user (for example, if current user
648 * has viewhiddenactivities capability, they can access the course-module even if it is not
649 * visible or not available, so this would be true in that case)
650 * @var bool
651 */
652 public $uservisible;
653
4478743c
PS
654 /**
655 * Module context - hacky shortcut
656 * @deprecated
657 * @var stdClass
658 */
659 public $context;
660
661
0d8b6a69 662 // New data available only via functions
663 ////////////////////////////////////////
664
665 /**
666 * @var moodle_url
667 */
668 private $url;
669
670 /**
671 * @var string
672 */
673 private $content;
674
675 /**
676 * @var string
677 */
678 private $extraclasses;
679
c443a1cd
EL
680 /**
681 * @var moodle_url full external url pointing to icon image for activity
682 */
683 private $iconurl;
684
0d8b6a69 685 /**
686 * @var string
687 */
688 private $onclick;
689
690 /**
691 * @var mixed
692 */
693 private $customdata;
694
695 /**
696 * @var string
697 */
698 private $afterlink;
699
700 /**
701 * @var string
702 */
703 private $afterediticons;
704
d57aa283
MG
705 /**
706 * Magic method getter
707 *
708 * @param string $name
709 * @return mixed
710 */
711 public function __get($name) {
712 switch ($name) {
713 case 'modplural':
714 return $this->get_module_type_name(true);
715 case 'modfullname':
716 return $this->get_module_type_name();
717 default:
718 debugging('Invalid cm_info property accessed: '.$name);
719 return null;
720 }
721 }
722
0d8b6a69 723 /**
724 * @return bool True if this module has a 'view' page that should be linked to in navigation
725 * etc (note: modules may still have a view.php file, but return false if this is not
726 * intended to be linked to from 'normal' parts of the interface; this is what label does).
727 */
728 public function has_view() {
729 return !is_null($this->url);
730 }
731
732 /**
733 * @return moodle_url URL to link to for this module, or null if it doesn't have a view page
734 */
735 public function get_url() {
736 return $this->url;
737 }
738
739 /**
740 * Obtains content to display on main (view) page.
741 * Note: Will collect view data, if not already obtained.
742 * @return string Content to display on main page below link, or empty string if none
743 */
744 public function get_content() {
745 $this->obtain_view_data();
746 return $this->content;
747 }
748
749 /**
750 * Note: Will collect view data, if not already obtained.
751 * @return string Extra CSS classes to add to html output for this activity on main page
752 */
753 public function get_extra_classes() {
754 $this->obtain_view_data();
755 return $this->extraclasses;
756 }
757
758 /**
759 * @return string Content of HTML on-click attribute. This string will be used literally
760 * as a string so should be pre-escaped.
761 */
762 public function get_on_click() {
763 // Does not need view data; may be used by navigation
764 return $this->onclick;
765 }
766 /**
767 * @return mixed Optional custom data stored in modinfo cache for this activity, or null if none
768 */
769 public function get_custom_data() {
770 return $this->customdata;
771 }
772
773 /**
774 * Note: Will collect view data, if not already obtained.
c443a1cd 775 * @return string Extra HTML code to display after link
0d8b6a69 776 */
777 public function get_after_link() {
778 $this->obtain_view_data();
779 return $this->afterlink;
780 }
781
782 /**
783 * Note: Will collect view data, if not already obtained.
784 * @return string Extra HTML code to display after editing icons (e.g. more icons)
785 */
786 public function get_after_edit_icons() {
787 $this->obtain_view_data();
788 return $this->afterediticons;
789 }
790
791 /**
792 * @param moodle_core_renderer $output Output render to use, or null for default (global)
793 * @return moodle_url Icon URL for a suitable icon to put beside this cm
794 */
795 public function get_icon_url($output = null) {
796 global $OUTPUT;
797 if (!$output) {
798 $output = $OUTPUT;
799 }
c443a1cd
EL
800 // Support modules setting their own, external, icon image
801 if (!empty($this->iconurl)) {
802 $icon = $this->iconurl;
803
804 // Fallback to normal local icon + component procesing
805 } else if (!empty($this->icon)) {
0d8b6a69 806 if (substr($this->icon, 0, 4) === 'mod/') {
807 list($modname, $iconname) = explode('/', substr($this->icon, 4), 2);
808 $icon = $output->pix_url($iconname, $modname);
809 } else {
810 if (!empty($this->iconcomponent)) {
811 // Icon has specified component
812 $icon = $output->pix_url($this->icon, $this->iconcomponent);
813 } else {
814 // Icon does not have specified component, use default
815 $icon = $output->pix_url($this->icon);
816 }
817 }
818 } else {
819 $icon = $output->pix_url('icon', $this->modname);
820 }
821 return $icon;
822 }
823
d57aa283
MG
824 /**
825 * Returns a localised human-readable name of the module type
826 *
827 * @param bool $plural return plural form
828 * @return string
829 */
830 public function get_module_type_name($plural = false) {
831 $modnames = get_module_types_names($plural);
832 if (isset($modnames[$this->modname])) {
833 return $modnames[$this->modname];
834 } else {
835 return null;
836 }
837 }
838
0d8b6a69 839 /**
840 * @return course_modinfo Modinfo object that this came from
841 */
842 public function get_modinfo() {
843 return $this->modinfo;
844 }
845
846 /**
847 * @return object Moodle course object that was used to construct this data
848 */
849 public function get_course() {
850 return $this->modinfo->get_course();
851 }
852
853 // Set functions
854 ////////////////
855
856 /**
857 * Sets content to display on course view page below link (if present).
858 * @param string $content New content as HTML string (empty string if none)
859 * @return void
860 */
861 public function set_content($content) {
862 $this->content = $content;
863 }
864
865 /**
866 * Sets extra classes to include in CSS.
867 * @param string $extraclasses Extra classes (empty string if none)
868 * @return void
869 */
870 public function set_extra_classes($extraclasses) {
871 $this->extraclasses = $extraclasses;
872 }
873
c443a1cd
EL
874 /**
875 * Sets the external full url that points to the icon being used
876 * by the activity. Useful for external-tool modules (lti...)
877 * If set, takes precedence over $icon and $iconcomponent
878 *
879 * @param moodle_url $iconurl full external url pointing to icon image for activity
880 * @return void
881 */
882 public function set_icon_url(moodle_url $iconurl) {
883 $this->iconurl = $iconurl;
884 }
885
0d8b6a69 886 /**
887 * Sets value of on-click attribute for JavaScript.
888 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
889 * @param string $onclick New onclick attribute which should be HTML-escaped
890 * (empty string if none)
891 * @return void
892 */
893 public function set_on_click($onclick) {
894 $this->check_not_view_only();
895 $this->onclick = $onclick;
896 }
897
898 /**
899 * Sets HTML that displays after link on course view page.
900 * @param string $afterlink HTML string (empty string if none)
901 * @return void
902 */
903 public function set_after_link($afterlink) {
904 $this->afterlink = $afterlink;
905 }
906
907 /**
908 * Sets HTML that displays after edit icons on course view page.
909 * @param string $afterediticons HTML string (empty string if none)
910 * @return void
911 */
912 public function set_after_edit_icons($afterediticons) {
913 $this->afterediticons = $afterediticons;
914 }
915
916 /**
917 * Changes the name (text of link) for this module instance.
918 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
919 * @param string $name Name of activity / link text
920 * @return void
921 */
922 public function set_name($name) {
923 $this->update_user_visible();
924 $this->name = $name;
925 }
926
927 /**
928 * Turns off the view link for this module instance.
929 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
930 * @return void
931 */
932 public function set_no_view_link() {
933 $this->check_not_view_only();
4478743c 934 $this->url = null;
0d8b6a69 935 }
936
937 /**
938 * Sets the 'uservisible' flag. This can be used (by setting false) to prevent access and
939 * display of this module link for the current user.
940 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
941 * @param bool $uservisible
942 * @return void
943 */
944 public function set_user_visible($uservisible) {
945 $this->check_not_view_only();
946 $this->uservisible = $uservisible;
947 }
948
949 /**
950 * Sets the 'available' flag and related details. This flag is normally used to make
951 * course modules unavailable until a certain date or condition is met. (When a course
952 * module is unavailable, it is still visible to users who have viewhiddenactivities
953 * permission.)
954 *
955 * When this is function is called, user-visible status is recalculated automatically.
956 *
957 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
958 * @param bool $available False if this item is not 'available'
959 * @param int $showavailability 0 = do not show this item at all if it's not available,
960 * 1 = show this item greyed out with the following message
961 * @param string $availableinfo Information about why this is not available which displays
962 * to those who have viewhiddenactivities, and to everyone if showavailability is set;
963 * note that this function replaces the existing data (if any)
964 * @return void
965 */
966 public function set_available($available, $showavailability=0, $availableinfo='') {
967 $this->check_not_view_only();
968 $this->available = $available;
969 $this->showavailability = $showavailability;
970 $this->availableinfo = $availableinfo;
971 $this->update_user_visible();
972 }
973
974 /**
975 * Some set functions can only be called from _cm_info_dynamic and not _cm_info_view.
976 * This is because they may affect parts of this object which are used on pages other
977 * than the view page (e.g. in the navigation block, or when checking access on
978 * module pages).
979 * @return void
980 */
981 private function check_not_view_only() {
982 if ($this->state >= self::STATE_DYNAMIC) {
983 throw new coding_exception('Cannot set this data from _cm_info_view because it may ' .
984 'affect other pages as well as view');
985 }
986 }
987
988 /**
989 * Constructor should not be called directly; use get_fast_modinfo.
990 * @param course_modinfo $modinfo Parent object
991 * @param object $course Course row
992 * @param object $mod Module object from the modinfo field of course table
993 * @param object $info Entire object from modinfo field of course table
994 */
995 public function __construct(course_modinfo $modinfo, $course, $mod, $info) {
996 global $CFG;
997 $this->modinfo = $modinfo;
998
999 $this->id = $mod->cm;
1000 $this->instance = $mod->id;
1001 $this->course = $course->id;
1002 $this->modname = $mod->mod;
1003 $this->idnumber = isset($mod->idnumber) ? $mod->idnumber : '';
1004 $this->name = $mod->name;
1005 $this->visible = $mod->visible;
adaeccb6 1006 $this->sectionnum = $mod->section; // Note weirdness with name here
0d8b6a69 1007 $this->groupmode = isset($mod->groupmode) ? $mod->groupmode : 0;
1008 $this->groupingid = isset($mod->groupingid) ? $mod->groupingid : 0;
1009 $this->groupmembersonly = isset($mod->groupmembersonly) ? $mod->groupmembersonly : 0;
1010 $this->indent = isset($mod->indent) ? $mod->indent : 0;
0d8b6a69 1011 $this->extra = isset($mod->extra) ? $mod->extra : '';
1012 $this->extraclasses = isset($mod->extraclasses) ? $mod->extraclasses : '';
c443a1cd 1013 $this->iconurl = isset($mod->iconurl) ? $mod->iconurl : '';
0d8b6a69 1014 $this->onclick = isset($mod->onclick) ? $mod->onclick : '';
1015 $this->content = isset($mod->content) ? $mod->content : '';
1016 $this->icon = isset($mod->icon) ? $mod->icon : '';
1017 $this->iconcomponent = isset($mod->iconcomponent) ? $mod->iconcomponent : '';
1018 $this->customdata = isset($mod->customdata) ? $mod->customdata : '';
b0c6dc1c 1019 $this->context = context_module::instance($mod->cm);
8c40662e 1020 $this->showdescription = isset($mod->showdescription) ? $mod->showdescription : 0;
0d8b6a69 1021 $this->state = self::STATE_BASIC;
1022
1023 // This special case handles old label data. Labels used to use the 'name' field for
1024 // content
1025 if ($this->modname === 'label' && $this->content === '') {
1026 $this->content = $this->extra;
1027 $this->extra = '';
1028 }
1029
adaeccb6 1030 // Note: These fields from $cm were not present in cm_info in Moodle
1031 // 2.0.2 and prior. They may not be available if course cache hasn't
1032 // been rebuilt since then.
1033 $this->section = isset($mod->sectionid) ? $mod->sectionid : 0;
1034 $this->module = isset($mod->module) ? $mod->module : 0;
1035 $this->added = isset($mod->added) ? $mod->added : 0;
1036 $this->score = isset($mod->score) ? $mod->score : 0;
1037 $this->visibleold = isset($mod->visibleold) ? $mod->visibleold : 0;
1038
1039 // Note: it saves effort and database space to always include the
1040 // availability and completion fields, even if availability or completion
1041 // are actually disabled
1042 $this->completion = isset($mod->completion) ? $mod->completion : 0;
1043 $this->completiongradeitemnumber = isset($mod->completiongradeitemnumber)
1044 ? $mod->completiongradeitemnumber : null;
1045 $this->completionview = isset($mod->completionview)
1046 ? $mod->completionview : 0;
1047 $this->completionexpected = isset($mod->completionexpected)
1048 ? $mod->completionexpected : 0;
1049 $this->showavailability = isset($mod->showavailability) ? $mod->showavailability : 0;
1050 $this->availablefrom = isset($mod->availablefrom) ? $mod->availablefrom : 0;
1051 $this->availableuntil = isset($mod->availableuntil) ? $mod->availableuntil : 0;
1052 $this->conditionscompletion = isset($mod->conditionscompletion)
1053 ? $mod->conditionscompletion : array();
1054 $this->conditionsgrade = isset($mod->conditionsgrade)
1055 ? $mod->conditionsgrade : array();
76af15bb
MN
1056 $this->conditionsfield = isset($mod->conditionsfield)
1057 ? $mod->conditionsfield : array();
0d8b6a69 1058
0d8b6a69 1059 static $modviews;
1060 if (!isset($modviews[$this->modname])) {
1061 $modviews[$this->modname] = !plugin_supports('mod', $this->modname,
1062 FEATURE_NO_VIEW_LINK);
1063 }
1064 $this->url = $modviews[$this->modname]
1065 ? new moodle_url('/mod/' . $this->modname . '/view.php', array('id'=>$this->id))
1066 : null;
1067 }
1068
1069 /**
1070 * If dynamic data for this course-module is not yet available, gets it.
1071 *
1072 * This function is automatically called when constructing course_modinfo, so users don't
1073 * need to call it.
1074 *
1075 * Dynamic data is data which does not come directly from the cache but is calculated at
1076 * runtime based on the current user. Primarily this concerns whether the user can access
1077 * the module or not.
1078 *
1079 * As part of this function, the module's _cm_info_dynamic function from its lib.php will
1080 * be called (if it exists).
1081 * @return void
1082 */
1083 public function obtain_dynamic_data() {
1084 global $CFG;
1085 if ($this->state >= self::STATE_DYNAMIC) {
1086 return;
1087 }
1088 $userid = $this->modinfo->get_user_id();
1089
1090 if (!empty($CFG->enableavailability)) {
1091 // Get availability information
1092 $ci = new condition_info($this);
1093 // Note that the modinfo currently available only includes minimal details (basic data)
1094 // so passing it to this function is a bit dangerous as it would cause infinite
1095 // recursion if it tried to get dynamic data, however we know that this function only
1096 // uses basic data.
1097 $this->available = $ci->is_available($this->availableinfo, true,
1098 $userid, $this->modinfo);
ce4dfd27 1099
1100 // Check parent section
1101 $parentsection = $this->modinfo->get_section_info($this->sectionnum);
1102 if (!$parentsection->available) {
1103 // Do not store info from section here, as that is already
1104 // presented from the section (if appropriate) - just change
1105 // the flag
1106 $this->available = false;
1107 }
0d8b6a69 1108 } else {
1109 $this->available = true;
1110 }
1111
1112 // Update visible state for current user
1113 $this->update_user_visible();
1114
1115 // Let module make dynamic changes at this point
1116 $this->call_mod_function('cm_info_dynamic');
1117 $this->state = self::STATE_DYNAMIC;
1118 }
1119
1120 /**
1121 * Works out whether activity is visible *for current user* - if this is false, they
1122 * aren't allowed to access it.
1123 * @return void
1124 */
1125 private function update_user_visible() {
1126 global $CFG;
b0c6dc1c 1127 $modcontext = context_module::instance($this->id);
0d8b6a69 1128 $userid = $this->modinfo->get_user_id();
1129 $this->uservisible = true;
a098f340 1130 // Check visibility/availability conditions.
0d8b6a69 1131 if ((!$this->visible or !$this->available) and
1132 !has_capability('moodle/course:viewhiddenactivities', $modcontext, $userid)) {
1133 // If the activity is hidden or unavailable, and you don't have viewhiddenactivities,
a098f340 1134 // set it so that user can't see or access it.
0d8b6a69 1135 $this->uservisible = false;
a098f340 1136 }
1137 // Check group membership. The grouping option makes the activity
1138 // completely invisible as it does not apply to the user at all.
5fee56d5
FM
1139 if ($this->is_user_access_restricted_by_group()) {
1140 $this->uservisible = false;
1141 // Ensure activity is completely hidden from user.
1142 $this->showavailability = 0;
1143 }
1144 }
1145
1146 /**
1147 * Checks whether the module group settings restrict the user access.
1148 * @return bool true if the user access is restricted
1149 */
1150 public function is_user_access_restricted_by_group() {
1151 global $CFG;
1152 $modcontext = context_module::instance($this->id);
1153 $userid = $this->modinfo->get_user_id();
a098f340 1154 if (!empty($CFG->enablegroupmembersonly) and !empty($this->groupmembersonly)
0d8b6a69 1155 and !has_capability('moodle/site:accessallgroups', $modcontext, $userid)) {
1156 // If the activity has 'group members only' and you don't have accessallgroups...
12923c92
PS
1157 $groups = $this->modinfo->get_groups($this->groupingid);
1158 if (empty($groups)) {
0d8b6a69 1159 // ...and you don't belong to a group, then set it so you can't see/access it
5fee56d5 1160 return true;
0d8b6a69 1161 }
1162 }
5fee56d5 1163 return false;
0d8b6a69 1164 }
1165
1166 /**
1167 * Calls a module function (if exists), passing in one parameter: this object.
1168 * @param string $type Name of function e.g. if this is 'grooblezorb' and the modname is
1169 * 'forum' then it will try to call 'mod_forum_grooblezorb' or 'forum_grooblezorb'
1170 * @return void
1171 */
1172 private function call_mod_function($type) {
1173 global $CFG;
1174 $libfile = $CFG->dirroot . '/mod/' . $this->modname . '/lib.php';
1175 if (file_exists($libfile)) {
1176 include_once($libfile);
1177 $function = 'mod_' . $this->modname . '_' . $type;
1178 if (function_exists($function)) {
1179 $function($this);
1180 } else {
1181 $function = $this->modname . '_' . $type;
1182 if (function_exists($function)) {
1183 $function($this);
1184 }
1185 }
1186 }
1187 }
1188
1189 /**
1190 * If view data for this course-module is not yet available, obtains it.
1191 *
1192 * This function is automatically called if any of the functions (marked) which require
1193 * view data are called.
1194 *
1195 * View data is data which is needed only for displaying the course main page (& any similar
1196 * functionality on other pages) but is not needed in general. Obtaining view data may have
1197 * a performance cost.
1198 *
1199 * As part of this function, the module's _cm_info_view function from its lib.php will
1200 * be called (if it exists).
1201 * @return void
1202 */
1203 private function obtain_view_data() {
1204 if ($this->state >= self::STATE_VIEW) {
1205 return;
1206 }
1207
1208 // Let module make changes at this point
1209 $this->call_mod_function('cm_info_view');
1210 $this->state = self::STATE_VIEW;
1211 }
1212}
1213
1214
0d8b6a69 1215/**
1216 * Returns reference to full info about modules in course (including visibility).
1217 * Cached and as fast as possible (0 or 1 db query).
1218 *
1219 * @global object
1220 * @global object
1221 * @global moodle_database
1222 * @uses MAX_MODINFO_CACHE_SIZE
1223 * @param mixed $course object or 'reset' string to reset caches, modinfo may be updated in db
1224 * @param int $userid Defaults to current user id
1225 * @return course_modinfo Module information for course, or null if resetting
1226 */
1227function get_fast_modinfo(&$course, $userid=0) {
1228 global $CFG, $USER, $DB;
1229 require_once($CFG->dirroot.'/course/lib.php');
1230
1231 if (!empty($CFG->enableavailability)) {
1232 require_once($CFG->libdir.'/conditionlib.php');
1233 }
1234
1235 static $cache = array();
1236
1237 if ($course === 'reset') {
1238 $cache = array();
1239 return null;
1240 }
1241
1242 if (empty($userid)) {
1243 $userid = $USER->id;
1244 }
1245
1246 if (array_key_exists($course->id, $cache) and $cache[$course->id]->userid == $userid) {
1247 return $cache[$course->id];
1248 }
1249
1250 if (!property_exists($course, 'modinfo')) {
1251 debugging('Coding problem - missing course modinfo property in get_fast_modinfo() call');
1252 }
1253
fd0680ff
ARN
1254 if (!property_exists($course, 'sectioncache')) {
1255 debugging('Coding problem - missing course sectioncache property in get_fast_modinfo() call');
1256 }
1257
0d8b6a69 1258 unset($cache[$course->id]); // prevent potential reference problems when switching users
1259
adaeccb6 1260 $cache[$course->id] = new course_modinfo($course, $userid);
0d8b6a69 1261
1262 // Ensure cache does not use too much RAM
1263 if (count($cache) > MAX_MODINFO_CACHE_SIZE) {
1264 reset($cache);
1265 $key = key($cache);
0420f8dc
AO
1266 unset($cache[$key]->instances);
1267 unset($cache[$key]->cms);
0d8b6a69 1268 unset($cache[$key]);
1269 }
1270
1271 return $cache[$course->id];
1272}
1273
112d3b49
PS
1274/**
1275 * Rebuilds the cached list of course activities stored in the database
1276 * @param int $courseid - id of course to rebuild, empty means all
1277 * @param boolean $clearonly - only clear the modinfo fields, gets rebuild automatically on the fly
1278 */
1279function rebuild_course_cache($courseid=0, $clearonly=false) {
1280 global $COURSE, $DB, $CFG;
1281
1282 // Destroy navigation caches
1283 navigation_cache::destroy_volatile_caches();
1284
ee7084e9
MG
1285 if (class_exists('format_base')) {
1286 // if file containing class is not loaded, there is no cache there anyway
1287 format_base::reset_course_cache($courseid);
1288 }
1289
112d3b49
PS
1290 if ($clearonly) {
1291 if (empty($courseid)) {
ce4dfd27 1292 $DB->set_field('course', 'modinfo', null);
1293 $DB->set_field('course', 'sectioncache', null);
112d3b49 1294 } else {
ce4dfd27 1295 // Clear both fields in one update
1296 $resetobj = (object)array('id' => $courseid, 'modinfo' => null, 'sectioncache' => null);
1297 $DB->update_record('course', $resetobj);
112d3b49 1298 }
112d3b49
PS
1299 // update cached global COURSE too ;-)
1300 if ($courseid == $COURSE->id or empty($courseid)) {
1301 $COURSE->modinfo = null;
ce4dfd27 1302 $COURSE->sectioncache = null;
112d3b49
PS
1303 }
1304 // reset the fast modinfo cache
1305 $reset = 'reset';
1306 get_fast_modinfo($reset);
1307 return;
1308 }
1309
1310 require_once("$CFG->dirroot/course/lib.php");
1311
1312 if ($courseid) {
1313 $select = array('id'=>$courseid);
1314 } else {
1315 $select = array();
1316 @set_time_limit(0); // this could take a while! MDL-10954
1317 }
1318
1319 $rs = $DB->get_recordset("course", $select,'','id,fullname');
1320 foreach ($rs as $course) {
1321 $modinfo = serialize(get_array_of_activities($course->id));
ce4dfd27 1322 $sectioncache = serialize(course_modinfo::build_section_cache($course->id));
1323 $updateobj = (object)array('id' => $course->id,
1324 'modinfo' => $modinfo, 'sectioncache' => $sectioncache);
1325 $DB->update_record("course", $updateobj);
112d3b49
PS
1326 // update cached global COURSE too ;-)
1327 if ($course->id == $COURSE->id) {
1328 $COURSE->modinfo = $modinfo;
ce4dfd27 1329 $COURSE->sectioncache = $sectioncache;
112d3b49
PS
1330 }
1331 }
1332 $rs->close();
1333 // reset the fast modinfo cache
1334 $reset = 'reset';
1335 get_fast_modinfo($reset);
1336}
1337
0d8b6a69 1338
1339/**
1340 * Class that is the return value for the _get_coursemodule_info module API function.
1341 *
1342 * Note: For backward compatibility, you can also return a stdclass object from that function.
1343 * The difference is that the stdclass object may contain an 'extra' field (deprecated because
1344 * it was crazy, except for label which uses it differently). The stdclass object may not contain
1345 * the new fields defined here (content, extraclasses, customdata).
1346 */
1347class cached_cm_info {
1348 /**
1349 * Name (text of link) for this activity; Leave unset to accept default name
1350 * @var string
1351 */
1352 public $name;
1353
1354 /**
1355 * Name of icon for this activity. Normally, this should be used together with $iconcomponent
1356 * to define the icon, as per pix_url function.
1357 * For backward compatibility, if this value is of the form 'mod/forum/icon' then an icon
1358 * within that module will be used.
1359 * @see cm_info::get_icon_url()
1360 * @see renderer_base::pix_url()
1361 * @var string
1362 */
1363 public $icon;
1364
1365 /**
1366 * Component for icon for this activity, as per pix_url; leave blank to use default 'moodle'
1367 * component
1368 * @see renderer_base::pix_url()
1369 * @var string
1370 */
1371 public $iconcomponent;
1372
1373 /**
1374 * HTML content to be displayed on the main page below the link (if any) for this course-module
1375 * @var string
1376 */
1377 public $content;
1378
1379 /**
1380 * Custom data to be stored in modinfo for this activity; useful if there are cases when
1381 * internal information for this activity type needs to be accessible from elsewhere on the
1382 * course without making database queries. May be of any type but should be short.
1383 * @var mixed
1384 */
1385 public $customdata;
1386
1387 /**
1388 * Extra CSS class or classes to be added when this activity is displayed on the main page;
1389 * space-separated string
1390 * @var string
1391 */
1392 public $extraclasses;
1393
c443a1cd
EL
1394 /**
1395 * External URL image to be used by activity as icon, useful for some external-tool modules
1396 * like lti. If set, takes precedence over $icon and $iconcomponent
1397 * @var $moodle_url
1398 */
1399 public $iconurl;
1400
0d8b6a69 1401 /**
1402 * Content of onclick JavaScript; escaped HTML to be inserted as attribute value
1403 * @var string
1404 */
1405 public $onclick;
c443a1cd 1406}
ce4dfd27 1407
1408
1409/**
1410 * Data about a single section on a course. This contains the fields from the
1411 * course_sections table, plus additional data when required.
1412 */
1413class section_info extends stdClass {
1414 /**
1415 * Section ID - from course_sections table
1416 * @var int
1417 */
1418 public $id;
1419
1420 /**
1421 * Course ID - from course_sections table
1422 * @var int
1423 */
1424 public $course;
1425
1426 /**
1427 * Section number - from course_sections table
1428 * @var int
1429 */
1430 public $section;
1431
1432 /**
1433 * Section name if specified - from course_sections table
1434 * @var string
1435 */
1436 public $name;
1437
1438 /**
1439 * Section visibility (1 = visible) - from course_sections table
1440 * @var int
1441 */
1442 public $visible;
1443
1444 /**
1445 * Section summary text if specified - from course_sections table
1446 * @var string
1447 */
1448 public $summary;
1449
1450 /**
1451 * Section summary text format (FORMAT_xx constant) - from course_sections table
1452 * @var int
1453 */
1454 public $summaryformat;
1455
1456 /**
1457 * When section is unavailable, this field controls whether it is shown to students (0 =
1458 * hide completely, 1 = show greyed out with information about when it will be available) -
1459 * from course_sections table
1460 * @var int
1461 */
1462 public $showavailability;
1463
1464 /**
1465 * Available date for this section (0 if not set, or set to seconds since epoch; before this
1466 * date, section does not display to students) - from course_sections table
1467 * @var int
1468 */
1469 public $availablefrom;
1470
1471 /**
1472 * Available until date for this section (0 if not set, or set to seconds since epoch; from
1473 * this date, section does not display to students) - from course_sections table
1474 * @var int
1475 */
1476 public $availableuntil;
1477
1478 /**
1479 * If section is restricted to users of a particular grouping, this is its id
1480 * (0 if not set) - from course_sections table
1481 * @var int
1482 */
1483 public $groupingid;
1484
1485 /**
1486 * Availability conditions for this section based on the completion of
1487 * course-modules (array from course-module id to required completion state
1488 * for that module) - from cached data in sectioncache field
1489 * @var array
1490 */
1491 public $conditionscompletion;
1492
1493 /**
1494 * Availability conditions for this section based on course grades (array from
1495 * grade item id to object with ->min, ->max fields) - from cached data in
1496 * sectioncache field
1497 * @var array
1498 */
1499 public $conditionsgrade;
1500
1501 /**
1502 * True if this section is available to students i.e. if all availability conditions
1503 * are met - obtained dynamically
1504 * @var bool
1505 */
1506 public $available;
1507
1508 /**
1509 * If section is not available to students, this string gives information about
1510 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
1511 * January 2010') for display on main page - obtained dynamically
1512 * @var string
1513 */
1514 public $availableinfo;
1515
1516 /**
1517 * True if this section is available to the CURRENT user (for example, if current user
1518 * has viewhiddensections capability, they can access the section even if it is not
1519 * visible or not available, so this would be true in that case)
1520 * @var bool
1521 */
1522 public $uservisible;
1523
1524 /**
1525 * Default values for sectioncache fields; if a field has this value, it won't
1526 * be stored in the sectioncache cache, to save space. Checks are done by ===
1527 * which means values must all be strings.
1528 * @var array
1529 */
1530 private static $sectioncachedefaults = array(
1531 'name' => null,
1532 'summary' => '',
1533 'summaryformat' => '1', // FORMAT_HTML, but must be a string
1534 'visible' => '1',
1535 'showavailability' => '0',
1536 'availablefrom' => '0',
1537 'availableuntil' => '0',
1538 'groupingid' => '0',
1539 );
1540
1541 /**
1542 * Constructs object from database information plus extra required data.
1543 * @param object $data Array entry from cached sectioncache
1544 * @param int $number Section number (array key)
1545 * @param int $courseid Course ID
1546 * @param int $sequence Sequence of course-module ids contained within
1547 * @param course_modinfo $modinfo Owner (needed for checking availability)
1548 * @param int $userid User ID
1549 */
1550 public function __construct($data, $number, $courseid, $sequence, $modinfo, $userid) {
1551 global $CFG;
1552
1553 // Data that is always present
1554 $this->id = $data->id;
1555
1556 // Data that may use default values to save cache size
1557 foreach (self::$sectioncachedefaults as $field => $value) {
1558 if (isset($data->{$field})) {
1559 $this->{$field} = $data->{$field};
1560 } else {
1561 $this->{$field} = $value;
1562 }
1563 }
1564
1565 // Data with array defaults
1566 $this->conditionscompletion = isset($data->conditionscompletion)
1567 ? $data->conditionscompletion : array();
1568 $this->conditionsgrade = isset($data->conditionsgrade)
1569 ? $data->conditionsgrade : array();
e01fbcf7
MN
1570 $this->conditionsfield = isset($data->conditionsfield)
1571 ? $data->conditionsfield : array();
ce4dfd27 1572
1573 // Other data from other places
1574 $this->course = $courseid;
1575 $this->section = $number;
1576 $this->sequence = $sequence;
1577
1578 // Availability data
1579 if (!empty($CFG->enableavailability)) {
1580 // Get availability information
1581 $ci = new condition_info_section($this);
1582 $this->available = $ci->is_available($this->availableinfo, true,
1583 $userid, $modinfo);
1584 // Display grouping info if available & not already displaying
1585 // (it would already display if current user doesn't have access)
1586 // for people with managegroups - same logic/class as grouping label
1587 // on individual activities.
1588 $context = context_course::instance($courseid);
1589 if ($this->availableinfo === '' && $this->groupingid &&
1590 has_capability('moodle/course:managegroups', $context)) {
1591 $groupings = groups_get_all_groupings($courseid);
1592 $this->availableinfo = html_writer::tag('span', '(' . format_string(
1593 $groupings[$this->groupingid]->name, true, array('context' => $context)) .
1594 ')', array('class' => 'groupinglabel'));
1595 }
1596 } else {
1597 $this->available = true;
1598 }
1599
1600 // Update visibility for current user
1601 $this->update_user_visible($userid);
1602 }
1603
1604 /**
1605 * Works out whether activity is visible *for current user* - if this is false, they
1606 * aren't allowed to access it.
1607 * @param int $userid User ID
1608 * @return void
1609 */
1610 private function update_user_visible($userid) {
1611 global $CFG;
1612 $coursecontext = context_course::instance($this->course);
1613 $this->uservisible = true;
1614 if ((!$this->visible || !$this->available) &&
1615 !has_capability('moodle/course:viewhiddensections', $coursecontext, $userid)) {
1616 $this->uservisible = false;
1617 }
1618 }
1619
1620 /**
1621 * Prepares section data for inclusion in sectioncache cache, removing items
1622 * that are set to defaults, and adding availability data if required.
1623 *
1624 * Called by build_section_cache in course_modinfo only; do not use otherwise.
1625 * @param object $section Raw section data object
1626 */
1627 public static function convert_for_section_cache($section) {
1628 global $CFG;
1629
1630 // Course id stored in course table
1631 unset($section->course);
1632 // Section number stored in array key
1633 unset($section->section);
1634 // Sequence stored implicity in modinfo $sections array
1635 unset($section->sequence);
1636
1637 // Add availability data if turned on
1638 if ($CFG->enableavailability) {
1639 require_once($CFG->dirroot . '/lib/conditionlib.php');
1640 condition_info_section::fill_availability_conditions($section);
1641 if (count($section->conditionscompletion) == 0) {
1642 unset($section->conditionscompletion);
1643 }
1644 if (count($section->conditionsgrade) == 0) {
1645 unset($section->conditionsgrade);
1646 }
1647 }
1648
1649 // Remove default data
94dc3c7d 1650 foreach (self::$sectioncachedefaults as $field => $value) {
ce4dfd27 1651 // Exact compare as strings to avoid problems if some strings are set
1652 // to "0" etc.
1653 if (isset($section->{$field}) && $section->{$field} === $value) {
1654 unset($section->{$field});
1655 }
1656 }
1657 }
1658}