MDL-61305 modinfo: Add back missing require for course
[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.
44ddd2a1
MG
42 *
43 * Use {@link get_fast_modinfo()} to retrieve the instance of the object for particular course
44 * and particular user.
45 *
46 * @property-read int $courseid Course ID
47 * @property-read int $userid User ID
48 * @property-read array $sections Array from section number (e.g. 0) to array of course-module IDs in that
49 * section; this only includes sections that contain at least one course-module
50 * @property-read cm_info[] $cms Array from course-module instance to cm_info object within this course, in
51 * order of appearance
52 * @property-read cm_info[][] $instances Array from string (modname) => int (instance id) => cm_info object
53 * @property-read array $groups Groups that the current user belongs to. Calculated on the first request.
54 * Is an array of grouping id => array of group id => group id. Includes grouping id 0 for 'all groups'
0d8b6a69 55 */
44ddd2a1 56class course_modinfo {
08ec1b4e 57 /** @var int Maximum time the course cache building lock can be held */
58 const COURSE_CACHE_LOCK_EXPIRY = 180;
59
60 /** @var int Time to wait for the course cache building lock before throwing an exception */
61 const COURSE_CACHE_LOCK_WAIT = 60;
62
299cfee5
MG
63 /**
64 * List of fields from DB table 'course' that are cached in MUC and are always present in course_modinfo::$course
65 * @var array
66 */
67 public static $cachedfields = array('shortname', 'fullname', 'format',
68 'enablecompletion', 'groupmode', 'groupmodeforce', 'cacherev');
69
44ddd2a1
MG
70 /**
71 * For convenience we store the course object here as it is needed in other parts of code
72 * @var stdClass
73 */
0d8b6a69 74 private $course;
0d8b6a69 75
76 /**
44ddd2a1
MG
77 * Array of section data from cache
78 * @var section_info[]
0d8b6a69 79 */
44ddd2a1 80 private $sectioninfo;
0d8b6a69 81
82 /**
83 * User ID
84 * @var int
0d8b6a69 85 */
44ddd2a1 86 private $userid;
0d8b6a69 87
88 /**
89 * Array from int (section num, e.g. 0) => array of int (course-module id); this list only
90 * includes sections that actually contain at least one course-module
91 * @var array
0d8b6a69 92 */
44ddd2a1 93 private $sections;
0d8b6a69 94
95 /**
96 * Array from int (cm id) => cm_info object
44ddd2a1 97 * @var cm_info[]
0d8b6a69 98 */
44ddd2a1 99 private $cms;
0d8b6a69 100
101 /**
102 * Array from string (modname) => int (instance id) => cm_info object
44ddd2a1 103 * @var cm_info[][]
0d8b6a69 104 */
44ddd2a1 105 private $instances;
0d8b6a69 106
107 /**
8d1f33e1 108 * Groups that the current user belongs to. This value is calculated on first
109 * request to the property or function.
110 * When set, it is an array of grouping id => array of group id => group id.
111 * Includes grouping id 0 for 'all groups'.
44ddd2a1
MG
112 * @var int[][]
113 */
114 private $groups;
115
116 /**
117 * List of class read-only properties and their getter methods.
118 * Used by magic functions __get(), __isset(), __empty()
0d8b6a69 119 * @var array
0d8b6a69 120 */
44ddd2a1
MG
121 private static $standardproperties = array(
122 'courseid' => 'get_course_id',
123 'userid' => 'get_user_id',
124 'sections' => 'get_sections',
125 'cms' => 'get_cms',
126 'instances' => 'get_instances',
127 'groups' => 'get_groups_all',
128 );
0d8b6a69 129
44ddd2a1
MG
130 /**
131 * Magic method getter
132 *
133 * @param string $name
134 * @return mixed
135 */
136 public function __get($name) {
137 if (isset(self::$standardproperties[$name])) {
138 $method = self::$standardproperties[$name];
139 return $this->$method();
140 } else {
141 debugging('Invalid course_modinfo property accessed: '.$name);
142 return null;
143 }
144 }
0d8b6a69 145
146 /**
44ddd2a1
MG
147 * Magic method for function isset()
148 *
149 * @param string $name
150 * @return bool
151 */
152 public function __isset($name) {
153 if (isset(self::$standardproperties[$name])) {
154 $value = $this->__get($name);
155 return isset($value);
156 }
157 return false;
158 }
159
160 /**
161 * Magic method for function empty()
162 *
163 * @param string $name
164 * @return bool
165 */
166 public function __empty($name) {
167 if (isset(self::$standardproperties[$name])) {
168 $value = $this->__get($name);
169 return empty($value);
170 }
171 return true;
172 }
173
174 /**
175 * Magic method setter
176 *
177 * Will display the developer warning when trying to set/overwrite existing property.
178 *
179 * @param string $name
180 * @param mixed $value
181 */
182 public function __set($name, $value) {
183 debugging("It is not allowed to set the property course_modinfo::\${$name}", DEBUG_DEVELOPER);
184 }
185
186 /**
299cfee5
MG
187 * Returns course object that was used in the first {@link get_fast_modinfo()} call.
188 *
189 * It may not contain all fields from DB table {course} but always has at least the following:
190 * id,shortname,fullname,format,enablecompletion,groupmode,groupmodeforce,cacherev
44ddd2a1
MG
191 *
192 * @return stdClass
0d8b6a69 193 */
194 public function get_course() {
195 return $this->course;
196 }
197
198 /**
199 * @return int Course ID
200 */
201 public function get_course_id() {
44ddd2a1 202 return $this->course->id;
0d8b6a69 203 }
204
205 /**
206 * @return int User ID
207 */
208 public function get_user_id() {
209 return $this->userid;
210 }
211
212 /**
213 * @return array Array from section number (e.g. 0) to array of course-module IDs in that
214 * section; this only includes sections that contain at least one course-module
215 */
216 public function get_sections() {
217 return $this->sections;
218 }
219
220 /**
44ddd2a1 221 * @return cm_info[] Array from course-module instance to cm_info object within this course, in
0d8b6a69 222 * order of appearance
223 */
224 public function get_cms() {
225 return $this->cms;
226 }
227
228 /**
229 * Obtains a single course-module object (for a course-module that is on this course).
230 * @param int $cmid Course-module ID
231 * @return cm_info Information about that course-module
232 * @throws moodle_exception If the course-module does not exist
233 */
234 public function get_cm($cmid) {
235 if (empty($this->cms[$cmid])) {
236 throw new moodle_exception('invalidcoursemodule', 'error');
237 }
238 return $this->cms[$cmid];
239 }
240
241 /**
242 * Obtains all module instances on this course.
44ddd2a1 243 * @return cm_info[][] Array from module name => array from instance id => cm_info
0d8b6a69 244 */
245 public function get_instances() {
246 return $this->instances;
247 }
248
d57aa283
MG
249 /**
250 * Returns array of localised human-readable module names used in this course
251 *
252 * @param bool $plural if true returns the plural form of modules names
253 * @return array
254 */
255 public function get_used_module_names($plural = false) {
256 $modnames = get_module_types_names($plural);
257 $modnamesused = array();
258 foreach ($this->get_cms() as $cmid => $mod) {
c1518631 259 if (!isset($modnamesused[$mod->modname]) && isset($modnames[$mod->modname]) && $mod->uservisible) {
d57aa283
MG
260 $modnamesused[$mod->modname] = $modnames[$mod->modname];
261 }
262 }
2f1e464a 263 core_collator::asort($modnamesused);
d57aa283
MG
264 return $modnamesused;
265 }
266
0d8b6a69 267 /**
268 * Obtains all instances of a particular module on this course.
269 * @param $modname Name of module (not full frankenstyle) e.g. 'label'
44ddd2a1 270 * @return cm_info[] Array from instance id => cm_info for modules on this course; empty if none
0d8b6a69 271 */
272 public function get_instances_of($modname) {
273 if (empty($this->instances[$modname])) {
274 return array();
275 }
276 return $this->instances[$modname];
277 }
278
279 /**
44ddd2a1
MG
280 * Groups that the current user belongs to organised by grouping id. Calculated on the first request.
281 * @return int[][] array of grouping id => array of group id => group id. Includes grouping id 0 for 'all groups'
0d8b6a69 282 */
44ddd2a1 283 private function get_groups_all() {
0d8b6a69 284 if (is_null($this->groups)) {
285 // NOTE: Performance could be improved here. The system caches user groups
286 // in $USER->groupmember[$courseid] => array of groupid=>groupid. Unfortunately this
287 // structure does not include grouping information. It probably could be changed to
288 // do so, without a significant performance hit on login, thus saving this one query
289 // each request.
44ddd2a1 290 $this->groups = groups_get_user_groups($this->course->id, $this->userid);
0d8b6a69 291 }
44ddd2a1
MG
292 return $this->groups;
293 }
294
295 /**
296 * Returns groups that the current user belongs to on the course. Note: If not already
297 * available, this may make a database query.
298 * @param int $groupingid Grouping ID or 0 (default) for all groups
299 * @return int[] Array of int (group id) => int (same group id again); empty array if none
300 */
301 public function get_groups($groupingid = 0) {
302 $allgroups = $this->get_groups_all();
303 if (!isset($allgroups[$groupingid])) {
0d8b6a69 304 return array();
305 }
44ddd2a1 306 return $allgroups[$groupingid];
0d8b6a69 307 }
308
ce4dfd27 309 /**
310 * Gets all sections as array from section number => data about section.
44ddd2a1 311 * @return section_info[] Array of section_info objects organised by section number
ce4dfd27 312 */
313 public function get_section_info_all() {
314 return $this->sectioninfo;
315 }
316
317 /**
94dc3c7d
EL
318 * Gets data about specific numbered section.
319 * @param int $sectionnumber Number (not id) of section
c069dacf 320 * @param int $strictness Use MUST_EXIST to throw exception if it doesn't
321 * @return section_info Information for numbered section or null if not found
322 */
323 public function get_section_info($sectionnumber, $strictness = IGNORE_MISSING) {
324 if (!array_key_exists($sectionnumber, $this->sectioninfo)) {
325 if ($strictness === MUST_EXIST) {
326 throw new moodle_exception('sectionnotexist');
327 } else {
328 return null;
329 }
330 }
ce4dfd27 331 return $this->sectioninfo[$sectionnumber];
332 }
333
299cfee5
MG
334 /**
335 * Static cache for generated course_modinfo instances
336 *
337 * @see course_modinfo::instance()
338 * @see course_modinfo::clear_instance_cache()
339 * @var course_modinfo[]
340 */
341 protected static $instancecache = array();
342
343 /**
344 * Timestamps (microtime) when the course_modinfo instances were last accessed
345 *
346 * It is used to remove the least recent accessed instances when static cache is full
347 *
348 * @var float[]
349 */
350 protected static $cacheaccessed = array();
351
352 /**
353 * Clears the cache used in course_modinfo::instance()
354 *
355 * Used in {@link get_fast_modinfo()} when called with argument $reset = true
356 * and in {@link rebuild_course_cache()}
357 *
358 * @param null|int|stdClass $courseorid if specified removes only cached value for this course
359 */
360 public static function clear_instance_cache($courseorid = null) {
361 if (empty($courseorid)) {
362 self::$instancecache = array();
363 self::$cacheaccessed = array();
364 return;
365 }
366 if (is_object($courseorid)) {
367 $courseorid = $courseorid->id;
368 }
369 if (isset(self::$instancecache[$courseorid])) {
370 // Unsetting static variable in PHP is peculiar, it removes the reference,
371 // but data remain in memory. Prior to unsetting, the varable needs to be
372 // set to empty to remove its remains from memory.
373 self::$instancecache[$courseorid] = '';
374 unset(self::$instancecache[$courseorid]);
375 unset(self::$cacheaccessed[$courseorid]);
376 }
377 }
378
379 /**
380 * Returns the instance of course_modinfo for the specified course and specified user
381 *
382 * This function uses static cache for the retrieved instances. The cache
383 * size is limited by MAX_MODINFO_CACHE_SIZE. If instance is not found in
384 * the static cache or it was created for another user or the cacherev validation
385 * failed - a new instance is constructed and returned.
386 *
387 * Used in {@link get_fast_modinfo()}
388 *
389 * @param int|stdClass $courseorid object from DB table 'course' (must have field 'id'
390 * and recommended to have field 'cacherev') or just a course id
391 * @param int $userid User id to populate 'availble' and 'uservisible' attributes of modules and sections.
392 * Set to 0 for current user (default). Set to -1 to avoid calculation of dynamic user-depended data.
393 * @return course_modinfo
394 */
395 public static function instance($courseorid, $userid = 0) {
396 global $USER;
397 if (is_object($courseorid)) {
398 $course = $courseorid;
399 } else {
400 $course = (object)array('id' => $courseorid);
401 }
402 if (empty($userid)) {
403 $userid = $USER->id;
404 }
405
406 if (!empty(self::$instancecache[$course->id])) {
407 if (self::$instancecache[$course->id]->userid == $userid &&
408 (!isset($course->cacherev) ||
409 $course->cacherev == self::$instancecache[$course->id]->get_course()->cacherev)) {
410 // This course's modinfo for the same user was recently retrieved, return cached.
411 self::$cacheaccessed[$course->id] = microtime(true);
412 return self::$instancecache[$course->id];
413 } else {
414 // Prevent potential reference problems when switching users.
415 self::clear_instance_cache($course->id);
416 }
417 }
418 $modinfo = new course_modinfo($course, $userid);
419
420 // We have a limit of MAX_MODINFO_CACHE_SIZE entries to store in static variable.
421 if (count(self::$instancecache) >= MAX_MODINFO_CACHE_SIZE) {
422 // Find the course that was the least recently accessed.
423 asort(self::$cacheaccessed, SORT_NUMERIC);
424 $courseidtoremove = key(array_reverse(self::$cacheaccessed, true));
425 self::clear_instance_cache($courseidtoremove);
426 }
427
428 // Add modinfo to the static cache.
429 self::$instancecache[$course->id] = $modinfo;
430 self::$cacheaccessed[$course->id] = microtime(true);
431
432 return $modinfo;
433 }
434
0d8b6a69 435 /**
436 * Constructs based on course.
437 * Note: This constructor should not usually be called directly.
438 * Use get_fast_modinfo($course) instead as this maintains a cache.
299cfee5 439 * @param stdClass $course course object, only property id is required.
0d8b6a69 440 * @param int $userid User ID
299cfee5 441 * @throws moodle_exception if course is not found
0d8b6a69 442 */
443 public function __construct($course, $userid) {
299cfee5 444 global $CFG, $COURSE, $SITE, $DB;
0d8b6a69 445
299cfee5
MG
446 if (!isset($course->cacherev)) {
447 // We require presence of property cacherev to validate the course cache.
448 // No need to clone the $COURSE or $SITE object here because we clone it below anyway.
5a3204d0
MG
449 $course = get_course($course->id, false);
450 }
451
299cfee5
MG
452 $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
453
454 // Retrieve modinfo from cache. If not present or cacherev mismatches, call rebuild and retrieve again.
455 $coursemodinfo = $cachecoursemodinfo->get($course->id);
456 if ($coursemodinfo === false || ($course->cacherev != $coursemodinfo->cacherev)) {
08ec1b4e 457 $lock = self::get_course_cache_lock($course->id);
458 try {
459 // Only actually do the build if it's still needed after getting the lock (not if
460 // somebody else, who might have been holding the lock, built it already).
461 $coursemodinfo = $cachecoursemodinfo->get($course->id);
462 if ($coursemodinfo === false || ($course->cacherev != $coursemodinfo->cacherev)) {
463 $coursemodinfo = self::inner_build_course_cache($course, $lock);
464 }
465 } finally {
466 $lock->release();
467 }
ce4dfd27 468 }
469
0d8b6a69 470 // Set initial values
0d8b6a69 471 $this->userid = $userid;
472 $this->sections = array();
473 $this->cms = array();
474 $this->instances = array();
475 $this->groups = null;
ce4dfd27 476
0d8b6a69 477 // If we haven't already preloaded contexts for the course, do it now
676fa06a 478 // Modules are also cached here as long as it's the first time this course has been preloaded.
8f7d3d12 479 context_helper::preload_course($course->id);
0d8b6a69 480
676fa06a
MG
481 // Quick integrity check: as a result of race conditions modinfo may not be regenerated after the change.
482 // It is especially dangerous if modinfo contains the deleted course module, as it results in fatal error.
483 // We can check it very cheap by validating the existence of module context.
484 if ($course->id == $COURSE->id || $course->id == $SITE->id) {
485 // Only verify current course (or frontpage) as pages with many courses may not have module contexts cached.
486 // (Uncached modules will result in a very slow verification).
299cfee5 487 foreach ($coursemodinfo->modinfo as $mod) {
676fa06a
MG
488 if (!context_module::instance($mod->cm, IGNORE_MISSING)) {
489 debugging('Course cache integrity check failed: course module with id '. $mod->cm.
490 ' does not have context. Rebuilding cache for course '. $course->id);
299cfee5
MG
491 // Re-request the course record from DB as well, don't use get_course() here.
492 $course = $DB->get_record('course', array('id' => $course->id), '*', MUST_EXIST);
493 $coursemodinfo = self::build_course_cache($course);
676fa06a
MG
494 break;
495 }
496 }
497 }
498
299cfee5
MG
499 // Overwrite unset fields in $course object with cached values, store the course object.
500 $this->course = fullclone($course);
501 foreach ($coursemodinfo as $key => $value) {
502 if ($key !== 'modinfo' && $key !== 'sectioncache' &&
503 (!isset($this->course->$key) || $key === 'cacherev')) {
504 $this->course->$key = $value;
505 }
506 }
507
0d8b6a69 508 // Loop through each piece of module data, constructing it
44ddd2a1 509 static $modexists = array();
299cfee5 510 foreach ($coursemodinfo->modinfo as $mod) {
949c27a0 511 if (!isset($mod->name) || strval($mod->name) === '') {
0d8b6a69 512 // something is wrong here
513 continue;
514 }
515
516 // Skip modules which don't exist
44ddd2a1
MG
517 if (!array_key_exists($mod->mod, $modexists)) {
518 $modexists[$mod->mod] = file_exists("$CFG->dirroot/mod/$mod->mod/lib.php");
519 }
520 if (!$modexists[$mod->mod]) {
521 continue;
0d8b6a69 522 }
523
524 // Construct info for this module
d872881f 525 $cm = new cm_info($this, null, $mod, null);
0d8b6a69 526
527 // Store module in instances and cms array
528 if (!isset($this->instances[$cm->modname])) {
529 $this->instances[$cm->modname] = array();
530 }
531 $this->instances[$cm->modname][$cm->instance] = $cm;
532 $this->cms[$cm->id] = $cm;
533
534 // Reconstruct sections. This works because modules are stored in order
535 if (!isset($this->sections[$cm->sectionnum])) {
536 $this->sections[$cm->sectionnum] = array();
537 }
538 $this->sections[$cm->sectionnum][] = $cm->id;
539 }
540
ce4dfd27 541 // Expand section objects
542 $this->sectioninfo = array();
299cfee5 543 foreach ($coursemodinfo->sectioncache as $number => $data) {
4e430906
MG
544 $this->sectioninfo[$number] = new section_info($data, $number, null, null,
545 $this, null);
ce4dfd27 546 }
0d8b6a69 547 }
ce4dfd27 548
549 /**
7a07d34d 550 * This method can not be used anymore.
299cfee5 551 *
7a07d34d 552 * @see course_modinfo::build_course_cache()
299cfee5 553 * @deprecated since 2.6
ce4dfd27 554 */
555 public static function build_section_cache($courseid) {
7a07d34d
JP
556 throw new coding_exception('Function course_modinfo::build_section_cache() can not be used anymore.' .
557 ' Please use course_modinfo::build_course_cache() whenever applicable.');
299cfee5
MG
558 }
559
560 /**
561 * Builds a list of information about sections on a course to be stored in
562 * the course cache. (Does not include information that is already cached
563 * in some other way.)
564 *
565 * @param stdClass $course Course object (must contain fields
566 * @return array Information about sections, indexed by section number (not id)
567 */
568 protected static function build_course_section_cache($course) {
569 global $DB;
ce4dfd27 570
571 // Get section data
299cfee5 572 $sections = $DB->get_records('course_sections', array('course' => $course->id), 'section',
048f909b 573 'section, id, course, name, summary, summaryformat, sequence, visible, availability');
ce4dfd27 574 $compressedsections = array();
575
299cfee5 576 $formatoptionsdef = course_get_format($course)->section_format_options();
ce4dfd27 577 // Remove unnecessary data and add availability
578 foreach ($sections as $number => $section) {
aea2e3c3
MG
579 // Add cached options from course format to $section object
580 foreach ($formatoptionsdef as $key => $option) {
581 if (!empty($option['cache'])) {
299cfee5 582 $formatoptions = course_get_format($course)->get_format_options($section);
aea2e3c3
MG
583 if (!array_key_exists('cachedefault', $option) || $option['cachedefault'] !== $formatoptions[$key]) {
584 $section->$key = $formatoptions[$key];
585 }
586 }
587 }
99e9f9a6 588 // Clone just in case it is reused elsewhere
ce4dfd27 589 $compressedsections[$number] = clone($section);
590 section_info::convert_for_section_cache($compressedsections[$number]);
591 }
592
593 return $compressedsections;
594 }
299cfee5 595
08ec1b4e 596 /**
597 * Gets a lock for rebuilding the cache of a single course.
598 *
599 * Caller must release the returned lock.
600 *
601 * This is used to ensure that the cache rebuild doesn't happen multiple times in parallel.
602 * This function will wait up to 1 minute for the lock to be obtained. If the lock cannot
603 * be obtained, it throws an exception.
604 *
605 * @param int $courseid Course id
606 * @return \core\lock\lock Lock (must be released!)
607 * @throws moodle_exception If the lock cannot be obtained
608 */
609 protected static function get_course_cache_lock($courseid) {
610 // Get database lock to ensure this doesn't happen multiple times in parallel. Wait a
611 // reasonable time for the lock to be released, so we can give a suitable error message.
612 // In case the system crashes while building the course cache, the lock will automatically
613 // expire after a (slightly longer) period.
614 $lockfactory = \core\lock\lock_config::get_lock_factory('core_modinfo');
615 $lock = $lockfactory->get_lock('build_course_cache_' . $courseid,
616 self::COURSE_CACHE_LOCK_WAIT, self::COURSE_CACHE_LOCK_EXPIRY);
617 if (!$lock) {
618 throw new moodle_exception('locktimeout', '', '', null,
619 'core_modinfo/build_course_cache_' . $courseid);
620 }
621 return $lock;
622 }
623
299cfee5
MG
624 /**
625 * Builds and stores in MUC object containing information about course
626 * modules and sections together with cached fields from table course.
627 *
628 * @param stdClass $course object from DB table course. Must have property 'id'
629 * but preferably should have all cached fields.
630 * @return stdClass object with all cached keys of the course plus fields modinfo and sectioncache.
631 * The same object is stored in MUC
632 * @throws moodle_exception if course is not found (if $course object misses some of the
633 * necessary fields it is re-requested from database)
634 */
635 public static function build_course_cache($course) {
299cfee5
MG
636 if (empty($course->id)) {
637 throw new coding_exception('Object $course is missing required property \id\'');
638 }
08ec1b4e 639
640 $lock = self::get_course_cache_lock($course->id);
641 try {
642 return self::inner_build_course_cache($course, $lock);
643 } finally {
644 $lock->release();
645 }
646 }
647
648 /**
649 * Called to build course cache when there is already a lock obtained.
650 *
651 * @param stdClass $course object from DB table course
652 * @param \core\lock\lock $lock Lock object - not actually used, just there to indicate you have a lock
653 * @return stdClass Course object that has been stored in MUC
654 */
655 protected static function inner_build_course_cache($course, \core\lock\lock $lock) {
ada9d0fb
AN
656 global $DB, $CFG;
657 require_once("{$CFG->dirroot}/course/lib.php");
08ec1b4e 658
299cfee5
MG
659 // Ensure object has all necessary fields.
660 foreach (self::$cachedfields as $key) {
661 if (!isset($course->$key)) {
662 $course = $DB->get_record('course', array('id' => $course->id),
de170aac 663 implode(',', array_merge(array('id'), self::$cachedfields)), MUST_EXIST);
299cfee5
MG
664 break;
665 }
666 }
667 // Retrieve all information about activities and sections.
668 // This may take time on large courses and it is possible that another user modifies the same course during this process.
669 // Field cacherev stored in both DB and cache will ensure that cached data matches the current course state.
670 $coursemodinfo = new stdClass();
671 $coursemodinfo->modinfo = get_array_of_activities($course->id);
672 $coursemodinfo->sectioncache = self::build_course_section_cache($course);
673 foreach (self::$cachedfields as $key) {
674 $coursemodinfo->$key = $course->$key;
675 }
676 // Set the accumulated activities and sections information in cache, together with cacherev.
677 $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
678 $cachecoursemodinfo->set($course->id, $coursemodinfo);
679 return $coursemodinfo;
680 }
0d8b6a69 681}
682
683
684/**
685 * Data about a single module on a course. This contains most of the fields in the course_modules
686 * table, plus additional data when required.
687 *
d872881f
MG
688 * The object can be accessed by core or any plugin (i.e. course format, block, filter, etc.) as
689 * get_fast_modinfo($courseorid)->cms[$coursemoduleid]
690 * or
691 * get_fast_modinfo($courseorid)->instances[$moduletype][$instanceid]
692 *
693 * There are three stages when activity module can add/modify data in this object:
694 *
695 * <b>Stage 1 - during building the cache.</b>
696 * Allows to add to the course cache static user-independent information about the module.
697 * Modules should try to include only absolutely necessary information that may be required
698 * when displaying course view page. The information is stored in application-level cache
699 * and reset when {@link rebuild_course_cache()} is called or cache is purged by admin.
700 *
701 * Modules can implement callback XXX_get_coursemodule_info() returning instance of object
702 * {@link cached_cm_info}
703 *
704 * <b>Stage 2 - dynamic data.</b>
705 * Dynamic data is user-dependend, it is stored in request-level cache. To reset this cache
706 * {@link get_fast_modinfo()} with $reset argument may be called.
707 *
708 * Dynamic data is obtained when any of the following properties/methods is requested:
709 * - {@link cm_info::$url}
710 * - {@link cm_info::$name}
711 * - {@link cm_info::$onclick}
712 * - {@link cm_info::get_icon_url()}
713 * - {@link cm_info::$uservisible}
714 * - {@link cm_info::$available}
d872881f
MG
715 * - {@link cm_info::$availableinfo}
716 * - plus any of the properties listed in Stage 3.
717 *
718 * Modules can implement callback <b>XXX_cm_info_dynamic()</b> and inside this callback they
719 * are allowed to use any of the following set methods:
720 * - {@link cm_info::set_available()}
721 * - {@link cm_info::set_name()}
722 * - {@link cm_info::set_no_view_link()}
723 * - {@link cm_info::set_user_visible()}
724 * - {@link cm_info::set_on_click()}
725 * - {@link cm_info::set_icon_url()}
726 * Any methods affecting view elements can also be set in this callback.
727 *
728 * <b>Stage 3 (view data).</b>
729 * Also user-dependend data stored in request-level cache. Second stage is created
730 * because populating the view data can be expensive as it may access much more
731 * Moodle APIs such as filters, user information, output renderers and we
732 * don't want to request it until necessary.
733 * View data is obtained when any of the following properties/methods is requested:
734 * - {@link cm_info::$afterediticons}
735 * - {@link cm_info::$content}
736 * - {@link cm_info::get_formatted_content()}
737 * - {@link cm_info::$extraclasses}
738 * - {@link cm_info::$afterlink}
739 *
740 * Modules can implement callback <b>XXX_cm_info_view()</b> and inside this callback they
741 * are allowed to use any of the following set methods:
742 * - {@link cm_info::set_after_edit_icons()}
743 * - {@link cm_info::set_after_link()}
744 * - {@link cm_info::set_content()}
745 * - {@link cm_info::set_extra_classes()}
746 *
747 * @property-read int $id Course-module ID - from course_modules table
748 * @property-read int $instance Module instance (ID within module table) - from course_modules table
749 * @property-read int $course Course ID - from course_modules table
750 * @property-read string $idnumber 'ID number' from course-modules table (arbitrary text set by user) - from
751 * course_modules table
752 * @property-read int $added Time that this course-module was added (unix time) - from course_modules table
753 * @property-read int $visible Visible setting (0 or 1; if this is 0, students cannot see/access the activity) - from
754 * course_modules table
8341055e
MG
755 * @property-read int $visibleoncoursepage Visible on course page setting - from course_modules table, adjusted to
756 * whether course format allows this module to have the "stealth" mode
d872881f
MG
757 * @property-read int $visibleold Old visible setting (if the entire section is hidden, the previous value for
758 * visible is stored in this field) - from course_modules table
6d04c4f2
MG
759 * @property-read int $groupmode Group mode (one of the constants NOGROUPS, SEPARATEGROUPS, or VISIBLEGROUPS) - from
760 * course_modules table. Use {@link cm_info::$effectivegroupmode} to find the actual group mode that may be forced by course.
d872881f 761 * @property-read int $groupingid Grouping ID (0 = all groupings)
d872881f
MG
762 * @property-read bool $coursegroupmodeforce Indicates whether the course containing the module has forced the groupmode
763 * This means that cm_info::$groupmode should be ignored and cm_info::$coursegroupmode be used instead
6d04c4f2 764 * @property-read int $coursegroupmode Group mode (one of the constants NOGROUPS, SEPARATEGROUPS, or VISIBLEGROUPS) - from
d872881f
MG
765 * course table - as specified for the course containing the module
766 * Effective only if {@link cm_info::$coursegroupmodeforce} is set
6d04c4f2
MG
767 * @property-read int $effectivegroupmode Effective group mode for this module (one of the constants NOGROUPS, SEPARATEGROUPS,
768 * or VISIBLEGROUPS). This can be different from groupmode set for the module if the groupmode is forced for the course.
769 * This value will always be NOGROUPS if module type does not support group mode.
d872881f
MG
770 * @property-read int $indent Indent level on course page (0 = no indent) - from course_modules table
771 * @property-read int $completion Activity completion setting for this activity, COMPLETION_TRACKING_xx constant - from
772 * course_modules table
773 * @property-read mixed $completiongradeitemnumber Set to the item number (usually 0) if completion depends on a particular
774 * grade of this activity, or null if completion does not depend on a grade - from course_modules table
775 * @property-read int $completionview 1 if 'on view' completion is enabled, 0 otherwise - from course_modules table
776 * @property-read int $completionexpected Set to a unix time if completion of this activity is expected at a
777 * particular time, 0 if no time set - from course_modules table
8d1f33e1 778 * @property-read string $availability Availability information as JSON string or null if none -
d872881f
MG
779 * from course_modules table
780 * @property-read int $showdescription Controls whether the description of the activity displays on the course main page (in
781 * addition to anywhere it might display within the activity itself). 0 = do not show
782 * on main page, 1 = show on main page.
783 * @property-read string $extra (deprecated) Extra HTML that is put in an unhelpful part of the HTML when displaying this module in
784 * course page - from cached data in modinfo field. Deprecated, replaced by ->extraclasses and ->onclick
785 * @property-read string $icon Name of icon to use - from cached data in modinfo field
786 * @property-read string $iconcomponent Component that contains icon - from cached data in modinfo field
787 * @property-read string $modname Name of module e.g. 'forum' (this is the same name as the module's main database
788 * table) - from cached data in modinfo field
789 * @property-read int $module ID of module type - from course_modules table
790 * @property-read string $name Name of module instance for display on page e.g. 'General discussion forum' - from cached
791 * data in modinfo field
792 * @property-read int $sectionnum Section number that this course-module is in (section 0 = above the calendar, section 1
793 * = week/topic 1, etc) - from cached data in modinfo field
794 * @property-read int $section Section id - from course_modules table
795 * @property-read array $conditionscompletion Availability conditions for this course-module based on the completion of other
796 * course-modules (array from other course-module id to required completion state for that
797 * module) - from cached data in modinfo field
798 * @property-read array $conditionsgrade Availability conditions for this course-module based on course grades (array from
799 * grade item id to object with ->min, ->max fields) - from cached data in modinfo field
800 * @property-read array $conditionsfield Availability conditions for this course-module based on user fields
801 * @property-read bool $available True if this course-module is available to students i.e. if all availability conditions
802 * are met - obtained dynamically
803 * @property-read string $availableinfo If course-module is not available to students, this string gives information about
804 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
805 * January 2010') for display on main page - obtained dynamically
806 * @property-read bool $uservisible True if this course-module is available to the CURRENT user (for example, if current user
807 * has viewhiddenactivities capability, they can access the course-module even if it is not
808 * visible or not available, so this would be true in that case)
809 * @property-read context_module $context Module context
810 * @property-read string $modfullname Returns a localised human-readable name of the module type - calculated on request
811 * @property-read string $modplural Returns a localised human-readable name of the module type in plural form - calculated on request
812 * @property-read string $content Content to display on main (view) page - calculated on request
813 * @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
814 * @property-read string $extraclasses Extra CSS classes to add to html output for this activity on main page - calculated on request
815 * @property-read string $onclick Content of HTML on-click attribute already escaped - calculated on request
816 * @property-read mixed $customdata Optional custom data stored in modinfo cache for this activity, or null if none
817 * @property-read string $afterlink Extra HTML code to display after link - calculated on request
818 * @property-read string $afterediticons Extra HTML code to display after editing icons (e.g. more icons) - calculated on request
048f909b 819 * @property-read bool $deletioninprogress True if this course module is scheduled for deletion, false otherwise.
0d8b6a69 820 */
d872881f 821class cm_info implements IteratorAggregate {
0d8b6a69 822 /**
823 * State: Only basic data from modinfo cache is available.
824 */
825 const STATE_BASIC = 0;
826
d872881f
MG
827 /**
828 * State: In the process of building dynamic data (to avoid recursive calls to obtain_dynamic_data())
829 */
830 const STATE_BUILDING_DYNAMIC = 1;
831
0d8b6a69 832 /**
833 * State: Dynamic data is available too.
834 */
d872881f
MG
835 const STATE_DYNAMIC = 2;
836
837 /**
838 * State: In the process of building view data (to avoid recursive calls to obtain_view_data())
839 */
840 const STATE_BUILDING_VIEW = 3;
0d8b6a69 841
842 /**
843 * State: View data (for course page) is available.
844 */
d872881f 845 const STATE_VIEW = 4;
0d8b6a69 846
847 /**
848 * Parent object
849 * @var course_modinfo
850 */
851 private $modinfo;
852
853 /**
854 * Level of information stored inside this object (STATE_xx constant)
855 * @var int
856 */
857 private $state;
858
0d8b6a69 859 /**
860 * Course-module ID - from course_modules table
861 * @var int
862 */
d872881f 863 private $id;
0d8b6a69 864
865 /**
866 * Module instance (ID within module table) - from course_modules table
867 * @var int
868 */
d872881f 869 private $instance;
0d8b6a69 870
871 /**
872 * 'ID number' from course-modules table (arbitrary text set by user) - from
873 * course_modules table
874 * @var string
875 */
d872881f 876 private $idnumber;
0d8b6a69 877
878 /**
adaeccb6 879 * Time that this course-module was added (unix time) - from course_modules table
880 * @var int
881 */
d872881f 882 private $added;
adaeccb6 883
884 /**
885 * This variable is not used and is included here only so it can be documented.
886 * Once the database entry is removed from course_modules, it should be deleted
887 * here too.
888 * @var int
889 * @deprecated Do not use this variable
890 */
d872881f 891 private $score;
adaeccb6 892
893 /**
894 * Visible setting (0 or 1; if this is 0, students cannot see/access the activity) - from
0d8b6a69 895 * course_modules table
896 * @var int
897 */
d872881f 898 private $visible;
0d8b6a69 899
8341055e
MG
900 /**
901 * Visible on course page setting - from course_modules table
902 * @var int
903 */
904 private $visibleoncoursepage;
905
adaeccb6 906 /**
907 * Old visible setting (if the entire section is hidden, the previous value for
908 * visible is stored in this field) - from course_modules table
909 * @var int
910 */
d872881f 911 private $visibleold;
adaeccb6 912
0d8b6a69 913 /**
914 * Group mode (one of the constants NONE, SEPARATEGROUPS, or VISIBLEGROUPS) - from
915 * course_modules table
916 * @var int
917 */
d872881f 918 private $groupmode;
0d8b6a69 919
920 /**
921 * Grouping ID (0 = all groupings)
922 * @var int
923 */
d872881f 924 private $groupingid;
0d8b6a69 925
0d8b6a69 926 /**
927 * Indent level on course page (0 = no indent) - from course_modules table
928 * @var int
929 */
d872881f 930 private $indent;
0d8b6a69 931
932 /**
933 * Activity completion setting for this activity, COMPLETION_TRACKING_xx constant - from
934 * course_modules table
935 * @var int
936 */
d872881f 937 private $completion;
0d8b6a69 938
adaeccb6 939 /**
940 * Set to the item number (usually 0) if completion depends on a particular
941 * grade of this activity, or null if completion does not depend on a grade - from
942 * course_modules table
943 * @var mixed
944 */
d872881f 945 private $completiongradeitemnumber;
adaeccb6 946
947 /**
948 * 1 if 'on view' completion is enabled, 0 otherwise - from course_modules table
949 * @var int
950 */
d872881f 951 private $completionview;
adaeccb6 952
953 /**
954 * Set to a unix time if completion of this activity is expected at a
955 * particular time, 0 if no time set - from course_modules table
956 * @var int
957 */
d872881f 958 private $completionexpected;
adaeccb6 959
0d8b6a69 960 /**
8d1f33e1 961 * Availability information as JSON string or null if none - from course_modules table
962 * @var string
0d8b6a69 963 */
8d1f33e1 964 private $availability;
0d8b6a69 965
8c40662e 966 /**
967 * Controls whether the description of the activity displays on the course main page (in
968 * addition to anywhere it might display within the activity itself). 0 = do not show
969 * on main page, 1 = show on main page.
970 * @var int
971 */
d872881f 972 private $showdescription;
8c40662e 973
0d8b6a69 974 /**
975 * Extra HTML that is put in an unhelpful part of the HTML when displaying this module in
976 * course page - from cached data in modinfo field
977 * @deprecated This is crazy, don't use it. Replaced by ->extraclasses and ->onclick
978 * @var string
979 */
d872881f 980 private $extra;
0d8b6a69 981
982 /**
983 * Name of icon to use - from cached data in modinfo field
984 * @var string
985 */
d872881f 986 private $icon;
0d8b6a69 987
988 /**
989 * Component that contains icon - from cached data in modinfo field
990 * @var string
991 */
d872881f 992 private $iconcomponent;
0d8b6a69 993
994 /**
995 * Name of module e.g. 'forum' (this is the same name as the module's main database
996 * table) - from cached data in modinfo field
997 * @var string
998 */
d872881f 999 private $modname;
0d8b6a69 1000
adaeccb6 1001 /**
1002 * ID of module - from course_modules table
1003 * @var int
1004 */
d872881f 1005 private $module;
adaeccb6 1006
0d8b6a69 1007 /**
1008 * Name of module instance for display on page e.g. 'General discussion forum' - from cached
1009 * data in modinfo field
1010 * @var string
1011 */
d872881f 1012 private $name;
0d8b6a69 1013
1014 /**
1015 * Section number that this course-module is in (section 0 = above the calendar, section 1
1016 * = week/topic 1, etc) - from cached data in modinfo field
d872881f 1017 * @var int
0d8b6a69 1018 */
d872881f 1019 private $sectionnum;
0d8b6a69 1020
adaeccb6 1021 /**
1022 * Section id - from course_modules table
1023 * @var int
1024 */
d872881f 1025 private $section;
adaeccb6 1026
0d8b6a69 1027 /**
1028 * Availability conditions for this course-module based on the completion of other
1029 * course-modules (array from other course-module id to required completion state for that
1030 * module) - from cached data in modinfo field
1031 * @var array
1032 */
d872881f 1033 private $conditionscompletion;
0d8b6a69 1034
1035 /**
1036 * Availability conditions for this course-module based on course grades (array from
1037 * grade item id to object with ->min, ->max fields) - from cached data in modinfo field
1038 * @var array
1039 */
d872881f 1040 private $conditionsgrade;
0d8b6a69 1041
76af15bb
MN
1042 /**
1043 * Availability conditions for this course-module based on user fields
1044 * @var array
1045 */
d872881f 1046 private $conditionsfield;
76af15bb 1047
0d8b6a69 1048 /**
1049 * True if this course-module is available to students i.e. if all availability conditions
1050 * are met - obtained dynamically
1051 * @var bool
1052 */
d872881f 1053 private $available;
0d8b6a69 1054
1055 /**
1056 * If course-module is not available to students, this string gives information about
1057 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
1058 * January 2010') for display on main page - obtained dynamically
1059 * @var string
1060 */
d872881f 1061 private $availableinfo;
0d8b6a69 1062
1063 /**
1064 * True if this course-module is available to the CURRENT user (for example, if current user
1065 * has viewhiddenactivities capability, they can access the course-module even if it is not
1066 * visible or not available, so this would be true in that case)
1067 * @var bool
1068 */
d872881f 1069 private $uservisible;
0d8b6a69 1070
8341055e
MG
1071 /**
1072 * True if this course-module is visible to the CURRENT user on the course page
1073 * @var bool
1074 */
1075 private $uservisibleoncoursepage;
1076
0d8b6a69 1077 /**
1078 * @var moodle_url
1079 */
1080 private $url;
1081
1082 /**
1083 * @var string
1084 */
1085 private $content;
1086
1087 /**
1088 * @var string
1089 */
1090 private $extraclasses;
1091
c443a1cd
EL
1092 /**
1093 * @var moodle_url full external url pointing to icon image for activity
1094 */
1095 private $iconurl;
1096
0d8b6a69 1097 /**
1098 * @var string
1099 */
1100 private $onclick;
1101
1102 /**
1103 * @var mixed
1104 */
1105 private $customdata;
1106
1107 /**
1108 * @var string
1109 */
1110 private $afterlink;
1111
1112 /**
1113 * @var string
1114 */
1115 private $afterediticons;
1116
048f909b
JD
1117 /**
1118 * @var bool representing the deletion state of the module. True if the mod is scheduled for deletion.
1119 */
1120 private $deletioninprogress;
1121
d872881f
MG
1122 /**
1123 * List of class read-only properties and their getter methods.
1124 * Used by magic functions __get(), __isset(), __empty()
1125 * @var array
1126 */
1127 private static $standardproperties = array(
1128 'url' => 'get_url',
1129 'content' => 'get_content',
1130 'extraclasses' => 'get_extra_classes',
1131 'onclick' => 'get_on_click',
1132 'customdata' => 'get_custom_data',
1133 'afterlink' => 'get_after_link',
1134 'afterediticons' => 'get_after_edit_icons',
1135 'modfullname' => 'get_module_type_name',
1136 'modplural' => 'get_module_type_name_plural',
1137 'id' => false,
1138 'added' => false,
8d1f33e1 1139 'availability' => false,
d872881f 1140 'available' => 'get_available',
d872881f 1141 'availableinfo' => 'get_available_info',
d872881f
MG
1142 'completion' => false,
1143 'completionexpected' => false,
1144 'completiongradeitemnumber' => false,
1145 'completionview' => false,
1146 'conditionscompletion' => false,
1147 'conditionsfield' => false,
1148 'conditionsgrade' => false,
1149 'context' => 'get_context',
1150 'course' => 'get_course_id',
1151 'coursegroupmode' => 'get_course_groupmode',
1152 'coursegroupmodeforce' => 'get_course_groupmodeforce',
6d04c4f2 1153 'effectivegroupmode' => 'get_effective_groupmode',
d872881f
MG
1154 'extra' => false,
1155 'groupingid' => false,
061e6b28 1156 'groupmembersonly' => 'get_deprecated_group_members_only',
d872881f
MG
1157 'groupmode' => false,
1158 'icon' => false,
1159 'iconcomponent' => false,
1160 'idnumber' => false,
1161 'indent' => false,
1162 'instance' => false,
1163 'modname' => false,
1164 'module' => false,
1165 'name' => 'get_name',
1166 'score' => false,
1167 'section' => false,
1168 'sectionnum' => false,
d872881f
MG
1169 'showdescription' => false,
1170 'uservisible' => 'get_user_visible',
1171 'visible' => false,
8341055e 1172 'visibleoncoursepage' => false,
d872881f 1173 'visibleold' => false,
048f909b 1174 'deletioninprogress' => false
d872881f
MG
1175 );
1176
1177 /**
1178 * List of methods with no arguments that were public prior to Moodle 2.6.
1179 *
1180 * They can still be accessed publicly via magic __call() function with no warnings
1181 * but are not listed in the class methods list.
1182 * For the consistency of the code it is better to use corresponding properties.
1183 *
1184 * These methods be deprecated completely in later versions.
1185 *
1186 * @var array $standardmethods
1187 */
1188 private static $standardmethods = array(
1189 // Following methods are not recommended to use because there have associated read-only properties.
1190 'get_url',
1191 'get_content',
1192 'get_extra_classes',
1193 'get_on_click',
1194 'get_custom_data',
1195 'get_after_link',
1196 'get_after_edit_icons',
1197 // Method obtain_dynamic_data() should not be called from outside of this class but it was public before Moodle 2.6.
1198 'obtain_dynamic_data',
1199 );
1200
1201 /**
7a07d34d
JP
1202 * Magic method to call functions that are now declared as private but were public in Moodle before 2.6.
1203 * These private methods can not be used anymore.
d872881f
MG
1204 *
1205 * @param string $name
1206 * @param array $arguments
1207 * @return mixed
7a07d34d 1208 * @throws coding_exception
d872881f
MG
1209 */
1210 public function __call($name, $arguments) {
1211 if (in_array($name, self::$standardmethods)) {
7a07d34d
JP
1212 $message = "cm_info::$name() can not be used anymore.";
1213 if ($alternative = array_search($name, self::$standardproperties)) {
1214 $message .= " Please use the property cm_info->$alternative instead.";
07e78d93 1215 }
7a07d34d 1216 throw new coding_exception($message);
d872881f
MG
1217 }
1218 throw new coding_exception("Method cm_info::{$name}() does not exist");
1219 }
1220
d57aa283
MG
1221 /**
1222 * Magic method getter
1223 *
1224 * @param string $name
1225 * @return mixed
1226 */
1227 public function __get($name) {
d872881f
MG
1228 if (isset(self::$standardproperties[$name])) {
1229 if ($method = self::$standardproperties[$name]) {
1230 return $this->$method();
1231 } else {
1232 return $this->$name;
1233 }
1234 } else {
1235 debugging('Invalid cm_info property accessed: '.$name);
1236 return null;
d57aa283
MG
1237 }
1238 }
1239
d872881f
MG
1240 /**
1241 * Implementation of IteratorAggregate::getIterator(), allows to cycle through properties
1242 * and use {@link convert_to_array()}
1243 *
1244 * @return ArrayIterator
1245 */
1246 public function getIterator() {
1247 // Make sure dynamic properties are retrieved prior to view properties.
1248 $this->obtain_dynamic_data();
1249 $ret = array();
5793538a
AA
1250
1251 // Do not iterate over deprecated properties.
1252 $props = self::$standardproperties;
c62ba9b8 1253 unset($props['groupmembersonly']);
5793538a
AA
1254
1255 foreach ($props as $key => $unused) {
d872881f
MG
1256 $ret[$key] = $this->__get($key);
1257 }
1258 return new ArrayIterator($ret);
1259 }
1260
1261 /**
1262 * Magic method for function isset()
1263 *
1264 * @param string $name
1265 * @return bool
1266 */
1267 public function __isset($name) {
1268 if (isset(self::$standardproperties[$name])) {
1269 $value = $this->__get($name);
1270 return isset($value);
1271 }
1272 return false;
1273 }
1274
1275 /**
1276 * Magic method for function empty()
1277 *
1278 * @param string $name
1279 * @return bool
1280 */
1281 public function __empty($name) {
1282 if (isset(self::$standardproperties[$name])) {
1283 $value = $this->__get($name);
1284 return empty($value);
1285 }
1286 return true;
1287 }
1288
1289 /**
1290 * Magic method setter
1291 *
1292 * Will display the developer warning when trying to set/overwrite property.
1293 *
1294 * @param string $name
1295 * @param mixed $value
1296 */
1297 public function __set($name, $value) {
1298 debugging("It is not allowed to set the property cm_info::\${$name}", DEBUG_DEVELOPER);
1299 }
1300
0d8b6a69 1301 /**
1302 * @return bool True if this module has a 'view' page that should be linked to in navigation
1303 * etc (note: modules may still have a view.php file, but return false if this is not
1304 * intended to be linked to from 'normal' parts of the interface; this is what label does).
1305 */
1306 public function has_view() {
1307 return !is_null($this->url);
1308 }
1309
1310 /**
1311 * @return moodle_url URL to link to for this module, or null if it doesn't have a view page
1312 */
d872881f
MG
1313 private function get_url() {
1314 $this->obtain_dynamic_data();
0d8b6a69 1315 return $this->url;
1316 }
1317
1318 /**
1319 * Obtains content to display on main (view) page.
1320 * Note: Will collect view data, if not already obtained.
1321 * @return string Content to display on main page below link, or empty string if none
1322 */
d872881f 1323 private function get_content() {
0d8b6a69 1324 $this->obtain_view_data();
1325 return $this->content;
1326 }
1327
f89c53f6
MG
1328 /**
1329 * Returns the content to display on course/overview page, formatted and passed through filters
1330 *
1331 * if $options['context'] is not specified, the module context is used
1332 *
1333 * @param array|stdClass $options formatting options, see {@link format_text()}
1334 * @return string
1335 */
1336 public function get_formatted_content($options = array()) {
1337 $this->obtain_view_data();
1338 if (empty($this->content)) {
1339 return '';
1340 }
f89c53f6
MG
1341 // Improve filter performance by preloading filter setttings for all
1342 // activities on the course (this does nothing if called multiple
1343 // times)
1344 filter_preload_activities($this->get_modinfo());
1345
1346 $options = (array)$options;
1347 if (!isset($options['context'])) {
d872881f 1348 $options['context'] = $this->get_context();
f89c53f6
MG
1349 }
1350 return format_text($this->content, FORMAT_HTML, $options);
1351 }
1352
d872881f
MG
1353 /**
1354 * Getter method for property $name, ensures that dynamic data is obtained.
1355 * @return string
1356 */
1357 private function get_name() {
1358 $this->obtain_dynamic_data();
1359 return $this->name;
1360 }
1361
f89c53f6
MG
1362 /**
1363 * Returns the name to display on course/overview page, formatted and passed through filters
1364 *
1365 * if $options['context'] is not specified, the module context is used
1366 *
1367 * @param array|stdClass $options formatting options, see {@link format_string()}
1368 * @return string
1369 */
1370 public function get_formatted_name($options = array()) {
acbf4579 1371 global $CFG;
f89c53f6
MG
1372 $options = (array)$options;
1373 if (!isset($options['context'])) {
d872881f 1374 $options['context'] = $this->get_context();
f89c53f6 1375 }
0d9805dc
DW
1376 // Improve filter performance by preloading filter setttings for all
1377 // activities on the course (this does nothing if called multiple
1378 // times).
acbf4579
MG
1379 if (!empty($CFG->filterall)) {
1380 filter_preload_activities($this->get_modinfo());
1381 }
d872881f 1382 return format_string($this->get_name(), true, $options);
f89c53f6
MG
1383 }
1384
0d8b6a69 1385 /**
1386 * Note: Will collect view data, if not already obtained.
1387 * @return string Extra CSS classes to add to html output for this activity on main page
1388 */
d872881f 1389 private function get_extra_classes() {
0d8b6a69 1390 $this->obtain_view_data();
1391 return $this->extraclasses;
1392 }
1393
1394 /**
1395 * @return string Content of HTML on-click attribute. This string will be used literally
1396 * as a string so should be pre-escaped.
1397 */
d872881f 1398 private function get_on_click() {
0d8b6a69 1399 // Does not need view data; may be used by navigation
d872881f 1400 $this->obtain_dynamic_data();
0d8b6a69 1401 return $this->onclick;
1402 }
1403 /**
1404 * @return mixed Optional custom data stored in modinfo cache for this activity, or null if none
1405 */
d872881f 1406 private function get_custom_data() {
0d8b6a69 1407 return $this->customdata;
1408 }
1409
1410 /**
1411 * Note: Will collect view data, if not already obtained.
c443a1cd 1412 * @return string Extra HTML code to display after link
0d8b6a69 1413 */
d872881f 1414 private function get_after_link() {
0d8b6a69 1415 $this->obtain_view_data();
1416 return $this->afterlink;
1417 }
1418
1419 /**
1420 * Note: Will collect view data, if not already obtained.
1421 * @return string Extra HTML code to display after editing icons (e.g. more icons)
1422 */
d872881f 1423 private function get_after_edit_icons() {
0d8b6a69 1424 $this->obtain_view_data();
1425 return $this->afterediticons;
1426 }
1427
1428 /**
1429 * @param moodle_core_renderer $output Output render to use, or null for default (global)
1430 * @return moodle_url Icon URL for a suitable icon to put beside this cm
1431 */
1432 public function get_icon_url($output = null) {
1433 global $OUTPUT;
d872881f 1434 $this->obtain_dynamic_data();
0d8b6a69 1435 if (!$output) {
1436 $output = $OUTPUT;
1437 }
c443a1cd
EL
1438 // Support modules setting their own, external, icon image
1439 if (!empty($this->iconurl)) {
1440 $icon = $this->iconurl;
1441
1442 // Fallback to normal local icon + component procesing
1443 } else if (!empty($this->icon)) {
0d8b6a69 1444 if (substr($this->icon, 0, 4) === 'mod/') {
1445 list($modname, $iconname) = explode('/', substr($this->icon, 4), 2);
663640f5 1446 $icon = $output->image_url($iconname, $modname);
0d8b6a69 1447 } else {
1448 if (!empty($this->iconcomponent)) {
1449 // Icon has specified component
663640f5 1450 $icon = $output->image_url($this->icon, $this->iconcomponent);
0d8b6a69 1451 } else {
1452 // Icon does not have specified component, use default
663640f5 1453 $icon = $output->image_url($this->icon);
0d8b6a69 1454 }
1455 }
1456 } else {
663640f5 1457 $icon = $output->image_url('icon', $this->modname);
0d8b6a69 1458 }
1459 return $icon;
1460 }
1461
0556eaa9
JB
1462 /**
1463 * @param string $textclasses additionnal classes for grouping label
1464 * @return string An empty string or HTML grouping label span tag
1465 */
1466 public function get_grouping_label($textclasses = '') {
1467 $groupinglabel = '';
8341055e
MG
1468 if ($this->effectivegroupmode != NOGROUPS && !empty($this->groupingid) &&
1469 has_capability('moodle/course:managegroups', context_course::instance($this->course))) {
0556eaa9
JB
1470 $groupings = groups_get_all_groupings($this->course);
1471 $groupinglabel = html_writer::tag('span', '('.format_string($groupings[$this->groupingid]->name).')',
1472 array('class' => 'groupinglabel '.$textclasses));
1473 }
1474 return $groupinglabel;
1475 }
1476
d57aa283
MG
1477 /**
1478 * Returns a localised human-readable name of the module type
1479 *
1480 * @param bool $plural return plural form
1481 * @return string
1482 */
1483 public function get_module_type_name($plural = false) {
1484 $modnames = get_module_types_names($plural);
1485 if (isset($modnames[$this->modname])) {
1486 return $modnames[$this->modname];
1487 } else {
1488 return null;
1489 }
1490 }
1491
d872881f
MG
1492 /**
1493 * Returns a localised human-readable name of the module type in plural form - calculated on request
1494 *
1495 * @return string
1496 */
1497 private function get_module_type_name_plural() {
1498 return $this->get_module_type_name(true);
1499 }
1500
0d8b6a69 1501 /**
1502 * @return course_modinfo Modinfo object that this came from
1503 */
1504 public function get_modinfo() {
1505 return $this->modinfo;
1506 }
1507
8341055e
MG
1508 /**
1509 * Returns the section this module belongs to
1510 *
1511 * @return section_info
1512 */
1513 public function get_section_info() {
1514 return $this->modinfo->get_section_info($this->sectionnum);
1515 }
1516
0d8b6a69 1517 /**
299cfee5
MG
1518 * Returns course object that was used in the first {@link get_fast_modinfo()} call.
1519 *
1520 * It may not contain all fields from DB table {course} but always has at least the following:
1521 * id,shortname,fullname,format,enablecompletion,groupmode,groupmodeforce,cacherev
1522 *
1523 * If the course object lacks the field you need you can use the global
1524 * function {@link get_course()} that will save extra query if you access
1525 * current course or frontpage course.
1526 *
1527 * @return stdClass
0d8b6a69 1528 */
1529 public function get_course() {
1530 return $this->modinfo->get_course();
1531 }
1532
d872881f
MG
1533 /**
1534 * Returns course id for which the modinfo was generated.
1535 *
1536 * @return int
1537 */
1538 private function get_course_id() {
1539 return $this->modinfo->get_course_id();
1540 }
1541
1542 /**
1543 * Returns group mode used for the course containing the module
1544 *
1545 * @return int one of constants NOGROUPS, SEPARATEGROUPS, VISIBLEGROUPS
1546 */
1547 private function get_course_groupmode() {
1548 return $this->modinfo->get_course()->groupmode;
1549 }
1550
1551 /**
1552 * Returns whether group mode is forced for the course containing the module
1553 *
1554 * @return bool
1555 */
1556 private function get_course_groupmodeforce() {
1557 return $this->modinfo->get_course()->groupmodeforce;
1558 }
1559
6d04c4f2
MG
1560 /**
1561 * Returns effective groupmode of the module that may be overwritten by forced course groupmode.
1562 *
1563 * @return int one of constants NOGROUPS, SEPARATEGROUPS, VISIBLEGROUPS
1564 */
1565 private function get_effective_groupmode() {
1566 $groupmode = $this->groupmode;
1567 if ($this->modinfo->get_course()->groupmodeforce) {
1568 $groupmode = $this->modinfo->get_course()->groupmode;
1569 if ($groupmode != NOGROUPS && !plugin_supports('mod', $this->modname, FEATURE_GROUPS, 0)) {
1570 $groupmode = NOGROUPS;
1571 }
1572 }
1573 return $groupmode;
1574 }
1575
d872881f
MG
1576 /**
1577 * @return context_module Current module context
1578 */
1579 private function get_context() {
1580 return context_module::instance($this->id);
1581 }
1582
92e2e855
MG
1583 /**
1584 * Returns itself in the form of stdClass.
1585 *
1586 * The object includes all fields that table course_modules has and additionally
1587 * fields 'name', 'modname', 'sectionnum' (if requested).
1588 *
1589 * This can be used as a faster alternative to {@link get_coursemodule_from_id()}
1590 *
1591 * @param bool $additionalfields include additional fields 'name', 'modname', 'sectionnum'
1592 * @return stdClass
1593 */
1594 public function get_course_module_record($additionalfields = false) {
1595 $cmrecord = new stdClass();
1596
1597 // Standard fields from table course_modules.
1598 static $cmfields = array('id', 'course', 'module', 'instance', 'section', 'idnumber', 'added',
8341055e 1599 'score', 'indent', 'visible', 'visibleoncoursepage', 'visibleold', 'groupmode', 'groupingid',
92e2e855 1600 'completion', 'completiongradeitemnumber', 'completionview', 'completionexpected',
048f909b 1601 'showdescription', 'availability', 'deletioninprogress');
92e2e855
MG
1602 foreach ($cmfields as $key) {
1603 $cmrecord->$key = $this->$key;
1604 }
1605
1606 // Additional fields that function get_coursemodule_from_id() adds.
1607 if ($additionalfields) {
1608 $cmrecord->name = $this->name;
1609 $cmrecord->modname = $this->modname;
1610 $cmrecord->sectionnum = $this->sectionnum;
1611 }
1612
1613 return $cmrecord;
1614 }
1615
0d8b6a69 1616 // Set functions
1617 ////////////////
1618
1619 /**
1620 * Sets content to display on course view page below link (if present).
1621 * @param string $content New content as HTML string (empty string if none)
1622 * @return void
1623 */
1624 public function set_content($content) {
1625 $this->content = $content;
1626 }
1627
1628 /**
1629 * Sets extra classes to include in CSS.
1630 * @param string $extraclasses Extra classes (empty string if none)
1631 * @return void
1632 */
1633 public function set_extra_classes($extraclasses) {
1634 $this->extraclasses = $extraclasses;
1635 }
1636
c443a1cd
EL
1637 /**
1638 * Sets the external full url that points to the icon being used
1639 * by the activity. Useful for external-tool modules (lti...)
1640 * If set, takes precedence over $icon and $iconcomponent
1641 *
1642 * @param moodle_url $iconurl full external url pointing to icon image for activity
1643 * @return void
1644 */
1645 public function set_icon_url(moodle_url $iconurl) {
1646 $this->iconurl = $iconurl;
1647 }
1648
0d8b6a69 1649 /**
1650 * Sets value of on-click attribute for JavaScript.
1651 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1652 * @param string $onclick New onclick attribute which should be HTML-escaped
1653 * (empty string if none)
1654 * @return void
1655 */
1656 public function set_on_click($onclick) {
1657 $this->check_not_view_only();
1658 $this->onclick = $onclick;
1659 }
1660
1661 /**
1662 * Sets HTML that displays after link on course view page.
1663 * @param string $afterlink HTML string (empty string if none)
1664 * @return void
1665 */
1666 public function set_after_link($afterlink) {
1667 $this->afterlink = $afterlink;
1668 }
1669
1670 /**
1671 * Sets HTML that displays after edit icons on course view page.
1672 * @param string $afterediticons HTML string (empty string if none)
1673 * @return void
1674 */
1675 public function set_after_edit_icons($afterediticons) {
1676 $this->afterediticons = $afterediticons;
1677 }
1678
1679 /**
1680 * Changes the name (text of link) for this module instance.
1681 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1682 * @param string $name Name of activity / link text
1683 * @return void
1684 */
1685 public function set_name($name) {
d872881f
MG
1686 if ($this->state < self::STATE_BUILDING_DYNAMIC) {
1687 $this->update_user_visible();
1688 }
0d8b6a69 1689 $this->name = $name;
1690 }
1691
1692 /**
1693 * Turns off the view link for this module instance.
1694 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1695 * @return void
1696 */
1697 public function set_no_view_link() {
1698 $this->check_not_view_only();
4478743c 1699 $this->url = null;
0d8b6a69 1700 }
1701
1702 /**
1703 * Sets the 'uservisible' flag. This can be used (by setting false) to prevent access and
1704 * display of this module link for the current user.
1705 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1706 * @param bool $uservisible
1707 * @return void
1708 */
1709 public function set_user_visible($uservisible) {
1710 $this->check_not_view_only();
1711 $this->uservisible = $uservisible;
1712 }
1713
1714 /**
1715 * Sets the 'available' flag and related details. This flag is normally used to make
1716 * course modules unavailable until a certain date or condition is met. (When a course
1717 * module is unavailable, it is still visible to users who have viewhiddenactivities
1718 * permission.)
1719 *
1720 * When this is function is called, user-visible status is recalculated automatically.
1721 *
8d1f33e1 1722 * The $showavailability flag does not really do anything any more, but is retained
1723 * for backward compatibility. Setting this to false will cause $availableinfo to
1724 * be ignored.
1725 *
0d8b6a69 1726 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1727 * @param bool $available False if this item is not 'available'
1728 * @param int $showavailability 0 = do not show this item at all if it's not available,
1729 * 1 = show this item greyed out with the following message
8d1f33e1 1730 * @param string $availableinfo Information about why this is not available, or
1731 * empty string if not displaying
0d8b6a69 1732 * @return void
1733 */
1734 public function set_available($available, $showavailability=0, $availableinfo='') {
1735 $this->check_not_view_only();
1736 $this->available = $available;
8d1f33e1 1737 if (!$showavailability) {
1738 $availableinfo = '';
1739 }
0d8b6a69 1740 $this->availableinfo = $availableinfo;
1741 $this->update_user_visible();
1742 }
1743
1744 /**
1745 * Some set functions can only be called from _cm_info_dynamic and not _cm_info_view.
1746 * This is because they may affect parts of this object which are used on pages other
1747 * than the view page (e.g. in the navigation block, or when checking access on
1748 * module pages).
1749 * @return void
1750 */
1751 private function check_not_view_only() {
1752 if ($this->state >= self::STATE_DYNAMIC) {
1753 throw new coding_exception('Cannot set this data from _cm_info_view because it may ' .
1754 'affect other pages as well as view');
1755 }
1756 }
1757
1758 /**
d872881f
MG
1759 * Constructor should not be called directly; use {@link get_fast_modinfo()}
1760 *
0d8b6a69 1761 * @param course_modinfo $modinfo Parent object
d872881f
MG
1762 * @param stdClass $notused1 Argument not used
1763 * @param stdClass $mod Module object from the modinfo field of course table
1764 * @param stdClass $notused2 Argument not used
0d8b6a69 1765 */
d872881f 1766 public function __construct(course_modinfo $modinfo, $notused1, $mod, $notused2) {
0d8b6a69 1767 $this->modinfo = $modinfo;
1768
1769 $this->id = $mod->cm;
1770 $this->instance = $mod->id;
0d8b6a69 1771 $this->modname = $mod->mod;
1772 $this->idnumber = isset($mod->idnumber) ? $mod->idnumber : '';
1773 $this->name = $mod->name;
1774 $this->visible = $mod->visible;
8341055e 1775 $this->visibleoncoursepage = $mod->visibleoncoursepage;
adaeccb6 1776 $this->sectionnum = $mod->section; // Note weirdness with name here
0d8b6a69 1777 $this->groupmode = isset($mod->groupmode) ? $mod->groupmode : 0;
1778 $this->groupingid = isset($mod->groupingid) ? $mod->groupingid : 0;
0d8b6a69 1779 $this->indent = isset($mod->indent) ? $mod->indent : 0;
0d8b6a69 1780 $this->extra = isset($mod->extra) ? $mod->extra : '';
1781 $this->extraclasses = isset($mod->extraclasses) ? $mod->extraclasses : '';
4fcdb012
MG
1782 // iconurl may be stored as either string or instance of moodle_url.
1783 $this->iconurl = isset($mod->iconurl) ? new moodle_url($mod->iconurl) : '';
0d8b6a69 1784 $this->onclick = isset($mod->onclick) ? $mod->onclick : '';
1785 $this->content = isset($mod->content) ? $mod->content : '';
1786 $this->icon = isset($mod->icon) ? $mod->icon : '';
1787 $this->iconcomponent = isset($mod->iconcomponent) ? $mod->iconcomponent : '';
1788 $this->customdata = isset($mod->customdata) ? $mod->customdata : '';
8c40662e 1789 $this->showdescription = isset($mod->showdescription) ? $mod->showdescription : 0;
0d8b6a69 1790 $this->state = self::STATE_BASIC;
1791
adaeccb6 1792 $this->section = isset($mod->sectionid) ? $mod->sectionid : 0;
1793 $this->module = isset($mod->module) ? $mod->module : 0;
1794 $this->added = isset($mod->added) ? $mod->added : 0;
1795 $this->score = isset($mod->score) ? $mod->score : 0;
1796 $this->visibleold = isset($mod->visibleold) ? $mod->visibleold : 0;
048f909b 1797 $this->deletioninprogress = isset($mod->deletioninprogress) ? $mod->deletioninprogress : 0;
adaeccb6 1798
1799 // Note: it saves effort and database space to always include the
1800 // availability and completion fields, even if availability or completion
1801 // are actually disabled
1802 $this->completion = isset($mod->completion) ? $mod->completion : 0;
1803 $this->completiongradeitemnumber = isset($mod->completiongradeitemnumber)
1804 ? $mod->completiongradeitemnumber : null;
1805 $this->completionview = isset($mod->completionview)
1806 ? $mod->completionview : 0;
1807 $this->completionexpected = isset($mod->completionexpected)
1808 ? $mod->completionexpected : 0;
8d1f33e1 1809 $this->availability = isset($mod->availability) ? $mod->availability : null;
adaeccb6 1810 $this->conditionscompletion = isset($mod->conditionscompletion)
1811 ? $mod->conditionscompletion : array();
1812 $this->conditionsgrade = isset($mod->conditionsgrade)
1813 ? $mod->conditionsgrade : array();
76af15bb
MN
1814 $this->conditionsfield = isset($mod->conditionsfield)
1815 ? $mod->conditionsfield : array();
0d8b6a69 1816
d872881f 1817 static $modviews = array();
0d8b6a69 1818 if (!isset($modviews[$this->modname])) {
1819 $modviews[$this->modname] = !plugin_supports('mod', $this->modname,
1820 FEATURE_NO_VIEW_LINK);
1821 }
1822 $this->url = $modviews[$this->modname]
1823 ? new moodle_url('/mod/' . $this->modname . '/view.php', array('id'=>$this->id))
1824 : null;
1825 }
1826
d25c41fb 1827 /**
1828 * Creates a cm_info object from a database record (also accepts cm_info
1829 * in which case it is just returned unchanged).
1830 *
61c3b60c 1831 * @param stdClass|cm_info|null|bool $cm Stdclass or cm_info (or null or false)
d25c41fb 1832 * @param int $userid Optional userid (default to current)
61c3b60c 1833 * @return cm_info|null Object as cm_info, or null if input was null/false
d25c41fb 1834 */
1835 public static function create($cm, $userid = 0) {
61c3b60c 1836 // Null, false, etc. gets passed through as null.
1837 if (!$cm) {
d25c41fb 1838 return null;
1839 }
1840 // If it is already a cm_info object, just return it.
1841 if ($cm instanceof cm_info) {
1842 return $cm;
1843 }
1844 // Otherwise load modinfo.
1845 if (empty($cm->id) || empty($cm->course)) {
1846 throw new coding_exception('$cm must contain ->id and ->course');
1847 }
1848 $modinfo = get_fast_modinfo($cm->course, $userid);
1849 return $modinfo->get_cm($cm->id);
1850 }
1851
0d8b6a69 1852 /**
1853 * If dynamic data for this course-module is not yet available, gets it.
1854 *
d872881f
MG
1855 * This function is automatically called when requesting any course_modinfo property
1856 * that can be modified by modules (have a set_xxx method).
0d8b6a69 1857 *
1858 * Dynamic data is data which does not come directly from the cache but is calculated at
1859 * runtime based on the current user. Primarily this concerns whether the user can access
1860 * the module or not.
1861 *
1862 * As part of this function, the module's _cm_info_dynamic function from its lib.php will
1863 * be called (if it exists).
1864 * @return void
1865 */
d872881f 1866 private function obtain_dynamic_data() {
0d8b6a69 1867 global $CFG;
4cc819ad
MG
1868 $userid = $this->modinfo->get_user_id();
1869 if ($this->state >= self::STATE_BUILDING_DYNAMIC || $userid == -1) {
0d8b6a69 1870 return;
1871 }
d872881f 1872 $this->state = self::STATE_BUILDING_DYNAMIC;
0d8b6a69 1873
1874 if (!empty($CFG->enableavailability)) {
8d1f33e1 1875 // Get availability information.
1876 $ci = new \core_availability\info_module($this);
1877
0d8b6a69 1878 // Note that the modinfo currently available only includes minimal details (basic data)
d872881f 1879 // but we know that this function does not need anything more than basic data.
0d8b6a69 1880 $this->available = $ci->is_available($this->availableinfo, true,
1881 $userid, $this->modinfo);
daad1b4b
MG
1882 } else {
1883 $this->available = true;
1884 }
ce4dfd27 1885
daad1b4b
MG
1886 // Check parent section.
1887 if ($this->available) {
ce4dfd27 1888 $parentsection = $this->modinfo->get_section_info($this->sectionnum);
1889 if (!$parentsection->available) {
1890 // Do not store info from section here, as that is already
1891 // presented from the section (if appropriate) - just change
1892 // the flag
1893 $this->available = false;
1894 }
0d8b6a69 1895 }
1896
daad1b4b 1897 // Update visible state for current user.
0d8b6a69 1898 $this->update_user_visible();
1899
1900 // Let module make dynamic changes at this point
1901 $this->call_mod_function('cm_info_dynamic');
1902 $this->state = self::STATE_DYNAMIC;
1903 }
1904
d872881f
MG
1905 /**
1906 * Getter method for property $uservisible, ensures that dynamic data is retrieved.
1907 * @return bool
1908 */
1909 private function get_user_visible() {
1910 $this->obtain_dynamic_data();
1911 return $this->uservisible;
1912 }
1913
8341055e
MG
1914 /**
1915 * Returns whether this module is visible to the current user on course page
1916 *
1917 * Activity may be visible on the course page but not available, for example
1918 * when it is hidden conditionally but the condition information is displayed.
1919 *
1920 * @return bool
1921 */
1922 public function is_visible_on_course_page() {
1923 $this->obtain_dynamic_data();
1924 return $this->uservisibleoncoursepage;
1925 }
1926
1927 /**
1928 * Whether this module is available but hidden from course page
1929 *
1930 * "Stealth" modules are the ones that are not shown on course page but available by following url.
1931 * They are normally also displayed in grade reports and other reports.
1932 * Module will be stealth either if visibleoncoursepage=0 or it is a visible module inside the hidden
1933 * section.
1934 *
1935 * @return bool
1936 */
1937 public function is_stealth() {
1938 return !$this->visibleoncoursepage ||
1939 ($this->visible && ($section = $this->get_section_info()) && !$section->visible);
1940 }
1941
d872881f
MG
1942 /**
1943 * Getter method for property $available, ensures that dynamic data is retrieved
1944 * @return bool
1945 */
1946 private function get_available() {
1947 $this->obtain_dynamic_data();
1948 return $this->available;
1949 }
1950
061e6b28 1951 /**
7a07d34d 1952 * This method can not be used anymore.
061e6b28 1953 *
7a07d34d 1954 * @see \core_availability\info_module::filter_user_list()
061e6b28 1955 * @deprecated Since Moodle 2.8
1956 */
1957 private function get_deprecated_group_members_only() {
7a07d34d 1958 throw new coding_exception('$cm->groupmembersonly can not be used anymore. ' .
061e6b28 1959 'If used to restrict a list of enrolled users to only those who can ' .
7a07d34d 1960 'access the module, consider \core_availability\info_module::filter_user_list.');
061e6b28 1961 }
1962
d872881f
MG
1963 /**
1964 * Getter method for property $availableinfo, ensures that dynamic data is retrieved
061e6b28 1965 *
1966 * @return string Available info (HTML)
d872881f
MG
1967 */
1968 private function get_available_info() {
1969 $this->obtain_dynamic_data();
1970 return $this->availableinfo;
1971 }
1972
0d8b6a69 1973 /**
5e762271
AD
1974 * Works out whether activity is available to the current user
1975 *
1976 * If the activity is unavailable, additional checks are required to determine if its hidden or greyed out
1977 *
0d8b6a69 1978 * @return void
1979 */
1980 private function update_user_visible() {
0d8b6a69 1981 $userid = $this->modinfo->get_user_id();
4cc819ad
MG
1982 if ($userid == -1) {
1983 return null;
1984 }
0d8b6a69 1985 $this->uservisible = true;
5e762271 1986
048f909b
JD
1987 // If the module is being deleted, set the uservisible state to false and return.
1988 if ($this->deletioninprogress) {
1989 $this->uservisible = false;
1990 return null;
1991 }
1992
5e762271
AD
1993 // If the user cannot access the activity set the uservisible flag to false.
1994 // Additional checks are required to determine whether the activity is entirely hidden or just greyed out.
6a36b852
J
1995 if ((!$this->visible && !has_capability('moodle/course:viewhiddenactivities', $this->get_context(), $userid)) ||
1996 (!$this->get_available() &&
1997 !has_capability('moodle/course:ignoreavailabilityrestrictions', $this->get_context(), $userid))) {
5e762271 1998
0d8b6a69 1999 $this->uservisible = false;
a098f340 2000 }
5e762271
AD
2001
2002 // Check group membership.
061e6b28 2003 if ($this->is_user_access_restricted_by_capability()) {
5e762271
AD
2004
2005 $this->uservisible = false;
2006 // Ensure activity is completely hidden from the user.
8d1f33e1 2007 $this->availableinfo = '';
5fee56d5 2008 }
8341055e
MG
2009
2010 $this->uservisibleoncoursepage = $this->uservisible &&
2011 ($this->visibleoncoursepage ||
2012 has_capability('moodle/course:manageactivities', $this->get_context(), $userid) ||
2013 has_capability('moodle/course:activityvisibility', $this->get_context(), $userid));
2014 // Activity that is not available, not hidden from course page and has availability
2015 // info is actually visible on the course page (with availability info and without a link).
2016 if (!$this->uservisible && $this->visibleoncoursepage && $this->availableinfo) {
2017 $this->uservisibleoncoursepage = true;
2018 }
5fee56d5
FM
2019 }
2020
2021 /**
7a07d34d 2022 * This method has been deprecated and should not be used.
5e762271 2023 *
7a07d34d 2024 * @see $uservisible
061e6b28 2025 * @deprecated Since Moodle 2.8
5fee56d5
FM
2026 */
2027 public function is_user_access_restricted_by_group() {
7a07d34d
JP
2028 throw new coding_exception('cm_info::is_user_access_restricted_by_group() can not be used any more.' .
2029 ' Use $cm->uservisible to decide whether the current user can access an activity.');
5e762271
AD
2030 }
2031
9e1fe421
TH
2032 /**
2033 * Checks whether mod/...:view capability restricts the current user's access.
2034 *
2035 * @return bool True if the user access is restricted.
2036 */
2037 public function is_user_access_restricted_by_capability() {
4cc819ad
MG
2038 $userid = $this->modinfo->get_user_id();
2039 if ($userid == -1) {
2040 return null;
2041 }
9e1fe421
TH
2042 $capability = 'mod/' . $this->modname . ':view';
2043 $capabilityinfo = get_capability_info($capability);
2044 if (!$capabilityinfo) {
2045 // Capability does not exist, no one is prevented from seeing the activity.
2046 return false;
2047 }
2048
2049 // You are blocked if you don't have the capability.
d872881f 2050 return !has_capability($capability, $this->get_context(), $userid);
9e1fe421
TH
2051 }
2052
5e762271 2053 /**
8d1f33e1 2054 * Checks whether the module's conditional access settings mean that the
2055 * user cannot see the activity at all
2056 *
4d851042 2057 * @deprecated since 2.7 MDL-44070
5e762271
AD
2058 */
2059 public function is_user_access_restricted_by_conditional_access() {
4d851042
AA
2060 throw new coding_exception('cm_info::is_user_access_restricted_by_conditional_access() ' .
2061 'can not be used any more; this function is not needed (use $cm->uservisible ' .
061e6b28 2062 'and $cm->availableinfo to decide whether it should be available ' .
4d851042 2063 'or appear)');
0d8b6a69 2064 }
2065
2066 /**
2067 * Calls a module function (if exists), passing in one parameter: this object.
2068 * @param string $type Name of function e.g. if this is 'grooblezorb' and the modname is
2069 * 'forum' then it will try to call 'mod_forum_grooblezorb' or 'forum_grooblezorb'
2070 * @return void
2071 */
2072 private function call_mod_function($type) {
2073 global $CFG;
2074 $libfile = $CFG->dirroot . '/mod/' . $this->modname . '/lib.php';
2075 if (file_exists($libfile)) {
2076 include_once($libfile);
2077 $function = 'mod_' . $this->modname . '_' . $type;
2078 if (function_exists($function)) {
2079 $function($this);
2080 } else {
2081 $function = $this->modname . '_' . $type;
2082 if (function_exists($function)) {
2083 $function($this);
2084 }
2085 }
2086 }
2087 }
2088
2089 /**
2090 * If view data for this course-module is not yet available, obtains it.
2091 *
2092 * This function is automatically called if any of the functions (marked) which require
2093 * view data are called.
2094 *
2095 * View data is data which is needed only for displaying the course main page (& any similar
2096 * functionality on other pages) but is not needed in general. Obtaining view data may have
2097 * a performance cost.
2098 *
2099 * As part of this function, the module's _cm_info_view function from its lib.php will
2100 * be called (if it exists).
2101 * @return void
2102 */
2103 private function obtain_view_data() {
4cc819ad 2104 if ($this->state >= self::STATE_BUILDING_VIEW || $this->modinfo->get_user_id() == -1) {
0d8b6a69 2105 return;
2106 }
d872881f
MG
2107 $this->obtain_dynamic_data();
2108 $this->state = self::STATE_BUILDING_VIEW;
0d8b6a69 2109
2110 // Let module make changes at this point
2111 $this->call_mod_function('cm_info_view');
2112 $this->state = self::STATE_VIEW;
2113 }
2114}
2115
2116
0d8b6a69 2117/**
2118 * Returns reference to full info about modules in course (including visibility).
2119 * Cached and as fast as possible (0 or 1 db query).
2120 *
9428a154
MG
2121 * use get_fast_modinfo($courseid, 0, true) to reset the static cache for particular course
2122 * use get_fast_modinfo(0, 0, true) to reset the static cache for all courses
2123 *
299cfee5
MG
2124 * use rebuild_course_cache($courseid, true) to reset the application AND static cache
2125 * for particular course when it's contents has changed
2126 *
2127 * @param int|stdClass $courseorid object from DB table 'course' (must have field 'id'
2128 * and recommended to have field 'cacherev') or just a course id. Just course id
2129 * is enough when calling get_fast_modinfo() for current course or site or when
2130 * calling for any other course for the second time.
4cc819ad
MG
2131 * @param int $userid User id to populate 'availble' and 'uservisible' attributes of modules and sections.
2132 * Set to 0 for current user (default). Set to -1 to avoid calculation of dynamic user-depended data.
b46be6ad
MG
2133 * @param bool $resetonly whether we want to get modinfo or just reset the cache
2134 * @return course_modinfo|null Module information for course, or null if resetting
299cfee5 2135 * @throws moodle_exception when course is not found (nothing is thrown if resetting)
0d8b6a69 2136 */
b46be6ad 2137function get_fast_modinfo($courseorid, $userid = 0, $resetonly = false) {
b46be6ad
MG
2138 // compartibility with syntax prior to 2.4:
2139 if ($courseorid === 'reset') {
2140 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);
2141 $courseorid = 0;
2142 $resetonly = true;
2143 }
2144
4202471a
MG
2145 // Function get_fast_modinfo() can never be called during upgrade unless it is used for clearing cache only.
2146 if (!$resetonly) {
2147 upgrade_ensure_not_running();
2148 }
2149
b46be6ad
MG
2150 // Function is called with $reset = true
2151 if ($resetonly) {
299cfee5 2152 course_modinfo::clear_instance_cache($courseorid);
0d8b6a69 2153 return null;
2154 }
2155
b46be6ad 2156 // Function is called with $reset = false, retrieve modinfo
299cfee5 2157 return course_modinfo::instance($courseorid, $userid);
0d8b6a69 2158}
2159
d25c41fb 2160/**
2161 * Efficiently retrieves the $course (stdclass) and $cm (cm_info) objects, given
2162 * a cmid. If module name is also provided, it will ensure the cm is of that type.
2163 *
2164 * Usage:
2165 * list($course, $cm) = get_course_and_cm_from_cmid($cmid, 'forum');
2166 *
2167 * Using this method has a performance advantage because it works by loading
2168 * modinfo for the course - which will then be cached and it is needed later
2169 * in most requests. It also guarantees that the $cm object is a cm_info and
2170 * not a stdclass.
2171 *
2172 * The $course object can be supplied if already known and will speed
2173 * up this function - although it is more efficient to use this function to
2174 * get the course if you are starting from a cmid.
2175 *
2176 * To avoid security problems and obscure bugs, you should always specify
2177 * $modulename if the cmid value came from user input.
2178 *
2179 * By default this obtains information (for example, whether user can access
2180 * the activity) for current user, but you can specify a userid if required.
2181 *
2182 * @param stdClass|int $cmorid Id of course-module, or database object
2183 * @param string $modulename Optional modulename (improves security)
2184 * @param stdClass|int $courseorid Optional course object if already loaded
2185 * @param int $userid Optional userid (default = current)
2186 * @return array Array with 2 elements $course and $cm
2187 * @throws moodle_exception If the item doesn't exist or is of wrong module name
2188 */
2189function get_course_and_cm_from_cmid($cmorid, $modulename = '', $courseorid = 0, $userid = 0) {
2190 global $DB;
2191 if (is_object($cmorid)) {
2192 $cmid = $cmorid->id;
2193 if (isset($cmorid->course)) {
2194 $courseid = (int)$cmorid->course;
2195 } else {
2196 $courseid = 0;
2197 }
2198 } else {
2199 $cmid = (int)$cmorid;
2200 $courseid = 0;
2201 }
2202
2203 // Validate module name if supplied.
2204 if ($modulename && !core_component::is_valid_plugin_name('mod', $modulename)) {
2205 throw new coding_exception('Invalid modulename parameter');
2206 }
2207
2208 // Get course from last parameter if supplied.
2209 $course = null;
2210 if (is_object($courseorid)) {
2211 $course = $courseorid;
2212 } else if ($courseorid) {
2213 $courseid = (int)$courseorid;
2214 }
2215
2216 if (!$course) {
2217 if ($courseid) {
2218 // If course ID is known, get it using normal function.
2219 $course = get_course($courseid);
2220 } else {
2221 // Get course record in a single query based on cmid.
2222 $course = $DB->get_record_sql("
2223 SELECT c.*
2224 FROM {course_modules} cm
2225 JOIN {course} c ON c.id = cm.course
2226 WHERE cm.id = ?", array($cmid), MUST_EXIST);
2227 }
2228 }
2229
2230 // Get cm from get_fast_modinfo.
2231 $modinfo = get_fast_modinfo($course, $userid);
2232 $cm = $modinfo->get_cm($cmid);
2233 if ($modulename && $cm->modname !== $modulename) {
2234 throw new moodle_exception('invalidcoursemodule', 'error');
2235 }
2236 return array($course, $cm);
2237}
2238
2239/**
2240 * Efficiently retrieves the $course (stdclass) and $cm (cm_info) objects, given
2241 * an instance id or record and module name.
2242 *
2243 * Usage:
2244 * list($course, $cm) = get_course_and_cm_from_instance($forum, 'forum');
2245 *
2246 * Using this method has a performance advantage because it works by loading
2247 * modinfo for the course - which will then be cached and it is needed later
2248 * in most requests. It also guarantees that the $cm object is a cm_info and
2249 * not a stdclass.
2250 *
2251 * The $course object can be supplied if already known and will speed
2252 * up this function - although it is more efficient to use this function to
2253 * get the course if you are starting from an instance id.
2254 *
2255 * By default this obtains information (for example, whether user can access
2256 * the activity) for current user, but you can specify a userid if required.
2257 *
2258 * @param stdclass|int $instanceorid Id of module instance, or database object
2259 * @param string $modulename Modulename (required)
2260 * @param stdClass|int $courseorid Optional course object if already loaded
2261 * @param int $userid Optional userid (default = current)
2262 * @return array Array with 2 elements $course and $cm
2263 * @throws moodle_exception If the item doesn't exist or is of wrong module name
2264 */
2265function get_course_and_cm_from_instance($instanceorid, $modulename, $courseorid = 0, $userid = 0) {
2266 global $DB;
2267
2268 // Get data from parameter.
2269 if (is_object($instanceorid)) {
2270 $instanceid = $instanceorid->id;
2271 if (isset($instanceorid->course)) {
2272 $courseid = (int)$instanceorid->course;
2273 } else {
2274 $courseid = 0;
2275 }
2276 } else {
2277 $instanceid = (int)$instanceorid;
2278 $courseid = 0;
2279 }
2280
2281 // Get course from last parameter if supplied.
2282 $course = null;
2283 if (is_object($courseorid)) {
2284 $course = $courseorid;
2285 } else if ($courseorid) {
2286 $courseid = (int)$courseorid;
2287 }
2288
2289 // Validate module name if supplied.
2290 if (!core_component::is_valid_plugin_name('mod', $modulename)) {
2291 throw new coding_exception('Invalid modulename parameter');
2292 }
2293
2294 if (!$course) {
2295 if ($courseid) {
2296 // If course ID is known, get it using normal function.
2297 $course = get_course($courseid);
2298 } else {
2299 // Get course record in a single query based on instance id.
2300 $pagetable = '{' . $modulename . '}';
2301 $course = $DB->get_record_sql("
2302 SELECT c.*
2303 FROM $pagetable instance
2304 JOIN {course} c ON c.id = instance.course
2305 WHERE instance.id = ?", array($instanceid), MUST_EXIST);
2306 }
2307 }
2308
2309 // Get cm from get_fast_modinfo.
2310 $modinfo = get_fast_modinfo($course, $userid);
2311 $instances = $modinfo->get_instances_of($modulename);
2312 if (!array_key_exists($instanceid, $instances)) {
2313 throw new moodle_exception('invalidmoduleid', 'error', $instanceid);
2314 }
2315 return array($course, $instances[$instanceid]);
2316}
2317
2318
112d3b49 2319/**
299cfee5
MG
2320 * Rebuilds or resets the cached list of course activities stored in MUC.
2321 *
2322 * rebuild_course_cache() must NEVER be called from lib/db/upgrade.php.
2323 * At the same time course cache may ONLY be cleared using this function in
2324 * upgrade scripts of plugins.
2325 *
2326 * During the bulk operations if it is necessary to reset cache of multiple
2327 * courses it is enough to call {@link increment_revision_number()} for the
2328 * table 'course' and field 'cacherev' specifying affected courses in select.
2329 *
2330 * Cached course information is stored in MUC core/coursemodinfo and is
2331 * validated with the DB field {course}.cacherev
2332 *
2333 * @global moodle_database $DB
2334 * @param int $courseid id of course to rebuild, empty means all
2335 * @param boolean $clearonly only clear the cache, gets rebuild automatically on the fly.
2336 * Recommended to set to true to avoid unnecessary multiple rebuilding.
112d3b49
PS
2337 */
2338function rebuild_course_cache($courseid=0, $clearonly=false) {
e271f71d 2339 global $COURSE, $SITE, $DB, $CFG;
112d3b49 2340
4202471a
MG
2341 // Function rebuild_course_cache() can not be called during upgrade unless it's clear only.
2342 if (!$clearonly && !upgrade_ensure_not_running(true)) {
2343 $clearonly = true;
2344 }
2345
112d3b49
PS
2346 // Destroy navigation caches
2347 navigation_cache::destroy_volatile_caches();
2348
ee7084e9
MG
2349 if (class_exists('format_base')) {
2350 // if file containing class is not loaded, there is no cache there anyway
2351 format_base::reset_course_cache($courseid);
2352 }
2353
299cfee5
MG
2354 $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
2355 if (empty($courseid)) {
2356 // Clearing caches for all courses.
2357 increment_revision_number('course', 'cacherev', '');
2358 $cachecoursemodinfo->purge();
2359 course_modinfo::clear_instance_cache();
2360 // Update global values too.
2361 $sitecacherev = $DB->get_field('course', 'cacherev', array('id' => SITEID));
2362 $SITE->cachrev = $sitecacherev;
2363 if ($COURSE->id == SITEID) {
2364 $COURSE->cacherev = $sitecacherev;
487caf6b 2365 } else {
299cfee5 2366 $COURSE->cacherev = $DB->get_field('course', 'cacherev', array('id' => $COURSE->id));
487caf6b 2367 }
299cfee5
MG
2368 } else {
2369 // Clearing cache for one course, make sure it is deleted from user request cache as well.
2370 increment_revision_number('course', 'cacherev', 'id = :id', array('id' => $courseid));
2371 $cachecoursemodinfo->delete($courseid);
2372 course_modinfo::clear_instance_cache($courseid);
2373 // Update global values too.
2374 if ($courseid == $COURSE->id || $courseid == $SITE->id) {
2375 $cacherev = $DB->get_field('course', 'cacherev', array('id' => $courseid));
2376 if ($courseid == $COURSE->id) {
2377 $COURSE->cacherev = $cacherev;
2378 }
2379 if ($courseid == $SITE->id) {
2380 $SITE->cachrev = $cacherev;
2381 }
e271f71d 2382 }
112d3b49
PS
2383 }
2384
299cfee5
MG
2385 if ($clearonly) {
2386 return;
2387 }
112d3b49
PS
2388
2389 if ($courseid) {
2390 $select = array('id'=>$courseid);
2391 } else {
2392 $select = array();
3ef7279f 2393 core_php_time_limit::raise(); // this could take a while! MDL-10954
112d3b49
PS
2394 }
2395
299cfee5
MG
2396 $rs = $DB->get_recordset("course", $select,'','id,'.join(',', course_modinfo::$cachedfields));
2397 // Rebuild cache for each course.
112d3b49 2398 foreach ($rs as $course) {
299cfee5 2399 course_modinfo::build_course_cache($course);
112d3b49
PS
2400 }
2401 $rs->close();
112d3b49
PS
2402}
2403
0d8b6a69 2404
2405/**
2406 * Class that is the return value for the _get_coursemodule_info module API function.
2407 *
2408 * Note: For backward compatibility, you can also return a stdclass object from that function.
3008f86c
MG
2409 * The difference is that the stdclass object may contain an 'extra' field (deprecated,
2410 * use extraclasses and onclick instead). The stdclass object may not contain
0d8b6a69 2411 * the new fields defined here (content, extraclasses, customdata).
2412 */
2413class cached_cm_info {
2414 /**
2415 * Name (text of link) for this activity; Leave unset to accept default name
2416 * @var string
2417 */
2418 public $name;
2419
2420 /**
2421 * Name of icon for this activity. Normally, this should be used together with $iconcomponent
663640f5 2422 * to define the icon, as per image_url function.
0d8b6a69 2423 * For backward compatibility, if this value is of the form 'mod/forum/icon' then an icon
2424 * within that module will be used.
2425 * @see cm_info::get_icon_url()
663640f5 2426 * @see renderer_base::image_url()
0d8b6a69 2427 * @var string
2428 */
2429 public $icon;
2430
2431 /**
663640f5 2432 * Component for icon for this activity, as per image_url; leave blank to use default 'moodle'
0d8b6a69 2433 * component
663640f5 2434 * @see renderer_base::image_url()
0d8b6a69 2435 * @var string
2436 */
2437 public $iconcomponent;
2438
2439 /**
2440 * HTML content to be displayed on the main page below the link (if any) for this course-module
2441 * @var string
2442 */
2443 public $content;
2444
2445 /**
2446 * Custom data to be stored in modinfo for this activity; useful if there are cases when
2447 * internal information for this activity type needs to be accessible from elsewhere on the
2448 * course without making database queries. May be of any type but should be short.
2449 * @var mixed
2450 */
2451 public $customdata;
2452
2453 /**
2454 * Extra CSS class or classes to be added when this activity is displayed on the main page;
2455 * space-separated string
2456 * @var string
2457 */
2458 public $extraclasses;
2459
c443a1cd
EL
2460 /**
2461 * External URL image to be used by activity as icon, useful for some external-tool modules
2462 * like lti. If set, takes precedence over $icon and $iconcomponent
2463 * @var $moodle_url
2464 */
2465 public $iconurl;
2466
0d8b6a69 2467 /**
2468 * Content of onclick JavaScript; escaped HTML to be inserted as attribute value
2469 * @var string
2470 */
2471 public $onclick;
c443a1cd 2472}
ce4dfd27 2473
2474
2475/**
2476 * Data about a single section on a course. This contains the fields from the
2477 * course_sections table, plus additional data when required.
4e430906
MG
2478 *
2479 * @property-read int $id Section ID - from course_sections table
2480 * @property-read int $course Course ID - from course_sections table
2481 * @property-read int $section Section number - from course_sections table
2482 * @property-read string $name Section name if specified - from course_sections table
2483 * @property-read int $visible Section visibility (1 = visible) - from course_sections table
2484 * @property-read string $summary Section summary text if specified - from course_sections table
2485 * @property-read int $summaryformat Section summary text format (FORMAT_xx constant) - from course_sections table
8d1f33e1 2486 * @property-read string $availability Availability information as JSON string -
4e430906
MG
2487 * from course_sections table
2488 * @property-read array $conditionscompletion Availability conditions for this section based on the completion of
2489 * course-modules (array from course-module id to required completion state
2490 * for that module) - from cached data in sectioncache field
2491 * @property-read array $conditionsgrade Availability conditions for this section based on course grades (array from
2492 * grade item id to object with ->min, ->max fields) - from cached data in
2493 * sectioncache field
2494 * @property-read array $conditionsfield Availability conditions for this section based on user fields
2495 * @property-read bool $available True if this section is available to the given user i.e. if all availability conditions
2496 * are met - obtained dynamically
2497 * @property-read string $availableinfo If section is not available to some users, this string gives information about
2498 * availability which can be displayed to students and/or staff (e.g. 'Available from 3 January 2010')
2499 * for display on main page - obtained dynamically
2500 * @property-read bool $uservisible True if this section is available to the given user (for example, if current user
2501 * has viewhiddensections capability, they can access the section even if it is not
2502 * visible or not available, so this would be true in that case) - obtained dynamically
2503 * @property-read string $sequence Comma-separated list of all modules in the section. Note, this field may not exactly
2504 * match course_sections.sequence if later has references to non-existing modules or not modules of not available module types.
58d11393 2505 * @property-read course_modinfo $modinfo
ce4dfd27 2506 */
fc79ede5 2507class section_info implements IteratorAggregate {
ce4dfd27 2508 /**
2509 * Section ID - from course_sections table
2510 * @var int
2511 */
fc79ede5 2512 private $_id;
ce4dfd27 2513
ce4dfd27 2514 /**
2515 * Section number - from course_sections table
2516 * @var int
2517 */
fc79ede5 2518 private $_section;
ce4dfd27 2519
2520 /**
2521 * Section name if specified - from course_sections table
2522 * @var string
2523 */
fc79ede5 2524 private $_name;
ce4dfd27 2525
2526 /**
2527 * Section visibility (1 = visible) - from course_sections table
2528 * @var int
2529 */
fc79ede5 2530 private $_visible;
ce4dfd27 2531
2532 /**
2533 * Section summary text if specified - from course_sections table
2534 * @var string
2535 */
fc79ede5 2536 private $_summary;
ce4dfd27 2537
2538 /**
2539 * Section summary text format (FORMAT_xx constant) - from course_sections table
2540 * @var int
2541 */
fc79ede5 2542 private $_summaryformat;
ce4dfd27 2543
2544 /**
8d1f33e1 2545 * Availability information as JSON string - from course_sections table
2546 * @var string
ce4dfd27 2547 */
8d1f33e1 2548 private $_availability;
ce4dfd27 2549
2550 /**
2551 * Availability conditions for this section based on the completion of
2552 * course-modules (array from course-module id to required completion state
2553 * for that module) - from cached data in sectioncache field
2554 * @var array
2555 */
fc79ede5 2556 private $_conditionscompletion;
ce4dfd27 2557
2558 /**
2559 * Availability conditions for this section based on course grades (array from
2560 * grade item id to object with ->min, ->max fields) - from cached data in
2561 * sectioncache field
2562 * @var array
2563 */
fc79ede5
MG
2564 private $_conditionsgrade;
2565
2566 /**
2567 * Availability conditions for this section based on user fields
2568 * @var array
2569 */
2570 private $_conditionsfield;
ce4dfd27 2571
2572 /**
2573 * True if this section is available to students i.e. if all availability conditions
4e430906
MG
2574 * are met - obtained dynamically on request, see function {@link section_info::get_available()}
2575 * @var bool|null
ce4dfd27 2576 */
fc79ede5 2577 private $_available;
ce4dfd27 2578
2579 /**
4e430906 2580 * If section is not available to some users, this string gives information about
ce4dfd27 2581 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
4e430906
MG
2582 * January 2010') for display on main page - obtained dynamically on request, see
2583 * function {@link section_info::get_availableinfo()}
ce4dfd27 2584 * @var string
2585 */
fc79ede5 2586 private $_availableinfo;
ce4dfd27 2587
2588 /**
2589 * True if this section is available to the CURRENT user (for example, if current user
2590 * has viewhiddensections capability, they can access the section even if it is not
4e430906
MG
2591 * visible or not available, so this would be true in that case) - obtained dynamically
2592 * on request, see function {@link section_info::get_uservisible()}
2593 * @var bool|null
ce4dfd27 2594 */
fc79ede5 2595 private $_uservisible;
ce4dfd27 2596
2597 /**
2598 * Default values for sectioncache fields; if a field has this value, it won't
2599 * be stored in the sectioncache cache, to save space. Checks are done by ===
2600 * which means values must all be strings.
2601 * @var array
2602 */
2603 private static $sectioncachedefaults = array(
2604 'name' => null,
2605 'summary' => '',
2606 'summaryformat' => '1', // FORMAT_HTML, but must be a string
2607 'visible' => '1',
048f909b 2608 'availability' => null
ce4dfd27 2609 );
2610
aea2e3c3
MG
2611 /**
2612 * Stores format options that have been cached when building 'coursecache'
2613 * When the format option is requested we look first if it has been cached
2614 * @var array
2615 */
2616 private $cachedformatoptions = array();
2617
4e430906
MG
2618 /**
2619 * Stores the list of all possible section options defined in each used course format.
2620 * @var array
2621 */
2622 static private $sectionformatoptions = array();
2623
2624 /**
2625 * Stores the modinfo object passed in constructor, may be used when requesting
2626 * dynamically obtained attributes such as available, availableinfo, uservisible.
2627 * Also used to retrun information about current course or user.
2628 * @var course_modinfo
2629 */
2630 private $modinfo;
2631
ce4dfd27 2632 /**
2633 * Constructs object from database information plus extra required data.
2634 * @param object $data Array entry from cached sectioncache
2635 * @param int $number Section number (array key)
4e430906
MG
2636 * @param int $notused1 argument not used (informaion is available in $modinfo)
2637 * @param int $notused2 argument not used (informaion is available in $modinfo)
ce4dfd27 2638 * @param course_modinfo $modinfo Owner (needed for checking availability)
4e430906 2639 * @param int $notused3 argument not used (informaion is available in $modinfo)
ce4dfd27 2640 */
4e430906 2641 public function __construct($data, $number, $notused1, $notused2, $modinfo, $notused3) {
ce4dfd27 2642 global $CFG;
4202471a 2643 require_once($CFG->dirroot.'/course/lib.php');
ce4dfd27 2644
2645 // Data that is always present
fc79ede5
MG
2646 $this->_id = $data->id;
2647
2648 $defaults = self::$sectioncachedefaults +
2649 array('conditionscompletion' => array(),
2650 'conditionsgrade' => array(),
2651 'conditionsfield' => array());
ce4dfd27 2652
2653 // Data that may use default values to save cache size
fc79ede5 2654 foreach ($defaults as $field => $value) {
ce4dfd27 2655 if (isset($data->{$field})) {
fc79ede5 2656 $this->{'_'.$field} = $data->{$field};
ce4dfd27 2657 } else {
fc79ede5 2658 $this->{'_'.$field} = $value;
ce4dfd27 2659 }
2660 }
2661
4e430906
MG
2662 // Other data from constructor arguments.
2663 $this->_section = $number;
2664 $this->modinfo = $modinfo;
2665
2666 // Cached course format data.
2667 $course = $modinfo->get_course();
299cfee5
MG
2668 if (!isset(self::$sectionformatoptions[$course->format])) {
2669 // Store list of section format options defined in each used course format.
2670 // They do not depend on particular course but only on its format.
2671 self::$sectionformatoptions[$course->format] =
2672 course_get_format($course)->section_format_options();
4e430906
MG
2673 }
2674 foreach (self::$sectionformatoptions[$course->format] as $field => $option) {
aea2e3c3
MG
2675 if (!empty($option['cache'])) {
2676 if (isset($data->{$field})) {
2677 $this->cachedformatoptions[$field] = $data->{$field};
2678 } else if (array_key_exists('cachedefault', $option)) {
2679 $this->cachedformatoptions[$field] = $option['cachedefault'];
2680 }
2681 }
2682 }
ce4dfd27 2683 }
2684
fc79ede5
MG
2685 /**
2686 * Magic method to check if the property is set
2687 *
2688 * @param string $name name of the property
2689 * @return bool
2690 */
2691 public function __isset($name) {
4e430906
MG
2692 if (method_exists($this, 'get_'.$name) ||
2693 property_exists($this, '_'.$name) ||
2694 array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
fc79ede5
MG
2695 $value = $this->__get($name);
2696 return isset($value);
2697 }
2698 return false;
2699 }
2700
2701 /**
2702 * Magic method to check if the property is empty
2703 *
2704 * @param string $name name of the property
2705 * @return bool
2706 */
2707 public function __empty($name) {
4e430906
MG
2708 if (method_exists($this, 'get_'.$name) ||
2709 property_exists($this, '_'.$name) ||
724b00b2 2710 array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
fc79ede5
MG
2711 $value = $this->__get($name);
2712 return empty($value);
2713 }
2714 return true;
2715 }
2716
2717 /**
2718 * Magic method to retrieve the property, this is either basic section property
2719 * or availability information or additional properties added by course format
2720 *
2721 * @param string $name name of the property
2722 * @return bool
2723 */
2724 public function __get($name) {
4e430906
MG
2725 if (method_exists($this, 'get_'.$name)) {
2726 return $this->{'get_'.$name}();
2727 }
fc79ede5
MG
2728 if (property_exists($this, '_'.$name)) {
2729 return $this->{'_'.$name};
2730 }
aea2e3c3
MG
2731 if (array_key_exists($name, $this->cachedformatoptions)) {
2732 return $this->cachedformatoptions[$name];
2733 }
fc79ede5 2734 // precheck if the option is defined in format to avoid unnecessary DB queries in get_format_options()
724b00b2 2735 if (array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
4e430906 2736 $formatoptions = course_get_format($this->modinfo->get_course())->get_format_options($this);
fc79ede5
MG
2737 return $formatoptions[$name];
2738 }
2739 debugging('Invalid section_info property accessed! '.$name);
2740 return null;
2741 }
2742
4e430906
MG
2743 /**
2744 * Finds whether this section is available at the moment for the current user.
2745 *
2746 * The value can be accessed publicly as $sectioninfo->available
2747 *
2748 * @return bool
2749 */
2750 private function get_available() {
2751 global $CFG;
4cc819ad
MG
2752 $userid = $this->modinfo->get_user_id();
2753 if ($this->_available !== null || $userid == -1) {
2754 // Has already been calculated or does not need calculation.
4e430906
MG
2755 return $this->_available;
2756 }
daad1b4b
MG
2757 $this->_available = true;
2758 $this->_availableinfo = '';
4e430906 2759 if (!empty($CFG->enableavailability)) {
8d1f33e1 2760 // Get availability information.
2761 $ci = new \core_availability\info_section($this);
4e430906 2762 $this->_available = $ci->is_available($this->_availableinfo, true,
4cc819ad 2763 $userid, $this->modinfo);
daad1b4b
MG
2764 }
2765 // Execute the hook from the course format that may override the available/availableinfo properties.
2766 $currentavailable = $this->_available;
2767 course_get_format($this->modinfo->get_course())->
2768 section_get_available_hook($this, $this->_available, $this->_availableinfo);
2769 if (!$currentavailable && $this->_available) {
2770 debugging('section_get_available_hook() can not make unavailable section available', DEBUG_DEVELOPER);
2771 $this->_available = $currentavailable;
4e430906
MG
2772 }
2773 return $this->_available;
2774 }
2775
2776 /**
2777 * Returns the availability text shown next to the section on course page.
2778 *
2779 * @return string
2780 */
2781 private function get_availableinfo() {
eedf5a5a 2782 // Calling get_available() will also fill the availableinfo property
2783 // (or leave it null if there is no userid).
4e430906 2784 $this->get_available();
4e430906
MG
2785 return $this->_availableinfo;
2786 }
2787
fc79ede5
MG
2788 /**
2789 * Implementation of IteratorAggregate::getIterator(), allows to cycle through properties
2790 * and use {@link convert_to_array()}
2791 *
2792 * @return ArrayIterator
2793 */
2794 public function getIterator() {
2795 $ret = array();
2796 foreach (get_object_vars($this) as $key => $value) {
2797 if (substr($key, 0, 1) == '_') {
4e430906
MG
2798 if (method_exists($this, 'get'.$key)) {
2799 $ret[substr($key, 1)] = $this->{'get'.$key}();
2800 } else {
2801 $ret[substr($key, 1)] = $this->$key;
2802 }
fc79ede5
MG
2803 }
2804 }
4e430906
MG
2805 $ret['sequence'] = $this->get_sequence();
2806 $ret['course'] = $this->get_course();
2807 $ret = array_merge($ret, course_get_format($this->modinfo->get_course())->get_format_options($this->_section));
fc79ede5
MG
2808 return new ArrayIterator($ret);
2809 }
2810
ce4dfd27 2811 /**
2812 * Works out whether activity is visible *for current user* - if this is false, they
2813 * aren't allowed to access it.
4e430906
MG
2814 *
2815 * @return bool
ce4dfd27 2816 */
4e430906 2817 private function get_uservisible() {
4cc819ad
MG
2818 $userid = $this->modinfo->get_user_id();
2819 if ($this->_uservisible !== null || $userid == -1) {
2820 // Has already been calculated or does not need calculation.
4e430906
MG
2821 return $this->_uservisible;
2822 }
fc79ede5 2823 $this->_uservisible = true;
4e430906
MG
2824 if (!$this->_visible || !$this->get_available()) {
2825 $coursecontext = context_course::instance($this->get_course());
6a36b852
J
2826 if (!$this->_visible && !has_capability('moodle/course:viewhiddensections', $coursecontext, $userid) ||
2827 (!$this->get_available() &&
2828 !has_capability('moodle/course:ignoreavailabilityrestrictions', $coursecontext, $userid))) {
2829
4e430906
MG
2830 $this->_uservisible = false;
2831 }
ce4dfd27 2832 }
4e430906
MG
2833 return $this->_uservisible;
2834 }
2835
2836 /**
2837 * Restores the course_sections.sequence value
2838 *
2839 * @return string
2840 */
2841 private function get_sequence() {
2842 if (!empty($this->modinfo->sections[$this->_section])) {
2843 return implode(',', $this->modinfo->sections[$this->_section]);
2844 } else {
2845 return '';
2846 }
2847 }
2848
2849 /**
2850 * Returns course ID - from course_sections table
2851 *
2852 * @return int
2853 */
2854 private function get_course() {
2855 return $this->modinfo->get_course_id();
ce4dfd27 2856 }
58d11393
MG
2857
2858 /**
2859 * Modinfo object
2860 *
2861 * @return course_modinfo
2862 */
2863 private function get_modinfo() {
2864 return $this->modinfo;
2865 }
ce4dfd27 2866
2867 /**
2868 * Prepares section data for inclusion in sectioncache cache, removing items
2869 * that are set to defaults, and adding availability data if required.
2870 *
2871 * Called by build_section_cache in course_modinfo only; do not use otherwise.
2872 * @param object $section Raw section data object
2873 */
2874 public static function convert_for_section_cache($section) {
2875 global $CFG;
2876
2877 // Course id stored in course table
2878 unset($section->course);
2879 // Section number stored in array key
2880 unset($section->section);
2881 // Sequence stored implicity in modinfo $sections array
2882 unset($section->sequence);
2883
ce4dfd27 2884 // Remove default data
94dc3c7d 2885 foreach (self::$sectioncachedefaults as $field => $value) {
ce4dfd27 2886 // Exact compare as strings to avoid problems if some strings are set
2887 // to "0" etc.
2888 if (isset($section->{$field}) && $section->{$field} === $value) {
2889 unset($section->{$field});
2890 }
2891 }
2892 }
2893}