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