MDL-41192 course: Can not write to the read-only properties of cm_info
[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 }
2f1e464a 175 core_collator::asort($modnamesused);
d57aa283
MG
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) {
676fa06a 245 global $CFG, $DB, $COURSE, $SITE;
0d8b6a69 246
5a3204d0
MG
247 if (!isset($course->modinfo) || !isset($course->sectioncache)) {
248 $course = get_course($course->id, false);
249 }
250
ce4dfd27 251 // Check modinfo field is set. If not, build and load it.
252 if (empty($course->modinfo) || empty($course->sectioncache)) {
253 rebuild_course_cache($course->id);
74df2951 254 $course = $DB->get_record('course', array('id'=>$course->id), '*', MUST_EXIST);
ce4dfd27 255 }
256
0d8b6a69 257 // Set initial values
258 $this->courseid = $course->id;
259 $this->userid = $userid;
260 $this->sections = array();
261 $this->cms = array();
262 $this->instances = array();
263 $this->groups = null;
264 $this->course = $course;
265
0d8b6a69 266 // Load modinfo field into memory as PHP object and check it's valid
267 $info = unserialize($course->modinfo);
268 if (!is_array($info)) {
269 // hmm, something is wrong - lets try to fix it
270 rebuild_course_cache($course->id);
271 $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
272 $info = unserialize($course->modinfo);
273 if (!is_array($info)) {
274 // If it still fails, abort
275 debugging('Problem with "modinfo" data for this course');
276 return;
277 }
278 }
279
ce4dfd27 280 // Load sectioncache field into memory as PHP object and check it's valid
281 $sectioncache = unserialize($course->sectioncache);
00726467 282 if (!is_array($sectioncache)) {
ce4dfd27 283 // hmm, something is wrong - let's fix it
284 rebuild_course_cache($course->id);
285 $course->sectioncache = $DB->get_field('course', 'sectioncache', array('id'=>$course->id));
286 $sectioncache = unserialize($course->sectioncache);
287 if (!is_array($sectioncache)) {
288 // If it still fails, abort
289 debugging('Problem with "sectioncache" data for this course');
290 return;
291 }
292 }
293
0d8b6a69 294 // If we haven't already preloaded contexts for the course, do it now
676fa06a 295 // Modules are also cached here as long as it's the first time this course has been preloaded.
8f7d3d12 296 context_helper::preload_course($course->id);
0d8b6a69 297
676fa06a
MG
298 // Quick integrity check: as a result of race conditions modinfo may not be regenerated after the change.
299 // It is especially dangerous if modinfo contains the deleted course module, as it results in fatal error.
300 // We can check it very cheap by validating the existence of module context.
301 if ($course->id == $COURSE->id || $course->id == $SITE->id) {
302 // Only verify current course (or frontpage) as pages with many courses may not have module contexts cached.
303 // (Uncached modules will result in a very slow verification).
304 foreach ($info as $mod) {
305 if (!context_module::instance($mod->cm, IGNORE_MISSING)) {
306 debugging('Course cache integrity check failed: course module with id '. $mod->cm.
307 ' does not have context. Rebuilding cache for course '. $course->id);
308 rebuild_course_cache($course->id);
309 $this->course = $DB->get_record('course', array('id' => $course->id), '*', MUST_EXIST);
310 $info = unserialize($this->course->modinfo);
311 $sectioncache = unserialize($this->course->sectioncache);
312 break;
313 }
314 }
315 }
316
0d8b6a69 317 // Loop through each piece of module data, constructing it
318 $modexists = array();
319 foreach ($info as $mod) {
320 if (empty($mod->name)) {
321 // something is wrong here
322 continue;
323 }
324
325 // Skip modules which don't exist
326 if (empty($modexists[$mod->mod])) {
327 if (!file_exists("$CFG->dirroot/mod/$mod->mod/lib.php")) {
328 continue;
329 }
330 $modexists[$mod->mod] = true;
331 }
332
333 // Construct info for this module
334 $cm = new cm_info($this, $course, $mod, $info);
335
336 // Store module in instances and cms array
337 if (!isset($this->instances[$cm->modname])) {
338 $this->instances[$cm->modname] = array();
339 }
340 $this->instances[$cm->modname][$cm->instance] = $cm;
341 $this->cms[$cm->id] = $cm;
342
343 // Reconstruct sections. This works because modules are stored in order
344 if (!isset($this->sections[$cm->sectionnum])) {
345 $this->sections[$cm->sectionnum] = array();
346 }
347 $this->sections[$cm->sectionnum][] = $cm->id;
348 }
349
ce4dfd27 350 // Expand section objects
351 $this->sectioninfo = array();
352 foreach ($sectioncache as $number => $data) {
4e430906
MG
353 $this->sectioninfo[$number] = new section_info($data, $number, null, null,
354 $this, null);
ce4dfd27 355 }
356
0d8b6a69 357 // We need at least 'dynamic' data from each course-module (this is basically the remaining
358 // data which was always present in previous version of get_fast_modinfo, so it's required
359 // for BC). Creating it in a second pass is necessary because obtain_dynamic_data sometimes
360 // needs to be able to refer to a 'complete' (with basic data) modinfo.
361 foreach ($this->cms as $cm) {
362 $cm->obtain_dynamic_data();
363 }
364 }
ce4dfd27 365
366 /**
367 * Builds a list of information about sections on a course to be stored in
368 * the course cache. (Does not include information that is already cached
369 * in some other way.)
370 *
371 * Used internally by rebuild_course_cache function; do not use otherwise.
372 * @param int $courseid Course ID
373 * @return array Information about sections, indexed by section number (not id)
374 */
375 public static function build_section_cache($courseid) {
376 global $DB;
377
378 // Get section data
379 $sections = $DB->get_records('course_sections', array('course' => $courseid), 'section',
380 'section, id, course, name, summary, summaryformat, sequence, visible, ' .
381 'availablefrom, availableuntil, showavailability, groupingid');
382 $compressedsections = array();
383
aea2e3c3 384 $formatoptionsdef = course_get_format($courseid)->section_format_options();
ce4dfd27 385 // Remove unnecessary data and add availability
386 foreach ($sections as $number => $section) {
aea2e3c3
MG
387 // Add cached options from course format to $section object
388 foreach ($formatoptionsdef as $key => $option) {
389 if (!empty($option['cache'])) {
390 $formatoptions = course_get_format($courseid)->get_format_options($section);
391 if (!array_key_exists('cachedefault', $option) || $option['cachedefault'] !== $formatoptions[$key]) {
392 $section->$key = $formatoptions[$key];
393 }
394 }
395 }
99e9f9a6 396 // Clone just in case it is reused elsewhere
ce4dfd27 397 $compressedsections[$number] = clone($section);
398 section_info::convert_for_section_cache($compressedsections[$number]);
399 }
400
401 return $compressedsections;
402 }
0d8b6a69 403}
404
405
406/**
407 * Data about a single module on a course. This contains most of the fields in the course_modules
408 * table, plus additional data when required.
409 *
410 * This object has many public fields; code should treat all these fields as read-only and set
411 * data only using the supplied set functions. Setting the fields directly is not supported
412 * and may cause problems later.
413 */
ce4dfd27 414class cm_info extends stdClass {
0d8b6a69 415 /**
416 * State: Only basic data from modinfo cache is available.
417 */
418 const STATE_BASIC = 0;
419
420 /**
421 * State: Dynamic data is available too.
422 */
423 const STATE_DYNAMIC = 1;
424
425 /**
426 * State: View data (for course page) is available.
427 */
428 const STATE_VIEW = 2;
429
430 /**
431 * Parent object
432 * @var course_modinfo
433 */
434 private $modinfo;
435
436 /**
437 * Level of information stored inside this object (STATE_xx constant)
438 * @var int
439 */
440 private $state;
441
442 // Existing data fields
443 ///////////////////////
444
445 /**
446 * Course-module ID - from course_modules table
447 * @var int
448 */
449 public $id;
450
451 /**
452 * Module instance (ID within module table) - from course_modules table
453 * @var int
454 */
455 public $instance;
456
457 /**
458 * Course ID - from course_modules table
459 * @var int
460 */
461 public $course;
462
463 /**
464 * 'ID number' from course-modules table (arbitrary text set by user) - from
465 * course_modules table
466 * @var string
467 */
468 public $idnumber;
469
470 /**
adaeccb6 471 * Time that this course-module was added (unix time) - from course_modules table
472 * @var int
473 */
474 public $added;
475
476 /**
477 * This variable is not used and is included here only so it can be documented.
478 * Once the database entry is removed from course_modules, it should be deleted
479 * here too.
480 * @var int
481 * @deprecated Do not use this variable
482 */
483 public $score;
484
485 /**
486 * Visible setting (0 or 1; if this is 0, students cannot see/access the activity) - from
0d8b6a69 487 * course_modules table
488 * @var int
489 */
490 public $visible;
491
adaeccb6 492 /**
493 * Old visible setting (if the entire section is hidden, the previous value for
494 * visible is stored in this field) - from course_modules table
495 * @var int
496 */
497 public $visibleold;
498
0d8b6a69 499 /**
500 * Group mode (one of the constants NONE, SEPARATEGROUPS, or VISIBLEGROUPS) - from
501 * course_modules table
502 * @var int
503 */
504 public $groupmode;
505
506 /**
507 * Grouping ID (0 = all groupings)
508 * @var int
509 */
510 public $groupingid;
511
512 /**
513 * Group members only (if set to 1, only members of a suitable group see this link on the
514 * course page; 0 = everyone sees it even if they don't belong to a suitable group) - from
515 * course_modules table
516 * @var int
517 */
518 public $groupmembersonly;
519
5c016ab3
MG
520 /**
521 * Indicates whether the course containing the module has forced the groupmode
522 * This means that cm_info::$groupmode should be ignored and cm_info::$coursegroupmode be
523 * used instead
524 * @var bool
525 */
526 public $coursegroupmodeforce;
527
528 /**
529 * Group mode (one of the constants NONE, SEPARATEGROUPS, or VISIBLEGROUPS) - from
530 * course table - as specified for the course containing the module
531 * Effective only if cm_info::$coursegroupmodeforce is set
532 * @var int
533 */
534 public $coursegroupmode;
535
0d8b6a69 536 /**
537 * Indent level on course page (0 = no indent) - from course_modules table
538 * @var int
539 */
540 public $indent;
541
542 /**
543 * Activity completion setting for this activity, COMPLETION_TRACKING_xx constant - from
544 * course_modules table
545 * @var int
546 */
547 public $completion;
548
adaeccb6 549 /**
550 * Set to the item number (usually 0) if completion depends on a particular
551 * grade of this activity, or null if completion does not depend on a grade - from
552 * course_modules table
553 * @var mixed
554 */
555 public $completiongradeitemnumber;
556
557 /**
558 * 1 if 'on view' completion is enabled, 0 otherwise - from course_modules table
559 * @var int
560 */
561 public $completionview;
562
563 /**
564 * Set to a unix time if completion of this activity is expected at a
565 * particular time, 0 if no time set - from course_modules table
566 * @var int
567 */
568 public $completionexpected;
569
0d8b6a69 570 /**
571 * Available date for this activity (0 if not set, or set to seconds since epoch; before this
572 * date, activity does not display to students) - from course_modules table
573 * @var int
574 */
575 public $availablefrom;
576
577 /**
578 * Available until date for this activity (0 if not set, or set to seconds since epoch; from
579 * this date, activity does not display to students) - from course_modules table
580 * @var int
581 */
582 public $availableuntil;
583
584 /**
585 * When activity is unavailable, this field controls whether it is shown to students (0 =
586 * hide completely, 1 = show greyed out with information about when it will be available) -
587 * from course_modules table
588 * @var int
589 */
590 public $showavailability;
591
8c40662e 592 /**
593 * Controls whether the description of the activity displays on the course main page (in
594 * addition to anywhere it might display within the activity itself). 0 = do not show
595 * on main page, 1 = show on main page.
596 * @var int
597 */
598 public $showdescription;
599
0d8b6a69 600 /**
601 * Extra HTML that is put in an unhelpful part of the HTML when displaying this module in
602 * course page - from cached data in modinfo field
603 * @deprecated This is crazy, don't use it. Replaced by ->extraclasses and ->onclick
604 * @var string
605 */
606 public $extra;
607
608 /**
609 * Name of icon to use - from cached data in modinfo field
610 * @var string
611 */
612 public $icon;
613
614 /**
615 * Component that contains icon - from cached data in modinfo field
616 * @var string
617 */
618 public $iconcomponent;
619
620 /**
621 * Name of module e.g. 'forum' (this is the same name as the module's main database
622 * table) - from cached data in modinfo field
623 * @var string
624 */
625 public $modname;
626
adaeccb6 627 /**
628 * ID of module - from course_modules table
629 * @var int
630 */
631 public $module;
632
0d8b6a69 633 /**
634 * Name of module instance for display on page e.g. 'General discussion forum' - from cached
635 * data in modinfo field
636 * @var string
637 */
638 public $name;
639
640 /**
641 * Section number that this course-module is in (section 0 = above the calendar, section 1
642 * = week/topic 1, etc) - from cached data in modinfo field
643 * @var string
644 */
645 public $sectionnum;
646
adaeccb6 647 /**
648 * Section id - from course_modules table
649 * @var int
650 */
651 public $section;
652
0d8b6a69 653 /**
654 * Availability conditions for this course-module based on the completion of other
655 * course-modules (array from other course-module id to required completion state for that
656 * module) - from cached data in modinfo field
657 * @var array
658 */
659 public $conditionscompletion;
660
661 /**
662 * Availability conditions for this course-module based on course grades (array from
663 * grade item id to object with ->min, ->max fields) - from cached data in modinfo field
664 * @var array
665 */
666 public $conditionsgrade;
667
76af15bb
MN
668 /**
669 * Availability conditions for this course-module based on user fields
670 * @var array
671 */
672 public $conditionsfield;
673
0d8b6a69 674 /**
675 * True if this course-module is available to students i.e. if all availability conditions
676 * are met - obtained dynamically
677 * @var bool
678 */
679 public $available;
680
681 /**
682 * If course-module is not available to students, this string gives information about
683 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
684 * January 2010') for display on main page - obtained dynamically
685 * @var string
686 */
687 public $availableinfo;
688
689 /**
690 * True if this course-module is available to the CURRENT user (for example, if current user
691 * has viewhiddenactivities capability, they can access the course-module even if it is not
692 * visible or not available, so this would be true in that case)
693 * @var bool
694 */
695 public $uservisible;
696
4478743c
PS
697 /**
698 * Module context - hacky shortcut
699 * @deprecated
700 * @var stdClass
701 */
702 public $context;
703
704
0d8b6a69 705 // New data available only via functions
706 ////////////////////////////////////////
707
708 /**
709 * @var moodle_url
710 */
711 private $url;
712
713 /**
714 * @var string
715 */
716 private $content;
717
718 /**
719 * @var string
720 */
721 private $extraclasses;
722
c443a1cd
EL
723 /**
724 * @var moodle_url full external url pointing to icon image for activity
725 */
726 private $iconurl;
727
0d8b6a69 728 /**
729 * @var string
730 */
731 private $onclick;
732
733 /**
734 * @var mixed
735 */
736 private $customdata;
737
738 /**
739 * @var string
740 */
741 private $afterlink;
742
743 /**
744 * @var string
745 */
746 private $afterediticons;
747
d57aa283
MG
748 /**
749 * Magic method getter
750 *
751 * @param string $name
752 * @return mixed
753 */
754 public function __get($name) {
755 switch ($name) {
756 case 'modplural':
757 return $this->get_module_type_name(true);
758 case 'modfullname':
759 return $this->get_module_type_name();
760 default:
761 debugging('Invalid cm_info property accessed: '.$name);
762 return null;
763 }
764 }
765
0d8b6a69 766 /**
767 * @return bool True if this module has a 'view' page that should be linked to in navigation
768 * etc (note: modules may still have a view.php file, but return false if this is not
769 * intended to be linked to from 'normal' parts of the interface; this is what label does).
770 */
771 public function has_view() {
772 return !is_null($this->url);
773 }
774
775 /**
776 * @return moodle_url URL to link to for this module, or null if it doesn't have a view page
777 */
778 public function get_url() {
779 return $this->url;
780 }
781
782 /**
783 * Obtains content to display on main (view) page.
784 * Note: Will collect view data, if not already obtained.
785 * @return string Content to display on main page below link, or empty string if none
786 */
787 public function get_content() {
788 $this->obtain_view_data();
789 return $this->content;
790 }
791
f89c53f6
MG
792 /**
793 * Returns the content to display on course/overview page, formatted and passed through filters
794 *
795 * if $options['context'] is not specified, the module context is used
796 *
797 * @param array|stdClass $options formatting options, see {@link format_text()}
798 * @return string
799 */
800 public function get_formatted_content($options = array()) {
801 $this->obtain_view_data();
802 if (empty($this->content)) {
803 return '';
804 }
f89c53f6
MG
805 // Improve filter performance by preloading filter setttings for all
806 // activities on the course (this does nothing if called multiple
807 // times)
808 filter_preload_activities($this->get_modinfo());
809
810 $options = (array)$options;
811 if (!isset($options['context'])) {
812 $options['context'] = context_module::instance($this->id);
813 }
814 return format_text($this->content, FORMAT_HTML, $options);
815 }
816
817 /**
818 * Returns the name to display on course/overview page, formatted and passed through filters
819 *
820 * if $options['context'] is not specified, the module context is used
821 *
822 * @param array|stdClass $options formatting options, see {@link format_string()}
823 * @return string
824 */
825 public function get_formatted_name($options = array()) {
826 $options = (array)$options;
827 if (!isset($options['context'])) {
828 $options['context'] = context_module::instance($this->id);
829 }
830 return format_string($this->name, true, $options);
831 }
832
0d8b6a69 833 /**
834 * Note: Will collect view data, if not already obtained.
835 * @return string Extra CSS classes to add to html output for this activity on main page
836 */
837 public function get_extra_classes() {
838 $this->obtain_view_data();
839 return $this->extraclasses;
840 }
841
842 /**
843 * @return string Content of HTML on-click attribute. This string will be used literally
844 * as a string so should be pre-escaped.
845 */
846 public function get_on_click() {
847 // Does not need view data; may be used by navigation
848 return $this->onclick;
849 }
850 /**
851 * @return mixed Optional custom data stored in modinfo cache for this activity, or null if none
852 */
853 public function get_custom_data() {
854 return $this->customdata;
855 }
856
857 /**
858 * Note: Will collect view data, if not already obtained.
c443a1cd 859 * @return string Extra HTML code to display after link
0d8b6a69 860 */
861 public function get_after_link() {
862 $this->obtain_view_data();
863 return $this->afterlink;
864 }
865
866 /**
867 * Note: Will collect view data, if not already obtained.
868 * @return string Extra HTML code to display after editing icons (e.g. more icons)
869 */
870 public function get_after_edit_icons() {
871 $this->obtain_view_data();
872 return $this->afterediticons;
873 }
874
875 /**
876 * @param moodle_core_renderer $output Output render to use, or null for default (global)
877 * @return moodle_url Icon URL for a suitable icon to put beside this cm
878 */
879 public function get_icon_url($output = null) {
880 global $OUTPUT;
881 if (!$output) {
882 $output = $OUTPUT;
883 }
c443a1cd
EL
884 // Support modules setting their own, external, icon image
885 if (!empty($this->iconurl)) {
886 $icon = $this->iconurl;
887
888 // Fallback to normal local icon + component procesing
889 } else if (!empty($this->icon)) {
0d8b6a69 890 if (substr($this->icon, 0, 4) === 'mod/') {
891 list($modname, $iconname) = explode('/', substr($this->icon, 4), 2);
892 $icon = $output->pix_url($iconname, $modname);
893 } else {
894 if (!empty($this->iconcomponent)) {
895 // Icon has specified component
896 $icon = $output->pix_url($this->icon, $this->iconcomponent);
897 } else {
898 // Icon does not have specified component, use default
899 $icon = $output->pix_url($this->icon);
900 }
901 }
902 } else {
903 $icon = $output->pix_url('icon', $this->modname);
904 }
905 return $icon;
906 }
907
d57aa283
MG
908 /**
909 * Returns a localised human-readable name of the module type
910 *
911 * @param bool $plural return plural form
912 * @return string
913 */
914 public function get_module_type_name($plural = false) {
915 $modnames = get_module_types_names($plural);
916 if (isset($modnames[$this->modname])) {
917 return $modnames[$this->modname];
918 } else {
919 return null;
920 }
921 }
922
0d8b6a69 923 /**
924 * @return course_modinfo Modinfo object that this came from
925 */
926 public function get_modinfo() {
927 return $this->modinfo;
928 }
929
930 /**
931 * @return object Moodle course object that was used to construct this data
932 */
933 public function get_course() {
934 return $this->modinfo->get_course();
935 }
936
937 // Set functions
938 ////////////////
939
940 /**
941 * Sets content to display on course view page below link (if present).
942 * @param string $content New content as HTML string (empty string if none)
943 * @return void
944 */
945 public function set_content($content) {
946 $this->content = $content;
947 }
948
949 /**
950 * Sets extra classes to include in CSS.
951 * @param string $extraclasses Extra classes (empty string if none)
952 * @return void
953 */
954 public function set_extra_classes($extraclasses) {
955 $this->extraclasses = $extraclasses;
956 }
957
c443a1cd
EL
958 /**
959 * Sets the external full url that points to the icon being used
960 * by the activity. Useful for external-tool modules (lti...)
961 * If set, takes precedence over $icon and $iconcomponent
962 *
963 * @param moodle_url $iconurl full external url pointing to icon image for activity
964 * @return void
965 */
966 public function set_icon_url(moodle_url $iconurl) {
967 $this->iconurl = $iconurl;
968 }
969
0d8b6a69 970 /**
971 * Sets value of on-click attribute for JavaScript.
972 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
973 * @param string $onclick New onclick attribute which should be HTML-escaped
974 * (empty string if none)
975 * @return void
976 */
977 public function set_on_click($onclick) {
978 $this->check_not_view_only();
979 $this->onclick = $onclick;
980 }
981
982 /**
983 * Sets HTML that displays after link on course view page.
984 * @param string $afterlink HTML string (empty string if none)
985 * @return void
986 */
987 public function set_after_link($afterlink) {
988 $this->afterlink = $afterlink;
989 }
990
991 /**
992 * Sets HTML that displays after edit icons on course view page.
993 * @param string $afterediticons HTML string (empty string if none)
994 * @return void
995 */
996 public function set_after_edit_icons($afterediticons) {
997 $this->afterediticons = $afterediticons;
998 }
999
1000 /**
1001 * Changes the name (text of link) for this module instance.
1002 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1003 * @param string $name Name of activity / link text
1004 * @return void
1005 */
1006 public function set_name($name) {
1007 $this->update_user_visible();
1008 $this->name = $name;
1009 }
1010
1011 /**
1012 * Turns off the view link for this module instance.
1013 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1014 * @return void
1015 */
1016 public function set_no_view_link() {
1017 $this->check_not_view_only();
4478743c 1018 $this->url = null;
0d8b6a69 1019 }
1020
1021 /**
1022 * Sets the 'uservisible' flag. This can be used (by setting false) to prevent access and
1023 * display of this module link for the current user.
1024 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1025 * @param bool $uservisible
1026 * @return void
1027 */
1028 public function set_user_visible($uservisible) {
1029 $this->check_not_view_only();
1030 $this->uservisible = $uservisible;
1031 }
1032
1033 /**
1034 * Sets the 'available' flag and related details. This flag is normally used to make
1035 * course modules unavailable until a certain date or condition is met. (When a course
1036 * module is unavailable, it is still visible to users who have viewhiddenactivities
1037 * permission.)
1038 *
1039 * When this is function is called, user-visible status is recalculated automatically.
1040 *
1041 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1042 * @param bool $available False if this item is not 'available'
1043 * @param int $showavailability 0 = do not show this item at all if it's not available,
1044 * 1 = show this item greyed out with the following message
1045 * @param string $availableinfo Information about why this is not available which displays
1046 * to those who have viewhiddenactivities, and to everyone if showavailability is set;
1047 * note that this function replaces the existing data (if any)
1048 * @return void
1049 */
1050 public function set_available($available, $showavailability=0, $availableinfo='') {
1051 $this->check_not_view_only();
1052 $this->available = $available;
1053 $this->showavailability = $showavailability;
1054 $this->availableinfo = $availableinfo;
1055 $this->update_user_visible();
1056 }
1057
1058 /**
1059 * Some set functions can only be called from _cm_info_dynamic and not _cm_info_view.
1060 * This is because they may affect parts of this object which are used on pages other
1061 * than the view page (e.g. in the navigation block, or when checking access on
1062 * module pages).
1063 * @return void
1064 */
1065 private function check_not_view_only() {
1066 if ($this->state >= self::STATE_DYNAMIC) {
1067 throw new coding_exception('Cannot set this data from _cm_info_view because it may ' .
1068 'affect other pages as well as view');
1069 }
1070 }
1071
1072 /**
1073 * Constructor should not be called directly; use get_fast_modinfo.
1074 * @param course_modinfo $modinfo Parent object
1075 * @param object $course Course row
1076 * @param object $mod Module object from the modinfo field of course table
1077 * @param object $info Entire object from modinfo field of course table
1078 */
1079 public function __construct(course_modinfo $modinfo, $course, $mod, $info) {
1080 global $CFG;
1081 $this->modinfo = $modinfo;
1082
1083 $this->id = $mod->cm;
1084 $this->instance = $mod->id;
1085 $this->course = $course->id;
1086 $this->modname = $mod->mod;
1087 $this->idnumber = isset($mod->idnumber) ? $mod->idnumber : '';
1088 $this->name = $mod->name;
1089 $this->visible = $mod->visible;
adaeccb6 1090 $this->sectionnum = $mod->section; // Note weirdness with name here
0d8b6a69 1091 $this->groupmode = isset($mod->groupmode) ? $mod->groupmode : 0;
1092 $this->groupingid = isset($mod->groupingid) ? $mod->groupingid : 0;
1093 $this->groupmembersonly = isset($mod->groupmembersonly) ? $mod->groupmembersonly : 0;
5c016ab3
MG
1094 $this->coursegroupmodeforce = $course->groupmodeforce;
1095 $this->coursegroupmode = $course->groupmode;
0d8b6a69 1096 $this->indent = isset($mod->indent) ? $mod->indent : 0;
0d8b6a69 1097 $this->extra = isset($mod->extra) ? $mod->extra : '';
1098 $this->extraclasses = isset($mod->extraclasses) ? $mod->extraclasses : '';
4fcdb012
MG
1099 // iconurl may be stored as either string or instance of moodle_url.
1100 $this->iconurl = isset($mod->iconurl) ? new moodle_url($mod->iconurl) : '';
0d8b6a69 1101 $this->onclick = isset($mod->onclick) ? $mod->onclick : '';
1102 $this->content = isset($mod->content) ? $mod->content : '';
1103 $this->icon = isset($mod->icon) ? $mod->icon : '';
1104 $this->iconcomponent = isset($mod->iconcomponent) ? $mod->iconcomponent : '';
1105 $this->customdata = isset($mod->customdata) ? $mod->customdata : '';
b0c6dc1c 1106 $this->context = context_module::instance($mod->cm);
8c40662e 1107 $this->showdescription = isset($mod->showdescription) ? $mod->showdescription : 0;
0d8b6a69 1108 $this->state = self::STATE_BASIC;
1109
adaeccb6 1110 // Note: These fields from $cm were not present in cm_info in Moodle
1111 // 2.0.2 and prior. They may not be available if course cache hasn't
1112 // been rebuilt since then.
1113 $this->section = isset($mod->sectionid) ? $mod->sectionid : 0;
1114 $this->module = isset($mod->module) ? $mod->module : 0;
1115 $this->added = isset($mod->added) ? $mod->added : 0;
1116 $this->score = isset($mod->score) ? $mod->score : 0;
1117 $this->visibleold = isset($mod->visibleold) ? $mod->visibleold : 0;
1118
1119 // Note: it saves effort and database space to always include the
1120 // availability and completion fields, even if availability or completion
1121 // are actually disabled
1122 $this->completion = isset($mod->completion) ? $mod->completion : 0;
1123 $this->completiongradeitemnumber = isset($mod->completiongradeitemnumber)
1124 ? $mod->completiongradeitemnumber : null;
1125 $this->completionview = isset($mod->completionview)
1126 ? $mod->completionview : 0;
1127 $this->completionexpected = isset($mod->completionexpected)
1128 ? $mod->completionexpected : 0;
1129 $this->showavailability = isset($mod->showavailability) ? $mod->showavailability : 0;
1130 $this->availablefrom = isset($mod->availablefrom) ? $mod->availablefrom : 0;
1131 $this->availableuntil = isset($mod->availableuntil) ? $mod->availableuntil : 0;
1132 $this->conditionscompletion = isset($mod->conditionscompletion)
1133 ? $mod->conditionscompletion : array();
1134 $this->conditionsgrade = isset($mod->conditionsgrade)
1135 ? $mod->conditionsgrade : array();
76af15bb
MN
1136 $this->conditionsfield = isset($mod->conditionsfield)
1137 ? $mod->conditionsfield : array();
0d8b6a69 1138
0d8b6a69 1139 static $modviews;
1140 if (!isset($modviews[$this->modname])) {
1141 $modviews[$this->modname] = !plugin_supports('mod', $this->modname,
1142 FEATURE_NO_VIEW_LINK);
1143 }
1144 $this->url = $modviews[$this->modname]
1145 ? new moodle_url('/mod/' . $this->modname . '/view.php', array('id'=>$this->id))
1146 : null;
1147 }
1148
1149 /**
1150 * If dynamic data for this course-module is not yet available, gets it.
1151 *
1152 * This function is automatically called when constructing course_modinfo, so users don't
1153 * need to call it.
1154 *
1155 * Dynamic data is data which does not come directly from the cache but is calculated at
1156 * runtime based on the current user. Primarily this concerns whether the user can access
1157 * the module or not.
1158 *
1159 * As part of this function, the module's _cm_info_dynamic function from its lib.php will
1160 * be called (if it exists).
1161 * @return void
1162 */
1163 public function obtain_dynamic_data() {
1164 global $CFG;
1165 if ($this->state >= self::STATE_DYNAMIC) {
1166 return;
1167 }
1168 $userid = $this->modinfo->get_user_id();
1169
1170 if (!empty($CFG->enableavailability)) {
4e430906 1171 require_once($CFG->libdir. '/conditionlib.php');
0d8b6a69 1172 // Get availability information
1173 $ci = new condition_info($this);
1174 // Note that the modinfo currently available only includes minimal details (basic data)
1175 // so passing it to this function is a bit dangerous as it would cause infinite
1176 // recursion if it tried to get dynamic data, however we know that this function only
1177 // uses basic data.
1178 $this->available = $ci->is_available($this->availableinfo, true,
1179 $userid, $this->modinfo);
ce4dfd27 1180
1181 // Check parent section
1182 $parentsection = $this->modinfo->get_section_info($this->sectionnum);
1183 if (!$parentsection->available) {
1184 // Do not store info from section here, as that is already
1185 // presented from the section (if appropriate) - just change
1186 // the flag
1187 $this->available = false;
1188 }
0d8b6a69 1189 } else {
1190 $this->available = true;
1191 }
1192
1193 // Update visible state for current user
1194 $this->update_user_visible();
1195
1196 // Let module make dynamic changes at this point
1197 $this->call_mod_function('cm_info_dynamic');
1198 $this->state = self::STATE_DYNAMIC;
1199 }
1200
1201 /**
5e762271
AD
1202 * Works out whether activity is available to the current user
1203 *
1204 * If the activity is unavailable, additional checks are required to determine if its hidden or greyed out
1205 *
1206 * @see is_user_access_restricted_by_group()
1207 * @see is_user_access_restricted_by_conditional_access()
0d8b6a69 1208 * @return void
1209 */
1210 private function update_user_visible() {
1211 global $CFG;
b0c6dc1c 1212 $modcontext = context_module::instance($this->id);
0d8b6a69 1213 $userid = $this->modinfo->get_user_id();
1214 $this->uservisible = true;
5e762271
AD
1215
1216 // If the user cannot access the activity set the uservisible flag to false.
1217 // Additional checks are required to determine whether the activity is entirely hidden or just greyed out.
0d8b6a69 1218 if ((!$this->visible or !$this->available) and
1219 !has_capability('moodle/course:viewhiddenactivities', $modcontext, $userid)) {
5e762271 1220
0d8b6a69 1221 $this->uservisible = false;
a098f340 1222 }
5e762271
AD
1223
1224 // Check group membership.
9e1fe421
TH
1225 if ($this->is_user_access_restricted_by_group() ||
1226 $this->is_user_access_restricted_by_capability()) {
5e762271
AD
1227
1228 $this->uservisible = false;
1229 // Ensure activity is completely hidden from the user.
5fee56d5
FM
1230 $this->showavailability = 0;
1231 }
1232 }
1233
1234 /**
5e762271
AD
1235 * Checks whether the module's group settings restrict the current user's access
1236 *
1237 * @return bool True if the user access is restricted
5fee56d5
FM
1238 */
1239 public function is_user_access_restricted_by_group() {
1240 global $CFG;
5e762271
AD
1241
1242 if (!empty($CFG->enablegroupmembersonly) and !empty($this->groupmembersonly)) {
1243 $modcontext = context_module::instance($this->id);
1244 $userid = $this->modinfo->get_user_id();
1245 if (!has_capability('moodle/site:accessallgroups', $modcontext, $userid)) {
1246 // If the activity has 'group members only' and you don't have accessallgroups...
1247 $groups = $this->modinfo->get_groups($this->groupingid);
1248 if (empty($groups)) {
1249 // ...and you don't belong to a group, then set it so you can't see/access it
1250 return true;
1251 }
1252 }
1253 }
1254 return false;
1255 }
1256
9e1fe421
TH
1257 /**
1258 * Checks whether mod/...:view capability restricts the current user's access.
1259 *
1260 * @return bool True if the user access is restricted.
1261 */
1262 public function is_user_access_restricted_by_capability() {
1263 $capability = 'mod/' . $this->modname . ':view';
1264 $capabilityinfo = get_capability_info($capability);
1265 if (!$capabilityinfo) {
1266 // Capability does not exist, no one is prevented from seeing the activity.
1267 return false;
1268 }
1269
1270 // You are blocked if you don't have the capability.
3e439915
MG
1271 $userid = $this->modinfo->get_user_id();
1272 return !has_capability($capability, context_module::instance($this->id), $userid);
9e1fe421
TH
1273 }
1274
5e762271
AD
1275 /**
1276 * Checks whether the module's conditional access settings mean that the user cannot see the activity at all
1277 *
1278 * @return bool True if the user cannot see the module. False if the activity is either available or should be greyed out.
1279 */
1280 public function is_user_access_restricted_by_conditional_access() {
3e439915 1281 global $CFG;
5e762271
AD
1282
1283 if (empty($CFG->enableavailability)) {
1284 return false;
1285 }
1286
4e430906
MG
1287 require_once($CFG->libdir. '/conditionlib.php');
1288
5e762271
AD
1289 // If module will always be visible anyway (but greyed out), don't bother checking anything else
1290 if ($this->showavailability == CONDITION_STUDENTVIEW_SHOW) {
1291 return false;
1292 }
1293
1294 // Can the user see hidden modules?
5fee56d5
FM
1295 $modcontext = context_module::instance($this->id);
1296 $userid = $this->modinfo->get_user_id();
5e762271
AD
1297 if (has_capability('moodle/course:viewhiddenactivities', $modcontext, $userid)) {
1298 return false;
0d8b6a69 1299 }
5e762271
AD
1300
1301 // Is the module hidden due to unmet conditions?
1302 if (!$this->available) {
1303 return true;
1304 }
1305
5fee56d5 1306 return false;
0d8b6a69 1307 }
1308
1309 /**
1310 * Calls a module function (if exists), passing in one parameter: this object.
1311 * @param string $type Name of function e.g. if this is 'grooblezorb' and the modname is
1312 * 'forum' then it will try to call 'mod_forum_grooblezorb' or 'forum_grooblezorb'
1313 * @return void
1314 */
1315 private function call_mod_function($type) {
1316 global $CFG;
1317 $libfile = $CFG->dirroot . '/mod/' . $this->modname . '/lib.php';
1318 if (file_exists($libfile)) {
1319 include_once($libfile);
1320 $function = 'mod_' . $this->modname . '_' . $type;
1321 if (function_exists($function)) {
1322 $function($this);
1323 } else {
1324 $function = $this->modname . '_' . $type;
1325 if (function_exists($function)) {
1326 $function($this);
1327 }
1328 }
1329 }
1330 }
1331
1332 /**
1333 * If view data for this course-module is not yet available, obtains it.
1334 *
1335 * This function is automatically called if any of the functions (marked) which require
1336 * view data are called.
1337 *
1338 * View data is data which is needed only for displaying the course main page (& any similar
1339 * functionality on other pages) but is not needed in general. Obtaining view data may have
1340 * a performance cost.
1341 *
1342 * As part of this function, the module's _cm_info_view function from its lib.php will
1343 * be called (if it exists).
1344 * @return void
1345 */
1346 private function obtain_view_data() {
1347 if ($this->state >= self::STATE_VIEW) {
1348 return;
1349 }
1350
1351 // Let module make changes at this point
1352 $this->call_mod_function('cm_info_view');
1353 $this->state = self::STATE_VIEW;
1354 }
1355}
1356
1357
0d8b6a69 1358/**
1359 * Returns reference to full info about modules in course (including visibility).
1360 * Cached and as fast as possible (0 or 1 db query).
1361 *
9428a154
MG
1362 * use get_fast_modinfo($courseid, 0, true) to reset the static cache for particular course
1363 * use get_fast_modinfo(0, 0, true) to reset the static cache for all courses
1364 *
0d8b6a69 1365 * @uses MAX_MODINFO_CACHE_SIZE
9428a154
MG
1366 * @param int|stdClass $courseorid object from DB table 'course' or just a course id
1367 * @param int $userid User id to populate 'uservisible' attributes of modules and sections.
1368 * Set to 0 for current user (default)
b46be6ad
MG
1369 * @param bool $resetonly whether we want to get modinfo or just reset the cache
1370 * @return course_modinfo|null Module information for course, or null if resetting
0d8b6a69 1371 */
b46be6ad
MG
1372function get_fast_modinfo($courseorid, $userid = 0, $resetonly = false) {
1373 global $CFG, $USER;
0d8b6a69 1374
1375 static $cache = array();
1376
b46be6ad
MG
1377 // compartibility with syntax prior to 2.4:
1378 if ($courseorid === 'reset') {
1379 debugging("Using the string 'reset' as the first argument of get_fast_modinfo() is deprecated. Use get_fast_modinfo(0,0,true) instead.", DEBUG_DEVELOPER);
1380 $courseorid = 0;
1381 $resetonly = true;
1382 }
1383
4202471a
MG
1384 // Function get_fast_modinfo() can never be called during upgrade unless it is used for clearing cache only.
1385 if (!$resetonly) {
1386 upgrade_ensure_not_running();
1387 }
1388
b46be6ad
MG
1389 if (is_object($courseorid)) {
1390 $course = $courseorid;
1391 } else {
5a3204d0 1392 $course = (object)array('id' => $courseorid);
b46be6ad
MG
1393 }
1394
1395 // Function is called with $reset = true
1396 if ($resetonly) {
1397 if (isset($course->id) && $course->id > 0) {
1398 $cache[$course->id] = false;
1399 } else {
1400 foreach (array_keys($cache) as $key) {
1401 $cache[$key] = false;
1402 }
1403 }
0d8b6a69 1404 return null;
1405 }
1406
b46be6ad 1407 // Function is called with $reset = false, retrieve modinfo
0d8b6a69 1408 if (empty($userid)) {
1409 $userid = $USER->id;
1410 }
1411
b46be6ad
MG
1412 if (array_key_exists($course->id, $cache)) {
1413 if ($cache[$course->id] === false) {
1414 // this course has been recently reset, do not rely on modinfo and sectioncache in $course
1415 $course->modinfo = null;
1416 $course->sectioncache = null;
1417 } else if ($cache[$course->id]->userid == $userid) {
1418 // this course's modinfo for the same user was recently retrieved, return cached
1419 return $cache[$course->id];
1420 }
0d8b6a69 1421 }
1422
0d8b6a69 1423 unset($cache[$course->id]); // prevent potential reference problems when switching users
1424
adaeccb6 1425 $cache[$course->id] = new course_modinfo($course, $userid);
0d8b6a69 1426
1427 // Ensure cache does not use too much RAM
1428 if (count($cache) > MAX_MODINFO_CACHE_SIZE) {
1429 reset($cache);
1430 $key = key($cache);
b2b2c136
RK
1431 // Unsetting static variable in PHP is percular, it removes the reference,
1432 // but data remain in memory. Prior to unsetting, the varable needs to be
1433 // set to empty to remove its remains from memory.
1434 $cache[$key] = '';
0d8b6a69 1435 unset($cache[$key]);
1436 }
1437
1438 return $cache[$course->id];
1439}
1440
112d3b49
PS
1441/**
1442 * Rebuilds the cached list of course activities stored in the database
1443 * @param int $courseid - id of course to rebuild, empty means all
1444 * @param boolean $clearonly - only clear the modinfo fields, gets rebuild automatically on the fly
1445 */
1446function rebuild_course_cache($courseid=0, $clearonly=false) {
e271f71d 1447 global $COURSE, $SITE, $DB, $CFG;
112d3b49 1448
4202471a
MG
1449 // Function rebuild_course_cache() can not be called during upgrade unless it's clear only.
1450 if (!$clearonly && !upgrade_ensure_not_running(true)) {
1451 $clearonly = true;
1452 }
1453
112d3b49
PS
1454 // Destroy navigation caches
1455 navigation_cache::destroy_volatile_caches();
1456
ee7084e9
MG
1457 if (class_exists('format_base')) {
1458 // if file containing class is not loaded, there is no cache there anyway
1459 format_base::reset_course_cache($courseid);
1460 }
1461
112d3b49
PS
1462 if ($clearonly) {
1463 if (empty($courseid)) {
4202471a 1464 $DB->execute('UPDATE {course} set modinfo = ?, sectioncache = ?', array(null, null));
487caf6b
SH
1465 } else {
1466 // Clear both fields in one update
1467 $resetobj = (object)array('id' => $courseid, 'modinfo' => null, 'sectioncache' => null);
1468 $DB->update_record('course', $resetobj);
1469 }
1470 // update cached global COURSE too ;-)
1471 if ($courseid == $COURSE->id or empty($courseid)) {
112d3b49 1472 $COURSE->modinfo = null;
ce4dfd27 1473 $COURSE->sectioncache = null;
487caf6b
SH
1474 }
1475 if ($courseid == $SITE->id) {
e271f71d
PS
1476 $SITE->modinfo = null;
1477 $SITE->sectioncache = null;
1478 }
112d3b49 1479 // reset the fast modinfo cache
b46be6ad 1480 get_fast_modinfo($courseid, 0, true);
112d3b49
PS
1481 return;
1482 }
1483
1484 require_once("$CFG->dirroot/course/lib.php");
1485
1486 if ($courseid) {
1487 $select = array('id'=>$courseid);
1488 } else {
1489 $select = array();
1490 @set_time_limit(0); // this could take a while! MDL-10954
1491 }
1492
1493 $rs = $DB->get_recordset("course", $select,'','id,fullname');
1494 foreach ($rs as $course) {
1495 $modinfo = serialize(get_array_of_activities($course->id));
ce4dfd27 1496 $sectioncache = serialize(course_modinfo::build_section_cache($course->id));
1497 $updateobj = (object)array('id' => $course->id,
1498 'modinfo' => $modinfo, 'sectioncache' => $sectioncache);
487caf6b
SH
1499 $DB->update_record("course", $updateobj);
1500 // update cached global COURSE too ;-)
1501 if ($course->id == $COURSE->id) {
1502 $COURSE->modinfo = $modinfo;
1503 $COURSE->sectioncache = $sectioncache;
1504 }
1505 if ($course->id == $SITE->id) {
1506 $SITE->modinfo = $modinfo;
1507 $SITE->sectioncache = $sectioncache;
1508 }
112d3b49
PS
1509 }
1510 $rs->close();
1511 // reset the fast modinfo cache
b46be6ad 1512 get_fast_modinfo($courseid, 0, true);
112d3b49
PS
1513}
1514
0d8b6a69 1515
1516/**
1517 * Class that is the return value for the _get_coursemodule_info module API function.
1518 *
1519 * Note: For backward compatibility, you can also return a stdclass object from that function.
3008f86c
MG
1520 * The difference is that the stdclass object may contain an 'extra' field (deprecated,
1521 * use extraclasses and onclick instead). The stdclass object may not contain
0d8b6a69 1522 * the new fields defined here (content, extraclasses, customdata).
1523 */
1524class cached_cm_info {
1525 /**
1526 * Name (text of link) for this activity; Leave unset to accept default name
1527 * @var string
1528 */
1529 public $name;
1530
1531 /**
1532 * Name of icon for this activity. Normally, this should be used together with $iconcomponent
1533 * to define the icon, as per pix_url function.
1534 * For backward compatibility, if this value is of the form 'mod/forum/icon' then an icon
1535 * within that module will be used.
1536 * @see cm_info::get_icon_url()
1537 * @see renderer_base::pix_url()
1538 * @var string
1539 */
1540 public $icon;
1541
1542 /**
1543 * Component for icon for this activity, as per pix_url; leave blank to use default 'moodle'
1544 * component
1545 * @see renderer_base::pix_url()
1546 * @var string
1547 */
1548 public $iconcomponent;
1549
1550 /**
1551 * HTML content to be displayed on the main page below the link (if any) for this course-module
1552 * @var string
1553 */
1554 public $content;
1555
1556 /**
1557 * Custom data to be stored in modinfo for this activity; useful if there are cases when
1558 * internal information for this activity type needs to be accessible from elsewhere on the
1559 * course without making database queries. May be of any type but should be short.
1560 * @var mixed
1561 */
1562 public $customdata;
1563
1564 /**
1565 * Extra CSS class or classes to be added when this activity is displayed on the main page;
1566 * space-separated string
1567 * @var string
1568 */
1569 public $extraclasses;
1570
c443a1cd
EL
1571 /**
1572 * External URL image to be used by activity as icon, useful for some external-tool modules
1573 * like lti. If set, takes precedence over $icon and $iconcomponent
1574 * @var $moodle_url
1575 */
1576 public $iconurl;
1577
0d8b6a69 1578 /**
1579 * Content of onclick JavaScript; escaped HTML to be inserted as attribute value
1580 * @var string
1581 */
1582 public $onclick;
c443a1cd 1583}
ce4dfd27 1584
1585
1586/**
1587 * Data about a single section on a course. This contains the fields from the
1588 * course_sections table, plus additional data when required.
4e430906
MG
1589 *
1590 * @property-read int $id Section ID - from course_sections table
1591 * @property-read int $course Course ID - from course_sections table
1592 * @property-read int $section Section number - from course_sections table
1593 * @property-read string $name Section name if specified - from course_sections table
1594 * @property-read int $visible Section visibility (1 = visible) - from course_sections table
1595 * @property-read string $summary Section summary text if specified - from course_sections table
1596 * @property-read int $summaryformat Section summary text format (FORMAT_xx constant) - from course_sections table
1597 * @property-read int $showavailability When section is unavailable, this field controls whether it is shown to students (0 =
1598 * hide completely, 1 = show greyed out with information about when it will be available) -
1599 * from course_sections table
1600 * @property-read int $availablefrom Available date for this section (0 if not set, or set to seconds since epoch;
1601 * before this date, section does not display to students) - from course_sections table
1602 * @property-read int $availableuntil Available until date for this section (0 if not set, or set to seconds since epoch;
1603 * from this date, section does not display to students) - from course_sections table
1604 * @property-read int $groupingid If section is restricted to users of a particular grouping, this is its id (0 if not set) -
1605 * from course_sections table
1606 * @property-read array $conditionscompletion Availability conditions for this section based on the completion of
1607 * course-modules (array from course-module id to required completion state
1608 * for that module) - from cached data in sectioncache field
1609 * @property-read array $conditionsgrade Availability conditions for this section based on course grades (array from
1610 * grade item id to object with ->min, ->max fields) - from cached data in
1611 * sectioncache field
1612 * @property-read array $conditionsfield Availability conditions for this section based on user fields
1613 * @property-read bool $available True if this section is available to the given user i.e. if all availability conditions
1614 * are met - obtained dynamically
1615 * @property-read string $availableinfo If section is not available to some users, this string gives information about
1616 * availability which can be displayed to students and/or staff (e.g. 'Available from 3 January 2010')
1617 * for display on main page - obtained dynamically
1618 * @property-read bool $uservisible True if this section is available to the given user (for example, if current user
1619 * has viewhiddensections capability, they can access the section even if it is not
1620 * visible or not available, so this would be true in that case) - obtained dynamically
1621 * @property-read string $sequence Comma-separated list of all modules in the section. Note, this field may not exactly
1622 * match course_sections.sequence if later has references to non-existing modules or not modules of not available module types.
ce4dfd27 1623 */
fc79ede5 1624class section_info implements IteratorAggregate {
ce4dfd27 1625 /**
1626 * Section ID - from course_sections table
1627 * @var int
1628 */
fc79ede5 1629 private $_id;
ce4dfd27 1630
ce4dfd27 1631 /**
1632 * Section number - from course_sections table
1633 * @var int
1634 */
fc79ede5 1635 private $_section;
ce4dfd27 1636
1637 /**
1638 * Section name if specified - from course_sections table
1639 * @var string
1640 */
fc79ede5 1641 private $_name;
ce4dfd27 1642
1643 /**
1644 * Section visibility (1 = visible) - from course_sections table
1645 * @var int
1646 */
fc79ede5 1647 private $_visible;
ce4dfd27 1648
1649 /**
1650 * Section summary text if specified - from course_sections table
1651 * @var string
1652 */
fc79ede5 1653 private $_summary;
ce4dfd27 1654
1655 /**
1656 * Section summary text format (FORMAT_xx constant) - from course_sections table
1657 * @var int
1658 */
fc79ede5 1659 private $_summaryformat;
ce4dfd27 1660
1661 /**
1662 * When section is unavailable, this field controls whether it is shown to students (0 =
1663 * hide completely, 1 = show greyed out with information about when it will be available) -
1664 * from course_sections table
1665 * @var int
1666 */
fc79ede5 1667 private $_showavailability;
ce4dfd27 1668
1669 /**
1670 * Available date for this section (0 if not set, or set to seconds since epoch; before this
1671 * date, section does not display to students) - from course_sections table
1672 * @var int
1673 */
fc79ede5 1674 private $_availablefrom;
ce4dfd27 1675
1676 /**
1677 * Available until date for this section (0 if not set, or set to seconds since epoch; from
1678 * this date, section does not display to students) - from course_sections table
1679 * @var int
1680 */
fc79ede5 1681 private $_availableuntil;
ce4dfd27 1682
1683 /**
1684 * If section is restricted to users of a particular grouping, this is its id
1685 * (0 if not set) - from course_sections table
1686 * @var int
1687 */
fc79ede5 1688 private $_groupingid;
ce4dfd27 1689
1690 /**
1691 * Availability conditions for this section based on the completion of
1692 * course-modules (array from course-module id to required completion state
1693 * for that module) - from cached data in sectioncache field
1694 * @var array
1695 */
fc79ede5 1696 private $_conditionscompletion;
ce4dfd27 1697
1698 /**
1699 * Availability conditions for this section based on course grades (array from
1700 * grade item id to object with ->min, ->max fields) - from cached data in
1701 * sectioncache field
1702 * @var array
1703 */
fc79ede5
MG
1704 private $_conditionsgrade;
1705
1706 /**
1707 * Availability conditions for this section based on user fields
1708 * @var array
1709 */
1710 private $_conditionsfield;
ce4dfd27 1711
1712 /**
1713 * True if this section is available to students i.e. if all availability conditions
4e430906
MG
1714 * are met - obtained dynamically on request, see function {@link section_info::get_available()}
1715 * @var bool|null
ce4dfd27 1716 */
fc79ede5 1717 private $_available;
ce4dfd27 1718
1719 /**
4e430906 1720 * If section is not available to some users, this string gives information about
ce4dfd27 1721 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
4e430906
MG
1722 * January 2010') for display on main page - obtained dynamically on request, see
1723 * function {@link section_info::get_availableinfo()}
ce4dfd27 1724 * @var string
1725 */
fc79ede5 1726 private $_availableinfo;
ce4dfd27 1727
1728 /**
1729 * True if this section is available to the CURRENT user (for example, if current user
1730 * has viewhiddensections capability, they can access the section even if it is not
4e430906
MG
1731 * visible or not available, so this would be true in that case) - obtained dynamically
1732 * on request, see function {@link section_info::get_uservisible()}
1733 * @var bool|null
ce4dfd27 1734 */
fc79ede5 1735 private $_uservisible;
ce4dfd27 1736
1737 /**
1738 * Default values for sectioncache fields; if a field has this value, it won't
1739 * be stored in the sectioncache cache, to save space. Checks are done by ===
1740 * which means values must all be strings.
1741 * @var array
1742 */
1743 private static $sectioncachedefaults = array(
1744 'name' => null,
1745 'summary' => '',
1746 'summaryformat' => '1', // FORMAT_HTML, but must be a string
1747 'visible' => '1',
1748 'showavailability' => '0',
1749 'availablefrom' => '0',
1750 'availableuntil' => '0',
1751 'groupingid' => '0',
1752 );
1753
aea2e3c3
MG
1754 /**
1755 * Stores format options that have been cached when building 'coursecache'
1756 * When the format option is requested we look first if it has been cached
1757 * @var array
1758 */
1759 private $cachedformatoptions = array();
1760
4e430906
MG
1761 /**
1762 * Stores the list of all possible section options defined in each used course format.
1763 * @var array
1764 */
1765 static private $sectionformatoptions = array();
1766
1767 /**
1768 * Stores the modinfo object passed in constructor, may be used when requesting
1769 * dynamically obtained attributes such as available, availableinfo, uservisible.
1770 * Also used to retrun information about current course or user.
1771 * @var course_modinfo
1772 */
1773 private $modinfo;
1774
ce4dfd27 1775 /**
1776 * Constructs object from database information plus extra required data.
1777 * @param object $data Array entry from cached sectioncache
1778 * @param int $number Section number (array key)
4e430906
MG
1779 * @param int $notused1 argument not used (informaion is available in $modinfo)
1780 * @param int $notused2 argument not used (informaion is available in $modinfo)
ce4dfd27 1781 * @param course_modinfo $modinfo Owner (needed for checking availability)
4e430906 1782 * @param int $notused3 argument not used (informaion is available in $modinfo)
ce4dfd27 1783 */
4e430906 1784 public function __construct($data, $number, $notused1, $notused2, $modinfo, $notused3) {
ce4dfd27 1785 global $CFG;
4202471a 1786 require_once($CFG->dirroot.'/course/lib.php');
ce4dfd27 1787
1788 // Data that is always present
fc79ede5
MG
1789 $this->_id = $data->id;
1790
1791 $defaults = self::$sectioncachedefaults +
1792 array('conditionscompletion' => array(),
1793 'conditionsgrade' => array(),
1794 'conditionsfield' => array());
ce4dfd27 1795
1796 // Data that may use default values to save cache size
fc79ede5 1797 foreach ($defaults as $field => $value) {
ce4dfd27 1798 if (isset($data->{$field})) {
fc79ede5 1799 $this->{'_'.$field} = $data->{$field};
ce4dfd27 1800 } else {
fc79ede5 1801 $this->{'_'.$field} = $value;
ce4dfd27 1802 }
1803 }
1804
4e430906
MG
1805 // Other data from constructor arguments.
1806 $this->_section = $number;
1807 $this->modinfo = $modinfo;
1808
1809 // Cached course format data.
1810 $course = $modinfo->get_course();
1811 if (!isset($course->format) || !isset(self::$sectionformatoptions[$course->format])) {
1812 $courseformat = course_get_format(isset($course->format) ? $course : $course->id);
1813 if (!isset($course->format)) {
1814 $course->format = $courseformat->get_format();
1815 }
1816 self::$sectionformatoptions[$course->format] = $courseformat->section_format_options();
1817 }
1818 foreach (self::$sectionformatoptions[$course->format] as $field => $option) {
aea2e3c3
MG
1819 if (!empty($option['cache'])) {
1820 if (isset($data->{$field})) {
1821 $this->cachedformatoptions[$field] = $data->{$field};
1822 } else if (array_key_exists('cachedefault', $option)) {
1823 $this->cachedformatoptions[$field] = $option['cachedefault'];
1824 }
1825 }
1826 }
ce4dfd27 1827 }
1828
fc79ede5
MG
1829 /**
1830 * Magic method to check if the property is set
1831 *
1832 * @param string $name name of the property
1833 * @return bool
1834 */
1835 public function __isset($name) {
4e430906
MG
1836 if (method_exists($this, 'get_'.$name) ||
1837 property_exists($this, '_'.$name) ||
1838 array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
fc79ede5
MG
1839 $value = $this->__get($name);
1840 return isset($value);
1841 }
1842 return false;
1843 }
1844
1845 /**
1846 * Magic method to check if the property is empty
1847 *
1848 * @param string $name name of the property
1849 * @return bool
1850 */
1851 public function __empty($name) {
4e430906
MG
1852 if (method_exists($this, 'get_'.$name) ||
1853 property_exists($this, '_'.$name) ||
1854 in_array($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
fc79ede5
MG
1855 $value = $this->__get($name);
1856 return empty($value);
1857 }
1858 return true;
1859 }
1860
1861 /**
1862 * Magic method to retrieve the property, this is either basic section property
1863 * or availability information or additional properties added by course format
1864 *
1865 * @param string $name name of the property
1866 * @return bool
1867 */
1868 public function __get($name) {
4e430906
MG
1869 if (method_exists($this, 'get_'.$name)) {
1870 return $this->{'get_'.$name}();
1871 }
fc79ede5
MG
1872 if (property_exists($this, '_'.$name)) {
1873 return $this->{'_'.$name};
1874 }
aea2e3c3
MG
1875 if (array_key_exists($name, $this->cachedformatoptions)) {
1876 return $this->cachedformatoptions[$name];
1877 }
fc79ede5 1878 // precheck if the option is defined in format to avoid unnecessary DB queries in get_format_options()
4e430906
MG
1879 if (in_array($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
1880 $formatoptions = course_get_format($this->modinfo->get_course())->get_format_options($this);
fc79ede5
MG
1881 return $formatoptions[$name];
1882 }
1883 debugging('Invalid section_info property accessed! '.$name);
1884 return null;
1885 }
1886
4e430906
MG
1887 /**
1888 * Finds whether this section is available at the moment for the current user.
1889 *
1890 * The value can be accessed publicly as $sectioninfo->available
1891 *
1892 * @return bool
1893 */
1894 private function get_available() {
1895 global $CFG;
1896 if ($this->_available !== null) {
1897 // Has already been calculated.
1898 return $this->_available;
1899 }
1900 if (!empty($CFG->enableavailability)) {
1901 require_once($CFG->libdir. '/conditionlib.php');
1902 // Get availability information
1903 $ci = new condition_info_section($this);
1904 $this->_available = $ci->is_available($this->_availableinfo, true,
1905 $this->modinfo->get_user_id(), $this->modinfo);
1906 if ($this->_availableinfo === '' && $this->_groupingid) {
1907 // Still may have some extra text in availableinfo because of groupping.
1908 // Set as undefined so the next call to get_availabeinfo() calculates it.
1909 $this->_availableinfo = null;
1910 }
1911 } else {
1912 $this->_available = true;
1913 $this->_availableinfo = '';
1914 }
1915 return $this->_available;
1916 }
1917
1918 /**
1919 * Returns the availability text shown next to the section on course page.
1920 *
1921 * @return string
1922 */
1923 private function get_availableinfo() {
1924 // Make sure $this->_available has been calculated, it may also fill the _availableinfo property.
1925 $this->get_available();
1926 if ($this->_availableinfo !== null) {
1927 // It has been already calculated.
1928 return $this->_availableinfo;
1929 }
1930 $this->_availableinfo = '';
1931 // Display grouping info if available & not already displaying
1932 // (it would already display if current user doesn't have access)
1933 // for people with managegroups - same logic/class as grouping label
1934 // on individual activities.
1935 $context = context_course::instance($this->get_course());
1936 $userid = $this->modinfo->get_user_id();
1937 if ($this->_groupingid && has_capability('moodle/course:managegroups', $context, $userid)) {
1938 $groupings = groups_get_all_groupings($this->get_course());
1939 $this->_availableinfo = html_writer::tag('span', '(' . format_string(
1940 $groupings[$this->_groupingid]->name, true, array('context' => $context)) .
1941 ')', array('class' => 'groupinglabel'));
1942 }
1943 return $this->_availableinfo;
1944 }
1945
fc79ede5
MG
1946 /**
1947 * Implementation of IteratorAggregate::getIterator(), allows to cycle through properties
1948 * and use {@link convert_to_array()}
1949 *
1950 * @return ArrayIterator
1951 */
1952 public function getIterator() {
1953 $ret = array();
1954 foreach (get_object_vars($this) as $key => $value) {
1955 if (substr($key, 0, 1) == '_') {
4e430906
MG
1956 if (method_exists($this, 'get'.$key)) {
1957 $ret[substr($key, 1)] = $this->{'get'.$key}();
1958 } else {
1959 $ret[substr($key, 1)] = $this->$key;
1960 }
fc79ede5
MG
1961 }
1962 }
4e430906
MG
1963 $ret['sequence'] = $this->get_sequence();
1964 $ret['course'] = $this->get_course();
1965 $ret = array_merge($ret, course_get_format($this->modinfo->get_course())->get_format_options($this->_section));
fc79ede5
MG
1966 return new ArrayIterator($ret);
1967 }
1968
ce4dfd27 1969 /**
1970 * Works out whether activity is visible *for current user* - if this is false, they
1971 * aren't allowed to access it.
4e430906
MG
1972 *
1973 * @return bool
ce4dfd27 1974 */
4e430906
MG
1975 private function get_uservisible() {
1976 if ($this->_uservisible !== null) {
1977 // Has already been calculated.
1978 return $this->_uservisible;
1979 }
fc79ede5 1980 $this->_uservisible = true;
4e430906
MG
1981 if (!$this->_visible || !$this->get_available()) {
1982 $coursecontext = context_course::instance($this->get_course());
1983 $userid = $this->modinfo->get_user_id();
1984 if (!has_capability('moodle/course:viewhiddensections', $coursecontext, $userid)) {
1985 $this->_uservisible = false;
1986 }
ce4dfd27 1987 }
4e430906
MG
1988 return $this->_uservisible;
1989 }
1990
1991 /**
1992 * Restores the course_sections.sequence value
1993 *
1994 * @return string
1995 */
1996 private function get_sequence() {
1997 if (!empty($this->modinfo->sections[$this->_section])) {
1998 return implode(',', $this->modinfo->sections[$this->_section]);
1999 } else {
2000 return '';
2001 }
2002 }
2003
2004 /**
2005 * Returns course ID - from course_sections table
2006 *
2007 * @return int
2008 */
2009 private function get_course() {
2010 return $this->modinfo->get_course_id();
ce4dfd27 2011 }
2012
2013 /**
2014 * Prepares section data for inclusion in sectioncache cache, removing items
2015 * that are set to defaults, and adding availability data if required.
2016 *
2017 * Called by build_section_cache in course_modinfo only; do not use otherwise.
2018 * @param object $section Raw section data object
2019 */
2020 public static function convert_for_section_cache($section) {
2021 global $CFG;
2022
2023 // Course id stored in course table
2024 unset($section->course);
2025 // Section number stored in array key
2026 unset($section->section);
2027 // Sequence stored implicity in modinfo $sections array
2028 unset($section->sequence);
2029
2030 // Add availability data if turned on
2031 if ($CFG->enableavailability) {
2032 require_once($CFG->dirroot . '/lib/conditionlib.php');
2033 condition_info_section::fill_availability_conditions($section);
2034 if (count($section->conditionscompletion) == 0) {
2035 unset($section->conditionscompletion);
2036 }
2037 if (count($section->conditionsgrade) == 0) {
2038 unset($section->conditionsgrade);
2039 }
2040 }
2041
2042 // Remove default data
94dc3c7d 2043 foreach (self::$sectioncachedefaults as $field => $value) {
ce4dfd27 2044 // Exact compare as strings to avoid problems if some strings are set
2045 // to "0" etc.
2046 if (isset($section->{$field}) && $section->{$field} === $value) {
2047 unset($section->{$field});
2048 }
2049 }
2050 }
2051}