weekly release 3.5dev
[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) {
c1518631 253 if (!isset($modnamesused[$mod->modname]) && isset($modnames[$mod->modname]) && $mod->uservisible) {
d57aa283
MG
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 /**
7a07d34d 534 * This method can not be used anymore.
299cfee5 535 *
7a07d34d 536 * @see course_modinfo::build_course_cache()
299cfee5 537 * @deprecated since 2.6
ce4dfd27 538 */
539 public static function build_section_cache($courseid) {
7a07d34d
JP
540 throw new coding_exception('Function course_modinfo::build_section_cache() can not be used anymore.' .
541 ' Please use course_modinfo::build_course_cache() whenever applicable.');
299cfee5
MG
542 }
543
544 /**
545 * Builds a list of information about sections on a course to be stored in
546 * the course cache. (Does not include information that is already cached
547 * in some other way.)
548 *
549 * @param stdClass $course Course object (must contain fields
550 * @return array Information about sections, indexed by section number (not id)
551 */
552 protected static function build_course_section_cache($course) {
553 global $DB;
ce4dfd27 554
555 // Get section data
299cfee5 556 $sections = $DB->get_records('course_sections', array('course' => $course->id), 'section',
048f909b 557 'section, id, course, name, summary, summaryformat, sequence, visible, availability');
ce4dfd27 558 $compressedsections = array();
559
299cfee5 560 $formatoptionsdef = course_get_format($course)->section_format_options();
ce4dfd27 561 // Remove unnecessary data and add availability
562 foreach ($sections as $number => $section) {
aea2e3c3
MG
563 // Add cached options from course format to $section object
564 foreach ($formatoptionsdef as $key => $option) {
565 if (!empty($option['cache'])) {
299cfee5 566 $formatoptions = course_get_format($course)->get_format_options($section);
aea2e3c3
MG
567 if (!array_key_exists('cachedefault', $option) || $option['cachedefault'] !== $formatoptions[$key]) {
568 $section->$key = $formatoptions[$key];
569 }
570 }
571 }
99e9f9a6 572 // Clone just in case it is reused elsewhere
ce4dfd27 573 $compressedsections[$number] = clone($section);
574 section_info::convert_for_section_cache($compressedsections[$number]);
575 }
576
577 return $compressedsections;
578 }
299cfee5
MG
579
580 /**
581 * Builds and stores in MUC object containing information about course
582 * modules and sections together with cached fields from table course.
583 *
584 * @param stdClass $course object from DB table course. Must have property 'id'
585 * but preferably should have all cached fields.
586 * @return stdClass object with all cached keys of the course plus fields modinfo and sectioncache.
587 * The same object is stored in MUC
588 * @throws moodle_exception if course is not found (if $course object misses some of the
589 * necessary fields it is re-requested from database)
590 */
591 public static function build_course_cache($course) {
592 global $DB, $CFG;
593 require_once("$CFG->dirroot/course/lib.php");
594 if (empty($course->id)) {
595 throw new coding_exception('Object $course is missing required property \id\'');
596 }
597 // Ensure object has all necessary fields.
598 foreach (self::$cachedfields as $key) {
599 if (!isset($course->$key)) {
600 $course = $DB->get_record('course', array('id' => $course->id),
de170aac 601 implode(',', array_merge(array('id'), self::$cachedfields)), MUST_EXIST);
299cfee5
MG
602 break;
603 }
604 }
605 // Retrieve all information about activities and sections.
606 // This may take time on large courses and it is possible that another user modifies the same course during this process.
607 // Field cacherev stored in both DB and cache will ensure that cached data matches the current course state.
608 $coursemodinfo = new stdClass();
609 $coursemodinfo->modinfo = get_array_of_activities($course->id);
610 $coursemodinfo->sectioncache = self::build_course_section_cache($course);
611 foreach (self::$cachedfields as $key) {
612 $coursemodinfo->$key = $course->$key;
613 }
614 // Set the accumulated activities and sections information in cache, together with cacherev.
615 $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
616 $cachecoursemodinfo->set($course->id, $coursemodinfo);
617 return $coursemodinfo;
618 }
0d8b6a69 619}
620
621
622/**
623 * Data about a single module on a course. This contains most of the fields in the course_modules
624 * table, plus additional data when required.
625 *
d872881f
MG
626 * The object can be accessed by core or any plugin (i.e. course format, block, filter, etc.) as
627 * get_fast_modinfo($courseorid)->cms[$coursemoduleid]
628 * or
629 * get_fast_modinfo($courseorid)->instances[$moduletype][$instanceid]
630 *
631 * There are three stages when activity module can add/modify data in this object:
632 *
633 * <b>Stage 1 - during building the cache.</b>
634 * Allows to add to the course cache static user-independent information about the module.
635 * Modules should try to include only absolutely necessary information that may be required
636 * when displaying course view page. The information is stored in application-level cache
637 * and reset when {@link rebuild_course_cache()} is called or cache is purged by admin.
638 *
639 * Modules can implement callback XXX_get_coursemodule_info() returning instance of object
640 * {@link cached_cm_info}
641 *
642 * <b>Stage 2 - dynamic data.</b>
643 * Dynamic data is user-dependend, it is stored in request-level cache. To reset this cache
644 * {@link get_fast_modinfo()} with $reset argument may be called.
645 *
646 * Dynamic data is obtained when any of the following properties/methods is requested:
647 * - {@link cm_info::$url}
648 * - {@link cm_info::$name}
649 * - {@link cm_info::$onclick}
650 * - {@link cm_info::get_icon_url()}
651 * - {@link cm_info::$uservisible}
652 * - {@link cm_info::$available}
d872881f
MG
653 * - {@link cm_info::$availableinfo}
654 * - plus any of the properties listed in Stage 3.
655 *
656 * Modules can implement callback <b>XXX_cm_info_dynamic()</b> and inside this callback they
657 * are allowed to use any of the following set methods:
658 * - {@link cm_info::set_available()}
659 * - {@link cm_info::set_name()}
660 * - {@link cm_info::set_no_view_link()}
661 * - {@link cm_info::set_user_visible()}
662 * - {@link cm_info::set_on_click()}
663 * - {@link cm_info::set_icon_url()}
664 * Any methods affecting view elements can also be set in this callback.
665 *
666 * <b>Stage 3 (view data).</b>
667 * Also user-dependend data stored in request-level cache. Second stage is created
668 * because populating the view data can be expensive as it may access much more
669 * Moodle APIs such as filters, user information, output renderers and we
670 * don't want to request it until necessary.
671 * View data is obtained when any of the following properties/methods is requested:
672 * - {@link cm_info::$afterediticons}
673 * - {@link cm_info::$content}
674 * - {@link cm_info::get_formatted_content()}
675 * - {@link cm_info::$extraclasses}
676 * - {@link cm_info::$afterlink}
677 *
678 * Modules can implement callback <b>XXX_cm_info_view()</b> and inside this callback they
679 * are allowed to use any of the following set methods:
680 * - {@link cm_info::set_after_edit_icons()}
681 * - {@link cm_info::set_after_link()}
682 * - {@link cm_info::set_content()}
683 * - {@link cm_info::set_extra_classes()}
684 *
685 * @property-read int $id Course-module ID - from course_modules table
686 * @property-read int $instance Module instance (ID within module table) - from course_modules table
687 * @property-read int $course Course ID - from course_modules table
688 * @property-read string $idnumber 'ID number' from course-modules table (arbitrary text set by user) - from
689 * course_modules table
690 * @property-read int $added Time that this course-module was added (unix time) - from course_modules table
691 * @property-read int $visible Visible setting (0 or 1; if this is 0, students cannot see/access the activity) - from
692 * course_modules table
8341055e
MG
693 * @property-read int $visibleoncoursepage Visible on course page setting - from course_modules table, adjusted to
694 * whether course format allows this module to have the "stealth" mode
d872881f
MG
695 * @property-read int $visibleold Old visible setting (if the entire section is hidden, the previous value for
696 * visible is stored in this field) - from course_modules table
6d04c4f2
MG
697 * @property-read int $groupmode Group mode (one of the constants NOGROUPS, SEPARATEGROUPS, or VISIBLEGROUPS) - from
698 * course_modules table. Use {@link cm_info::$effectivegroupmode} to find the actual group mode that may be forced by course.
d872881f 699 * @property-read int $groupingid Grouping ID (0 = all groupings)
d872881f
MG
700 * @property-read bool $coursegroupmodeforce Indicates whether the course containing the module has forced the groupmode
701 * This means that cm_info::$groupmode should be ignored and cm_info::$coursegroupmode be used instead
6d04c4f2 702 * @property-read int $coursegroupmode Group mode (one of the constants NOGROUPS, SEPARATEGROUPS, or VISIBLEGROUPS) - from
d872881f
MG
703 * course table - as specified for the course containing the module
704 * Effective only if {@link cm_info::$coursegroupmodeforce} is set
6d04c4f2
MG
705 * @property-read int $effectivegroupmode Effective group mode for this module (one of the constants NOGROUPS, SEPARATEGROUPS,
706 * or VISIBLEGROUPS). This can be different from groupmode set for the module if the groupmode is forced for the course.
707 * This value will always be NOGROUPS if module type does not support group mode.
d872881f
MG
708 * @property-read int $indent Indent level on course page (0 = no indent) - from course_modules table
709 * @property-read int $completion Activity completion setting for this activity, COMPLETION_TRACKING_xx constant - from
710 * course_modules table
711 * @property-read mixed $completiongradeitemnumber Set to the item number (usually 0) if completion depends on a particular
712 * grade of this activity, or null if completion does not depend on a grade - from course_modules table
713 * @property-read int $completionview 1 if 'on view' completion is enabled, 0 otherwise - from course_modules table
714 * @property-read int $completionexpected Set to a unix time if completion of this activity is expected at a
715 * particular time, 0 if no time set - from course_modules table
8d1f33e1 716 * @property-read string $availability Availability information as JSON string or null if none -
d872881f
MG
717 * from course_modules table
718 * @property-read int $showdescription Controls whether the description of the activity displays on the course main page (in
719 * addition to anywhere it might display within the activity itself). 0 = do not show
720 * on main page, 1 = show on main page.
721 * @property-read string $extra (deprecated) Extra HTML that is put in an unhelpful part of the HTML when displaying this module in
722 * course page - from cached data in modinfo field. Deprecated, replaced by ->extraclasses and ->onclick
723 * @property-read string $icon Name of icon to use - from cached data in modinfo field
724 * @property-read string $iconcomponent Component that contains icon - from cached data in modinfo field
725 * @property-read string $modname Name of module e.g. 'forum' (this is the same name as the module's main database
726 * table) - from cached data in modinfo field
727 * @property-read int $module ID of module type - from course_modules table
728 * @property-read string $name Name of module instance for display on page e.g. 'General discussion forum' - from cached
729 * data in modinfo field
730 * @property-read int $sectionnum Section number that this course-module is in (section 0 = above the calendar, section 1
731 * = week/topic 1, etc) - from cached data in modinfo field
732 * @property-read int $section Section id - from course_modules table
733 * @property-read array $conditionscompletion Availability conditions for this course-module based on the completion of other
734 * course-modules (array from other course-module id to required completion state for that
735 * module) - from cached data in modinfo field
736 * @property-read array $conditionsgrade Availability conditions for this course-module based on course grades (array from
737 * grade item id to object with ->min, ->max fields) - from cached data in modinfo field
738 * @property-read array $conditionsfield Availability conditions for this course-module based on user fields
739 * @property-read bool $available True if this course-module is available to students i.e. if all availability conditions
740 * are met - obtained dynamically
741 * @property-read string $availableinfo If course-module is not available to students, this string gives information about
742 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
743 * January 2010') for display on main page - obtained dynamically
744 * @property-read bool $uservisible True if this course-module is available to the CURRENT user (for example, if current user
745 * has viewhiddenactivities capability, they can access the course-module even if it is not
746 * visible or not available, so this would be true in that case)
747 * @property-read context_module $context Module context
748 * @property-read string $modfullname Returns a localised human-readable name of the module type - calculated on request
749 * @property-read string $modplural Returns a localised human-readable name of the module type in plural form - calculated on request
750 * @property-read string $content Content to display on main (view) page - calculated on request
751 * @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
752 * @property-read string $extraclasses Extra CSS classes to add to html output for this activity on main page - calculated on request
753 * @property-read string $onclick Content of HTML on-click attribute already escaped - calculated on request
754 * @property-read mixed $customdata Optional custom data stored in modinfo cache for this activity, or null if none
755 * @property-read string $afterlink Extra HTML code to display after link - calculated on request
756 * @property-read string $afterediticons Extra HTML code to display after editing icons (e.g. more icons) - calculated on request
048f909b 757 * @property-read bool $deletioninprogress True if this course module is scheduled for deletion, false otherwise.
0d8b6a69 758 */
d872881f 759class cm_info implements IteratorAggregate {
0d8b6a69 760 /**
761 * State: Only basic data from modinfo cache is available.
762 */
763 const STATE_BASIC = 0;
764
d872881f
MG
765 /**
766 * State: In the process of building dynamic data (to avoid recursive calls to obtain_dynamic_data())
767 */
768 const STATE_BUILDING_DYNAMIC = 1;
769
0d8b6a69 770 /**
771 * State: Dynamic data is available too.
772 */
d872881f
MG
773 const STATE_DYNAMIC = 2;
774
775 /**
776 * State: In the process of building view data (to avoid recursive calls to obtain_view_data())
777 */
778 const STATE_BUILDING_VIEW = 3;
0d8b6a69 779
780 /**
781 * State: View data (for course page) is available.
782 */
d872881f 783 const STATE_VIEW = 4;
0d8b6a69 784
785 /**
786 * Parent object
787 * @var course_modinfo
788 */
789 private $modinfo;
790
791 /**
792 * Level of information stored inside this object (STATE_xx constant)
793 * @var int
794 */
795 private $state;
796
0d8b6a69 797 /**
798 * Course-module ID - from course_modules table
799 * @var int
800 */
d872881f 801 private $id;
0d8b6a69 802
803 /**
804 * Module instance (ID within module table) - from course_modules table
805 * @var int
806 */
d872881f 807 private $instance;
0d8b6a69 808
809 /**
810 * 'ID number' from course-modules table (arbitrary text set by user) - from
811 * course_modules table
812 * @var string
813 */
d872881f 814 private $idnumber;
0d8b6a69 815
816 /**
adaeccb6 817 * Time that this course-module was added (unix time) - from course_modules table
818 * @var int
819 */
d872881f 820 private $added;
adaeccb6 821
822 /**
823 * This variable is not used and is included here only so it can be documented.
824 * Once the database entry is removed from course_modules, it should be deleted
825 * here too.
826 * @var int
827 * @deprecated Do not use this variable
828 */
d872881f 829 private $score;
adaeccb6 830
831 /**
832 * Visible setting (0 or 1; if this is 0, students cannot see/access the activity) - from
0d8b6a69 833 * course_modules table
834 * @var int
835 */
d872881f 836 private $visible;
0d8b6a69 837
8341055e
MG
838 /**
839 * Visible on course page setting - from course_modules table
840 * @var int
841 */
842 private $visibleoncoursepage;
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
8341055e
MG
1009 /**
1010 * True if this course-module is visible to the CURRENT user on the course page
1011 * @var bool
1012 */
1013 private $uservisibleoncoursepage;
1014
0d8b6a69 1015 /**
1016 * @var moodle_url
1017 */
1018 private $url;
1019
1020 /**
1021 * @var string
1022 */
1023 private $content;
1024
1025 /**
1026 * @var string
1027 */
1028 private $extraclasses;
1029
c443a1cd
EL
1030 /**
1031 * @var moodle_url full external url pointing to icon image for activity
1032 */
1033 private $iconurl;
1034
0d8b6a69 1035 /**
1036 * @var string
1037 */
1038 private $onclick;
1039
1040 /**
1041 * @var mixed
1042 */
1043 private $customdata;
1044
1045 /**
1046 * @var string
1047 */
1048 private $afterlink;
1049
1050 /**
1051 * @var string
1052 */
1053 private $afterediticons;
1054
048f909b
JD
1055 /**
1056 * @var bool representing the deletion state of the module. True if the mod is scheduled for deletion.
1057 */
1058 private $deletioninprogress;
1059
d872881f
MG
1060 /**
1061 * List of class read-only properties and their getter methods.
1062 * Used by magic functions __get(), __isset(), __empty()
1063 * @var array
1064 */
1065 private static $standardproperties = array(
1066 'url' => 'get_url',
1067 'content' => 'get_content',
1068 'extraclasses' => 'get_extra_classes',
1069 'onclick' => 'get_on_click',
1070 'customdata' => 'get_custom_data',
1071 'afterlink' => 'get_after_link',
1072 'afterediticons' => 'get_after_edit_icons',
1073 'modfullname' => 'get_module_type_name',
1074 'modplural' => 'get_module_type_name_plural',
1075 'id' => false,
1076 'added' => false,
8d1f33e1 1077 'availability' => false,
d872881f 1078 'available' => 'get_available',
d872881f 1079 'availableinfo' => 'get_available_info',
d872881f
MG
1080 'completion' => false,
1081 'completionexpected' => false,
1082 'completiongradeitemnumber' => false,
1083 'completionview' => false,
1084 'conditionscompletion' => false,
1085 'conditionsfield' => false,
1086 'conditionsgrade' => false,
1087 'context' => 'get_context',
1088 'course' => 'get_course_id',
1089 'coursegroupmode' => 'get_course_groupmode',
1090 'coursegroupmodeforce' => 'get_course_groupmodeforce',
6d04c4f2 1091 'effectivegroupmode' => 'get_effective_groupmode',
d872881f
MG
1092 'extra' => false,
1093 'groupingid' => false,
061e6b28 1094 'groupmembersonly' => 'get_deprecated_group_members_only',
d872881f
MG
1095 'groupmode' => false,
1096 'icon' => false,
1097 'iconcomponent' => false,
1098 'idnumber' => false,
1099 'indent' => false,
1100 'instance' => false,
1101 'modname' => false,
1102 'module' => false,
1103 'name' => 'get_name',
1104 'score' => false,
1105 'section' => false,
1106 'sectionnum' => false,
d872881f
MG
1107 'showdescription' => false,
1108 'uservisible' => 'get_user_visible',
1109 'visible' => false,
8341055e 1110 'visibleoncoursepage' => false,
d872881f 1111 'visibleold' => false,
048f909b 1112 'deletioninprogress' => false
d872881f
MG
1113 );
1114
1115 /**
1116 * List of methods with no arguments that were public prior to Moodle 2.6.
1117 *
1118 * They can still be accessed publicly via magic __call() function with no warnings
1119 * but are not listed in the class methods list.
1120 * For the consistency of the code it is better to use corresponding properties.
1121 *
1122 * These methods be deprecated completely in later versions.
1123 *
1124 * @var array $standardmethods
1125 */
1126 private static $standardmethods = array(
1127 // Following methods are not recommended to use because there have associated read-only properties.
1128 'get_url',
1129 'get_content',
1130 'get_extra_classes',
1131 'get_on_click',
1132 'get_custom_data',
1133 'get_after_link',
1134 'get_after_edit_icons',
1135 // Method obtain_dynamic_data() should not be called from outside of this class but it was public before Moodle 2.6.
1136 'obtain_dynamic_data',
1137 );
1138
1139 /**
7a07d34d
JP
1140 * Magic method to call functions that are now declared as private but were public in Moodle before 2.6.
1141 * These private methods can not be used anymore.
d872881f
MG
1142 *
1143 * @param string $name
1144 * @param array $arguments
1145 * @return mixed
7a07d34d 1146 * @throws coding_exception
d872881f
MG
1147 */
1148 public function __call($name, $arguments) {
1149 if (in_array($name, self::$standardmethods)) {
7a07d34d
JP
1150 $message = "cm_info::$name() can not be used anymore.";
1151 if ($alternative = array_search($name, self::$standardproperties)) {
1152 $message .= " Please use the property cm_info->$alternative instead.";
07e78d93 1153 }
7a07d34d 1154 throw new coding_exception($message);
d872881f
MG
1155 }
1156 throw new coding_exception("Method cm_info::{$name}() does not exist");
1157 }
1158
d57aa283
MG
1159 /**
1160 * Magic method getter
1161 *
1162 * @param string $name
1163 * @return mixed
1164 */
1165 public function __get($name) {
d872881f
MG
1166 if (isset(self::$standardproperties[$name])) {
1167 if ($method = self::$standardproperties[$name]) {
1168 return $this->$method();
1169 } else {
1170 return $this->$name;
1171 }
1172 } else {
1173 debugging('Invalid cm_info property accessed: '.$name);
1174 return null;
d57aa283
MG
1175 }
1176 }
1177
d872881f
MG
1178 /**
1179 * Implementation of IteratorAggregate::getIterator(), allows to cycle through properties
1180 * and use {@link convert_to_array()}
1181 *
1182 * @return ArrayIterator
1183 */
1184 public function getIterator() {
1185 // Make sure dynamic properties are retrieved prior to view properties.
1186 $this->obtain_dynamic_data();
1187 $ret = array();
5793538a
AA
1188
1189 // Do not iterate over deprecated properties.
1190 $props = self::$standardproperties;
c62ba9b8 1191 unset($props['groupmembersonly']);
5793538a
AA
1192
1193 foreach ($props as $key => $unused) {
d872881f
MG
1194 $ret[$key] = $this->__get($key);
1195 }
1196 return new ArrayIterator($ret);
1197 }
1198
1199 /**
1200 * Magic method for function isset()
1201 *
1202 * @param string $name
1203 * @return bool
1204 */
1205 public function __isset($name) {
1206 if (isset(self::$standardproperties[$name])) {
1207 $value = $this->__get($name);
1208 return isset($value);
1209 }
1210 return false;
1211 }
1212
1213 /**
1214 * Magic method for function empty()
1215 *
1216 * @param string $name
1217 * @return bool
1218 */
1219 public function __empty($name) {
1220 if (isset(self::$standardproperties[$name])) {
1221 $value = $this->__get($name);
1222 return empty($value);
1223 }
1224 return true;
1225 }
1226
1227 /**
1228 * Magic method setter
1229 *
1230 * Will display the developer warning when trying to set/overwrite property.
1231 *
1232 * @param string $name
1233 * @param mixed $value
1234 */
1235 public function __set($name, $value) {
1236 debugging("It is not allowed to set the property cm_info::\${$name}", DEBUG_DEVELOPER);
1237 }
1238
0d8b6a69 1239 /**
1240 * @return bool True if this module has a 'view' page that should be linked to in navigation
1241 * etc (note: modules may still have a view.php file, but return false if this is not
1242 * intended to be linked to from 'normal' parts of the interface; this is what label does).
1243 */
1244 public function has_view() {
1245 return !is_null($this->url);
1246 }
1247
1248 /**
1249 * @return moodle_url URL to link to for this module, or null if it doesn't have a view page
1250 */
d872881f
MG
1251 private function get_url() {
1252 $this->obtain_dynamic_data();
0d8b6a69 1253 return $this->url;
1254 }
1255
1256 /**
1257 * Obtains content to display on main (view) page.
1258 * Note: Will collect view data, if not already obtained.
1259 * @return string Content to display on main page below link, or empty string if none
1260 */
d872881f 1261 private function get_content() {
0d8b6a69 1262 $this->obtain_view_data();
1263 return $this->content;
1264 }
1265
f89c53f6
MG
1266 /**
1267 * Returns the content to display on course/overview page, formatted and passed through filters
1268 *
1269 * if $options['context'] is not specified, the module context is used
1270 *
1271 * @param array|stdClass $options formatting options, see {@link format_text()}
1272 * @return string
1273 */
1274 public function get_formatted_content($options = array()) {
1275 $this->obtain_view_data();
1276 if (empty($this->content)) {
1277 return '';
1278 }
f89c53f6
MG
1279 // Improve filter performance by preloading filter setttings for all
1280 // activities on the course (this does nothing if called multiple
1281 // times)
1282 filter_preload_activities($this->get_modinfo());
1283
1284 $options = (array)$options;
1285 if (!isset($options['context'])) {
d872881f 1286 $options['context'] = $this->get_context();
f89c53f6
MG
1287 }
1288 return format_text($this->content, FORMAT_HTML, $options);
1289 }
1290
d872881f
MG
1291 /**
1292 * Getter method for property $name, ensures that dynamic data is obtained.
1293 * @return string
1294 */
1295 private function get_name() {
1296 $this->obtain_dynamic_data();
1297 return $this->name;
1298 }
1299
f89c53f6
MG
1300 /**
1301 * Returns the name to display on course/overview page, formatted and passed through filters
1302 *
1303 * if $options['context'] is not specified, the module context is used
1304 *
1305 * @param array|stdClass $options formatting options, see {@link format_string()}
1306 * @return string
1307 */
1308 public function get_formatted_name($options = array()) {
acbf4579 1309 global $CFG;
f89c53f6
MG
1310 $options = (array)$options;
1311 if (!isset($options['context'])) {
d872881f 1312 $options['context'] = $this->get_context();
f89c53f6 1313 }
0d9805dc
DW
1314 // Improve filter performance by preloading filter setttings for all
1315 // activities on the course (this does nothing if called multiple
1316 // times).
acbf4579
MG
1317 if (!empty($CFG->filterall)) {
1318 filter_preload_activities($this->get_modinfo());
1319 }
d872881f 1320 return format_string($this->get_name(), true, $options);
f89c53f6
MG
1321 }
1322
0d8b6a69 1323 /**
1324 * Note: Will collect view data, if not already obtained.
1325 * @return string Extra CSS classes to add to html output for this activity on main page
1326 */
d872881f 1327 private function get_extra_classes() {
0d8b6a69 1328 $this->obtain_view_data();
1329 return $this->extraclasses;
1330 }
1331
1332 /**
1333 * @return string Content of HTML on-click attribute. This string will be used literally
1334 * as a string so should be pre-escaped.
1335 */
d872881f 1336 private function get_on_click() {
0d8b6a69 1337 // Does not need view data; may be used by navigation
d872881f 1338 $this->obtain_dynamic_data();
0d8b6a69 1339 return $this->onclick;
1340 }
1341 /**
1342 * @return mixed Optional custom data stored in modinfo cache for this activity, or null if none
1343 */
d872881f 1344 private function get_custom_data() {
0d8b6a69 1345 return $this->customdata;
1346 }
1347
1348 /**
1349 * Note: Will collect view data, if not already obtained.
c443a1cd 1350 * @return string Extra HTML code to display after link
0d8b6a69 1351 */
d872881f 1352 private function get_after_link() {
0d8b6a69 1353 $this->obtain_view_data();
1354 return $this->afterlink;
1355 }
1356
1357 /**
1358 * Note: Will collect view data, if not already obtained.
1359 * @return string Extra HTML code to display after editing icons (e.g. more icons)
1360 */
d872881f 1361 private function get_after_edit_icons() {
0d8b6a69 1362 $this->obtain_view_data();
1363 return $this->afterediticons;
1364 }
1365
1366 /**
1367 * @param moodle_core_renderer $output Output render to use, or null for default (global)
1368 * @return moodle_url Icon URL for a suitable icon to put beside this cm
1369 */
1370 public function get_icon_url($output = null) {
1371 global $OUTPUT;
d872881f 1372 $this->obtain_dynamic_data();
0d8b6a69 1373 if (!$output) {
1374 $output = $OUTPUT;
1375 }
c443a1cd
EL
1376 // Support modules setting their own, external, icon image
1377 if (!empty($this->iconurl)) {
1378 $icon = $this->iconurl;
1379
1380 // Fallback to normal local icon + component procesing
1381 } else if (!empty($this->icon)) {
0d8b6a69 1382 if (substr($this->icon, 0, 4) === 'mod/') {
1383 list($modname, $iconname) = explode('/', substr($this->icon, 4), 2);
663640f5 1384 $icon = $output->image_url($iconname, $modname);
0d8b6a69 1385 } else {
1386 if (!empty($this->iconcomponent)) {
1387 // Icon has specified component
663640f5 1388 $icon = $output->image_url($this->icon, $this->iconcomponent);
0d8b6a69 1389 } else {
1390 // Icon does not have specified component, use default
663640f5 1391 $icon = $output->image_url($this->icon);
0d8b6a69 1392 }
1393 }
1394 } else {
663640f5 1395 $icon = $output->image_url('icon', $this->modname);
0d8b6a69 1396 }
1397 return $icon;
1398 }
1399
0556eaa9
JB
1400 /**
1401 * @param string $textclasses additionnal classes for grouping label
1402 * @return string An empty string or HTML grouping label span tag
1403 */
1404 public function get_grouping_label($textclasses = '') {
1405 $groupinglabel = '';
8341055e
MG
1406 if ($this->effectivegroupmode != NOGROUPS && !empty($this->groupingid) &&
1407 has_capability('moodle/course:managegroups', context_course::instance($this->course))) {
0556eaa9
JB
1408 $groupings = groups_get_all_groupings($this->course);
1409 $groupinglabel = html_writer::tag('span', '('.format_string($groupings[$this->groupingid]->name).')',
1410 array('class' => 'groupinglabel '.$textclasses));
1411 }
1412 return $groupinglabel;
1413 }
1414
d57aa283
MG
1415 /**
1416 * Returns a localised human-readable name of the module type
1417 *
1418 * @param bool $plural return plural form
1419 * @return string
1420 */
1421 public function get_module_type_name($plural = false) {
1422 $modnames = get_module_types_names($plural);
1423 if (isset($modnames[$this->modname])) {
1424 return $modnames[$this->modname];
1425 } else {
1426 return null;
1427 }
1428 }
1429
d872881f
MG
1430 /**
1431 * Returns a localised human-readable name of the module type in plural form - calculated on request
1432 *
1433 * @return string
1434 */
1435 private function get_module_type_name_plural() {
1436 return $this->get_module_type_name(true);
1437 }
1438
0d8b6a69 1439 /**
1440 * @return course_modinfo Modinfo object that this came from
1441 */
1442 public function get_modinfo() {
1443 return $this->modinfo;
1444 }
1445
8341055e
MG
1446 /**
1447 * Returns the section this module belongs to
1448 *
1449 * @return section_info
1450 */
1451 public function get_section_info() {
1452 return $this->modinfo->get_section_info($this->sectionnum);
1453 }
1454
0d8b6a69 1455 /**
299cfee5
MG
1456 * Returns course object that was used in the first {@link get_fast_modinfo()} call.
1457 *
1458 * It may not contain all fields from DB table {course} but always has at least the following:
1459 * id,shortname,fullname,format,enablecompletion,groupmode,groupmodeforce,cacherev
1460 *
1461 * If the course object lacks the field you need you can use the global
1462 * function {@link get_course()} that will save extra query if you access
1463 * current course or frontpage course.
1464 *
1465 * @return stdClass
0d8b6a69 1466 */
1467 public function get_course() {
1468 return $this->modinfo->get_course();
1469 }
1470
d872881f
MG
1471 /**
1472 * Returns course id for which the modinfo was generated.
1473 *
1474 * @return int
1475 */
1476 private function get_course_id() {
1477 return $this->modinfo->get_course_id();
1478 }
1479
1480 /**
1481 * Returns group mode used for the course containing the module
1482 *
1483 * @return int one of constants NOGROUPS, SEPARATEGROUPS, VISIBLEGROUPS
1484 */
1485 private function get_course_groupmode() {
1486 return $this->modinfo->get_course()->groupmode;
1487 }
1488
1489 /**
1490 * Returns whether group mode is forced for the course containing the module
1491 *
1492 * @return bool
1493 */
1494 private function get_course_groupmodeforce() {
1495 return $this->modinfo->get_course()->groupmodeforce;
1496 }
1497
6d04c4f2
MG
1498 /**
1499 * Returns effective groupmode of the module that may be overwritten by forced course groupmode.
1500 *
1501 * @return int one of constants NOGROUPS, SEPARATEGROUPS, VISIBLEGROUPS
1502 */
1503 private function get_effective_groupmode() {
1504 $groupmode = $this->groupmode;
1505 if ($this->modinfo->get_course()->groupmodeforce) {
1506 $groupmode = $this->modinfo->get_course()->groupmode;
1507 if ($groupmode != NOGROUPS && !plugin_supports('mod', $this->modname, FEATURE_GROUPS, 0)) {
1508 $groupmode = NOGROUPS;
1509 }
1510 }
1511 return $groupmode;
1512 }
1513
d872881f
MG
1514 /**
1515 * @return context_module Current module context
1516 */
1517 private function get_context() {
1518 return context_module::instance($this->id);
1519 }
1520
92e2e855
MG
1521 /**
1522 * Returns itself in the form of stdClass.
1523 *
1524 * The object includes all fields that table course_modules has and additionally
1525 * fields 'name', 'modname', 'sectionnum' (if requested).
1526 *
1527 * This can be used as a faster alternative to {@link get_coursemodule_from_id()}
1528 *
1529 * @param bool $additionalfields include additional fields 'name', 'modname', 'sectionnum'
1530 * @return stdClass
1531 */
1532 public function get_course_module_record($additionalfields = false) {
1533 $cmrecord = new stdClass();
1534
1535 // Standard fields from table course_modules.
1536 static $cmfields = array('id', 'course', 'module', 'instance', 'section', 'idnumber', 'added',
8341055e 1537 'score', 'indent', 'visible', 'visibleoncoursepage', 'visibleold', 'groupmode', 'groupingid',
92e2e855 1538 'completion', 'completiongradeitemnumber', 'completionview', 'completionexpected',
048f909b 1539 'showdescription', 'availability', 'deletioninprogress');
92e2e855
MG
1540 foreach ($cmfields as $key) {
1541 $cmrecord->$key = $this->$key;
1542 }
1543
1544 // Additional fields that function get_coursemodule_from_id() adds.
1545 if ($additionalfields) {
1546 $cmrecord->name = $this->name;
1547 $cmrecord->modname = $this->modname;
1548 $cmrecord->sectionnum = $this->sectionnum;
1549 }
1550
1551 return $cmrecord;
1552 }
1553
0d8b6a69 1554 // Set functions
1555 ////////////////
1556
1557 /**
1558 * Sets content to display on course view page below link (if present).
1559 * @param string $content New content as HTML string (empty string if none)
1560 * @return void
1561 */
1562 public function set_content($content) {
1563 $this->content = $content;
1564 }
1565
1566 /**
1567 * Sets extra classes to include in CSS.
1568 * @param string $extraclasses Extra classes (empty string if none)
1569 * @return void
1570 */
1571 public function set_extra_classes($extraclasses) {
1572 $this->extraclasses = $extraclasses;
1573 }
1574
c443a1cd
EL
1575 /**
1576 * Sets the external full url that points to the icon being used
1577 * by the activity. Useful for external-tool modules (lti...)
1578 * If set, takes precedence over $icon and $iconcomponent
1579 *
1580 * @param moodle_url $iconurl full external url pointing to icon image for activity
1581 * @return void
1582 */
1583 public function set_icon_url(moodle_url $iconurl) {
1584 $this->iconurl = $iconurl;
1585 }
1586
0d8b6a69 1587 /**
1588 * Sets value of on-click attribute for JavaScript.
1589 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1590 * @param string $onclick New onclick attribute which should be HTML-escaped
1591 * (empty string if none)
1592 * @return void
1593 */
1594 public function set_on_click($onclick) {
1595 $this->check_not_view_only();
1596 $this->onclick = $onclick;
1597 }
1598
1599 /**
1600 * Sets HTML that displays after link on course view page.
1601 * @param string $afterlink HTML string (empty string if none)
1602 * @return void
1603 */
1604 public function set_after_link($afterlink) {
1605 $this->afterlink = $afterlink;
1606 }
1607
1608 /**
1609 * Sets HTML that displays after edit icons on course view page.
1610 * @param string $afterediticons HTML string (empty string if none)
1611 * @return void
1612 */
1613 public function set_after_edit_icons($afterediticons) {
1614 $this->afterediticons = $afterediticons;
1615 }
1616
1617 /**
1618 * Changes the name (text of link) for this module instance.
1619 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1620 * @param string $name Name of activity / link text
1621 * @return void
1622 */
1623 public function set_name($name) {
d872881f
MG
1624 if ($this->state < self::STATE_BUILDING_DYNAMIC) {
1625 $this->update_user_visible();
1626 }
0d8b6a69 1627 $this->name = $name;
1628 }
1629
1630 /**
1631 * Turns off the view link for this module instance.
1632 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1633 * @return void
1634 */
1635 public function set_no_view_link() {
1636 $this->check_not_view_only();
4478743c 1637 $this->url = null;
0d8b6a69 1638 }
1639
1640 /**
1641 * Sets the 'uservisible' flag. This can be used (by setting false) to prevent access and
1642 * display of this module link for the current user.
1643 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1644 * @param bool $uservisible
1645 * @return void
1646 */
1647 public function set_user_visible($uservisible) {
1648 $this->check_not_view_only();
1649 $this->uservisible = $uservisible;
1650 }
1651
1652 /**
1653 * Sets the 'available' flag and related details. This flag is normally used to make
1654 * course modules unavailable until a certain date or condition is met. (When a course
1655 * module is unavailable, it is still visible to users who have viewhiddenactivities
1656 * permission.)
1657 *
1658 * When this is function is called, user-visible status is recalculated automatically.
1659 *
8d1f33e1 1660 * The $showavailability flag does not really do anything any more, but is retained
1661 * for backward compatibility. Setting this to false will cause $availableinfo to
1662 * be ignored.
1663 *
0d8b6a69 1664 * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
1665 * @param bool $available False if this item is not 'available'
1666 * @param int $showavailability 0 = do not show this item at all if it's not available,
1667 * 1 = show this item greyed out with the following message
8d1f33e1 1668 * @param string $availableinfo Information about why this is not available, or
1669 * empty string if not displaying
0d8b6a69 1670 * @return void
1671 */
1672 public function set_available($available, $showavailability=0, $availableinfo='') {
1673 $this->check_not_view_only();
1674 $this->available = $available;
8d1f33e1 1675 if (!$showavailability) {
1676 $availableinfo = '';
1677 }
0d8b6a69 1678 $this->availableinfo = $availableinfo;
1679 $this->update_user_visible();
1680 }
1681
1682 /**
1683 * Some set functions can only be called from _cm_info_dynamic and not _cm_info_view.
1684 * This is because they may affect parts of this object which are used on pages other
1685 * than the view page (e.g. in the navigation block, or when checking access on
1686 * module pages).
1687 * @return void
1688 */
1689 private function check_not_view_only() {
1690 if ($this->state >= self::STATE_DYNAMIC) {
1691 throw new coding_exception('Cannot set this data from _cm_info_view because it may ' .
1692 'affect other pages as well as view');
1693 }
1694 }
1695
1696 /**
d872881f
MG
1697 * Constructor should not be called directly; use {@link get_fast_modinfo()}
1698 *
0d8b6a69 1699 * @param course_modinfo $modinfo Parent object
d872881f
MG
1700 * @param stdClass $notused1 Argument not used
1701 * @param stdClass $mod Module object from the modinfo field of course table
1702 * @param stdClass $notused2 Argument not used
0d8b6a69 1703 */
d872881f 1704 public function __construct(course_modinfo $modinfo, $notused1, $mod, $notused2) {
0d8b6a69 1705 $this->modinfo = $modinfo;
1706
1707 $this->id = $mod->cm;
1708 $this->instance = $mod->id;
0d8b6a69 1709 $this->modname = $mod->mod;
1710 $this->idnumber = isset($mod->idnumber) ? $mod->idnumber : '';
1711 $this->name = $mod->name;
1712 $this->visible = $mod->visible;
8341055e 1713 $this->visibleoncoursepage = $mod->visibleoncoursepage;
adaeccb6 1714 $this->sectionnum = $mod->section; // Note weirdness with name here
0d8b6a69 1715 $this->groupmode = isset($mod->groupmode) ? $mod->groupmode : 0;
1716 $this->groupingid = isset($mod->groupingid) ? $mod->groupingid : 0;
0d8b6a69 1717 $this->indent = isset($mod->indent) ? $mod->indent : 0;
0d8b6a69 1718 $this->extra = isset($mod->extra) ? $mod->extra : '';
1719 $this->extraclasses = isset($mod->extraclasses) ? $mod->extraclasses : '';
4fcdb012
MG
1720 // iconurl may be stored as either string or instance of moodle_url.
1721 $this->iconurl = isset($mod->iconurl) ? new moodle_url($mod->iconurl) : '';
0d8b6a69 1722 $this->onclick = isset($mod->onclick) ? $mod->onclick : '';
1723 $this->content = isset($mod->content) ? $mod->content : '';
1724 $this->icon = isset($mod->icon) ? $mod->icon : '';
1725 $this->iconcomponent = isset($mod->iconcomponent) ? $mod->iconcomponent : '';
1726 $this->customdata = isset($mod->customdata) ? $mod->customdata : '';
8c40662e 1727 $this->showdescription = isset($mod->showdescription) ? $mod->showdescription : 0;
0d8b6a69 1728 $this->state = self::STATE_BASIC;
1729
adaeccb6 1730 $this->section = isset($mod->sectionid) ? $mod->sectionid : 0;
1731 $this->module = isset($mod->module) ? $mod->module : 0;
1732 $this->added = isset($mod->added) ? $mod->added : 0;
1733 $this->score = isset($mod->score) ? $mod->score : 0;
1734 $this->visibleold = isset($mod->visibleold) ? $mod->visibleold : 0;
048f909b 1735 $this->deletioninprogress = isset($mod->deletioninprogress) ? $mod->deletioninprogress : 0;
adaeccb6 1736
1737 // Note: it saves effort and database space to always include the
1738 // availability and completion fields, even if availability or completion
1739 // are actually disabled
1740 $this->completion = isset($mod->completion) ? $mod->completion : 0;
1741 $this->completiongradeitemnumber = isset($mod->completiongradeitemnumber)
1742 ? $mod->completiongradeitemnumber : null;
1743 $this->completionview = isset($mod->completionview)
1744 ? $mod->completionview : 0;
1745 $this->completionexpected = isset($mod->completionexpected)
1746 ? $mod->completionexpected : 0;
8d1f33e1 1747 $this->availability = isset($mod->availability) ? $mod->availability : null;
adaeccb6 1748 $this->conditionscompletion = isset($mod->conditionscompletion)
1749 ? $mod->conditionscompletion : array();
1750 $this->conditionsgrade = isset($mod->conditionsgrade)
1751 ? $mod->conditionsgrade : array();
76af15bb
MN
1752 $this->conditionsfield = isset($mod->conditionsfield)
1753 ? $mod->conditionsfield : array();
0d8b6a69 1754
d872881f 1755 static $modviews = array();
0d8b6a69 1756 if (!isset($modviews[$this->modname])) {
1757 $modviews[$this->modname] = !plugin_supports('mod', $this->modname,
1758 FEATURE_NO_VIEW_LINK);
1759 }
1760 $this->url = $modviews[$this->modname]
1761 ? new moodle_url('/mod/' . $this->modname . '/view.php', array('id'=>$this->id))
1762 : null;
1763 }
1764
d25c41fb 1765 /**
1766 * Creates a cm_info object from a database record (also accepts cm_info
1767 * in which case it is just returned unchanged).
1768 *
61c3b60c 1769 * @param stdClass|cm_info|null|bool $cm Stdclass or cm_info (or null or false)
d25c41fb 1770 * @param int $userid Optional userid (default to current)
61c3b60c 1771 * @return cm_info|null Object as cm_info, or null if input was null/false
d25c41fb 1772 */
1773 public static function create($cm, $userid = 0) {
61c3b60c 1774 // Null, false, etc. gets passed through as null.
1775 if (!$cm) {
d25c41fb 1776 return null;
1777 }
1778 // If it is already a cm_info object, just return it.
1779 if ($cm instanceof cm_info) {
1780 return $cm;
1781 }
1782 // Otherwise load modinfo.
1783 if (empty($cm->id) || empty($cm->course)) {
1784 throw new coding_exception('$cm must contain ->id and ->course');
1785 }
1786 $modinfo = get_fast_modinfo($cm->course, $userid);
1787 return $modinfo->get_cm($cm->id);
1788 }
1789
0d8b6a69 1790 /**
1791 * If dynamic data for this course-module is not yet available, gets it.
1792 *
d872881f
MG
1793 * This function is automatically called when requesting any course_modinfo property
1794 * that can be modified by modules (have a set_xxx method).
0d8b6a69 1795 *
1796 * Dynamic data is data which does not come directly from the cache but is calculated at
1797 * runtime based on the current user. Primarily this concerns whether the user can access
1798 * the module or not.
1799 *
1800 * As part of this function, the module's _cm_info_dynamic function from its lib.php will
1801 * be called (if it exists).
1802 * @return void
1803 */
d872881f 1804 private function obtain_dynamic_data() {
0d8b6a69 1805 global $CFG;
4cc819ad
MG
1806 $userid = $this->modinfo->get_user_id();
1807 if ($this->state >= self::STATE_BUILDING_DYNAMIC || $userid == -1) {
0d8b6a69 1808 return;
1809 }
d872881f 1810 $this->state = self::STATE_BUILDING_DYNAMIC;
0d8b6a69 1811
1812 if (!empty($CFG->enableavailability)) {
8d1f33e1 1813 // Get availability information.
1814 $ci = new \core_availability\info_module($this);
1815
0d8b6a69 1816 // Note that the modinfo currently available only includes minimal details (basic data)
d872881f 1817 // but we know that this function does not need anything more than basic data.
0d8b6a69 1818 $this->available = $ci->is_available($this->availableinfo, true,
1819 $userid, $this->modinfo);
daad1b4b
MG
1820 } else {
1821 $this->available = true;
1822 }
ce4dfd27 1823
daad1b4b
MG
1824 // Check parent section.
1825 if ($this->available) {
ce4dfd27 1826 $parentsection = $this->modinfo->get_section_info($this->sectionnum);
1827 if (!$parentsection->available) {
1828 // Do not store info from section here, as that is already
1829 // presented from the section (if appropriate) - just change
1830 // the flag
1831 $this->available = false;
1832 }
0d8b6a69 1833 }
1834
daad1b4b 1835 // Update visible state for current user.
0d8b6a69 1836 $this->update_user_visible();
1837
1838 // Let module make dynamic changes at this point
1839 $this->call_mod_function('cm_info_dynamic');
1840 $this->state = self::STATE_DYNAMIC;
1841 }
1842
d872881f
MG
1843 /**
1844 * Getter method for property $uservisible, ensures that dynamic data is retrieved.
1845 * @return bool
1846 */
1847 private function get_user_visible() {
1848 $this->obtain_dynamic_data();
1849 return $this->uservisible;
1850 }
1851
8341055e
MG
1852 /**
1853 * Returns whether this module is visible to the current user on course page
1854 *
1855 * Activity may be visible on the course page but not available, for example
1856 * when it is hidden conditionally but the condition information is displayed.
1857 *
1858 * @return bool
1859 */
1860 public function is_visible_on_course_page() {
1861 $this->obtain_dynamic_data();
1862 return $this->uservisibleoncoursepage;
1863 }
1864
1865 /**
1866 * Whether this module is available but hidden from course page
1867 *
1868 * "Stealth" modules are the ones that are not shown on course page but available by following url.
1869 * They are normally also displayed in grade reports and other reports.
1870 * Module will be stealth either if visibleoncoursepage=0 or it is a visible module inside the hidden
1871 * section.
1872 *
1873 * @return bool
1874 */
1875 public function is_stealth() {
1876 return !$this->visibleoncoursepage ||
1877 ($this->visible && ($section = $this->get_section_info()) && !$section->visible);
1878 }
1879
d872881f
MG
1880 /**
1881 * Getter method for property $available, ensures that dynamic data is retrieved
1882 * @return bool
1883 */
1884 private function get_available() {
1885 $this->obtain_dynamic_data();
1886 return $this->available;
1887 }
1888
061e6b28 1889 /**
7a07d34d 1890 * This method can not be used anymore.
061e6b28 1891 *
7a07d34d 1892 * @see \core_availability\info_module::filter_user_list()
061e6b28 1893 * @deprecated Since Moodle 2.8
1894 */
1895 private function get_deprecated_group_members_only() {
7a07d34d 1896 throw new coding_exception('$cm->groupmembersonly can not be used anymore. ' .
061e6b28 1897 'If used to restrict a list of enrolled users to only those who can ' .
7a07d34d 1898 'access the module, consider \core_availability\info_module::filter_user_list.');
061e6b28 1899 }
1900
d872881f
MG
1901 /**
1902 * Getter method for property $availableinfo, ensures that dynamic data is retrieved
061e6b28 1903 *
1904 * @return string Available info (HTML)
d872881f
MG
1905 */
1906 private function get_available_info() {
1907 $this->obtain_dynamic_data();
1908 return $this->availableinfo;
1909 }
1910
0d8b6a69 1911 /**
5e762271
AD
1912 * Works out whether activity is available to the current user
1913 *
1914 * If the activity is unavailable, additional checks are required to determine if its hidden or greyed out
1915 *
0d8b6a69 1916 * @return void
1917 */
1918 private function update_user_visible() {
0d8b6a69 1919 $userid = $this->modinfo->get_user_id();
4cc819ad
MG
1920 if ($userid == -1) {
1921 return null;
1922 }
0d8b6a69 1923 $this->uservisible = true;
5e762271 1924
048f909b
JD
1925 // If the module is being deleted, set the uservisible state to false and return.
1926 if ($this->deletioninprogress) {
1927 $this->uservisible = false;
1928 return null;
1929 }
1930
5e762271
AD
1931 // If the user cannot access the activity set the uservisible flag to false.
1932 // Additional checks are required to determine whether the activity is entirely hidden or just greyed out.
6a36b852
J
1933 if ((!$this->visible && !has_capability('moodle/course:viewhiddenactivities', $this->get_context(), $userid)) ||
1934 (!$this->get_available() &&
1935 !has_capability('moodle/course:ignoreavailabilityrestrictions', $this->get_context(), $userid))) {
5e762271 1936
0d8b6a69 1937 $this->uservisible = false;
a098f340 1938 }
5e762271
AD
1939
1940 // Check group membership.
061e6b28 1941 if ($this->is_user_access_restricted_by_capability()) {
5e762271
AD
1942
1943 $this->uservisible = false;
1944 // Ensure activity is completely hidden from the user.
8d1f33e1 1945 $this->availableinfo = '';
5fee56d5 1946 }
8341055e
MG
1947
1948 $this->uservisibleoncoursepage = $this->uservisible &&
1949 ($this->visibleoncoursepage ||
1950 has_capability('moodle/course:manageactivities', $this->get_context(), $userid) ||
1951 has_capability('moodle/course:activityvisibility', $this->get_context(), $userid));
1952 // Activity that is not available, not hidden from course page and has availability
1953 // info is actually visible on the course page (with availability info and without a link).
1954 if (!$this->uservisible && $this->visibleoncoursepage && $this->availableinfo) {
1955 $this->uservisibleoncoursepage = true;
1956 }
5fee56d5
FM
1957 }
1958
1959 /**
7a07d34d 1960 * This method has been deprecated and should not be used.
5e762271 1961 *
7a07d34d 1962 * @see $uservisible
061e6b28 1963 * @deprecated Since Moodle 2.8
5fee56d5
FM
1964 */
1965 public function is_user_access_restricted_by_group() {
7a07d34d
JP
1966 throw new coding_exception('cm_info::is_user_access_restricted_by_group() can not be used any more.' .
1967 ' Use $cm->uservisible to decide whether the current user can access an activity.');
5e762271
AD
1968 }
1969
9e1fe421
TH
1970 /**
1971 * Checks whether mod/...:view capability restricts the current user's access.
1972 *
1973 * @return bool True if the user access is restricted.
1974 */
1975 public function is_user_access_restricted_by_capability() {
4cc819ad
MG
1976 $userid = $this->modinfo->get_user_id();
1977 if ($userid == -1) {
1978 return null;
1979 }
9e1fe421
TH
1980 $capability = 'mod/' . $this->modname . ':view';
1981 $capabilityinfo = get_capability_info($capability);
1982 if (!$capabilityinfo) {
1983 // Capability does not exist, no one is prevented from seeing the activity.
1984 return false;
1985 }
1986
1987 // You are blocked if you don't have the capability.
d872881f 1988 return !has_capability($capability, $this->get_context(), $userid);
9e1fe421
TH
1989 }
1990
5e762271 1991 /**
8d1f33e1 1992 * Checks whether the module's conditional access settings mean that the
1993 * user cannot see the activity at all
1994 *
4d851042 1995 * @deprecated since 2.7 MDL-44070
5e762271
AD
1996 */
1997 public function is_user_access_restricted_by_conditional_access() {
4d851042
AA
1998 throw new coding_exception('cm_info::is_user_access_restricted_by_conditional_access() ' .
1999 'can not be used any more; this function is not needed (use $cm->uservisible ' .
061e6b28 2000 'and $cm->availableinfo to decide whether it should be available ' .
4d851042 2001 'or appear)');
0d8b6a69 2002 }
2003
2004 /**
2005 * Calls a module function (if exists), passing in one parameter: this object.
2006 * @param string $type Name of function e.g. if this is 'grooblezorb' and the modname is
2007 * 'forum' then it will try to call 'mod_forum_grooblezorb' or 'forum_grooblezorb'
2008 * @return void
2009 */
2010 private function call_mod_function($type) {
2011 global $CFG;
2012 $libfile = $CFG->dirroot . '/mod/' . $this->modname . '/lib.php';
2013 if (file_exists($libfile)) {
2014 include_once($libfile);
2015 $function = 'mod_' . $this->modname . '_' . $type;
2016 if (function_exists($function)) {
2017 $function($this);
2018 } else {
2019 $function = $this->modname . '_' . $type;
2020 if (function_exists($function)) {
2021 $function($this);
2022 }
2023 }
2024 }
2025 }
2026
2027 /**
2028 * If view data for this course-module is not yet available, obtains it.
2029 *
2030 * This function is automatically called if any of the functions (marked) which require
2031 * view data are called.
2032 *
2033 * View data is data which is needed only for displaying the course main page (& any similar
2034 * functionality on other pages) but is not needed in general. Obtaining view data may have
2035 * a performance cost.
2036 *
2037 * As part of this function, the module's _cm_info_view function from its lib.php will
2038 * be called (if it exists).
2039 * @return void
2040 */
2041 private function obtain_view_data() {
4cc819ad 2042 if ($this->state >= self::STATE_BUILDING_VIEW || $this->modinfo->get_user_id() == -1) {
0d8b6a69 2043 return;
2044 }
d872881f
MG
2045 $this->obtain_dynamic_data();
2046 $this->state = self::STATE_BUILDING_VIEW;
0d8b6a69 2047
2048 // Let module make changes at this point
2049 $this->call_mod_function('cm_info_view');
2050 $this->state = self::STATE_VIEW;
2051 }
2052}
2053
2054
0d8b6a69 2055/**
2056 * Returns reference to full info about modules in course (including visibility).
2057 * Cached and as fast as possible (0 or 1 db query).
2058 *
9428a154
MG
2059 * use get_fast_modinfo($courseid, 0, true) to reset the static cache for particular course
2060 * use get_fast_modinfo(0, 0, true) to reset the static cache for all courses
2061 *
299cfee5
MG
2062 * use rebuild_course_cache($courseid, true) to reset the application AND static cache
2063 * for particular course when it's contents has changed
2064 *
2065 * @param int|stdClass $courseorid object from DB table 'course' (must have field 'id'
2066 * and recommended to have field 'cacherev') or just a course id. Just course id
2067 * is enough when calling get_fast_modinfo() for current course or site or when
2068 * calling for any other course for the second time.
4cc819ad
MG
2069 * @param int $userid User id to populate 'availble' and 'uservisible' attributes of modules and sections.
2070 * Set to 0 for current user (default). Set to -1 to avoid calculation of dynamic user-depended data.
b46be6ad
MG
2071 * @param bool $resetonly whether we want to get modinfo or just reset the cache
2072 * @return course_modinfo|null Module information for course, or null if resetting
299cfee5 2073 * @throws moodle_exception when course is not found (nothing is thrown if resetting)
0d8b6a69 2074 */
b46be6ad 2075function get_fast_modinfo($courseorid, $userid = 0, $resetonly = false) {
b46be6ad
MG
2076 // compartibility with syntax prior to 2.4:
2077 if ($courseorid === 'reset') {
2078 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);
2079 $courseorid = 0;
2080 $resetonly = true;
2081 }
2082
4202471a
MG
2083 // Function get_fast_modinfo() can never be called during upgrade unless it is used for clearing cache only.
2084 if (!$resetonly) {
2085 upgrade_ensure_not_running();
2086 }
2087
b46be6ad
MG
2088 // Function is called with $reset = true
2089 if ($resetonly) {
299cfee5 2090 course_modinfo::clear_instance_cache($courseorid);
0d8b6a69 2091 return null;
2092 }
2093
b46be6ad 2094 // Function is called with $reset = false, retrieve modinfo
299cfee5 2095 return course_modinfo::instance($courseorid, $userid);
0d8b6a69 2096}
2097
d25c41fb 2098/**
2099 * Efficiently retrieves the $course (stdclass) and $cm (cm_info) objects, given
2100 * a cmid. If module name is also provided, it will ensure the cm is of that type.
2101 *
2102 * Usage:
2103 * list($course, $cm) = get_course_and_cm_from_cmid($cmid, 'forum');
2104 *
2105 * Using this method has a performance advantage because it works by loading
2106 * modinfo for the course - which will then be cached and it is needed later
2107 * in most requests. It also guarantees that the $cm object is a cm_info and
2108 * not a stdclass.
2109 *
2110 * The $course object can be supplied if already known and will speed
2111 * up this function - although it is more efficient to use this function to
2112 * get the course if you are starting from a cmid.
2113 *
2114 * To avoid security problems and obscure bugs, you should always specify
2115 * $modulename if the cmid value came from user input.
2116 *
2117 * By default this obtains information (for example, whether user can access
2118 * the activity) for current user, but you can specify a userid if required.
2119 *
2120 * @param stdClass|int $cmorid Id of course-module, or database object
2121 * @param string $modulename Optional modulename (improves security)
2122 * @param stdClass|int $courseorid Optional course object if already loaded
2123 * @param int $userid Optional userid (default = current)
2124 * @return array Array with 2 elements $course and $cm
2125 * @throws moodle_exception If the item doesn't exist or is of wrong module name
2126 */
2127function get_course_and_cm_from_cmid($cmorid, $modulename = '', $courseorid = 0, $userid = 0) {
2128 global $DB;
2129 if (is_object($cmorid)) {
2130 $cmid = $cmorid->id;
2131 if (isset($cmorid->course)) {
2132 $courseid = (int)$cmorid->course;
2133 } else {
2134 $courseid = 0;
2135 }
2136 } else {
2137 $cmid = (int)$cmorid;
2138 $courseid = 0;
2139 }
2140
2141 // Validate module name if supplied.
2142 if ($modulename && !core_component::is_valid_plugin_name('mod', $modulename)) {
2143 throw new coding_exception('Invalid modulename parameter');
2144 }
2145
2146 // Get course from last parameter if supplied.
2147 $course = null;
2148 if (is_object($courseorid)) {
2149 $course = $courseorid;
2150 } else if ($courseorid) {
2151 $courseid = (int)$courseorid;
2152 }
2153
2154 if (!$course) {
2155 if ($courseid) {
2156 // If course ID is known, get it using normal function.
2157 $course = get_course($courseid);
2158 } else {
2159 // Get course record in a single query based on cmid.
2160 $course = $DB->get_record_sql("
2161 SELECT c.*
2162 FROM {course_modules} cm
2163 JOIN {course} c ON c.id = cm.course
2164 WHERE cm.id = ?", array($cmid), MUST_EXIST);
2165 }
2166 }
2167
2168 // Get cm from get_fast_modinfo.
2169 $modinfo = get_fast_modinfo($course, $userid);
2170 $cm = $modinfo->get_cm($cmid);
2171 if ($modulename && $cm->modname !== $modulename) {
2172 throw new moodle_exception('invalidcoursemodule', 'error');
2173 }
2174 return array($course, $cm);
2175}
2176
2177/**
2178 * Efficiently retrieves the $course (stdclass) and $cm (cm_info) objects, given
2179 * an instance id or record and module name.
2180 *
2181 * Usage:
2182 * list($course, $cm) = get_course_and_cm_from_instance($forum, 'forum');
2183 *
2184 * Using this method has a performance advantage because it works by loading
2185 * modinfo for the course - which will then be cached and it is needed later
2186 * in most requests. It also guarantees that the $cm object is a cm_info and
2187 * not a stdclass.
2188 *
2189 * The $course object can be supplied if already known and will speed
2190 * up this function - although it is more efficient to use this function to
2191 * get the course if you are starting from an instance id.
2192 *
2193 * By default this obtains information (for example, whether user can access
2194 * the activity) for current user, but you can specify a userid if required.
2195 *
2196 * @param stdclass|int $instanceorid Id of module instance, or database object
2197 * @param string $modulename Modulename (required)
2198 * @param stdClass|int $courseorid Optional course object if already loaded
2199 * @param int $userid Optional userid (default = current)
2200 * @return array Array with 2 elements $course and $cm
2201 * @throws moodle_exception If the item doesn't exist or is of wrong module name
2202 */
2203function get_course_and_cm_from_instance($instanceorid, $modulename, $courseorid = 0, $userid = 0) {
2204 global $DB;
2205
2206 // Get data from parameter.
2207 if (is_object($instanceorid)) {
2208 $instanceid = $instanceorid->id;
2209 if (isset($instanceorid->course)) {
2210 $courseid = (int)$instanceorid->course;
2211 } else {
2212 $courseid = 0;
2213 }
2214 } else {
2215 $instanceid = (int)$instanceorid;
2216 $courseid = 0;
2217 }
2218
2219 // Get course from last parameter if supplied.
2220 $course = null;
2221 if (is_object($courseorid)) {
2222 $course = $courseorid;
2223 } else if ($courseorid) {
2224 $courseid = (int)$courseorid;
2225 }
2226
2227 // Validate module name if supplied.
2228 if (!core_component::is_valid_plugin_name('mod', $modulename)) {
2229 throw new coding_exception('Invalid modulename parameter');
2230 }
2231
2232 if (!$course) {
2233 if ($courseid) {
2234 // If course ID is known, get it using normal function.
2235 $course = get_course($courseid);
2236 } else {
2237 // Get course record in a single query based on instance id.
2238 $pagetable = '{' . $modulename . '}';
2239 $course = $DB->get_record_sql("
2240 SELECT c.*
2241 FROM $pagetable instance
2242 JOIN {course} c ON c.id = instance.course
2243 WHERE instance.id = ?", array($instanceid), MUST_EXIST);
2244 }
2245 }
2246
2247 // Get cm from get_fast_modinfo.
2248 $modinfo = get_fast_modinfo($course, $userid);
2249 $instances = $modinfo->get_instances_of($modulename);
2250 if (!array_key_exists($instanceid, $instances)) {
2251 throw new moodle_exception('invalidmoduleid', 'error', $instanceid);
2252 }
2253 return array($course, $instances[$instanceid]);
2254}
2255
2256
112d3b49 2257/**
299cfee5
MG
2258 * Rebuilds or resets the cached list of course activities stored in MUC.
2259 *
2260 * rebuild_course_cache() must NEVER be called from lib/db/upgrade.php.
2261 * At the same time course cache may ONLY be cleared using this function in
2262 * upgrade scripts of plugins.
2263 *
2264 * During the bulk operations if it is necessary to reset cache of multiple
2265 * courses it is enough to call {@link increment_revision_number()} for the
2266 * table 'course' and field 'cacherev' specifying affected courses in select.
2267 *
2268 * Cached course information is stored in MUC core/coursemodinfo and is
2269 * validated with the DB field {course}.cacherev
2270 *
2271 * @global moodle_database $DB
2272 * @param int $courseid id of course to rebuild, empty means all
2273 * @param boolean $clearonly only clear the cache, gets rebuild automatically on the fly.
2274 * Recommended to set to true to avoid unnecessary multiple rebuilding.
112d3b49
PS
2275 */
2276function rebuild_course_cache($courseid=0, $clearonly=false) {
e271f71d 2277 global $COURSE, $SITE, $DB, $CFG;
112d3b49 2278
4202471a
MG
2279 // Function rebuild_course_cache() can not be called during upgrade unless it's clear only.
2280 if (!$clearonly && !upgrade_ensure_not_running(true)) {
2281 $clearonly = true;
2282 }
2283
112d3b49
PS
2284 // Destroy navigation caches
2285 navigation_cache::destroy_volatile_caches();
2286
ee7084e9
MG
2287 if (class_exists('format_base')) {
2288 // if file containing class is not loaded, there is no cache there anyway
2289 format_base::reset_course_cache($courseid);
2290 }
2291
299cfee5
MG
2292 $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
2293 if (empty($courseid)) {
2294 // Clearing caches for all courses.
2295 increment_revision_number('course', 'cacherev', '');
2296 $cachecoursemodinfo->purge();
2297 course_modinfo::clear_instance_cache();
2298 // Update global values too.
2299 $sitecacherev = $DB->get_field('course', 'cacherev', array('id' => SITEID));
2300 $SITE->cachrev = $sitecacherev;
2301 if ($COURSE->id == SITEID) {
2302 $COURSE->cacherev = $sitecacherev;
487caf6b 2303 } else {
299cfee5 2304 $COURSE->cacherev = $DB->get_field('course', 'cacherev', array('id' => $COURSE->id));
487caf6b 2305 }
299cfee5
MG
2306 } else {
2307 // Clearing cache for one course, make sure it is deleted from user request cache as well.
2308 increment_revision_number('course', 'cacherev', 'id = :id', array('id' => $courseid));
2309 $cachecoursemodinfo->delete($courseid);
2310 course_modinfo::clear_instance_cache($courseid);
2311 // Update global values too.
2312 if ($courseid == $COURSE->id || $courseid == $SITE->id) {
2313 $cacherev = $DB->get_field('course', 'cacherev', array('id' => $courseid));
2314 if ($courseid == $COURSE->id) {
2315 $COURSE->cacherev = $cacherev;
2316 }
2317 if ($courseid == $SITE->id) {
2318 $SITE->cachrev = $cacherev;
2319 }
e271f71d 2320 }
112d3b49
PS
2321 }
2322
299cfee5
MG
2323 if ($clearonly) {
2324 return;
2325 }
112d3b49
PS
2326
2327 if ($courseid) {
2328 $select = array('id'=>$courseid);
2329 } else {
2330 $select = array();
3ef7279f 2331 core_php_time_limit::raise(); // this could take a while! MDL-10954
112d3b49
PS
2332 }
2333
299cfee5
MG
2334 $rs = $DB->get_recordset("course", $select,'','id,'.join(',', course_modinfo::$cachedfields));
2335 // Rebuild cache for each course.
112d3b49 2336 foreach ($rs as $course) {
299cfee5 2337 course_modinfo::build_course_cache($course);
112d3b49
PS
2338 }
2339 $rs->close();
112d3b49
PS
2340}
2341
0d8b6a69 2342
2343/**
2344 * Class that is the return value for the _get_coursemodule_info module API function.
2345 *
2346 * Note: For backward compatibility, you can also return a stdclass object from that function.
3008f86c
MG
2347 * The difference is that the stdclass object may contain an 'extra' field (deprecated,
2348 * use extraclasses and onclick instead). The stdclass object may not contain
0d8b6a69 2349 * the new fields defined here (content, extraclasses, customdata).
2350 */
2351class cached_cm_info {
2352 /**
2353 * Name (text of link) for this activity; Leave unset to accept default name
2354 * @var string
2355 */
2356 public $name;
2357
2358 /**
2359 * Name of icon for this activity. Normally, this should be used together with $iconcomponent
663640f5 2360 * to define the icon, as per image_url function.
0d8b6a69 2361 * For backward compatibility, if this value is of the form 'mod/forum/icon' then an icon
2362 * within that module will be used.
2363 * @see cm_info::get_icon_url()
663640f5 2364 * @see renderer_base::image_url()
0d8b6a69 2365 * @var string
2366 */
2367 public $icon;
2368
2369 /**
663640f5 2370 * Component for icon for this activity, as per image_url; leave blank to use default 'moodle'
0d8b6a69 2371 * component
663640f5 2372 * @see renderer_base::image_url()
0d8b6a69 2373 * @var string
2374 */
2375 public $iconcomponent;
2376
2377 /**
2378 * HTML content to be displayed on the main page below the link (if any) for this course-module
2379 * @var string
2380 */
2381 public $content;
2382
2383 /**
2384 * Custom data to be stored in modinfo for this activity; useful if there are cases when
2385 * internal information for this activity type needs to be accessible from elsewhere on the
2386 * course without making database queries. May be of any type but should be short.
2387 * @var mixed
2388 */
2389 public $customdata;
2390
2391 /**
2392 * Extra CSS class or classes to be added when this activity is displayed on the main page;
2393 * space-separated string
2394 * @var string
2395 */
2396 public $extraclasses;
2397
c443a1cd
EL
2398 /**
2399 * External URL image to be used by activity as icon, useful for some external-tool modules
2400 * like lti. If set, takes precedence over $icon and $iconcomponent
2401 * @var $moodle_url
2402 */
2403 public $iconurl;
2404
0d8b6a69 2405 /**
2406 * Content of onclick JavaScript; escaped HTML to be inserted as attribute value
2407 * @var string
2408 */
2409 public $onclick;
c443a1cd 2410}
ce4dfd27 2411
2412
2413/**
2414 * Data about a single section on a course. This contains the fields from the
2415 * course_sections table, plus additional data when required.
4e430906
MG
2416 *
2417 * @property-read int $id Section ID - from course_sections table
2418 * @property-read int $course Course ID - from course_sections table
2419 * @property-read int $section Section number - from course_sections table
2420 * @property-read string $name Section name if specified - from course_sections table
2421 * @property-read int $visible Section visibility (1 = visible) - from course_sections table
2422 * @property-read string $summary Section summary text if specified - from course_sections table
2423 * @property-read int $summaryformat Section summary text format (FORMAT_xx constant) - from course_sections table
8d1f33e1 2424 * @property-read string $availability Availability information as JSON string -
4e430906
MG
2425 * from course_sections table
2426 * @property-read array $conditionscompletion Availability conditions for this section based on the completion of
2427 * course-modules (array from course-module id to required completion state
2428 * for that module) - from cached data in sectioncache field
2429 * @property-read array $conditionsgrade Availability conditions for this section based on course grades (array from
2430 * grade item id to object with ->min, ->max fields) - from cached data in
2431 * sectioncache field
2432 * @property-read array $conditionsfield Availability conditions for this section based on user fields
2433 * @property-read bool $available True if this section is available to the given user i.e. if all availability conditions
2434 * are met - obtained dynamically
2435 * @property-read string $availableinfo If section is not available to some users, this string gives information about
2436 * availability which can be displayed to students and/or staff (e.g. 'Available from 3 January 2010')
2437 * for display on main page - obtained dynamically
2438 * @property-read bool $uservisible True if this section is available to the given user (for example, if current user
2439 * has viewhiddensections capability, they can access the section even if it is not
2440 * visible or not available, so this would be true in that case) - obtained dynamically
2441 * @property-read string $sequence Comma-separated list of all modules in the section. Note, this field may not exactly
2442 * match course_sections.sequence if later has references to non-existing modules or not modules of not available module types.
58d11393 2443 * @property-read course_modinfo $modinfo
ce4dfd27 2444 */
fc79ede5 2445class section_info implements IteratorAggregate {
ce4dfd27 2446 /**
2447 * Section ID - from course_sections table
2448 * @var int
2449 */
fc79ede5 2450 private $_id;
ce4dfd27 2451
ce4dfd27 2452 /**
2453 * Section number - from course_sections table
2454 * @var int
2455 */
fc79ede5 2456 private $_section;
ce4dfd27 2457
2458 /**
2459 * Section name if specified - from course_sections table
2460 * @var string
2461 */
fc79ede5 2462 private $_name;
ce4dfd27 2463
2464 /**
2465 * Section visibility (1 = visible) - from course_sections table
2466 * @var int
2467 */
fc79ede5 2468 private $_visible;
ce4dfd27 2469
2470 /**
2471 * Section summary text if specified - from course_sections table
2472 * @var string
2473 */
fc79ede5 2474 private $_summary;
ce4dfd27 2475
2476 /**
2477 * Section summary text format (FORMAT_xx constant) - from course_sections table
2478 * @var int
2479 */
fc79ede5 2480 private $_summaryformat;
ce4dfd27 2481
2482 /**
8d1f33e1 2483 * Availability information as JSON string - from course_sections table
2484 * @var string
ce4dfd27 2485 */
8d1f33e1 2486 private $_availability;
ce4dfd27 2487
2488 /**
2489 * Availability conditions for this section based on the completion of
2490 * course-modules (array from course-module id to required completion state
2491 * for that module) - from cached data in sectioncache field
2492 * @var array
2493 */
fc79ede5 2494 private $_conditionscompletion;
ce4dfd27 2495
2496 /**
2497 * Availability conditions for this section based on course grades (array from
2498 * grade item id to object with ->min, ->max fields) - from cached data in
2499 * sectioncache field
2500 * @var array
2501 */
fc79ede5
MG
2502 private $_conditionsgrade;
2503
2504 /**
2505 * Availability conditions for this section based on user fields
2506 * @var array
2507 */
2508 private $_conditionsfield;
ce4dfd27 2509
2510 /**
2511 * True if this section is available to students i.e. if all availability conditions
4e430906
MG
2512 * are met - obtained dynamically on request, see function {@link section_info::get_available()}
2513 * @var bool|null
ce4dfd27 2514 */
fc79ede5 2515 private $_available;
ce4dfd27 2516
2517 /**
4e430906 2518 * If section is not available to some users, this string gives information about
ce4dfd27 2519 * availability which can be displayed to students and/or staff (e.g. 'Available from 3
4e430906
MG
2520 * January 2010') for display on main page - obtained dynamically on request, see
2521 * function {@link section_info::get_availableinfo()}
ce4dfd27 2522 * @var string
2523 */
fc79ede5 2524 private $_availableinfo;
ce4dfd27 2525
2526 /**
2527 * True if this section is available to the CURRENT user (for example, if current user
2528 * has viewhiddensections capability, they can access the section even if it is not
4e430906
MG
2529 * visible or not available, so this would be true in that case) - obtained dynamically
2530 * on request, see function {@link section_info::get_uservisible()}
2531 * @var bool|null
ce4dfd27 2532 */
fc79ede5 2533 private $_uservisible;
ce4dfd27 2534
2535 /**
2536 * Default values for sectioncache fields; if a field has this value, it won't
2537 * be stored in the sectioncache cache, to save space. Checks are done by ===
2538 * which means values must all be strings.
2539 * @var array
2540 */
2541 private static $sectioncachedefaults = array(
2542 'name' => null,
2543 'summary' => '',
2544 'summaryformat' => '1', // FORMAT_HTML, but must be a string
2545 'visible' => '1',
048f909b 2546 'availability' => null
ce4dfd27 2547 );
2548
aea2e3c3
MG
2549 /**
2550 * Stores format options that have been cached when building 'coursecache'
2551 * When the format option is requested we look first if it has been cached
2552 * @var array
2553 */
2554 private $cachedformatoptions = array();
2555
4e430906
MG
2556 /**
2557 * Stores the list of all possible section options defined in each used course format.
2558 * @var array
2559 */
2560 static private $sectionformatoptions = array();
2561
2562 /**
2563 * Stores the modinfo object passed in constructor, may be used when requesting
2564 * dynamically obtained attributes such as available, availableinfo, uservisible.
2565 * Also used to retrun information about current course or user.
2566 * @var course_modinfo
2567 */
2568 private $modinfo;
2569
ce4dfd27 2570 /**
2571 * Constructs object from database information plus extra required data.
2572 * @param object $data Array entry from cached sectioncache
2573 * @param int $number Section number (array key)
4e430906
MG
2574 * @param int $notused1 argument not used (informaion is available in $modinfo)
2575 * @param int $notused2 argument not used (informaion is available in $modinfo)
ce4dfd27 2576 * @param course_modinfo $modinfo Owner (needed for checking availability)
4e430906 2577 * @param int $notused3 argument not used (informaion is available in $modinfo)
ce4dfd27 2578 */
4e430906 2579 public function __construct($data, $number, $notused1, $notused2, $modinfo, $notused3) {
ce4dfd27 2580 global $CFG;
4202471a 2581 require_once($CFG->dirroot.'/course/lib.php');
ce4dfd27 2582
2583 // Data that is always present
fc79ede5
MG
2584 $this->_id = $data->id;
2585
2586 $defaults = self::$sectioncachedefaults +
2587 array('conditionscompletion' => array(),
2588 'conditionsgrade' => array(),
2589 'conditionsfield' => array());
ce4dfd27 2590
2591 // Data that may use default values to save cache size
fc79ede5 2592 foreach ($defaults as $field => $value) {
ce4dfd27 2593 if (isset($data->{$field})) {
fc79ede5 2594 $this->{'_'.$field} = $data->{$field};
ce4dfd27 2595 } else {
fc79ede5 2596 $this->{'_'.$field} = $value;
ce4dfd27 2597 }
2598 }
2599
4e430906
MG
2600 // Other data from constructor arguments.
2601 $this->_section = $number;
2602 $this->modinfo = $modinfo;
2603
2604 // Cached course format data.
2605 $course = $modinfo->get_course();
299cfee5
MG
2606 if (!isset(self::$sectionformatoptions[$course->format])) {
2607 // Store list of section format options defined in each used course format.
2608 // They do not depend on particular course but only on its format.
2609 self::$sectionformatoptions[$course->format] =
2610 course_get_format($course)->section_format_options();
4e430906
MG
2611 }
2612 foreach (self::$sectionformatoptions[$course->format] as $field => $option) {
aea2e3c3
MG
2613 if (!empty($option['cache'])) {
2614 if (isset($data->{$field})) {
2615 $this->cachedformatoptions[$field] = $data->{$field};
2616 } else if (array_key_exists('cachedefault', $option)) {
2617 $this->cachedformatoptions[$field] = $option['cachedefault'];
2618 }
2619 }
2620 }
ce4dfd27 2621 }
2622
fc79ede5
MG
2623 /**
2624 * Magic method to check if the property is set
2625 *
2626 * @param string $name name of the property
2627 * @return bool
2628 */
2629 public function __isset($name) {
4e430906
MG
2630 if (method_exists($this, 'get_'.$name) ||
2631 property_exists($this, '_'.$name) ||
2632 array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
fc79ede5
MG
2633 $value = $this->__get($name);
2634 return isset($value);
2635 }
2636 return false;
2637 }
2638
2639 /**
2640 * Magic method to check if the property is empty
2641 *
2642 * @param string $name name of the property
2643 * @return bool
2644 */
2645 public function __empty($name) {
4e430906
MG
2646 if (method_exists($this, 'get_'.$name) ||
2647 property_exists($this, '_'.$name) ||
724b00b2 2648 array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
fc79ede5
MG
2649 $value = $this->__get($name);
2650 return empty($value);
2651 }
2652 return true;
2653 }
2654
2655 /**
2656 * Magic method to retrieve the property, this is either basic section property
2657 * or availability information or additional properties added by course format
2658 *
2659 * @param string $name name of the property
2660 * @return bool
2661 */
2662 public function __get($name) {
4e430906
MG
2663 if (method_exists($this, 'get_'.$name)) {
2664 return $this->{'get_'.$name}();
2665 }
fc79ede5
MG
2666 if (property_exists($this, '_'.$name)) {
2667 return $this->{'_'.$name};
2668 }
aea2e3c3
MG
2669 if (array_key_exists($name, $this->cachedformatoptions)) {
2670 return $this->cachedformatoptions[$name];
2671 }
fc79ede5 2672 // precheck if the option is defined in format to avoid unnecessary DB queries in get_format_options()
724b00b2 2673 if (array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
4e430906 2674 $formatoptions = course_get_format($this->modinfo->get_course())->get_format_options($this);
fc79ede5
MG
2675 return $formatoptions[$name];
2676 }
2677 debugging('Invalid section_info property accessed! '.$name);
2678 return null;
2679 }
2680
4e430906
MG
2681 /**
2682 * Finds whether this section is available at the moment for the current user.
2683 *
2684 * The value can be accessed publicly as $sectioninfo->available
2685 *
2686 * @return bool
2687 */
2688 private function get_available() {
2689 global $CFG;
4cc819ad
MG
2690 $userid = $this->modinfo->get_user_id();
2691 if ($this->_available !== null || $userid == -1) {
2692 // Has already been calculated or does not need calculation.
4e430906
MG
2693 return $this->_available;
2694 }
daad1b4b
MG
2695 $this->_available = true;
2696 $this->_availableinfo = '';
4e430906 2697 if (!empty($CFG->enableavailability)) {
8d1f33e1 2698 // Get availability information.
2699 $ci = new \core_availability\info_section($this);
4e430906 2700 $this->_available = $ci->is_available($this->_availableinfo, true,
4cc819ad 2701 $userid, $this->modinfo);
daad1b4b
MG
2702 }
2703 // Execute the hook from the course format that may override the available/availableinfo properties.
2704 $currentavailable = $this->_available;
2705 course_get_format($this->modinfo->get_course())->
2706 section_get_available_hook($this, $this->_available, $this->_availableinfo);
2707 if (!$currentavailable && $this->_available) {
2708 debugging('section_get_available_hook() can not make unavailable section available', DEBUG_DEVELOPER);
2709 $this->_available = $currentavailable;
4e430906
MG
2710 }
2711 return $this->_available;
2712 }
2713
2714 /**
2715 * Returns the availability text shown next to the section on course page.
2716 *
2717 * @return string
2718 */
2719 private function get_availableinfo() {
eedf5a5a 2720 // Calling get_available() will also fill the availableinfo property
2721 // (or leave it null if there is no userid).
4e430906 2722 $this->get_available();
4e430906
MG
2723 return $this->_availableinfo;
2724 }
2725
fc79ede5
MG
2726 /**
2727 * Implementation of IteratorAggregate::getIterator(), allows to cycle through properties
2728 * and use {@link convert_to_array()}
2729 *
2730 * @return ArrayIterator
2731 */
2732 public function getIterator() {
2733 $ret = array();
2734 foreach (get_object_vars($this) as $key => $value) {
2735 if (substr($key, 0, 1) == '_') {
4e430906
MG
2736 if (method_exists($this, 'get'.$key)) {
2737 $ret[substr($key, 1)] = $this->{'get'.$key}();
2738 } else {
2739 $ret[substr($key, 1)] = $this->$key;
2740 }
fc79ede5
MG
2741 }
2742 }
4e430906
MG
2743 $ret['sequence'] = $this->get_sequence();
2744 $ret['course'] = $this->get_course();
2745 $ret = array_merge($ret, course_get_format($this->modinfo->get_course())->get_format_options($this->_section));
fc79ede5
MG
2746 return new ArrayIterator($ret);
2747 }
2748
ce4dfd27 2749 /**
2750 * Works out whether activity is visible *for current user* - if this is false, they
2751 * aren't allowed to access it.
4e430906
MG
2752 *
2753 * @return bool
ce4dfd27 2754 */
4e430906 2755 private function get_uservisible() {
4cc819ad
MG
2756 $userid = $this->modinfo->get_user_id();
2757 if ($this->_uservisible !== null || $userid == -1) {
2758 // Has already been calculated or does not need calculation.
4e430906
MG
2759 return $this->_uservisible;
2760 }
fc79ede5 2761 $this->_uservisible = true;
4e430906
MG
2762 if (!$this->_visible || !$this->get_available()) {
2763 $coursecontext = context_course::instance($this->get_course());
6a36b852
J
2764 if (!$this->_visible && !has_capability('moodle/course:viewhiddensections', $coursecontext, $userid) ||
2765 (!$this->get_available() &&
2766 !has_capability('moodle/course:ignoreavailabilityrestrictions', $coursecontext, $userid))) {
2767
4e430906
MG
2768 $this->_uservisible = false;
2769 }
ce4dfd27 2770 }
4e430906
MG
2771 return $this->_uservisible;
2772 }
2773
2774 /**
2775 * Restores the course_sections.sequence value
2776 *
2777 * @return string
2778 */
2779 private function get_sequence() {
2780 if (!empty($this->modinfo->sections[$this->_section])) {
2781 return implode(',', $this->modinfo->sections[$this->_section]);
2782 } else {
2783 return '';
2784 }
2785 }
2786
2787 /**
2788 * Returns course ID - from course_sections table
2789 *
2790 * @return int
2791 */
2792 private function get_course() {
2793 return $this->modinfo->get_course_id();
ce4dfd27 2794 }
58d11393
MG
2795
2796 /**
2797 * Modinfo object
2798 *
2799 * @return course_modinfo
2800 */
2801 private function get_modinfo() {
2802 return $this->modinfo;
2803 }
ce4dfd27 2804
2805 /**
2806 * Prepares section data for inclusion in sectioncache cache, removing items
2807 * that are set to defaults, and adding availability data if required.
2808 *
2809 * Called by build_section_cache in course_modinfo only; do not use otherwise.
2810 * @param object $section Raw section data object
2811 */
2812 public static function convert_for_section_cache($section) {
2813 global $CFG;
2814
2815 // Course id stored in course table
2816 unset($section->course);
2817 // Section number stored in array key
2818 unset($section->section);
2819 // Sequence stored implicity in modinfo $sections array
2820 unset($section->sequence);
2821
ce4dfd27 2822 // Remove default data
94dc3c7d 2823 foreach (self::$sectioncachedefaults as $field => $value) {
ce4dfd27 2824 // Exact compare as strings to avoid problems if some strings are set
2825 // to "0" etc.
2826 if (isset($section->{$field}) && $section->{$field} === $value) {
2827 unset($section->{$field});
2828 }
2829 }
2830 }
2831}