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