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