PageRenderTime 53ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/modinfolib.php

http://github.com/moodle/moodle
PHP | 2904 lines | 1177 code | 269 blank | 1458 comment | 204 complexity | 3e90787f094cc9e98544553b9a3dedf3 MD5 | raw file
Possible License(s): MIT, AGPL-3.0, MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, Apache-2.0, LGPL-2.1, BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  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. * modinfolib.php - Functions/classes relating to cached information about module instances on
  18. * a course.
  19. * @package core
  20. * @subpackage lib
  21. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  22. * @author sam marshall
  23. */
  24. // Maximum number of modinfo items to keep in memory cache. Do not increase this to a large
  25. // number because:
  26. // a) modinfo can be big (megabyte range) for some courses
  27. // b) performance of cache will deteriorate if there are very many items in it
  28. if (!defined('MAX_MODINFO_CACHE_SIZE')) {
  29. define('MAX_MODINFO_CACHE_SIZE', 10);
  30. }
  31. /**
  32. * Information about a course that is cached in the course table 'modinfo' field (and then in
  33. * memory) in order to reduce the need for other database queries.
  34. *
  35. * This includes information about the course-modules and the sections on the course. It can also
  36. * include dynamic data that has been updated for the current user.
  37. *
  38. * Use {@link get_fast_modinfo()} to retrieve the instance of the object for particular course
  39. * and particular user.
  40. *
  41. * @property-read int $courseid Course ID
  42. * @property-read int $userid User ID
  43. * @property-read array $sections Array from section number (e.g. 0) to array of course-module IDs in that
  44. * section; this only includes sections that contain at least one course-module
  45. * @property-read cm_info[] $cms Array from course-module instance to cm_info object within this course, in
  46. * order of appearance
  47. * @property-read cm_info[][] $instances Array from string (modname) => int (instance id) => cm_info object
  48. * @property-read array $groups Groups that the current user belongs to. Calculated on the first request.
  49. * Is an array of grouping id => array of group id => group id. Includes grouping id 0 for 'all groups'
  50. */
  51. class course_modinfo {
  52. /** @var int Maximum time the course cache building lock can be held */
  53. const COURSE_CACHE_LOCK_EXPIRY = 180;
  54. /** @var int Time to wait for the course cache building lock before throwing an exception */
  55. const COURSE_CACHE_LOCK_WAIT = 60;
  56. /**
  57. * List of fields from DB table 'course' that are cached in MUC and are always present in course_modinfo::$course
  58. * @var array
  59. */
  60. public static $cachedfields = array('shortname', 'fullname', 'format',
  61. 'enablecompletion', 'groupmode', 'groupmodeforce', 'cacherev');
  62. /**
  63. * For convenience we store the course object here as it is needed in other parts of code
  64. * @var stdClass
  65. */
  66. private $course;
  67. /**
  68. * Array of section data from cache
  69. * @var section_info[]
  70. */
  71. private $sectioninfo;
  72. /**
  73. * User ID
  74. * @var int
  75. */
  76. private $userid;
  77. /**
  78. * Array from int (section num, e.g. 0) => array of int (course-module id); this list only
  79. * includes sections that actually contain at least one course-module
  80. * @var array
  81. */
  82. private $sections;
  83. /**
  84. * Array from int (cm id) => cm_info object
  85. * @var cm_info[]
  86. */
  87. private $cms;
  88. /**
  89. * Array from string (modname) => int (instance id) => cm_info object
  90. * @var cm_info[][]
  91. */
  92. private $instances;
  93. /**
  94. * Groups that the current user belongs to. This value is calculated on first
  95. * request to the property or function.
  96. * When set, it is an array of grouping id => array of group id => group id.
  97. * Includes grouping id 0 for 'all groups'.
  98. * @var int[][]
  99. */
  100. private $groups;
  101. /**
  102. * List of class read-only properties and their getter methods.
  103. * Used by magic functions __get(), __isset(), __empty()
  104. * @var array
  105. */
  106. private static $standardproperties = array(
  107. 'courseid' => 'get_course_id',
  108. 'userid' => 'get_user_id',
  109. 'sections' => 'get_sections',
  110. 'cms' => 'get_cms',
  111. 'instances' => 'get_instances',
  112. 'groups' => 'get_groups_all',
  113. );
  114. /**
  115. * Magic method getter
  116. *
  117. * @param string $name
  118. * @return mixed
  119. */
  120. public function __get($name) {
  121. if (isset(self::$standardproperties[$name])) {
  122. $method = self::$standardproperties[$name];
  123. return $this->$method();
  124. } else {
  125. debugging('Invalid course_modinfo property accessed: '.$name);
  126. return null;
  127. }
  128. }
  129. /**
  130. * Magic method for function isset()
  131. *
  132. * @param string $name
  133. * @return bool
  134. */
  135. public function __isset($name) {
  136. if (isset(self::$standardproperties[$name])) {
  137. $value = $this->__get($name);
  138. return isset($value);
  139. }
  140. return false;
  141. }
  142. /**
  143. * Magic method for function empty()
  144. *
  145. * @param string $name
  146. * @return bool
  147. */
  148. public function __empty($name) {
  149. if (isset(self::$standardproperties[$name])) {
  150. $value = $this->__get($name);
  151. return empty($value);
  152. }
  153. return true;
  154. }
  155. /**
  156. * Magic method setter
  157. *
  158. * Will display the developer warning when trying to set/overwrite existing property.
  159. *
  160. * @param string $name
  161. * @param mixed $value
  162. */
  163. public function __set($name, $value) {
  164. debugging("It is not allowed to set the property course_modinfo::\${$name}", DEBUG_DEVELOPER);
  165. }
  166. /**
  167. * Returns course object that was used in the first {@link get_fast_modinfo()} call.
  168. *
  169. * It may not contain all fields from DB table {course} but always has at least the following:
  170. * id,shortname,fullname,format,enablecompletion,groupmode,groupmodeforce,cacherev
  171. *
  172. * @return stdClass
  173. */
  174. public function get_course() {
  175. return $this->course;
  176. }
  177. /**
  178. * @return int Course ID
  179. */
  180. public function get_course_id() {
  181. return $this->course->id;
  182. }
  183. /**
  184. * @return int User ID
  185. */
  186. public function get_user_id() {
  187. return $this->userid;
  188. }
  189. /**
  190. * @return array Array from section number (e.g. 0) to array of course-module IDs in that
  191. * section; this only includes sections that contain at least one course-module
  192. */
  193. public function get_sections() {
  194. return $this->sections;
  195. }
  196. /**
  197. * @return cm_info[] Array from course-module instance to cm_info object within this course, in
  198. * order of appearance
  199. */
  200. public function get_cms() {
  201. return $this->cms;
  202. }
  203. /**
  204. * Obtains a single course-module object (for a course-module that is on this course).
  205. * @param int $cmid Course-module ID
  206. * @return cm_info Information about that course-module
  207. * @throws moodle_exception If the course-module does not exist
  208. */
  209. public function get_cm($cmid) {
  210. if (empty($this->cms[$cmid])) {
  211. throw new moodle_exception('invalidcoursemodule', 'error');
  212. }
  213. return $this->cms[$cmid];
  214. }
  215. /**
  216. * Obtains all module instances on this course.
  217. * @return cm_info[][] Array from module name => array from instance id => cm_info
  218. */
  219. public function get_instances() {
  220. return $this->instances;
  221. }
  222. /**
  223. * Returns array of localised human-readable module names used in this course
  224. *
  225. * @param bool $plural if true returns the plural form of modules names
  226. * @return array
  227. */
  228. public function get_used_module_names($plural = false) {
  229. $modnames = get_module_types_names($plural);
  230. $modnamesused = array();
  231. foreach ($this->get_cms() as $cmid => $mod) {
  232. if (!isset($modnamesused[$mod->modname]) && isset($modnames[$mod->modname]) && $mod->uservisible) {
  233. $modnamesused[$mod->modname] = $modnames[$mod->modname];
  234. }
  235. }
  236. return $modnamesused;
  237. }
  238. /**
  239. * Obtains all instances of a particular module on this course.
  240. * @param $modname Name of module (not full frankenstyle) e.g. 'label'
  241. * @return cm_info[] Array from instance id => cm_info for modules on this course; empty if none
  242. */
  243. public function get_instances_of($modname) {
  244. if (empty($this->instances[$modname])) {
  245. return array();
  246. }
  247. return $this->instances[$modname];
  248. }
  249. /**
  250. * Groups that the current user belongs to organised by grouping id. Calculated on the first request.
  251. * @return int[][] array of grouping id => array of group id => group id. Includes grouping id 0 for 'all groups'
  252. */
  253. private function get_groups_all() {
  254. if (is_null($this->groups)) {
  255. // NOTE: Performance could be improved here. The system caches user groups
  256. // in $USER->groupmember[$courseid] => array of groupid=>groupid. Unfortunately this
  257. // structure does not include grouping information. It probably could be changed to
  258. // do so, without a significant performance hit on login, thus saving this one query
  259. // each request.
  260. $this->groups = groups_get_user_groups($this->course->id, $this->userid);
  261. }
  262. return $this->groups;
  263. }
  264. /**
  265. * Returns groups that the current user belongs to on the course. Note: If not already
  266. * available, this may make a database query.
  267. * @param int $groupingid Grouping ID or 0 (default) for all groups
  268. * @return int[] Array of int (group id) => int (same group id again); empty array if none
  269. */
  270. public function get_groups($groupingid = 0) {
  271. $allgroups = $this->get_groups_all();
  272. if (!isset($allgroups[$groupingid])) {
  273. return array();
  274. }
  275. return $allgroups[$groupingid];
  276. }
  277. /**
  278. * Gets all sections as array from section number => data about section.
  279. * @return section_info[] Array of section_info objects organised by section number
  280. */
  281. public function get_section_info_all() {
  282. return $this->sectioninfo;
  283. }
  284. /**
  285. * Gets data about specific numbered section.
  286. * @param int $sectionnumber Number (not id) of section
  287. * @param int $strictness Use MUST_EXIST to throw exception if it doesn't
  288. * @return section_info Information for numbered section or null if not found
  289. */
  290. public function get_section_info($sectionnumber, $strictness = IGNORE_MISSING) {
  291. if (!array_key_exists($sectionnumber, $this->sectioninfo)) {
  292. if ($strictness === MUST_EXIST) {
  293. throw new moodle_exception('sectionnotexist');
  294. } else {
  295. return null;
  296. }
  297. }
  298. return $this->sectioninfo[$sectionnumber];
  299. }
  300. /**
  301. * Static cache for generated course_modinfo instances
  302. *
  303. * @see course_modinfo::instance()
  304. * @see course_modinfo::clear_instance_cache()
  305. * @var course_modinfo[]
  306. */
  307. protected static $instancecache = array();
  308. /**
  309. * Timestamps (microtime) when the course_modinfo instances were last accessed
  310. *
  311. * It is used to remove the least recent accessed instances when static cache is full
  312. *
  313. * @var float[]
  314. */
  315. protected static $cacheaccessed = array();
  316. /**
  317. * Clears the cache used in course_modinfo::instance()
  318. *
  319. * Used in {@link get_fast_modinfo()} when called with argument $reset = true
  320. * and in {@link rebuild_course_cache()}
  321. *
  322. * @param null|int|stdClass $courseorid if specified removes only cached value for this course
  323. */
  324. public static function clear_instance_cache($courseorid = null) {
  325. if (empty($courseorid)) {
  326. self::$instancecache = array();
  327. self::$cacheaccessed = array();
  328. return;
  329. }
  330. if (is_object($courseorid)) {
  331. $courseorid = $courseorid->id;
  332. }
  333. if (isset(self::$instancecache[$courseorid])) {
  334. // Unsetting static variable in PHP is peculiar, it removes the reference,
  335. // but data remain in memory. Prior to unsetting, the varable needs to be
  336. // set to empty to remove its remains from memory.
  337. self::$instancecache[$courseorid] = '';
  338. unset(self::$instancecache[$courseorid]);
  339. unset(self::$cacheaccessed[$courseorid]);
  340. }
  341. }
  342. /**
  343. * Returns the instance of course_modinfo for the specified course and specified user
  344. *
  345. * This function uses static cache for the retrieved instances. The cache
  346. * size is limited by MAX_MODINFO_CACHE_SIZE. If instance is not found in
  347. * the static cache or it was created for another user or the cacherev validation
  348. * failed - a new instance is constructed and returned.
  349. *
  350. * Used in {@link get_fast_modinfo()}
  351. *
  352. * @param int|stdClass $courseorid object from DB table 'course' (must have field 'id'
  353. * and recommended to have field 'cacherev') or just a course id
  354. * @param int $userid User id to populate 'availble' and 'uservisible' attributes of modules and sections.
  355. * Set to 0 for current user (default). Set to -1 to avoid calculation of dynamic user-depended data.
  356. * @return course_modinfo
  357. */
  358. public static function instance($courseorid, $userid = 0) {
  359. global $USER;
  360. if (is_object($courseorid)) {
  361. $course = $courseorid;
  362. } else {
  363. $course = (object)array('id' => $courseorid);
  364. }
  365. if (empty($userid)) {
  366. $userid = $USER->id;
  367. }
  368. if (!empty(self::$instancecache[$course->id])) {
  369. if (self::$instancecache[$course->id]->userid == $userid &&
  370. (!isset($course->cacherev) ||
  371. $course->cacherev == self::$instancecache[$course->id]->get_course()->cacherev)) {
  372. // This course's modinfo for the same user was recently retrieved, return cached.
  373. self::$cacheaccessed[$course->id] = microtime(true);
  374. return self::$instancecache[$course->id];
  375. } else {
  376. // Prevent potential reference problems when switching users.
  377. self::clear_instance_cache($course->id);
  378. }
  379. }
  380. $modinfo = new course_modinfo($course, $userid);
  381. // We have a limit of MAX_MODINFO_CACHE_SIZE entries to store in static variable.
  382. if (count(self::$instancecache) >= MAX_MODINFO_CACHE_SIZE) {
  383. // Find the course that was the least recently accessed.
  384. asort(self::$cacheaccessed, SORT_NUMERIC);
  385. $courseidtoremove = key(array_reverse(self::$cacheaccessed, true));
  386. self::clear_instance_cache($courseidtoremove);
  387. }
  388. // Add modinfo to the static cache.
  389. self::$instancecache[$course->id] = $modinfo;
  390. self::$cacheaccessed[$course->id] = microtime(true);
  391. return $modinfo;
  392. }
  393. /**
  394. * Constructs based on course.
  395. * Note: This constructor should not usually be called directly.
  396. * Use get_fast_modinfo($course) instead as this maintains a cache.
  397. * @param stdClass $course course object, only property id is required.
  398. * @param int $userid User ID
  399. * @throws moodle_exception if course is not found
  400. */
  401. public function __construct($course, $userid) {
  402. global $CFG, $COURSE, $SITE, $DB;
  403. if (!isset($course->cacherev)) {
  404. // We require presence of property cacherev to validate the course cache.
  405. // No need to clone the $COURSE or $SITE object here because we clone it below anyway.
  406. $course = get_course($course->id, false);
  407. }
  408. $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
  409. // Retrieve modinfo from cache. If not present or cacherev mismatches, call rebuild and retrieve again.
  410. $coursemodinfo = $cachecoursemodinfo->get($course->id);
  411. if ($coursemodinfo === false || ($course->cacherev != $coursemodinfo->cacherev)) {
  412. $lock = self::get_course_cache_lock($course->id);
  413. try {
  414. // Only actually do the build if it's still needed after getting the lock (not if
  415. // somebody else, who might have been holding the lock, built it already).
  416. $coursemodinfo = $cachecoursemodinfo->get($course->id);
  417. if ($coursemodinfo === false || ($course->cacherev != $coursemodinfo->cacherev)) {
  418. $coursemodinfo = self::inner_build_course_cache($course, $lock);
  419. }
  420. } finally {
  421. $lock->release();
  422. }
  423. }
  424. // Set initial values
  425. $this->userid = $userid;
  426. $this->sections = array();
  427. $this->cms = array();
  428. $this->instances = array();
  429. $this->groups = null;
  430. // If we haven't already preloaded contexts for the course, do it now
  431. // Modules are also cached here as long as it's the first time this course has been preloaded.
  432. context_helper::preload_course($course->id);
  433. // Quick integrity check: as a result of race conditions modinfo may not be regenerated after the change.
  434. // It is especially dangerous if modinfo contains the deleted course module, as it results in fatal error.
  435. // We can check it very cheap by validating the existence of module context.
  436. if ($course->id == $COURSE->id || $course->id == $SITE->id) {
  437. // Only verify current course (or frontpage) as pages with many courses may not have module contexts cached.
  438. // (Uncached modules will result in a very slow verification).
  439. foreach ($coursemodinfo->modinfo as $mod) {
  440. if (!context_module::instance($mod->cm, IGNORE_MISSING)) {
  441. debugging('Course cache integrity check failed: course module with id '. $mod->cm.
  442. ' does not have context. Rebuilding cache for course '. $course->id);
  443. // Re-request the course record from DB as well, don't use get_course() here.
  444. $course = $DB->get_record('course', array('id' => $course->id), '*', MUST_EXIST);
  445. $coursemodinfo = self::build_course_cache($course);
  446. break;
  447. }
  448. }
  449. }
  450. // Overwrite unset fields in $course object with cached values, store the course object.
  451. $this->course = fullclone($course);
  452. foreach ($coursemodinfo as $key => $value) {
  453. if ($key !== 'modinfo' && $key !== 'sectioncache' &&
  454. (!isset($this->course->$key) || $key === 'cacherev')) {
  455. $this->course->$key = $value;
  456. }
  457. }
  458. // Loop through each piece of module data, constructing it
  459. static $modexists = array();
  460. foreach ($coursemodinfo->modinfo as $mod) {
  461. if (!isset($mod->name) || strval($mod->name) === '') {
  462. // something is wrong here
  463. continue;
  464. }
  465. // Skip modules which don't exist
  466. if (!array_key_exists($mod->mod, $modexists)) {
  467. $modexists[$mod->mod] = file_exists("$CFG->dirroot/mod/$mod->mod/lib.php");
  468. }
  469. if (!$modexists[$mod->mod]) {
  470. continue;
  471. }
  472. // Construct info for this module
  473. $cm = new cm_info($this, null, $mod, null);
  474. // Store module in instances and cms array
  475. if (!isset($this->instances[$cm->modname])) {
  476. $this->instances[$cm->modname] = array();
  477. }
  478. $this->instances[$cm->modname][$cm->instance] = $cm;
  479. $this->cms[$cm->id] = $cm;
  480. // Reconstruct sections. This works because modules are stored in order
  481. if (!isset($this->sections[$cm->sectionnum])) {
  482. $this->sections[$cm->sectionnum] = array();
  483. }
  484. $this->sections[$cm->sectionnum][] = $cm->id;
  485. }
  486. // Expand section objects
  487. $this->sectioninfo = array();
  488. foreach ($coursemodinfo->sectioncache as $number => $data) {
  489. $this->sectioninfo[$number] = new section_info($data, $number, null, null,
  490. $this, null);
  491. }
  492. }
  493. /**
  494. * This method can not be used anymore.
  495. *
  496. * @see course_modinfo::build_course_cache()
  497. * @deprecated since 2.6
  498. */
  499. public static function build_section_cache($courseid) {
  500. throw new coding_exception('Function course_modinfo::build_section_cache() can not be used anymore.' .
  501. ' Please use course_modinfo::build_course_cache() whenever applicable.');
  502. }
  503. /**
  504. * Builds a list of information about sections on a course to be stored in
  505. * the course cache. (Does not include information that is already cached
  506. * in some other way.)
  507. *
  508. * @param stdClass $course Course object (must contain fields
  509. * @return array Information about sections, indexed by section number (not id)
  510. */
  511. protected static function build_course_section_cache($course) {
  512. global $DB;
  513. // Get section data
  514. $sections = $DB->get_records('course_sections', array('course' => $course->id), 'section',
  515. 'section, id, course, name, summary, summaryformat, sequence, visible, availability');
  516. $compressedsections = array();
  517. $formatoptionsdef = course_get_format($course)->section_format_options();
  518. // Remove unnecessary data and add availability
  519. foreach ($sections as $number => $section) {
  520. // Add cached options from course format to $section object
  521. foreach ($formatoptionsdef as $key => $option) {
  522. if (!empty($option['cache'])) {
  523. $formatoptions = course_get_format($course)->get_format_options($section);
  524. if (!array_key_exists('cachedefault', $option) || $option['cachedefault'] !== $formatoptions[$key]) {
  525. $section->$key = $formatoptions[$key];
  526. }
  527. }
  528. }
  529. // Clone just in case it is reused elsewhere
  530. $compressedsections[$number] = clone($section);
  531. section_info::convert_for_section_cache($compressedsections[$number]);
  532. }
  533. return $compressedsections;
  534. }
  535. /**
  536. * Gets a lock for rebuilding the cache of a single course.
  537. *
  538. * Caller must release the returned lock.
  539. *
  540. * This is used to ensure that the cache rebuild doesn't happen multiple times in parallel.
  541. * This function will wait up to 1 minute for the lock to be obtained. If the lock cannot
  542. * be obtained, it throws an exception.
  543. *
  544. * @param int $courseid Course id
  545. * @return \core\lock\lock Lock (must be released!)
  546. * @throws moodle_exception If the lock cannot be obtained
  547. */
  548. protected static function get_course_cache_lock($courseid) {
  549. // Get database lock to ensure this doesn't happen multiple times in parallel. Wait a
  550. // reasonable time for the lock to be released, so we can give a suitable error message.
  551. // In case the system crashes while building the course cache, the lock will automatically
  552. // expire after a (slightly longer) period.
  553. $lockfactory = \core\lock\lock_config::get_lock_factory('core_modinfo');
  554. $lock = $lockfactory->get_lock('build_course_cache_' . $courseid,
  555. self::COURSE_CACHE_LOCK_WAIT, self::COURSE_CACHE_LOCK_EXPIRY);
  556. if (!$lock) {
  557. throw new moodle_exception('locktimeout', '', '', null,
  558. 'core_modinfo/build_course_cache_' . $courseid);
  559. }
  560. return $lock;
  561. }
  562. /**
  563. * Builds and stores in MUC object containing information about course
  564. * modules and sections together with cached fields from table course.
  565. *
  566. * @param stdClass $course object from DB table course. Must have property 'id'
  567. * but preferably should have all cached fields.
  568. * @return stdClass object with all cached keys of the course plus fields modinfo and sectioncache.
  569. * The same object is stored in MUC
  570. * @throws moodle_exception if course is not found (if $course object misses some of the
  571. * necessary fields it is re-requested from database)
  572. */
  573. public static function build_course_cache($course) {
  574. if (empty($course->id)) {
  575. throw new coding_exception('Object $course is missing required property \id\'');
  576. }
  577. $lock = self::get_course_cache_lock($course->id);
  578. try {
  579. return self::inner_build_course_cache($course, $lock);
  580. } finally {
  581. $lock->release();
  582. }
  583. }
  584. /**
  585. * Called to build course cache when there is already a lock obtained.
  586. *
  587. * @param stdClass $course object from DB table course
  588. * @param \core\lock\lock $lock Lock object - not actually used, just there to indicate you have a lock
  589. * @return stdClass Course object that has been stored in MUC
  590. */
  591. protected static function inner_build_course_cache($course, \core\lock\lock $lock) {
  592. global $DB, $CFG;
  593. require_once("{$CFG->dirroot}/course/lib.php");
  594. // Ensure object has all necessary fields.
  595. foreach (self::$cachedfields as $key) {
  596. if (!isset($course->$key)) {
  597. $course = $DB->get_record('course', array('id' => $course->id),
  598. implode(',', array_merge(array('id'), self::$cachedfields)), MUST_EXIST);
  599. break;
  600. }
  601. }
  602. // Retrieve all information about activities and sections.
  603. // This may take time on large courses and it is possible that another user modifies the same course during this process.
  604. // Field cacherev stored in both DB and cache will ensure that cached data matches the current course state.
  605. $coursemodinfo = new stdClass();
  606. $coursemodinfo->modinfo = get_array_of_activities($course->id);
  607. $coursemodinfo->sectioncache = self::build_course_section_cache($course);
  608. foreach (self::$cachedfields as $key) {
  609. $coursemodinfo->$key = $course->$key;
  610. }
  611. // Set the accumulated activities and sections information in cache, together with cacherev.
  612. $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
  613. $cachecoursemodinfo->set($course->id, $coursemodinfo);
  614. return $coursemodinfo;
  615. }
  616. }
  617. /**
  618. * Data about a single module on a course. This contains most of the fields in the course_modules
  619. * table, plus additional data when required.
  620. *
  621. * The object can be accessed by core or any plugin (i.e. course format, block, filter, etc.) as
  622. * get_fast_modinfo($courseorid)->cms[$coursemoduleid]
  623. * or
  624. * get_fast_modinfo($courseorid)->instances[$moduletype][$instanceid]
  625. *
  626. * There are three stages when activity module can add/modify data in this object:
  627. *
  628. * <b>Stage 1 - during building the cache.</b>
  629. * Allows to add to the course cache static user-independent information about the module.
  630. * Modules should try to include only absolutely necessary information that may be required
  631. * when displaying course view page. The information is stored in application-level cache
  632. * and reset when {@link rebuild_course_cache()} is called or cache is purged by admin.
  633. *
  634. * Modules can implement callback XXX_get_coursemodule_info() returning instance of object
  635. * {@link cached_cm_info}
  636. *
  637. * <b>Stage 2 - dynamic data.</b>
  638. * Dynamic data is user-dependend, it is stored in request-level cache. To reset this cache
  639. * {@link get_fast_modinfo()} with $reset argument may be called.
  640. *
  641. * Dynamic data is obtained when any of the following properties/methods is requested:
  642. * - {@link cm_info::$url}
  643. * - {@link cm_info::$name}
  644. * - {@link cm_info::$onclick}
  645. * - {@link cm_info::get_icon_url()}
  646. * - {@link cm_info::$uservisible}
  647. * - {@link cm_info::$available}
  648. * - {@link cm_info::$availableinfo}
  649. * - plus any of the properties listed in Stage 3.
  650. *
  651. * Modules can implement callback <b>XXX_cm_info_dynamic()</b> and inside this callback they
  652. * are allowed to use any of the following set methods:
  653. * - {@link cm_info::set_available()}
  654. * - {@link cm_info::set_name()}
  655. * - {@link cm_info::set_no_view_link()}
  656. * - {@link cm_info::set_user_visible()}
  657. * - {@link cm_info::set_on_click()}
  658. * - {@link cm_info::set_icon_url()}
  659. * Any methods affecting view elements can also be set in this callback.
  660. *
  661. * <b>Stage 3 (view data).</b>
  662. * Also user-dependend data stored in request-level cache. Second stage is created
  663. * because populating the view data can be expensive as it may access much more
  664. * Moodle APIs such as filters, user information, output renderers and we
  665. * don't want to request it until necessary.
  666. * View data is obtained when any of the following properties/methods is requested:
  667. * - {@link cm_info::$afterediticons}
  668. * - {@link cm_info::$content}
  669. * - {@link cm_info::get_formatted_content()}
  670. * - {@link cm_info::$extraclasses}
  671. * - {@link cm_info::$afterlink}
  672. *
  673. * Modules can implement callback <b>XXX_cm_info_view()</b> and inside this callback they
  674. * are allowed to use any of the following set methods:
  675. * - {@link cm_info::set_after_edit_icons()}
  676. * - {@link cm_info::set_after_link()}
  677. * - {@link cm_info::set_content()}
  678. * - {@link cm_info::set_extra_classes()}
  679. *
  680. * @property-read int $id Course-module ID - from course_modules table
  681. * @property-read int $instance Module instance (ID within module table) - from course_modules table
  682. * @property-read int $course Course ID - from course_modules table
  683. * @property-read string $idnumber 'ID number' from course-modules table (arbitrary text set by user) - from
  684. * course_modules table
  685. * @property-read int $added Time that this course-module was added (unix time) - from course_modules table
  686. * @property-read int $visible Visible setting (0 or 1; if this is 0, students cannot see/access the activity) - from
  687. * course_modules table
  688. * @property-read int $visibleoncoursepage Visible on course page setting - from course_modules table, adjusted to
  689. * whether course format allows this module to have the "stealth" mode
  690. * @property-read int $visibleold Old visible setting (if the entire section is hidden, the previous value for
  691. * visible is stored in this field) - from course_modules table
  692. * @property-read int $groupmode Group mode (one of the constants NOGROUPS, SEPARATEGROUPS, or VISIBLEGROUPS) - from
  693. * course_modules table. Use {@link cm_info::$effectivegroupmode} to find the actual group mode that may be forced by course.
  694. * @property-read int $groupingid Grouping ID (0 = all groupings)
  695. * @property-read bool $coursegroupmodeforce Indicates whether the course containing the module has forced the groupmode
  696. * This means that cm_info::$groupmode should be ignored and cm_info::$coursegroupmode be used instead
  697. * @property-read int $coursegroupmode Group mode (one of the constants NOGROUPS, SEPARATEGROUPS, or VISIBLEGROUPS) - from
  698. * course table - as specified for the course containing the module
  699. * Effective only if {@link cm_info::$coursegroupmodeforce} is set
  700. * @property-read int $effectivegroupmode Effective group mode for this module (one of the constants NOGROUPS, SEPARATEGROUPS,
  701. * or VISIBLEGROUPS). This can be different from groupmode set for the module if the groupmode is forced for the course.
  702. * This value will always be NOGROUPS if module type does not support group mode.
  703. * @property-read int $indent Indent level on course page (0 = no indent) - from course_modules table
  704. * @property-read int $completion Activity completion setting for this activity, COMPLETION_TRACKING_xx constant - from
  705. * course_modules table
  706. * @property-read mixed $completiongradeitemnumber Set to the item number (usually 0) if completion depends on a particular
  707. * grade of this activity, or null if completion does not depend on a grade - from course_modules table
  708. * @property-read int $completionview 1 if 'on view' completion is enabled, 0 otherwise - from course_modules table
  709. * @property-read int $completionexpected Set to a unix time if completion of this activity is expected at a
  710. * particular time, 0 if no time set - from course_modules table
  711. * @property-read string $availability Availability information as JSON string or null if none -
  712. * from course_modules table
  713. * @property-read int $showdescription Controls whether the description of the activity displays on the course main page (in
  714. * addition to anywhere it might display within the activity itself). 0 = do not show
  715. * on main page, 1 = show on main page.
  716. * @property-read string $extra (deprecated) Extra HTML that is put in an unhelpful part of the HTML when displaying this module in
  717. * course page - from cached data in modinfo field. Deprecated, replaced by ->extraclasses and ->onclick
  718. * @property-read string $icon Name of icon to use - from cached data in modinfo field
  719. * @property-read string $iconcomponent Component that contains icon - from cached data in modinfo field
  720. * @property-read string $modname Name of module e.g. 'forum' (this is the same name as the module's main database
  721. * table) - from cached data in modinfo field
  722. * @property-read int $module ID of module type - from course_modules table
  723. * @property-read string $name Name of module instance for display on page e.g. 'General discussion forum' - from cached
  724. * data in modinfo field
  725. * @property-read int $sectionnum Section number that this course-module is in (section 0 = above the calendar, section 1
  726. * = week/topic 1, etc) - from cached data in modinfo field
  727. * @property-read int $section Section id - from course_modules table
  728. * @property-read array $conditionscompletion Availability conditions for this course-module based on the completion of other
  729. * course-modules (array from other course-module id to required completion state for that
  730. * module) - from cached data in modinfo field
  731. * @property-read array $conditionsgrade Availability conditions for this course-module based on course grades (array from
  732. * grade item id to object with ->min, ->max fields) - from cached data in modinfo field
  733. * @property-read array $conditionsfield Availability conditions for this course-module based on user fields
  734. * @property-read bool $available True if this course-module is available to students i.e. if all availability conditions
  735. * are met - obtained dynamically
  736. * @property-read string $availableinfo If course-module is not available to students, this string gives information about
  737. * availability which can be displayed to students and/or staff (e.g. 'Available from 3
  738. * January 2010') for display on main page - obtained dynamically
  739. * @property-read bool $uservisible True if this course-module is available to the CURRENT user (for example, if current user
  740. * has viewhiddenactivities capability, they can access the course-module even if it is not
  741. * visible or not available, so this would be true in that case)
  742. * @property-read context_module $context Module context
  743. * @property-read string $modfullname Returns a localised human-readable name of the module type - calculated on request
  744. * @property-read string $modplural Returns a localised human-readable name of the module type in plural form - calculated on request
  745. * @property-read string $content Content to display on main (view) page - calculated on request
  746. * @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
  747. * @property-read string $extraclasses Extra CSS classes to add to html output for this activity on main page - calculated on request
  748. * @property-read string $onclick Content of HTML on-click attribute already escaped - calculated on request
  749. * @property-read mixed $customdata Optional custom data stored in modinfo cache for this activity, or null if none
  750. * @property-read string $afterlink Extra HTML code to display after link - calculated on request
  751. * @property-read string $afterediticons Extra HTML code to display after editing icons (e.g. more icons) - calculated on request
  752. * @property-read bool $deletioninprogress True if this course module is scheduled for deletion, false otherwise.
  753. */
  754. class cm_info implements IteratorAggregate {
  755. /**
  756. * State: Only basic data from modinfo cache is available.
  757. */
  758. const STATE_BASIC = 0;
  759. /**
  760. * State: In the process of building dynamic data (to avoid recursive calls to obtain_dynamic_data())
  761. */
  762. const STATE_BUILDING_DYNAMIC = 1;
  763. /**
  764. * State: Dynamic data is available too.
  765. */
  766. const STATE_DYNAMIC = 2;
  767. /**
  768. * State: In the process of building view data (to avoid recursive calls to obtain_view_data())
  769. */
  770. const STATE_BUILDING_VIEW = 3;
  771. /**
  772. * State: View data (for course page) is available.
  773. */
  774. const STATE_VIEW = 4;
  775. /**
  776. * Parent object
  777. * @var course_modinfo
  778. */
  779. private $modinfo;
  780. /**
  781. * Level of information stored inside this object (STATE_xx constant)
  782. * @var int
  783. */
  784. private $state;
  785. /**
  786. * Course-module ID - from course_modules table
  787. * @var int
  788. */
  789. private $id;
  790. /**
  791. * Module instance (ID within module table) - from course_modules table
  792. * @var int
  793. */
  794. private $instance;
  795. /**
  796. * 'ID number' from course-modules table (arbitrary text set by user) - from
  797. * course_modules table
  798. * @var string
  799. */
  800. private $idnumber;
  801. /**
  802. * Time that this course-module was added (unix time) - from course_modules table
  803. * @var int
  804. */
  805. private $added;
  806. /**
  807. * This variable is not used and is included here only so it can be documented.
  808. * Once the database entry is removed from course_modules, it should be deleted
  809. * here too.
  810. * @var int
  811. * @deprecated Do not use this variable
  812. */
  813. private $score;
  814. /**
  815. * Visible setting (0 or 1; if this is 0, students cannot see/access the activity) - from
  816. * course_modules table
  817. * @var int
  818. */
  819. private $visible;
  820. /**
  821. * Visible on course page setting - from course_modules table
  822. * @var int
  823. */
  824. private $visibleoncoursepage;
  825. /**
  826. * Old visible setting (if the entire section is hidden, the previous value for
  827. * visible is stored in this field) - from course_modules table
  828. * @var int
  829. */
  830. private $visibleold;
  831. /**
  832. * Group mode (one of the constants NONE, SEPARATEGROUPS, or VISIBLEGROUPS) - from
  833. * course_modules table
  834. * @var int
  835. */
  836. private $groupmode;
  837. /**
  838. * Grouping ID (0 = all groupings)
  839. * @var int
  840. */
  841. private $groupingid;
  842. /**
  843. * Indent level on course page (0 = no indent) - from course_modules table
  844. * @var int
  845. */
  846. private $indent;
  847. /**
  848. * Activity completion setting for this activity, COMPLETION_TRACKING_xx constant - from
  849. * course_modules table
  850. * @var int
  851. */
  852. private $completion;
  853. /**
  854. * Set to the item number (usually 0) if completion depends on a particular
  855. * grade of this activity, or null if completion does not depend on a grade - from
  856. * course_modules table
  857. * @var mixed
  858. */
  859. private $completiongradeitemnumber;
  860. /**
  861. * 1 if 'on view' completion is enabled, 0 otherwise - from course_modules table
  862. * @var int
  863. */
  864. private $completionview;
  865. /**
  866. * Set to a unix time if completion of this activity is expected at a
  867. * particular time, 0 if no time set - from course_modules table
  868. * @var int
  869. */
  870. private $completionexpected;
  871. /**
  872. * Availability information as JSON string or null if none - from course_modules table
  873. * @var string
  874. */
  875. private $availability;
  876. /**
  877. * Controls whether the description of the activity displays on the course main page (in
  878. * addition to anywhere it might display within the activity itself). 0 = do not show
  879. * on main page, 1 = show on main page.
  880. * @var int
  881. */
  882. private $showdescription;
  883. /**
  884. * Extra HTML that is put in an unhelpful part of the HTML when displaying this module in
  885. * course page - from cached data in modinfo field
  886. * @deprecated This is crazy, don't use it. Replaced by ->extraclasses and ->onclick
  887. * @var string
  888. */
  889. private $extra;
  890. /**
  891. * Name of icon to use - from cached data in modinfo field
  892. * @var string
  893. */
  894. private $icon;
  895. /**
  896. * Component that contains icon - from cached data in modinfo field
  897. * @var string
  898. */
  899. private $iconcomponent;
  900. /**
  901. * Name of module e.g. 'forum' (this is the same name as the module's main database
  902. * table) - from cached data in modinfo field
  903. * @var string
  904. */
  905. private $modname;
  906. /**
  907. * ID of module - from course_modules table
  908. * @var int
  909. */
  910. private $module;
  911. /**
  912. * Name of module instance for display on page e.g. 'General discussion forum' - from cached
  913. * data in modinfo field
  914. * @var string
  915. */
  916. private $name;
  917. /**
  918. * Section number that this course-module is in (section 0 = above the calendar, section 1
  919. * = week/topic 1, etc) - from cached data in modinfo field
  920. * @var int
  921. */
  922. private $sectionnum;
  923. /**
  924. * Section id - from course_modules table
  925. * @var int
  926. */
  927. private $section;
  928. /**
  929. * Availability conditions for this course-module based on the completion of other
  930. * course-modules (array from other course-module id to required completion state for that
  931. * module) - from cached data in modinfo field
  932. * @var array
  933. */
  934. private $conditionscompletion;
  935. /**
  936. * Availability conditions for this course-module based on course grades (array from
  937. * grade item id to object with ->min, ->max fields) - from cached data in modinfo field
  938. * @var array
  939. */
  940. private $conditionsgrade;
  941. /**
  942. * Availability conditions for this course-module based on user fields
  943. * @var array
  944. */
  945. private $conditionsfield;
  946. /**
  947. * True if this course-module is available to students i.e. if all availability conditions
  948. * are met - obtained dynamically
  949. * @var bool
  950. */
  951. private $available;
  952. /**
  953. * If course-module is not available to students, this string gives information about
  954. * availability which can be displayed to students and/or staff (e.g. 'Available from 3
  955. * January 2010') for display on main page - obtained dynamically
  956. * @var string
  957. */
  958. private $availableinfo;
  959. /**
  960. * True if this course-module is available to the CURRENT user (for example, if current user
  961. * has viewhiddenactivities capability, they can access the course-module even if it is not
  962. * visible or not available, so this would be true in that case)
  963. * @var bool
  964. */
  965. private $uservisible;
  966. /**
  967. * True if this course-module is visible to the CURRENT user on the course page
  968. * @var bool
  969. */
  970. private $uservisibleoncoursepage;
  971. /**
  972. * @var moodle_url
  973. */
  974. private $url;
  975. /**
  976. * @var string
  977. */
  978. private $content;
  979. /**
  980. * @var bool
  981. */
  982. private $contentisformatted;
  983. /**
  984. * @var string
  985. */
  986. private $extraclasses;
  987. /**
  988. * @var moodle_url full external url pointing to icon image for activity
  989. */
  990. private $iconurl;
  991. /**
  992. * @var string
  993. */
  994. private $onclick;
  995. /**
  996. * @var mixed
  997. */
  998. private $customdata;
  999. /**
  1000. * @var string
  1001. */
  1002. private $afterlink;
  1003. /**
  1004. * @var string
  1005. */
  1006. private $afterediticons;
  1007. /**
  1008. * @var bool representing the deletion state of the module. True if the mod is scheduled for deletion.
  1009. */
  1010. private $deletioninprogress;
  1011. /**
  1012. * List of class read-only properties and their getter methods.
  1013. * Used by magic functions __get(), __isset(), __empty()
  1014. * @var array
  1015. */
  1016. private static $standardproperties = array(
  1017. 'url' => 'get_url',
  1018. 'content' => 'get_content',
  1019. 'extraclasses' => 'get_extra_classes',
  1020. 'onclick' => 'get_on_click',
  1021. 'customdata' => 'get_custom_data',
  1022. 'afterlink' => 'get_after_link',
  1023. 'afterediticons' => 'get_after_edit_icons',
  1024. 'modfullname' => 'get_module_type_name',
  1025. 'modplural' => 'get_module_type_name_plural',
  1026. 'id' => false,
  1027. 'added' => false,
  1028. 'availability' => false,
  1029. 'available' => 'get_available',
  1030. 'availableinfo' => 'get_available_info',
  1031. 'completion' => false,
  1032. 'completionexpected' => false,
  1033. 'completiongradeitemnumber' => false,
  1034. 'completionview' => false,
  1035. 'conditionscompletion' => false,
  1036. 'conditionsfield' => false,
  1037. 'conditionsgrade' => false,
  1038. 'context' => 'get_context',
  1039. 'course' => 'get_course_id',
  1040. 'coursegroupmode' => 'get_course_groupmode',
  1041. 'coursegroupmodeforce' => 'get_course_groupmodeforce',
  1042. 'effectivegroupmode' => 'get_effective_groupmode',
  1043. 'extra' => false,
  1044. 'groupingid' => false,
  1045. 'groupmembersonly' => 'get_deprecated_group_members_only',
  1046. 'groupmode' => false,
  1047. 'icon' => false,
  1048. 'iconcomponent' => false,
  1049. 'idnumber' => false,
  1050. 'indent' => false,
  1051. 'instance' => false,
  1052. 'modname' => false,
  1053. 'module' => false,
  1054. 'name' => 'get_name',
  1055. 'score' => false,
  1056. 'section' => false,
  1057. 'sectionnum' => false,
  1058. 'showdescription' => false,
  1059. 'uservisible' => 'get_user_visible',
  1060. 'visible' => false,
  1061. 'visibleoncoursepage' => false,
  1062. 'visibleold' => false,
  1063. 'deletioninprogress' => false
  1064. );
  1065. /**
  1066. * List of methods with no arguments that were public prior to Moodle 2.6.
  1067. *
  1068. * They can still be accessed publicly via magic __call() function with no warnings
  1069. * but are not listed in the class methods list.
  1070. * For the consistency of the code it is better to use corresponding properties.
  1071. *
  1072. * These methods be deprecated completely in later versions.
  1073. *
  1074. * @var array $standardmethods
  1075. */
  1076. private static $standardmethods = array(
  1077. // Following methods are not recommended to use because there have associated read-only properties.
  1078. 'get_url',
  1079. 'get_content',
  1080. 'get_extra_classes',
  1081. 'get_on_click',
  1082. 'get_custom_data',
  1083. 'get_after_link',
  1084. 'get_after_edit_icons',
  1085. // Method obtain_dynamic_data() should not be called from outside of this class but it was public before Moodle 2.6.
  1086. 'obtain_dynamic_data',
  1087. );
  1088. /**
  1089. * Magic method to call functions that are now declared as private but were public in Moodle before 2.6.
  1090. * These private methods can not be used anymore.
  1091. *
  1092. * @param string $name
  1093. * @param array $arguments
  1094. * @return mixed
  1095. * @throws coding_exception
  1096. */
  1097. public function __call($name, $arguments) {
  1098. if (in_array($name, self::$standardmethods)) {
  1099. $message = "cm_info::$name() can not be used anymore.";
  1100. if ($alternative = array_search($name, self::$standardproperties)) {
  1101. $message .= " Please use the property cm_info->$alternative instead.";
  1102. }
  1103. throw new coding_exception($message);
  1104. }
  1105. throw new coding_exception("Method cm_info::{$name}() does not exist");
  1106. }
  1107. /**
  1108. * Magic method getter
  1109. *
  1110. * @param string $name
  1111. * @return mixed
  1112. */
  1113. public function __get($name) {
  1114. if (isset(self::$standardproperties[$name])) {
  1115. if ($method = self::$standardproperties[$name]) {
  1116. return $this->$method();
  1117. } else {
  1118. return $this->$name;
  1119. }
  1120. } else {
  1121. debugging('Invalid cm_info property accessed: '.$name);
  1122. return null;
  1123. }
  1124. }
  1125. /**
  1126. * Implementation of IteratorAggregate::getIterator(), allows to cycle through properties
  1127. * and use {@link convert_to_array()}
  1128. *
  1129. * @return ArrayIterator
  1130. */
  1131. public function getIterator() {
  1132. // Make sure dynamic properties are retrieved prior to view properties.
  1133. $this->obtain_dynamic_data();
  1134. $ret = array();
  1135. // Do not iterate over deprecated properties.
  1136. $props = self::$standardproperties;
  1137. unset($props['groupmembersonly']);
  1138. foreach ($props as $key => $unused) {
  1139. $ret[$key] = $this->__get($key);
  1140. }
  1141. return new ArrayIterator($ret);
  1142. }
  1143. /**
  1144. * Magic method for function isset()
  1145. *
  1146. * @param string $name
  1147. * @return bool
  1148. */
  1149. public function __isset($name) {
  1150. if (isset(self::$standardproperties[$name])) {
  1151. $value = $this->__get($name);
  1152. return isset($value);
  1153. }
  1154. return false;
  1155. }
  1156. /**
  1157. * Magic method for function empty()
  1158. *
  1159. * @param string $name
  1160. * @return bool
  1161. */
  1162. public function __empty($name) {
  1163. if (isset(self::$standardproperties[$name])) {
  1164. $value = $this->__get($name);

Large files files are truncated, but you can click here to view the full file