PageRenderTime 67ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/modinfolib.php

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