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