PageRenderTime 47ms CodeModel.GetById 24ms 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
  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 cycle through properties
  1157. * and use {@link convert_to_array()}
  1158. *
  1159. * @return ArrayIterator
  1160. */
  1161. public function getIterator() {
  1162. // Make sure dynamic properties are retrieved prior to view properties.
  1163. $this->obtain_dynamic_data();
  1164. $ret = array();
  1165. // Do not iterate over deprecated properties.
  1166. $props = self::$standardproperties;
  1167. unset($props['groupmembersonly']);
  1168. foreach ($props as $key => $unused) {
  1169. $ret[$key] = $this->__get($key);
  1170. }
  1171. return new ArrayIterator($ret);
  1172. }
  1173. /**
  1174. * Magic method for function isset()
  1175. *
  1176. * @param string $name
  1177. * @return bool
  1178. */
  1179. public function __isset($name) {
  1180. if (isset(self::$standardproperties[$name])) {
  1181. $value = $this->__get($name);
  1182. return isset($value);
  1183. }
  1184. return false;
  1185. }
  1186. /**
  1187. * Magic method for function empty()
  1188. *
  1189. * @param string $name
  1190. * @return bool
  1191. */
  1192. public function __empty($name) {
  1193. if (isset(self::$standardproperties[$name])) {
  1194. $value = $this->__get($name);
  1195. return empty($value);
  1196. }
  1197. return true;
  1198. }
  1199. /**
  1200. * Magic method setter
  1201. *
  1202. * Will display the developer warning when trying to set/overwrite property.
  1203. *
  1204. * @param string $name
  1205. * @param mixed $value
  1206. */
  1207. public function __set($name, $value) {
  1208. debugging("It is not allowed to set the property cm_info::\${$name}", DEBUG_DEVELOPER);
  1209. }
  1210. /**
  1211. * @return bool True if this module has a 'view' page that should be linked to in navigation
  1212. * etc (note: modules may still have a view.php file, but return false if this is not
  1213. * intended to be linked to from 'normal' parts of the interface; this is what label does).
  1214. */
  1215. public function has_view() {
  1216. return !is_null($this->url);
  1217. }
  1218. /**
  1219. * Gets the URL to link to for this module.
  1220. *
  1221. * This method is normally called by the property ->url, but can be called directly if
  1222. * there is a case when it might be called recursively (you can't call property values
  1223. * recursively).
  1224. *
  1225. * @return moodle_url URL to link to for this module, or null if it doesn't have a view page
  1226. */
  1227. public function get_url() {
  1228. $this->obtain_dynamic_data();
  1229. return $this->url;
  1230. }
  1231. /**
  1232. * Obtains content to display on main (view) page.
  1233. * Note: Will collect view data, if not already obtained.
  1234. * @return string Content to display on main page below link, or empty string if none
  1235. */
  1236. private function get_content() {
  1237. $this->obtain_view_data();
  1238. return $this->content;
  1239. }
  1240. /**
  1241. * Returns the content to display on course/overview page, formatted and passed through filters
  1242. *
  1243. * if $options['context'] is not specified, the module context is used
  1244. *
  1245. * @param array|stdClass $options formatting options, see {@link format_text()}
  1246. * @return string
  1247. */
  1248. public function get_formatted_content($options = array()) {
  1249. $this->obtain_view_data();
  1250. if (empty($this->content)) {
  1251. return '';
  1252. }
  1253. if ($this->contentisformatted) {
  1254. return $this->content;
  1255. }
  1256. // Improve filter performance by preloading filter setttings for all
  1257. // activities on the course (this does nothing if called multiple
  1258. // times)
  1259. filter_preload_activities($this->get_modinfo());
  1260. $options = (array)$options;
  1261. if (!isset($options['context'])) {
  1262. $options['context'] = $this->get_context();
  1263. }
  1264. return format_text($this->content, FORMAT_HTML, $options);
  1265. }
  1266. /**
  1267. * Getter method for property $name, ensures that dynamic data is obtained.
  1268. *
  1269. * This method is normally called by the property ->name, but can be called directly if there
  1270. * is a case when it might be called recursively (you can't call property values recursively).
  1271. *
  1272. * @return string
  1273. */
  1274. public function get_name() {
  1275. $this->obtain_dynamic_data();
  1276. return $this->name;
  1277. }
  1278. /**
  1279. * Returns the name to display on course/overview page, formatted and passed through filters
  1280. *
  1281. * if $options['context'] is not specified, the module context is used
  1282. *
  1283. * @param array|stdClass $options formatting options, see {@link format_string()}
  1284. * @return string
  1285. */
  1286. public function get_formatted_name($options = array()) {
  1287. global $CFG;
  1288. $options = (array)$options;
  1289. if (!isset($options['context'])) {
  1290. $options['context'] = $this->get_context();
  1291. }
  1292. // Improve filter performance by preloading filter setttings for all
  1293. // activities on the course (this does nothing if called multiple
  1294. // times).
  1295. if (!empty($CFG->filterall)) {
  1296. filter_preload_activities($this->get_modinfo());
  1297. }
  1298. return format_string($this->get_name(), true, $options);
  1299. }
  1300. /**
  1301. * Note: Will collect view data, if not already obtained.
  1302. * @return string Extra CSS classes to add to html output for this activity on main page
  1303. */
  1304. private function get_extra_classes() {
  1305. $this->obtain_view_data();
  1306. return $this->extraclasses;
  1307. }
  1308. /**
  1309. * @return string Content of HTML on-click attribute. This string will be used literally
  1310. * as a string so should be pre-escaped.
  1311. */
  1312. private function get_on_click() {
  1313. // Does not need view data; may be used by navigation
  1314. $this->obtain_dynamic_data();
  1315. return $this->onclick;
  1316. }
  1317. /**
  1318. * Getter method for property $customdata, ensures that dynamic data is retrieved.
  1319. *
  1320. * This method is normally called by the property ->customdata, but can be called directly if there
  1321. * is a case when it might be called recursively (you can't call property values recursively).
  1322. *
  1323. * @return mixed Optional custom data stored in modinfo cache for this activity, or null if none
  1324. */
  1325. public function get_custom_data() {
  1326. $this->obtain_dynamic_data();
  1327. return $this->customdata;
  1328. }
  1329. /**
  1330. * Note: Will collect view data, if not already obtained.
  1331. * @return string Extra HTML code to display after link
  1332. */
  1333. private function get_after_link() {
  1334. $this->obtain_view_data();
  1335. return $this->afterlink;
  1336. }
  1337. /**
  1338. * Note: Will collect view data, if not already obtained.
  1339. * @return string Extra HTML code to display after editing icons (e.g. more icons)
  1340. */
  1341. private function get_after_edit_icons() {
  1342. $this->obtain_view_data();
  1343. return $this->afterediticons;
  1344. }
  1345. /**
  1346. * @param moodle_core_renderer $output Output render to use, or null for default (global)
  1347. * @return moodle_url Icon URL for a suitable icon to put beside this cm
  1348. */
  1349. public function get_icon_url($output = null) {
  1350. global $OUTPUT;
  1351. $this->obtain_dynamic_data();
  1352. if (!$output) {
  1353. $output = $OUTPUT;
  1354. }
  1355. // Support modules setting their own, external, icon image
  1356. if (!empty($this->iconurl)) {
  1357. $icon = $this->iconurl;
  1358. // Fallback to normal local icon + component procesing
  1359. } else if (!empty($this->icon)) {
  1360. if (substr($this->icon, 0, 4) === 'mod/') {
  1361. list($modname, $iconname) = explode('/', substr($this->icon, 4), 2);
  1362. $icon = $output->image_url($iconname, $modname);
  1363. } else {
  1364. if (!empty($this->iconcomponent)) {
  1365. // Icon has specified component
  1366. $icon = $output->image_url($this->icon, $this->iconcomponent);
  1367. } else {
  1368. // Icon does not have specified component, use default
  1369. $icon = $output->image_url($this->icon);
  1370. }
  1371. }
  1372. } else {
  1373. $icon = $output->image_url('icon', $this->modname);
  1374. }
  1375. return $icon;
  1376. }
  1377. /**
  1378. * @param string $textclasses additionnal classes for grouping label
  1379. * @return string An empty string or HTML grouping label span tag
  1380. */
  1381. public function get_grouping_label($textclasses = '') {
  1382. $groupinglabel = '';
  1383. if ($this->effectivegroupmode != NOGROUPS && !empty($this->groupingid) &&
  1384. has_capability('moodle/course:managegroups', context_course::instance($this->course))) {
  1385. $groupings = groups_get_all_groupings($this->course);
  1386. $groupinglabel = html_writer::tag('span', '('.format_string($groupings[$this->groupingid]->name).')',
  1387. array('class' => 'groupinglabel '.$textclasses));
  1388. }
  1389. return $groupinglabel;
  1390. }
  1391. /**
  1392. * Returns a localised human-readable name of the module type
  1393. *
  1394. * @param bool $plural return plural form
  1395. * @return string
  1396. */
  1397. public function get_module_type_name($plural = false) {
  1398. $modnames = get_module_types_names($plural);
  1399. if (isset($modnames[$this->modname])) {
  1400. return $modnames[$this->modname];
  1401. } else {
  1402. return null;
  1403. }
  1404. }
  1405. /**
  1406. * Returns a localised human-readable name of the module type in plural form - calculated on request
  1407. *
  1408. * @return string
  1409. */
  1410. private function get_module_type_name_plural() {
  1411. return $this->get_module_type_name(true);
  1412. }
  1413. /**
  1414. * @return course_modinfo Modinfo object that this came from
  1415. */
  1416. public function get_modinfo() {
  1417. return $this->modinfo;
  1418. }
  1419. /**
  1420. * Returns the section this module belongs to
  1421. *
  1422. * @return section_info
  1423. */
  1424. public function get_section_info() {
  1425. return $this->modinfo->get_section_info($this->sectionnum);
  1426. }
  1427. /**
  1428. * Returns course object that was used in the first {@link get_fast_modinfo()} call.
  1429. *
  1430. * It may not contain all fields from DB table {course} but always has at least the following:
  1431. * id,shortname,fullname,format,enablecompletion,groupmode,groupmodeforce,cacherev
  1432. *
  1433. * If the course object lacks the field you need you can use the global
  1434. * function {@link get_course()} that will save extra query if you access
  1435. * current course or frontpage course.
  1436. *
  1437. * @return stdClass
  1438. */
  1439. public function get_course() {
  1440. return $this->modinfo->get_course();
  1441. }
  1442. /**
  1443. * Returns course id for which the modinfo was generated.
  1444. *
  1445. * @return int
  1446. */
  1447. private function get_course_id() {
  1448. return $this->modinfo->get_course_id();
  1449. }
  1450. /**
  1451. * Returns group mode used for the course containing the module
  1452. *
  1453. * @return int one of constants NOGROUPS, SEPARATEGROUPS, VISIBLEGROUPS
  1454. */
  1455. private function get_course_groupmode() {
  1456. return $this->modinfo->get_course()->groupmode;
  1457. }
  1458. /**
  1459. * Returns whether group mode is forced for the course containing the module
  1460. *
  1461. * @return bool
  1462. */
  1463. private function get_course_groupmodeforce() {
  1464. return $this->modinfo->get_course()->groupmodeforce;
  1465. }
  1466. /**
  1467. * Returns effective groupmode of the module that may be overwritten by forced course groupmode.
  1468. *
  1469. * @return int one of constants NOGROUPS, SEPARATEGROUPS, VISIBLEGROUPS
  1470. */
  1471. private function get_effective_groupmode() {
  1472. $groupmode = $this->groupmode;
  1473. if ($this->modinfo->get_course()->groupmodeforce) {
  1474. $groupmode = $this->modinfo->get_course()->groupmode;
  1475. if ($groupmode != NOGROUPS && !plugin_supports('mod', $this->modname, FEATURE_GROUPS, false)) {
  1476. $groupmode = NOGROUPS;
  1477. }
  1478. }
  1479. return $groupmode;
  1480. }
  1481. /**
  1482. * @return context_module Current module context
  1483. */
  1484. private function get_context() {
  1485. return context_module::instance($this->id);
  1486. }
  1487. /**
  1488. * Returns itself in the form of stdClass.
  1489. *
  1490. * The object includes all fields that table course_modules has and additionally
  1491. * fields 'name', 'modname', 'sectionnum' (if requested).
  1492. *
  1493. * This can be used as a faster alternative to {@link get_coursemodule_from_id()}
  1494. *
  1495. * @param bool $additionalfields include additional fields 'name', 'modname', 'sectionnum'
  1496. * @return stdClass
  1497. */
  1498. public function get_course_module_record($additionalfields = false) {
  1499. $cmrecord = new stdClass();
  1500. // Standard fields from table course_modules.
  1501. static $cmfields = array('id', 'course', 'module', 'instance', 'section', 'idnumber', 'added',
  1502. 'score', 'indent', 'visible', 'visibleoncoursepage', 'visibleold', 'groupmode', 'groupingid',
  1503. 'completion', 'completiongradeitemnumber', 'completionview', 'completionexpected', 'completionpassgrade',
  1504. 'showdescription', 'availability', 'deletioninprogress');
  1505. foreach ($cmfields as $key) {
  1506. $cmrecord->$key = $this->$key;
  1507. }
  1508. // Additional fields that function get_coursemodule_from_id() adds.
  1509. if ($additionalfields) {
  1510. $cmrecord->name = $this->name;
  1511. $cmrecord->modname = $this->modname;
  1512. $cmrecord->sectionnum = $this->sectionnum;
  1513. }
  1514. return $cmrecord;
  1515. }
  1516. // Set functions
  1517. ////////////////
  1518. /**
  1519. * Sets content to display on course view page below link (if present).
  1520. * @param string $content New content as HTML string (empty string if none)
  1521. * @param bool $isformatted Whether user content is already passed through format_text/format_string and should not
  1522. * be formatted again. This can be useful when module adds interactive elements on top of formatted user text.
  1523. * @return void
  1524. */
  1525. public function set_content($content, $isformatted = false) {
  1526. $this->content = $content;
  1527. $this->contentisformatted = $isformatted;
  1528. }
  1529. /**
  1530. * Sets extra classes to include in CSS.
  1531. * @param string $extraclasses Extra classes (empty string if none)
  1532. * @return void
  1533. */
  1534. public function set_extra_classes($extraclasses) {
  1535. $this->extraclasses = $extraclasses;
  1536. }
  1537. /**
  1538. * Sets the external full url that points to the icon being used
  1539. * by the activity. Useful for external-tool modules (lti...)
  1540. * If set, takes precedence over $icon and $iconcomponent
  1541. *
  1542. * @param moodle_url $iconurl full external url pointing to icon image for activity
  1543. * @return void
  1544. */
  1545. public function set_icon_url(moodle_url $iconurl) {
  1546. $this->iconurl = $iconurl;
  1547. }
  1548. /**
  1549. * Sets value of on-click attribute for JavaScript.
  1550. * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
  1551. * @param string $onclick New onclick attribute which should be HTML-escaped
  1552. * (empty string if none)
  1553. * @return void
  1554. */
  1555. public function set_on_click($onclick) {
  1556. $this->check_not_view_only();
  1557. $this->onclick = $onclick;
  1558. }
  1559. /**
  1560. * Overrides the value of an element in the customdata array.
  1561. *
  1562. * @param string $name The key in the customdata array
  1563. * @param mixed $value The value
  1564. */
  1565. public function override_customdata($name, $value) {
  1566. if (!is_array($this->customdata)) {
  1567. $this->customdata = [];
  1568. }
  1569. $this->customdata[$name] = $value;
  1570. }
  1571. /**
  1572. * Sets HTML that displays after link on course view page.
  1573. * @param string $afterlink HTML string (empty string if none)
  1574. * @return void
  1575. */
  1576. public function set_after_link($afterlink) {
  1577. $this->afterlink = $afterlink;
  1578. }
  1579. /**
  1580. * Sets HTML that displays after edit icons on course view page.
  1581. * @param string $afterediticons HTML string (empty string if none)
  1582. * @return void
  1583. */
  1584. public function set_after_edit_icons($afterediticons) {
  1585. $this->afterediticons = $afterediticons;
  1586. }
  1587. /**
  1588. * Changes the name (text of link) for this module instance.
  1589. * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
  1590. * @param string $name Name of activity / link text
  1591. * @return void
  1592. */
  1593. public function set_name($name) {
  1594. if ($this->state < self::STATE_BUILDING_DYNAMIC) {
  1595. $this->update_user_visible();
  1596. }
  1597. $this->name = $name;
  1598. }
  1599. /**
  1600. * Turns off the view link for this module instance.
  1601. * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
  1602. * @return void
  1603. */
  1604. public function set_no_view_link() {
  1605. $this->check_not_view_only();
  1606. $this->url = null;
  1607. }
  1608. /**
  1609. * Sets the 'uservisible' flag. This can be used (by setting false) to prevent access and
  1610. * display of this module link for the current user.
  1611. * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
  1612. * @param bool $uservisible
  1613. * @return void
  1614. */
  1615. public function set_user_visible($uservisible) {
  1616. $this->check_not_view_only();
  1617. $this->uservisible = $uservisible;
  1618. }
  1619. /**
  1620. * Sets the 'available' flag and related details. This flag is normally used to make
  1621. * course modules unavailable until a certain date or condition is met. (When a course
  1622. * module is unavailable, it is still visible to users who have viewhiddenactivities
  1623. * permission.)
  1624. *
  1625. * When this is function is called, user-visible status is recalculated automatically.
  1626. *
  1627. * The $showavailability flag does not really do anything any more, but is retained
  1628. * for backward compatibility. Setting this to false will cause $availableinfo to
  1629. * be ignored.
  1630. *
  1631. * Note: May not be called from _cm_info_view (only _cm_info_dynamic).
  1632. * @param bool $available False if this item is not 'available'
  1633. * @param int $showavailability 0 = do not show this item at all if it's not available,
  1634. * 1 = show this item greyed out with the following message
  1635. * @param string $availableinfo Information about why this is not available, or
  1636. * empty string if not displaying
  1637. * @return void
  1638. */
  1639. public function set_available($available, $showavailability=0, $availableinfo='') {
  1640. $this->check_not_view_only();
  1641. $this->available = $available;
  1642. if (!$showavailability) {
  1643. $availableinfo = '';
  1644. }
  1645. $this->availableinfo = $availableinfo;
  1646. $this->update_user_visible();
  1647. }
  1648. /**
  1649. * Some set functions can only be called from _cm_info_dynamic and not _cm_info_view.
  1650. * This is because they may affect parts of this object which are used on pages other
  1651. * than the view page (e.g. in the navigation block, or when checking access on
  1652. * module pages).
  1653. * @return void
  1654. */
  1655. private function check_not_view_only() {
  1656. if ($this->state >= self::STATE_DYNAMIC) {
  1657. throw new coding_exception('Cannot set this data from _cm_info_view because it may ' .
  1658. 'affect other pages as well as view');
  1659. }
  1660. }
  1661. /**
  1662. * Constructor should not be called directly; use {@link get_fast_modinfo()}
  1663. *
  1664. * @param course_modinfo $modinfo Parent object
  1665. * @param stdClass $notused1 Argument not used
  1666. * @param stdClass $mod Module object from the modinfo field of course table
  1667. * @param stdClass $notused2 Argument not used
  1668. */
  1669. public function __construct(course_modinfo $modinfo, $notused1, $mod, $notused2) {
  1670. $this->modinfo = $modinfo;
  1671. $this->id = $mod->cm;
  1672. $this->instance = $mod->id;
  1673. $this->modname = $mod->mod;
  1674. $this->idnumber = isset($mod->idnumber) ? $mod->idnumber : '';
  1675. $this->name = $mod->name;
  1676. $this->visible = $mod->visible;
  1677. $this->visibleoncoursepage = $mod->visibleoncoursepage;
  1678. $this->sectionnum = $mod->section; // Note weirdness with name here
  1679. $this->groupmode = isset($mod->groupmode) ? $mod->groupmode : 0;
  1680. $this->groupingid = isset($mod->groupingid) ? $mod->groupingid : 0;
  1681. $this->indent = isset($mod->indent) ? $mod->indent : 0;
  1682. $this->extra = isset($mod->extra) ? $mod->extra : '';
  1683. $this->extraclasses = isset($mod->extraclasses) ? $mod->extraclasses : '';
  1684. // iconurl may be stored as either string or instance of moodle_url.
  1685. $this->iconurl = isset($mod->iconurl) ? new moodle_url($mod->iconurl) : '';
  1686. $this->onclick = isset($mod->onclick) ? $mod->onclick : '';
  1687. $this->content = isset($mod->content) ? $mod->content : '';
  1688. $this->icon = isset($mod->icon) ? $mod->icon : '';
  1689. $this->iconcomponent = isset($mod->iconcomponent) ? $mod->iconcomponent : '';
  1690. $this->customdata = isset($mod->customdata) ? $mod->customdata : '';
  1691. $this->showdescription = isset($mod->showdescription) ? $mod->showdescription : 0;
  1692. $this->state = self::STATE_BASIC;
  1693. $this->section = isset($mod->sectionid) ? $mod->sectionid : 0;
  1694. $this->module = isset($mod->module) ? $mod->module : 0;
  1695. $this->added = isset($mod->added) ? $mod->added : 0;
  1696. $this->score = isset($mod->score) ? $mod->score : 0;
  1697. $this->visibleold = isset($mod->visibleold) ? $mod->visibleold : 0;
  1698. $this->deletioninprogress = isset($mod->deletioninprogress) ? $mod->deletioninprogress : 0;
  1699. // Note: it saves effort and database space to always include the
  1700. // availability and completion fields, even if availability or completion
  1701. // are actually disabled
  1702. $this->completion = isset($mod->completion) ? $mod->completion : 0;
  1703. $this->completionpassgrade = isset($mod->completionpassgrade) ? $mod->completionpassgrade : 0;
  1704. $this->completiongradeitemnumber = isset($mod->completiongradeitemnumber)
  1705. ? $mod->completiongradeitemnumber : null;
  1706. $this->completionview = isset($mod->completionview)
  1707. ? $mod->completionview : 0;
  1708. $this->completionexpected = isset($mod->completionexpected)
  1709. ? $mod->completionexpected : 0;
  1710. $this->availability = isset($mod->availability) ? $mod->availability : null;
  1711. $this->conditionscompletion = isset($mod->conditionscompletion)
  1712. ? $mod->conditionscompletion : array();
  1713. $this->conditionsgrade = isset($mod->conditionsgrade)
  1714. ? $mod->conditionsgrade : array();
  1715. $this->conditionsfield = isset($mod->conditionsfield)
  1716. ? $mod->conditionsfield : array();
  1717. static $modviews = array();
  1718. if (!isset($modviews[$this->modname])) {
  1719. $modviews[$this->modname] = !plugin_supports('mod', $this->modname,
  1720. FEATURE_NO_VIEW_LINK);
  1721. }
  1722. $this->url = $modviews[$this->modname]
  1723. ? new moodle_url('/mod/' . $this->modname . '/view.php', array('id'=>$this->id))
  1724. : null;
  1725. }
  1726. /**
  1727. * Creates a cm_info object from a database record (also accepts cm_info
  1728. * in which case it is just returned unchanged).
  1729. *
  1730. * @param stdClass|cm_info|null|bool $cm Stdclass or cm_info (or null or false)
  1731. * @param int $userid Optional userid (default to current)
  1732. * @return cm_info|null Object as cm_info, or null if input was null/false
  1733. */
  1734. public static function create($cm, $userid = 0) {
  1735. // Null, false, etc. gets passed through as null.
  1736. if (!$cm) {
  1737. return null;
  1738. }
  1739. // If it is already a cm_info object, just return it.
  1740. if ($cm instanceof cm_info) {
  1741. return $cm;
  1742. }
  1743. // Otherwise load modinfo.
  1744. if (empty($cm->id) || empty($cm->course)) {
  1745. throw new coding_exception('$cm must contain ->id and ->course');
  1746. }
  1747. $modinfo = get_fast_modinfo($cm->course, $userid);
  1748. return $modinfo->get_cm($cm->id);
  1749. }
  1750. /**
  1751. * If dynamic data for this course-module is not yet available, gets it.
  1752. *
  1753. * This function is automatically called when requesting any course_modinfo property
  1754. * that can be modified by modules (have a set_xxx method).
  1755. *
  1756. * Dynamic data is data which does not come directly from the cache but is calculated at
  1757. * runtime based on the current user. Primarily this concerns whether the user can access
  1758. * the module or not.
  1759. *
  1760. * As part of this function, the module's _cm_info_dynamic function from its lib.php will
  1761. * be called (if it exists). Make sure that the functions that are called here do not use
  1762. * any getter magic method from cm_info.
  1763. * @return void
  1764. */
  1765. private function obtain_dynamic_data() {
  1766. global $CFG;
  1767. $userid = $this->modinfo->get_user_id();
  1768. if ($this->state >= self::STATE_BUILDING_DYNAMIC || $userid == -1) {
  1769. return;
  1770. }
  1771. $this->state = self::STATE_BUILDING_DYNAMIC;
  1772. if (!empty($CFG->enableavailability)) {
  1773. // Get availability information.
  1774. $ci = new \core_availability\info_module($this);
  1775. // Note that the modinfo currently available only includes minimal details (basic data)
  1776. // but we know that this function does not need anything more than basic data.
  1777. $this->available = $ci->is_available($this->availableinfo, true,
  1778. $userid, $this->modinfo);
  1779. } else {
  1780. $this->available = true;
  1781. }
  1782. // Check parent section.
  1783. if ($this->available) {
  1784. $parentsection = $this->modinfo->get_section_info($this->sectionnum);
  1785. if (!$parentsection->get_available()) {
  1786. // Do not store info from section here, as that is already
  1787. // presented from the section (if appropriate) - just change
  1788. // the flag
  1789. $this->available = false;
  1790. }
  1791. }
  1792. // Update visible state for current user.
  1793. $this->update_user_visible();
  1794. // Let module make dynamic changes at this point
  1795. $this->call_mod_function('cm_info_dynamic');
  1796. $this->state = self::STATE_DYNAMIC;
  1797. }
  1798. /**
  1799. * Getter method for property $uservisible, ensures that dynamic data is retrieved.
  1800. *
  1801. * This method is normally called by the property ->uservisible, but can be called directly if
  1802. * there is a case when it might be called recursively (you can't call property values
  1803. * recursively).
  1804. *
  1805. * @return bool
  1806. */
  1807. public function get_user_visible() {
  1808. $this->obtain_dynamic_data();
  1809. return $this->uservisible;
  1810. }
  1811. /**
  1812. * Returns whether this module is visible to the current user on course page
  1813. *
  1814. * Activity may be visible on the course page but not available, for example
  1815. * when it is hidden conditionally but the condition information is displayed.
  1816. *
  1817. * @return bool
  1818. */
  1819. public function is_visible_on_course_page() {
  1820. $this->obtain_dynamic_data();
  1821. return $this->uservisibleoncoursepage;
  1822. }
  1823. /**
  1824. * Whether this module is available but hidden from course page
  1825. *
  1826. * "Stealth" modules are the ones that are not shown on course page but available by following url.
  1827. * They are normally also displayed in grade reports and other reports.
  1828. * Module will be stealth either if visibleoncoursepage=0 or it is a visible module inside the hidden
  1829. * section.
  1830. *
  1831. * @return bool
  1832. */
  1833. public function is_stealth() {
  1834. return !$this->visibleoncoursepage ||
  1835. ($this->visible && ($section = $this->get_section_info()) && !$section->visible);
  1836. }
  1837. /**
  1838. * Getter method for property $available, ensures that dynamic data is retrieved
  1839. * @return bool
  1840. */
  1841. private function get_available() {
  1842. $this->obtain_dynamic_data();
  1843. return $this->available;
  1844. }
  1845. /**
  1846. * This method can not be used anymore.
  1847. *
  1848. * @see \core_availability\info_module::filter_user_list()
  1849. * @deprecated Since Moodle 2.8
  1850. */
  1851. private function get_deprecated_group_members_only() {
  1852. throw new coding_exception('$cm->groupmembersonly can not be used anymore. ' .
  1853. 'If used to restrict a list of enrolled users to only those who can ' .
  1854. 'access the module, consider \core_availability\info_module::filter_user_list.');
  1855. }
  1856. /**
  1857. * Getter method for property $availableinfo, ensures that dynamic data is retrieved
  1858. *
  1859. * @return string Available info (HTML)
  1860. */
  1861. private function get_available_info() {
  1862. $this->obtain_dynamic_data();
  1863. return $this->availableinfo;
  1864. }
  1865. /**
  1866. * Works out whether activity is available to the current user
  1867. *
  1868. * If the activity is unavailable, additional checks are required to determine if its hidden or greyed out
  1869. *
  1870. * @return void
  1871. */
  1872. private function update_user_visible() {
  1873. $userid = $this->modinfo->get_user_id();
  1874. if ($userid == -1) {
  1875. return null;
  1876. }
  1877. $this->uservisible = true;
  1878. // If the module is being deleted, set the uservisible state to false and return.
  1879. if ($this->deletioninprogress) {
  1880. $this->uservisible = false;
  1881. return null;
  1882. }
  1883. // If the user cannot access the activity set the uservisible flag to false.
  1884. // Additional checks are required to determine whether the activity is entirely hidden or just greyed out.
  1885. if ((!$this->visible && !has_capability('moodle/course:viewhiddenactivities', $this->get_context(), $userid)) ||
  1886. (!$this->get_available() &&
  1887. !has_capability('moodle/course:ignoreavailabilityrestrictions', $this->get_context(), $userid))) {
  1888. $this->uservisible = false;
  1889. }
  1890. // Check group membership.
  1891. if ($this->is_user_access_restricted_by_capability()) {
  1892. $this->uservisible = false;
  1893. // Ensure activity is completely hidden from the user.
  1894. $this->availableinfo = '';
  1895. }
  1896. $this->uservisibleoncoursepage = $this->uservisible &&
  1897. ($this->visibleoncoursepage ||
  1898. has_capability('moodle/course:manageactivities', $this->get_context(), $userid) ||
  1899. has_capability('moodle/course:activityvisibility', $this->get_context(), $userid));
  1900. // Activity that is not available, not hidden from course page and has availability
  1901. // info is actually visible on the course page (with availability info and without a link).
  1902. if (!$this->uservisible && $this->visibleoncoursepage && $this->availableinfo) {
  1903. $this->uservisibleoncoursepage = true;
  1904. }
  1905. }
  1906. /**
  1907. * This method has been deprecated and should not be used.
  1908. *
  1909. * @see $uservisible
  1910. * @deprecated Since Moodle 2.8
  1911. */
  1912. public function is_user_access_restricted_by_group() {
  1913. throw new coding_exception('cm_info::is_user_access_restricted_by_group() can not be used any more.' .
  1914. ' Use $cm->uservisible to decide whether the current user can access an activity.');
  1915. }
  1916. /**
  1917. * Checks whether mod/...:view capability restricts the current user's access.
  1918. *
  1919. * @return bool True if the user access is restricted.
  1920. */
  1921. public function is_user_access_restricted_by_capability() {
  1922. $userid = $this->modinfo->get_user_id();
  1923. if ($userid == -1) {
  1924. return null;
  1925. }
  1926. $capability = 'mod/' . $this->modname . ':view';
  1927. $capabilityinfo = get_capability_info($capability);
  1928. if (!$capabilityinfo) {
  1929. // Capability does not exist, no one is prevented from seeing the activity.
  1930. return false;
  1931. }
  1932. // You are blocked if you don't have the capability.
  1933. return !has_capability($capability, $this->get_context(), $userid);
  1934. }
  1935. /**
  1936. * Checks whether the module's conditional access settings mean that the
  1937. * user cannot see the activity at all
  1938. *
  1939. * @deprecated since 2.7 MDL-44070
  1940. */
  1941. public function is_user_access_restricted_by_conditional_access() {
  1942. throw new coding_exception('cm_info::is_user_access_restricted_by_conditional_access() ' .
  1943. 'can not be used any more; this function is not needed (use $cm->uservisible ' .
  1944. 'and $cm->availableinfo to decide whether it should be available ' .
  1945. 'or appear)');
  1946. }
  1947. /**
  1948. * Calls a module function (if exists), passing in one parameter: this object.
  1949. * @param string $type Name of function e.g. if this is 'grooblezorb' and the modname is
  1950. * 'forum' then it will try to call 'mod_forum_grooblezorb' or 'forum_grooblezorb'
  1951. * @return void
  1952. */
  1953. private function call_mod_function($type) {
  1954. global $CFG;
  1955. $libfile = $CFG->dirroot . '/mod/' . $this->modname . '/lib.php';
  1956. if (file_exists($libfile)) {
  1957. include_once($libfile);
  1958. $function = 'mod_' . $this->modname . '_' . $type;
  1959. if (function_exists($function)) {
  1960. $function($this);
  1961. } else {
  1962. $function = $this->modname . '_' . $type;
  1963. if (function_exists($function)) {
  1964. $function($this);
  1965. }
  1966. }
  1967. }
  1968. }
  1969. /**
  1970. * If view data for this course-module is not yet available, obtains it.
  1971. *
  1972. * This function is automatically called if any of the functions (marked) which require
  1973. * view data are called.
  1974. *
  1975. * View data is data which is needed only for displaying the course main page (& any similar
  1976. * functionality on other pages) but is not needed in general. Obtaining view data may have
  1977. * a performance cost.
  1978. *
  1979. * As part of this function, the module's _cm_info_view function from its lib.php will
  1980. * be called (if it exists).
  1981. * @return void
  1982. */
  1983. private function obtain_view_data() {
  1984. if ($this->state >= self::STATE_BUILDING_VIEW || $this->modinfo->get_user_id() == -1) {
  1985. return;
  1986. }
  1987. $this->obtain_dynamic_data();
  1988. $this->state = self::STATE_BUILDING_VIEW;
  1989. // Let module make changes at this point
  1990. $this->call_mod_function('cm_info_view');
  1991. $this->state = self::STATE_VIEW;
  1992. }
  1993. }
  1994. /**
  1995. * Returns reference to full info about modules in course (including visibility).
  1996. * Cached and as fast as possible (0 or 1 db query).
  1997. *
  1998. * use get_fast_modinfo($courseid, 0, true) to reset the static cache for particular course
  1999. * use get_fast_modinfo(0, 0, true) to reset the static cache for all courses
  2000. *
  2001. * use rebuild_course_cache($courseid, true) to reset the application AND static cache
  2002. * for particular course when it's contents has changed
  2003. *
  2004. * @param int|stdClass $courseorid object from DB table 'course' (must have field 'id'
  2005. * and recommended to have field 'cacherev') or just a course id. Just course id
  2006. * is enough when calling get_fast_modinfo() for current course or site or when
  2007. * calling for any other course for the second time.
  2008. * @param int $userid User id to populate 'availble' and 'uservisible' attributes of modules and sections.
  2009. * Set to 0 for current user (default). Set to -1 to avoid calculation of dynamic user-depended data.
  2010. * @param bool $resetonly whether we want to get modinfo or just reset the cache
  2011. * @return course_modinfo|null Module information for course, or null if resetting
  2012. * @throws moodle_exception when course is not found (nothing is thrown if resetting)
  2013. */
  2014. function get_fast_modinfo($courseorid, $userid = 0, $resetonly = false) {
  2015. // compartibility with syntax prior to 2.4:
  2016. if ($courseorid === 'reset') {
  2017. debugging("Using the string 'reset' as the first argument of get_fast_modinfo() is deprecated. Use get_fast_modinfo(0,0,true) instead.", DEBUG_DEVELOPER);
  2018. $courseorid = 0;
  2019. $resetonly = true;
  2020. }
  2021. // Function get_fast_modinfo() can never be called during upgrade unless it is used for clearing cache only.
  2022. if (!$resetonly) {
  2023. upgrade_ensure_not_running();
  2024. }
  2025. // Function is called with $reset = true
  2026. if ($resetonly) {
  2027. course_modinfo::clear_instance_cache($courseorid);
  2028. return null;
  2029. }
  2030. // Function is called with $reset = false, retrieve modinfo
  2031. return course_modinfo::instance($courseorid, $userid);
  2032. }
  2033. /**
  2034. * Efficiently retrieves the $course (stdclass) and $cm (cm_info) objects, given
  2035. * a cmid. If module name is also provided, it will ensure the cm is of that type.
  2036. *
  2037. * Usage:
  2038. * list($course, $cm) = get_course_and_cm_from_cmid($cmid, 'forum');
  2039. *
  2040. * Using this method has a performance advantage because it works by loading
  2041. * modinfo for the course - which will then be cached and it is needed later
  2042. * in most requests. It also guarantees that the $cm object is a cm_info and
  2043. * not a stdclass.
  2044. *
  2045. * The $course object can be supplied if already known and will speed
  2046. * up this function - although it is more efficient to use this function to
  2047. * get the course if you are starting from a cmid.
  2048. *
  2049. * To avoid security problems and obscure bugs, you should always specify
  2050. * $modulename if the cmid value came from user input.
  2051. *
  2052. * By default this obtains information (for example, whether user can access
  2053. * the activity) for current user, but you can specify a userid if required.
  2054. *
  2055. * @param stdClass|int $cmorid Id of course-module, or database object
  2056. * @param string $modulename Optional modulename (improves security)
  2057. * @param stdClass|int $courseorid Optional course object if already loaded
  2058. * @param int $userid Optional userid (default = current)
  2059. * @return array Array with 2 elements $course and $cm
  2060. * @throws moodle_exception If the item doesn't exist or is of wrong module name
  2061. */
  2062. function get_course_and_cm_from_cmid($cmorid, $modulename = '', $courseorid = 0, $userid = 0) {
  2063. global $DB;
  2064. if (is_object($cmorid)) {
  2065. $cmid = $cmorid->id;
  2066. if (isset($cmorid->course)) {
  2067. $courseid = (int)$cmorid->course;
  2068. } else {
  2069. $courseid = 0;
  2070. }
  2071. } else {
  2072. $cmid = (int)$cmorid;
  2073. $courseid = 0;
  2074. }
  2075. // Validate module name if supplied.
  2076. if ($modulename && !core_component::is_valid_plugin_name('mod', $modulename)) {
  2077. throw new coding_exception('Invalid modulename parameter');
  2078. }
  2079. // Get course from last parameter if supplied.
  2080. $course = null;
  2081. if (is_object($courseorid)) {
  2082. $course = $courseorid;
  2083. } else if ($courseorid) {
  2084. $courseid = (int)$courseorid;
  2085. }
  2086. if (!$course) {
  2087. if ($courseid) {
  2088. // If course ID is known, get it using normal function.
  2089. $course = get_course($courseid);
  2090. } else {
  2091. // Get course record in a single query based on cmid.
  2092. $course = $DB->get_record_sql("
  2093. SELECT c.*
  2094. FROM {course_modules} cm
  2095. JOIN {course} c ON c.id = cm.course
  2096. WHERE cm.id = ?", array($cmid), MUST_EXIST);
  2097. }
  2098. }
  2099. // Get cm from get_fast_modinfo.
  2100. $modinfo = get_fast_modinfo($course, $userid);
  2101. $cm = $modinfo->get_cm($cmid);
  2102. if ($modulename && $cm->modname !== $modulename) {
  2103. throw new moodle_exception('invalidcoursemodule', 'error');
  2104. }
  2105. return array($course, $cm);
  2106. }
  2107. /**
  2108. * Efficiently retrieves the $course (stdclass) and $cm (cm_info) objects, given
  2109. * an instance id or record and module name.
  2110. *
  2111. * Usage:
  2112. * list($course, $cm) = get_course_and_cm_from_instance($forum, 'forum');
  2113. *
  2114. * Using this method has a performance advantage because it works by loading
  2115. * modinfo for the course - which will then be cached and it is needed later
  2116. * in most requests. It also guarantees that the $cm object is a cm_info and
  2117. * not a stdclass.
  2118. *
  2119. * The $course object can be supplied if already known and will speed
  2120. * up this function - although it is more efficient to use this function to
  2121. * get the course if you are starting from an instance id.
  2122. *
  2123. * By default this obtains information (for example, whether user can access
  2124. * the activity) for current user, but you can specify a userid if required.
  2125. *
  2126. * @param stdclass|int $instanceorid Id of module instance, or database object
  2127. * @param string $modulename Modulename (required)
  2128. * @param stdClass|int $courseorid Optional course object if already loaded
  2129. * @param int $userid Optional userid (default = current)
  2130. * @return array Array with 2 elements $course and $cm
  2131. * @throws moodle_exception If the item doesn't exist or is of wrong module name
  2132. */
  2133. function get_course_and_cm_from_instance($instanceorid, $modulename, $courseorid = 0, $userid = 0) {
  2134. global $DB;
  2135. // Get data from parameter.
  2136. if (is_object($instanceorid)) {
  2137. $instanceid = $instanceorid->id;
  2138. if (isset($instanceorid->course)) {
  2139. $courseid = (int)$instanceorid->course;
  2140. } else {
  2141. $courseid = 0;
  2142. }
  2143. } else {
  2144. $instanceid = (int)$instanceorid;
  2145. $courseid = 0;
  2146. }
  2147. // Get course from last parameter if supplied.
  2148. $course = null;
  2149. if (is_object($courseorid)) {
  2150. $course = $courseorid;
  2151. } else if ($courseorid) {
  2152. $courseid = (int)$courseorid;
  2153. }
  2154. // Validate module name if supplied.
  2155. if (!core_component::is_valid_plugin_name('mod', $modulename)) {
  2156. throw new coding_exception('Invalid modulename parameter');
  2157. }
  2158. if (!$course) {
  2159. if ($courseid) {
  2160. // If course ID is known, get it using normal function.
  2161. $course = get_course($courseid);
  2162. } else {
  2163. // Get course record in a single query based on instance id.
  2164. $pagetable = '{' . $modulename . '}';
  2165. $course = $DB->get_record_sql("
  2166. SELECT c.*
  2167. FROM $pagetable instance
  2168. JOIN {course} c ON c.id = instance.course
  2169. WHERE instance.id = ?", array($instanceid), MUST_EXIST);
  2170. }
  2171. }
  2172. // Get cm from get_fast_modinfo.
  2173. $modinfo = get_fast_modinfo($course, $userid);
  2174. $instances = $modinfo->get_instances_of($modulename);
  2175. if (!array_key_exists($instanceid, $instances)) {
  2176. throw new moodle_exception('invalidmoduleid', 'error', $instanceid);
  2177. }
  2178. return array($course, $instances[$instanceid]);
  2179. }
  2180. /**
  2181. * Rebuilds or resets the cached list of course activities stored in MUC.
  2182. *
  2183. * rebuild_course_cache() must NEVER be called from lib/db/upgrade.php.
  2184. * At the same time course cache may ONLY be cleared using this function in
  2185. * upgrade scripts of plugins.
  2186. *
  2187. * During the bulk operations if it is necessary to reset cache of multiple
  2188. * courses it is enough to call {@link increment_revision_number()} for the
  2189. * table 'course' and field 'cacherev' specifying affected courses in select.
  2190. *
  2191. * Cached course information is stored in MUC core/coursemodinfo and is
  2192. * validated with the DB field {course}.cacherev
  2193. *
  2194. * @global moodle_database $DB
  2195. * @param int $courseid id of course to rebuild, empty means all
  2196. * @param boolean $clearonly only clear the cache, gets rebuild automatically on the fly.
  2197. * Recommended to set to true to avoid unnecessary multiple rebuilding.
  2198. */
  2199. function rebuild_course_cache($courseid=0, $clearonly=false) {
  2200. global $COURSE, $SITE, $DB, $CFG;
  2201. // Function rebuild_course_cache() can not be called during upgrade unless it's clear only.
  2202. if (!$clearonly && !upgrade_ensure_not_running(true)) {
  2203. $clearonly = true;
  2204. }
  2205. // Destroy navigation caches
  2206. navigation_cache::destroy_volatile_caches();
  2207. core_courseformat\base::reset_course_cache($courseid);
  2208. $cachecoursemodinfo = cache::make('core', 'coursemodinfo');
  2209. if (empty($courseid)) {
  2210. // Clearing caches for all courses.
  2211. increment_revision_number('course', 'cacherev', '');
  2212. $cachecoursemodinfo->purge();
  2213. course_modinfo::clear_instance_cache();
  2214. // Update global values too.
  2215. $sitecacherev = $DB->get_field('course', 'cacherev', array('id' => SITEID));
  2216. $SITE->cachrev = $sitecacherev;
  2217. if ($COURSE->id == SITEID) {
  2218. $COURSE->cacherev = $sitecacherev;
  2219. } else {
  2220. $COURSE->cacherev = $DB->get_field('course', 'cacherev', array('id' => $COURSE->id));
  2221. }
  2222. } else {
  2223. // Clearing cache for one course, make sure it is deleted from user request cache as well.
  2224. increment_revision_number('course', 'cacherev', 'id = :id', array('id' => $courseid));
  2225. $cachecoursemodinfo->delete($courseid);
  2226. course_modinfo::clear_instance_cache($courseid);
  2227. // Update global values too.
  2228. if ($courseid == $COURSE->id || $courseid == $SITE->id) {
  2229. $cacherev = $DB->get_field('course', 'cacherev', array('id' => $courseid));
  2230. if ($courseid == $COURSE->id) {
  2231. $COURSE->cacherev = $cacherev;
  2232. }
  2233. if ($courseid == $SITE->id) {
  2234. $SITE->cachrev = $cacherev;
  2235. }
  2236. }
  2237. }
  2238. if ($clearonly) {
  2239. return;
  2240. }
  2241. if ($courseid) {
  2242. $select = array('id'=>$courseid);
  2243. } else {
  2244. $select = array();
  2245. core_php_time_limit::raise(); // this could take a while! MDL-10954
  2246. }
  2247. $rs = $DB->get_recordset("course", $select,'','id,'.join(',', course_modinfo::$cachedfields));
  2248. // Rebuild cache for each course.
  2249. foreach ($rs as $course) {
  2250. course_modinfo::build_course_cache($course);
  2251. }
  2252. $rs->close();
  2253. }
  2254. /**
  2255. * Class that is the return value for the _get_coursemodule_info module API function.
  2256. *
  2257. * Note: For backward compatibility, you can also return a stdclass object from that function.
  2258. * The difference is that the stdclass object may contain an 'extra' field (deprecated,
  2259. * use extraclasses and onclick instead). The stdclass object may not contain
  2260. * the new fields defined here (content, extraclasses, customdata).
  2261. */
  2262. class cached_cm_info {
  2263. /**
  2264. * Name (text of link) for this activity; Leave unset to accept default name
  2265. * @var string
  2266. */
  2267. public $name;
  2268. /**
  2269. * Name of icon for this activity. Normally, this should be used together with $iconcomponent
  2270. * to define the icon, as per image_url function.
  2271. * For backward compatibility, if this value is of the form 'mod/forum/icon' then an icon
  2272. * within that module will be used.
  2273. * @see cm_info::get_icon_url()
  2274. * @see renderer_base::image_url()
  2275. * @var string
  2276. */
  2277. public $icon;
  2278. /**
  2279. * Component for icon for this activity, as per image_url; leave blank to use default 'moodle'
  2280. * component
  2281. * @see renderer_base::image_url()
  2282. * @var string
  2283. */
  2284. public $iconcomponent;
  2285. /**
  2286. * HTML content to be displayed on the main page below the link (if any) for this course-module
  2287. * @var string
  2288. */
  2289. public $content;
  2290. /**
  2291. * Custom data to be stored in modinfo for this activity; useful if there are cases when
  2292. * internal information for this activity type needs to be accessible from elsewhere on the
  2293. * course without making database queries. May be of any type but should be short.
  2294. * @var mixed
  2295. */
  2296. public $customdata;
  2297. /**
  2298. * Extra CSS class or classes to be added when this activity is displayed on the main page;
  2299. * space-separated string
  2300. * @var string
  2301. */
  2302. public $extraclasses;
  2303. /**
  2304. * External URL image to be used by activity as icon, useful for some external-tool modules
  2305. * like lti. If set, takes precedence over $icon and $iconcomponent
  2306. * @var $moodle_url
  2307. */
  2308. public $iconurl;
  2309. /**
  2310. * Content of onclick JavaScript; escaped HTML to be inserted as attribute value
  2311. * @var string
  2312. */
  2313. public $onclick;
  2314. }
  2315. /**
  2316. * Data about a single section on a course. This contains the fields from the
  2317. * course_sections table, plus additional data when required.
  2318. *
  2319. * @property-read int $id Section ID - from course_sections table
  2320. * @property-read int $course Course ID - from course_sections table
  2321. * @property-read int $section Section number - from course_sections table
  2322. * @property-read string $name Section name if specified - from course_sections table
  2323. * @property-read int $visible Section visibility (1 = visible) - from course_sections table
  2324. * @property-read string $summary Section summary text if specified - from course_sections table
  2325. * @property-read int $summaryformat Section summary text format (FORMAT_xx constant) - from course_sections table
  2326. * @property-read string $availability Availability information as JSON string -
  2327. * from course_sections table
  2328. * @property-read array $conditionscompletion Availability conditions for this section based on the completion of
  2329. * course-modules (array from course-module id to required completion state
  2330. * for that module) - from cached data in sectioncache field
  2331. * @property-read array $conditionsgrade Availability conditions for this section based on course grades (array from
  2332. * grade item id to object with ->min, ->max fields) - from cached data in
  2333. * sectioncache field
  2334. * @property-read array $conditionsfield Availability conditions for this section based on user fields
  2335. * @property-read bool $available True if this section is available to the given user i.e. if all availability conditions
  2336. * are met - obtained dynamically
  2337. * @property-read string $availableinfo If section is not available to some users, this string gives information about
  2338. * availability which can be displayed to students and/or staff (e.g. 'Available from 3 January 2010')
  2339. * for display on main page - obtained dynamically
  2340. * @property-read bool $uservisible True if this section is available to the given user (for example, if current user
  2341. * has viewhiddensections capability, they can access the section even if it is not
  2342. * visible or not available, so this would be true in that case) - obtained dynamically
  2343. * @property-read string $sequence Comma-separated list of all modules in the section. Note, this field may not exactly
  2344. * match course_sections.sequence if later has references to non-existing modules or not modules of not available module types.
  2345. * @property-read course_modinfo $modinfo
  2346. */
  2347. class section_info implements IteratorAggregate {
  2348. /**
  2349. * Section ID - from course_sections table
  2350. * @var int
  2351. */
  2352. private $_id;
  2353. /**
  2354. * Section number - from course_sections table
  2355. * @var int
  2356. */
  2357. private $_section;
  2358. /**
  2359. * Section name if specified - from course_sections table
  2360. * @var string
  2361. */
  2362. private $_name;
  2363. /**
  2364. * Section visibility (1 = visible) - from course_sections table
  2365. * @var int
  2366. */
  2367. private $_visible;
  2368. /**
  2369. * Section summary text if specified - from course_sections table
  2370. * @var string
  2371. */
  2372. private $_summary;
  2373. /**
  2374. * Section summary text format (FORMAT_xx constant) - from course_sections table
  2375. * @var int
  2376. */
  2377. private $_summaryformat;
  2378. /**
  2379. * Availability information as JSON string - from course_sections table
  2380. * @var string
  2381. */
  2382. private $_availability;
  2383. /**
  2384. * Availability conditions for this section based on the completion of
  2385. * course-modules (array from course-module id to required completion state
  2386. * for that module) - from cached data in sectioncache field
  2387. * @var array
  2388. */
  2389. private $_conditionscompletion;
  2390. /**
  2391. * Availability conditions for this section based on course grades (array from
  2392. * grade item id to object with ->min, ->max fields) - from cached data in
  2393. * sectioncache field
  2394. * @var array
  2395. */
  2396. private $_conditionsgrade;
  2397. /**
  2398. * Availability conditions for this section based on user fields
  2399. * @var array
  2400. */
  2401. private $_conditionsfield;
  2402. /**
  2403. * True if this section is available to students i.e. if all availability conditions
  2404. * are met - obtained dynamically on request, see function {@link section_info::get_available()}
  2405. * @var bool|null
  2406. */
  2407. private $_available;
  2408. /**
  2409. * If section is not available to some users, this string gives information about
  2410. * availability which can be displayed to students and/or staff (e.g. 'Available from 3
  2411. * January 2010') for display on main page - obtained dynamically on request, see
  2412. * function {@link section_info::get_availableinfo()}
  2413. * @var string
  2414. */
  2415. private $_availableinfo;
  2416. /**
  2417. * True if this section is available to the CURRENT user (for example, if current user
  2418. * has viewhiddensections capability, they can access the section even if it is not
  2419. * visible or not available, so this would be true in that case) - obtained dynamically
  2420. * on request, see function {@link section_info::get_uservisible()}
  2421. * @var bool|null
  2422. */
  2423. private $_uservisible;
  2424. /**
  2425. * Default values for sectioncache fields; if a field has this value, it won't
  2426. * be stored in the sectioncache cache, to save space. Checks are done by ===
  2427. * which means values must all be strings.
  2428. * @var array
  2429. */
  2430. private static $sectioncachedefaults = array(
  2431. 'name' => null,
  2432. 'summary' => '',
  2433. 'summaryformat' => '1', // FORMAT_HTML, but must be a string
  2434. 'visible' => '1',
  2435. 'availability' => null
  2436. );
  2437. /**
  2438. * Stores format options that have been cached when building 'coursecache'
  2439. * When the format option is requested we look first if it has been cached
  2440. * @var array
  2441. */
  2442. private $cachedformatoptions = array();
  2443. /**
  2444. * Stores the list of all possible section options defined in each used course format.
  2445. * @var array
  2446. */
  2447. static private $sectionformatoptions = array();
  2448. /**
  2449. * Stores the modinfo object passed in constructor, may be used when requesting
  2450. * dynamically obtained attributes such as available, availableinfo, uservisible.
  2451. * Also used to retrun information about current course or user.
  2452. * @var course_modinfo
  2453. */
  2454. private $modinfo;
  2455. /**
  2456. * Constructs object from database information plus extra required data.
  2457. * @param object $data Array entry from cached sectioncache
  2458. * @param int $number Section number (array key)
  2459. * @param int $notused1 argument not used (informaion is available in $modinfo)
  2460. * @param int $notused2 argument not used (informaion is available in $modinfo)
  2461. * @param course_modinfo $modinfo Owner (needed for checking availability)
  2462. * @param int $notused3 argument not used (informaion is available in $modinfo)
  2463. */
  2464. public function __construct($data, $number, $notused1, $notused2, $modinfo, $notused3) {
  2465. global $CFG;
  2466. require_once($CFG->dirroot.'/course/lib.php');
  2467. // Data that is always present
  2468. $this->_id = $data->id;
  2469. $defaults = self::$sectioncachedefaults +
  2470. array('conditionscompletion' => array(),
  2471. 'conditionsgrade' => array(),
  2472. 'conditionsfield' => array());
  2473. // Data that may use default values to save cache size
  2474. foreach ($defaults as $field => $value) {
  2475. if (isset($data->{$field})) {
  2476. $this->{'_'.$field} = $data->{$field};
  2477. } else {
  2478. $this->{'_'.$field} = $value;
  2479. }
  2480. }
  2481. // Other data from constructor arguments.
  2482. $this->_section = $number;
  2483. $this->modinfo = $modinfo;
  2484. // Cached course format data.
  2485. $course = $modinfo->get_course();
  2486. if (!isset(self::$sectionformatoptions[$course->format])) {
  2487. // Store list of section format options defined in each used course format.
  2488. // They do not depend on particular course but only on its format.
  2489. self::$sectionformatoptions[$course->format] =
  2490. course_get_format($course)->section_format_options();
  2491. }
  2492. foreach (self::$sectionformatoptions[$course->format] as $field => $option) {
  2493. if (!empty($option['cache'])) {
  2494. if (isset($data->{$field})) {
  2495. $this->cachedformatoptions[$field] = $data->{$field};
  2496. } else if (array_key_exists('cachedefault', $option)) {
  2497. $this->cachedformatoptions[$field] = $option['cachedefault'];
  2498. }
  2499. }
  2500. }
  2501. }
  2502. /**
  2503. * Magic method to check if the property is set
  2504. *
  2505. * @param string $name name of the property
  2506. * @return bool
  2507. */
  2508. public function __isset($name) {
  2509. if (method_exists($this, 'get_'.$name) ||
  2510. property_exists($this, '_'.$name) ||
  2511. array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
  2512. $value = $this->__get($name);
  2513. return isset($value);
  2514. }
  2515. return false;
  2516. }
  2517. /**
  2518. * Magic method to check if the property is empty
  2519. *
  2520. * @param string $name name of the property
  2521. * @return bool
  2522. */
  2523. public function __empty($name) {
  2524. if (method_exists($this, 'get_'.$name) ||
  2525. property_exists($this, '_'.$name) ||
  2526. array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
  2527. $value = $this->__get($name);
  2528. return empty($value);
  2529. }
  2530. return true;
  2531. }
  2532. /**
  2533. * Magic method to retrieve the property, this is either basic section property
  2534. * or availability information or additional properties added by course format
  2535. *
  2536. * @param string $name name of the property
  2537. * @return bool
  2538. */
  2539. public function __get($name) {
  2540. if (method_exists($this, 'get_'.$name)) {
  2541. return $this->{'get_'.$name}();
  2542. }
  2543. if (property_exists($this, '_'.$name)) {
  2544. return $this->{'_'.$name};
  2545. }
  2546. if (array_key_exists($name, $this->cachedformatoptions)) {
  2547. return $this->cachedformatoptions[$name];
  2548. }
  2549. // precheck if the option is defined in format to avoid unnecessary DB queries in get_format_options()
  2550. if (array_key_exists($name, self::$sectionformatoptions[$this->modinfo->get_course()->format])) {
  2551. $formatoptions = course_get_format($this->modinfo->get_course())->get_format_options($this);
  2552. return $formatoptions[$name];
  2553. }
  2554. debugging('Invalid section_info property accessed! '.$name);
  2555. return null;
  2556. }
  2557. /**
  2558. * Finds whether this section is available at the moment for the current user.
  2559. *
  2560. * The value can be accessed publicly as $sectioninfo->available, but can be called directly if there
  2561. * is a case when it might be called recursively (you can't call property values recursively).
  2562. *
  2563. * @return bool
  2564. */
  2565. public function get_available() {
  2566. global $CFG;
  2567. $userid = $this->modinfo->get_user_id();
  2568. if ($this->_available !== null || $userid == -1) {
  2569. // Has already been calculated or does not need calculation.
  2570. return $this->_available;
  2571. }
  2572. $this->_available = true;
  2573. $this->_availableinfo = '';
  2574. if (!empty($CFG->enableavailability)) {
  2575. // Get availability information.
  2576. $ci = new \core_availability\info_section($this);
  2577. $this->_available = $ci->is_available($this->_availableinfo, true,
  2578. $userid, $this->modinfo);
  2579. }
  2580. // Execute the hook from the course format that may override the available/availableinfo properties.
  2581. $currentavailable = $this->_available;
  2582. course_get_format($this->modinfo->get_course())->
  2583. section_get_available_hook($this, $this->_available, $this->_availableinfo);
  2584. if (!$currentavailable && $this->_available) {
  2585. debugging('section_get_available_hook() can not make unavailable section available', DEBUG_DEVELOPER);
  2586. $this->_available = $currentavailable;
  2587. }
  2588. return $this->_available;
  2589. }
  2590. /**
  2591. * Returns the availability text shown next to the section on course page.
  2592. *
  2593. * @return string
  2594. */
  2595. private function get_availableinfo() {
  2596. // Calling get_available() will also fill the availableinfo property
  2597. // (or leave it null if there is no userid).
  2598. $this->get_available();
  2599. return $this->_availableinfo;
  2600. }
  2601. /**
  2602. * Implementation of IteratorAggregate::getIterator(), allows to cycle through properties
  2603. * and use {@link convert_to_array()}
  2604. *
  2605. * @return ArrayIterator
  2606. */
  2607. public function getIterator() {
  2608. $ret = array();
  2609. foreach (get_object_vars($this) as $key => $value) {
  2610. if (substr($key, 0, 1) == '_') {
  2611. if (method_exists($this, 'get'.$key)) {
  2612. $ret[substr($key, 1)] = $this->{'get'.$key}();
  2613. } else {
  2614. $ret[substr($key, 1)] = $this->$key;
  2615. }
  2616. }
  2617. }
  2618. $ret['sequence'] = $this->get_sequence();
  2619. $ret['course'] = $this->get_course();
  2620. $ret = array_merge($ret, course_get_format($this->modinfo->get_course())->get_format_options($this->_section));
  2621. return new ArrayIterator($ret);
  2622. }
  2623. /**
  2624. * Works out whether activity is visible *for current user* - if this is false, they
  2625. * aren't allowed to access it.
  2626. *
  2627. * @return bool
  2628. */
  2629. private function get_uservisible() {
  2630. $userid = $this->modinfo->get_user_id();
  2631. if ($this->_uservisible !== null || $userid == -1) {
  2632. // Has already been calculated or does not need calculation.
  2633. return $this->_uservisible;
  2634. }
  2635. $this->_uservisible = true;
  2636. if (!$this->_visible || !$this->get_available()) {
  2637. $coursecontext = context_course::instance($this->get_course());
  2638. if (!$this->_visible && !has_capability('moodle/course:viewhiddensections', $coursecontext, $userid) ||
  2639. (!$this->get_available() &&
  2640. !has_capability('moodle/course:ignoreavailabilityrestrictions', $coursecontext, $userid))) {
  2641. $this->_uservisible = false;
  2642. }
  2643. }
  2644. return $this->_uservisible;
  2645. }
  2646. /**
  2647. * Restores the course_sections.sequence value
  2648. *
  2649. * @return string
  2650. */
  2651. private function get_sequence() {
  2652. if (!empty($this->modinfo->sections[$this->_section])) {
  2653. return implode(',', $this->modinfo->sections[$this->_section]);
  2654. } else {
  2655. return '';
  2656. }
  2657. }
  2658. /**
  2659. * Returns course ID - from course_sections table
  2660. *
  2661. * @return int
  2662. */
  2663. private function get_course() {
  2664. return $this->modinfo->get_course_id();
  2665. }
  2666. /**
  2667. * Modinfo object
  2668. *
  2669. * @return course_modinfo
  2670. */
  2671. private function get_modinfo() {
  2672. return $this->modinfo;
  2673. }
  2674. /**
  2675. * Prepares section data for inclusion in sectioncache cache, removing items
  2676. * that are set to defaults, and adding availability data if required.
  2677. *
  2678. * Called by build_section_cache in course_modinfo only; do not use otherwise.
  2679. * @param object $section Raw section data object
  2680. */
  2681. public static function convert_for_section_cache($section) {
  2682. global $CFG;
  2683. // Course id stored in course table
  2684. unset($section->course);
  2685. // Section number stored in array key
  2686. unset($section->section);
  2687. // Sequence stored implicity in modinfo $sections array
  2688. unset($section->sequence);
  2689. // Remove default data
  2690. foreach (self::$sectioncachedefaults as $field => $value) {
  2691. // Exact compare as strings to avoid problems if some strings are set
  2692. // to "0" etc.
  2693. if (isset($section->{$field}) && $section->{$field} === $value) {
  2694. unset($section->{$field});
  2695. }
  2696. }
  2697. }
  2698. }