[ Index ]

PHP Cross Reference of Unnamed Project

title

Body

[close]

/lib/ -> modinfolib.php (source)

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


Generated: Thu Aug 11 10:00:09 2016 Cross-referenced by PHPXref 0.7.1