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