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