PageRenderTime 63ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/modinfolib.php

https://bitbucket.org/moodle/moodle
PHP | 2972 lines | 1198 code | 274 blank | 1500 comment | 207 complexity | f3e3973bdd4daa1c227eb84da8c13716 MD5 | raw file
Possible License(s): Apache-2.0, LGPL-2.1, BSD-3-Clause, MIT, GPL-3.0

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

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