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