Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 3.9.x will end* 10 May 2021 (12 months).
  • Bug fixes for security issues in 3.9.x will end* 8 May 2023 (36 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.

Differences Between: [Versions 39 and 310] [Versions 39 and 311] [Versions 39 and 400] [Versions 39 and 401] [Versions 39 and 402] [Versions 39 and 403]

   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   * Base class for conditional availability information (for module or section).
  19   *
  20   * @package core_availability
  21   * @copyright 2014 The Open University
  22   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23   */
  24  
  25  namespace core_availability;
  26  
  27  defined('MOODLE_INTERNAL') || die();
  28  
  29  /**
  30   * Base class for conditional availability information (for module or section).
  31   *
  32   * @package core_availability
  33   * @copyright 2014 The Open University
  34   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  35   */
  36  abstract class info {
  37      /** @var \stdClass Course */
  38      protected $course;
  39  
  40      /** @var \course_modinfo Modinfo (available only during some functions) */
  41      protected $modinfo = null;
  42  
  43      /** @var bool Visibility flag (eye icon) */
  44      protected $visible;
  45  
  46      /** @var string Availability data as JSON string */
  47      protected $availability;
  48  
  49      /** @var tree Availability configuration, decoded from JSON; null if unset */
  50      protected $availabilitytree;
  51  
  52      /** @var array|null Array of information about current restore if any */
  53      protected static $restoreinfo = null;
  54  
  55      /**
  56       * Constructs with item details.
  57       *
  58       * @param \stdClass $course Course object
  59       * @param int $visible Value of visible flag (eye icon)
  60       * @param string $availability Availability definition (JSON format) or null
  61       * @throws \coding_exception If data is not valid JSON format
  62       */
  63      public function __construct($course, $visible, $availability) {
  64          // Set basic values.
  65          $this->course = $course;
  66          $this->visible = (bool)$visible;
  67          $this->availability = $availability;
  68      }
  69  
  70      /**
  71       * Obtains the course associated with this availability information.
  72       *
  73       * @return \stdClass Moodle course object
  74       */
  75      public function get_course() {
  76          return $this->course;
  77      }
  78  
  79      /**
  80       * Gets context used for checking capabilities for this item.
  81       *
  82       * @return \context Context for this item
  83       */
  84      public abstract function get_context();
  85  
  86      /**
  87       * Obtains the modinfo associated with this availability information.
  88       *
  89       * Note: This field is available ONLY for use by conditions when calculating
  90       * availability or information.
  91       *
  92       * @return \course_modinfo Modinfo
  93       * @throws \coding_exception If called at incorrect times
  94       */
  95      public function get_modinfo() {
  96          if (!$this->modinfo) {
  97              throw new \coding_exception(
  98                      'info::get_modinfo available only during condition checking');
  99          }
 100          return $this->modinfo;
 101      }
 102  
 103      /**
 104       * Gets the availability tree, decoding it if not already done.
 105       *
 106       * @return tree Availability tree
 107       */
 108      public function get_availability_tree() {
 109          if (is_null($this->availabilitytree)) {
 110              if (is_null($this->availability)) {
 111                  throw new \coding_exception(
 112                          'Cannot call get_availability_tree with null availability');
 113              }
 114              $this->availabilitytree = $this->decode_availability($this->availability, true);
 115          }
 116          return $this->availabilitytree;
 117      }
 118  
 119      /**
 120       * Decodes availability data from JSON format.
 121       *
 122       * This function also validates the retrieved data as follows:
 123       * 1. Data that does not meet the API-defined structure causes a
 124       *    coding_exception (this should be impossible unless there is
 125       *    a system bug or somebody manually hacks the database).
 126       * 2. Data that meets the structure but cannot be implemented (e.g.
 127       *    reference to missing plugin or to module that doesn't exist) is
 128       *    either silently discarded (if $lax is true) or causes a
 129       *    coding_exception (if $lax is false).
 130       *
 131       * @param string $availability Availability string in JSON format
 132       * @param boolean $lax If true, throw exceptions only for invalid structure
 133       * @return tree Availability tree
 134       * @throws \coding_exception If data is not valid JSON format
 135       */
 136      protected function decode_availability($availability, $lax) {
 137          // Decode JSON data.
 138          $structure = json_decode($availability);
 139          if (is_null($structure)) {
 140              throw new \coding_exception('Invalid availability text', $availability);
 141          }
 142  
 143          // Recursively decode tree.
 144          return new tree($structure, $lax);
 145      }
 146  
 147      /**
 148       * Determines whether this particular item is currently available
 149       * according to the availability criteria.
 150       *
 151       * - This does not include the 'visible' setting (i.e. this might return
 152       *   true even if visible is false); visible is handled independently.
 153       * - This does not take account of the viewhiddenactivities capability.
 154       *   That should apply later.
 155       *
 156       * Depending on options selected, a description of the restrictions which
 157       * mean the student can't view it (in HTML format) may be stored in
 158       * $information. If there is nothing in $information and this function
 159       * returns false, then the activity should not be displayed at all.
 160       *
 161       * This function displays debugging() messages if the availability
 162       * information is invalid.
 163       *
 164       * @param string $information String describing restrictions in HTML format
 165       * @param bool $grabthelot Performance hint: if true, caches information
 166       *   required for all course-modules, to make the front page and similar
 167       *   pages work more quickly (works only for current user)
 168       * @param int $userid If set, specifies a different user ID to check availability for
 169       * @param \course_modinfo $modinfo Usually leave as null for default. Specify when
 170       *   calling recursively from inside get_fast_modinfo()
 171       * @return bool True if this item is available to the user, false otherwise
 172       */
 173      public function is_available(&$information, $grabthelot = false, $userid = 0,
 174              \course_modinfo $modinfo = null) {
 175          global $USER;
 176  
 177          // Default to no information.
 178          $information = '';
 179  
 180          // Do nothing if there are no availability restrictions.
 181          if (is_null($this->availability)) {
 182              return true;
 183          }
 184  
 185          // Resolve optional parameters.
 186          if (!$userid) {
 187              $userid = $USER->id;
 188          }
 189          if (!$modinfo) {
 190              $modinfo = get_fast_modinfo($this->course, $userid);
 191          }
 192          $this->modinfo = $modinfo;
 193  
 194          // Get availability from tree.
 195          try {
 196              $tree = $this->get_availability_tree();
 197              $result = $tree->check_available(false, $this, $grabthelot, $userid);
 198          } catch (\coding_exception $e) {
 199              $this->warn_about_invalid_availability($e);
 200              $this->modinfo = null;
 201              return false;
 202          }
 203  
 204          // See if there are any messages.
 205          if ($result->is_available()) {
 206              $this->modinfo = null;
 207              return true;
 208          } else {
 209              // If the item is marked as 'not visible' then we don't change the available
 210              // flag (visible/available are treated distinctly), but we remove any
 211              // availability info. If the item is hidden with the eye icon, it doesn't
 212              // make sense to show 'Available from <date>' or similar, because even
 213              // when that date arrives it will still not be available unless somebody
 214              // toggles the eye icon.
 215              if ($this->visible) {
 216                  $information = $tree->get_result_information($this, $result);
 217              }
 218  
 219              $this->modinfo = null;
 220              return false;
 221          }
 222      }
 223  
 224      /**
 225       * Checks whether this activity is going to be available for all users.
 226       *
 227       * Normally, if there are any conditions, then it may be hidden depending
 228       * on the user. However in the case of date conditions there are some
 229       * conditions which will definitely not result in it being hidden for
 230       * anyone.
 231       *
 232       * @return bool True if activity is available for all
 233       */
 234      public function is_available_for_all() {
 235          if (is_null($this->availability)) {
 236              return true;
 237          } else {
 238              try {
 239                  return $this->get_availability_tree()->is_available_for_all();
 240              } catch (\coding_exception $e) {
 241                  $this->warn_about_invalid_availability($e);
 242                  return false;
 243              }
 244          }
 245      }
 246  
 247      /**
 248       * Obtains a string describing all availability restrictions (even if
 249       * they do not apply any more). Used to display information for staff
 250       * editing the website.
 251       *
 252       * The modinfo parameter must be specified when it is called from inside
 253       * get_fast_modinfo, to avoid infinite recursion.
 254       *
 255       * This function displays debugging() messages if the availability
 256       * information is invalid.
 257       *
 258       * @param \course_modinfo $modinfo Usually leave as null for default
 259       * @return string Information string (for admin) about all restrictions on
 260       *   this item
 261       */
 262      public function get_full_information(\course_modinfo $modinfo = null) {
 263          // Do nothing if there are no availability restrictions.
 264          if (is_null($this->availability)) {
 265              return '';
 266          }
 267  
 268          // Resolve optional parameter.
 269          if (!$modinfo) {
 270              $modinfo = get_fast_modinfo($this->course);
 271          }
 272          $this->modinfo = $modinfo;
 273  
 274          try {
 275              $result = $this->get_availability_tree()->get_full_information($this);
 276              $this->modinfo = null;
 277              return $result;
 278          } catch (\coding_exception $e) {
 279              $this->warn_about_invalid_availability($e);
 280              return false;
 281          }
 282      }
 283  
 284      /**
 285       * In some places we catch coding_exception because if a bug happens, it
 286       * would be fatal for the course page GUI; instead we just show a developer
 287       * debug message.
 288       *
 289       * @param \coding_exception $e Exception that occurred
 290       */
 291      protected function warn_about_invalid_availability(\coding_exception $e) {
 292          $name = $this->get_thing_name();
 293          $htmlname = $this->format_info($name, $this->course);
 294          // Because we call format_info here, likely in the middle of building dynamic data for the
 295          // activity, there could be a chance that the name might not be available.
 296          if ($htmlname === '') {
 297              // So instead use the numbers (cmid) from the tag.
 298              $htmlname = preg_replace('~[^0-9]~', '', $name);
 299          }
 300          $info = 'Error processing availability data for &lsquo;' . $htmlname
 301                   . '&rsquo;: ' . s($e->a);
 302          debugging($info, DEBUG_DEVELOPER);
 303      }
 304  
 305      /**
 306       * Called during restore (near end of restore). Updates any necessary ids
 307       * and writes the updated tree to the database. May output warnings if
 308       * necessary (e.g. if a course-module cannot be found after restore).
 309       *
 310       * @param string $restoreid Restore identifier
 311       * @param int $courseid Target course id
 312       * @param \base_logger $logger Logger for any warnings
 313       * @param int $dateoffset Date offset to be added to any dates (0 = none)
 314       * @param \base_task $task Restore task
 315       */
 316      public function update_after_restore($restoreid, $courseid, \base_logger $logger,
 317              $dateoffset, \base_task $task) {
 318          $tree = $this->get_availability_tree();
 319          // Set static data for use by get_restore_date_offset function.
 320          self::$restoreinfo = array('restoreid' => $restoreid, 'dateoffset' => $dateoffset,
 321                  'task' => $task);
 322          $changed = $tree->update_after_restore($restoreid, $courseid, $logger,
 323                  $this->get_thing_name());
 324          if ($changed) {
 325              // Save modified data.
 326              if ($tree->is_empty()) {
 327                  // If the tree is empty, but the tree has changed, remove this condition.
 328                  $this->set_in_database(null);
 329              } else {
 330                  $structure = $tree->save();
 331                  $this->set_in_database(json_encode($structure));
 332              }
 333          }
 334      }
 335  
 336      /**
 337       * Gets the date offset (amount by which any date values should be
 338       * adjusted) for the current restore.
 339       *
 340       * @param string $restoreid Restore identifier
 341       * @return int Date offset (0 if none)
 342       * @throws coding_exception If not in a restore (or not in that restore)
 343       */
 344      public static function get_restore_date_offset($restoreid) {
 345          if (!self::$restoreinfo) {
 346              throw new coding_exception('Only valid during restore');
 347          }
 348          if (self::$restoreinfo['restoreid'] !== $restoreid) {
 349              throw new coding_exception('Data not available for that restore id');
 350          }
 351          return self::$restoreinfo['dateoffset'];
 352      }
 353  
 354      /**
 355       * Gets the restore task (specifically, the task that calls the
 356       * update_after_restore method) for the current restore.
 357       *
 358       * @param string $restoreid Restore identifier
 359       * @return \base_task Restore task
 360       * @throws coding_exception If not in a restore (or not in that restore)
 361       */
 362      public static function get_restore_task($restoreid) {
 363          if (!self::$restoreinfo) {
 364              throw new coding_exception('Only valid during restore');
 365          }
 366          if (self::$restoreinfo['restoreid'] !== $restoreid) {
 367              throw new coding_exception('Data not available for that restore id');
 368          }
 369          return self::$restoreinfo['task'];
 370      }
 371  
 372      /**
 373       * Obtains the name of the item (cm_info or section_info, at present) that
 374       * this is controlling availability of. Name should be formatted ready
 375       * for on-screen display.
 376       *
 377       * @return string Name of item
 378       */
 379      protected abstract function get_thing_name();
 380  
 381      /**
 382       * Stores an updated availability tree JSON structure into the relevant
 383       * database table.
 384       *
 385       * @param string $availabilty New JSON value
 386       */
 387      protected abstract function set_in_database($availabilty);
 388  
 389      /**
 390       * In rare cases the system may want to change all references to one ID
 391       * (e.g. one course-module ID) to another one, within a course. This
 392       * function does that for the conditional availability data for all
 393       * modules and sections on the course.
 394       *
 395       * @param int|\stdClass $courseorid Course id or object
 396       * @param string $table Table name e.g. 'course_modules'
 397       * @param int $oldid Previous ID
 398       * @param int $newid New ID
 399       * @return bool True if anything changed, otherwise false
 400       */
 401      public static function update_dependency_id_across_course(
 402              $courseorid, $table, $oldid, $newid) {
 403          global $DB;
 404          $transaction = $DB->start_delegated_transaction();
 405          $modinfo = get_fast_modinfo($courseorid);
 406          $anychanged = false;
 407          foreach ($modinfo->get_cms() as $cm) {
 408              $info = new info_module($cm);
 409              $changed = $info->update_dependency_id($table, $oldid, $newid);
 410              $anychanged = $anychanged || $changed;
 411          }
 412          foreach ($modinfo->get_section_info_all() as $section) {
 413              $info = new info_section($section);
 414              $changed = $info->update_dependency_id($table, $oldid, $newid);
 415              $anychanged = $anychanged || $changed;
 416          }
 417          $transaction->allow_commit();
 418          if ($anychanged) {
 419              get_fast_modinfo($courseorid, 0, true);
 420          }
 421          return $anychanged;
 422      }
 423  
 424      /**
 425       * Called on a single item. If necessary, updates availability data where
 426       * it has a dependency on an item with a particular id.
 427       *
 428       * @param string $table Table name e.g. 'course_modules'
 429       * @param int $oldid Previous ID
 430       * @param int $newid New ID
 431       * @return bool True if it changed, otherwise false
 432       */
 433      protected function update_dependency_id($table, $oldid, $newid) {
 434          // Do nothing if there are no availability restrictions.
 435          if (is_null($this->availability)) {
 436              return false;
 437          }
 438          // Pass requirement on to tree object.
 439          $tree = $this->get_availability_tree();
 440          $changed = $tree->update_dependency_id($table, $oldid, $newid);
 441          if ($changed) {
 442              // Save modified data.
 443              $structure = $tree->save();
 444              $this->set_in_database(json_encode($structure));
 445          }
 446          return $changed;
 447      }
 448  
 449      /**
 450       * Converts legacy data from fields (if provided) into the new availability
 451       * syntax.
 452       *
 453       * Supported fields: availablefrom, availableuntil, showavailability
 454       * (and groupingid for sections).
 455       *
 456       * It also supports the groupmembersonly field for modules. This part was
 457       * optional in 2.7 but now always runs (because groupmembersonly has been
 458       * removed).
 459       *
 460       * @param \stdClass $rec Object possibly containing legacy fields
 461       * @param bool $section True if this is a section
 462       * @param bool $modgroupmembersonlyignored Ignored option, previously used
 463       * @return string|null New availability value or null if none
 464       */
 465      public static function convert_legacy_fields($rec, $section, $modgroupmembersonlyignored = false) {
 466          // Do nothing if the fields are not set.
 467          if (empty($rec->availablefrom) && empty($rec->availableuntil) &&
 468                  (empty($rec->groupmembersonly)) &&
 469                  (!$section || empty($rec->groupingid))) {
 470              return null;
 471          }
 472  
 473          // Handle legacy availability data.
 474          $conditions = array();
 475          $shows = array();
 476  
 477          // Groupmembersonly condition (if enabled) for modules, groupingid for
 478          // sections.
 479          if (!empty($rec->groupmembersonly) ||
 480                  (!empty($rec->groupingid) && $section)) {
 481              if (!empty($rec->groupingid)) {
 482                  $conditions[] = '{"type":"grouping"' .
 483                          ($rec->groupingid ? ',"id":' . $rec->groupingid : '') . '}';
 484              } else {
 485                  // No grouping specified, so allow any group.
 486                  $conditions[] = '{"type":"group"}';
 487              }
 488              // Group members only condition was not displayed to students.
 489              $shows[] = 'false';
 490          }
 491  
 492          // Date conditions.
 493          if (!empty($rec->availablefrom)) {
 494              $conditions[] = '{"type":"date","d":">=","t":' . $rec->availablefrom . '}';
 495              $shows[] = !empty($rec->showavailability) ? 'true' : 'false';
 496          }
 497          if (!empty($rec->availableuntil)) {
 498              $conditions[] = '{"type":"date","d":"<","t":' . $rec->availableuntil . '}';
 499              // Until dates never showed to students.
 500              $shows[] = 'false';
 501          }
 502  
 503          // If there are some conditions, return them.
 504          if ($conditions) {
 505              return '{"op":"&","showc":[' . implode(',', $shows) . '],' .
 506                      '"c":[' . implode(',', $conditions) . ']}';
 507          } else {
 508              return null;
 509          }
 510      }
 511  
 512      /**
 513       * Adds a condition from the legacy availability condition.
 514       *
 515       * (For use during restore only.)
 516       *
 517       * This function assumes that the activity either has no conditions, or
 518       * that it has an AND tree with one or more conditions.
 519       *
 520       * @param string|null $availability Current availability conditions
 521       * @param \stdClass $rec Object containing information from old table
 522       * @param bool $show True if 'show' option should be enabled
 523       * @return string New availability conditions
 524       */
 525      public static function add_legacy_availability_condition($availability, $rec, $show) {
 526          if (!empty($rec->sourcecmid)) {
 527              // Completion condition.
 528              $condition = '{"type":"completion","cm":' . $rec->sourcecmid .
 529                      ',"e":' . $rec->requiredcompletion . '}';
 530          } else {
 531              // Grade condition.
 532              $minmax = '';
 533              if (!empty($rec->grademin)) {
 534                  $minmax .= ',"min":' . sprintf('%.5f', $rec->grademin);
 535              }
 536              if (!empty($rec->grademax)) {
 537                  $minmax .= ',"max":' . sprintf('%.5f', $rec->grademax);
 538              }
 539              $condition = '{"type":"grade","id":' . $rec->gradeitemid . $minmax . '}';
 540          }
 541  
 542          return self::add_legacy_condition($availability, $condition, $show);
 543      }
 544  
 545      /**
 546       * Adds a condition from the legacy availability field condition.
 547       *
 548       * (For use during restore only.)
 549       *
 550       * This function assumes that the activity either has no conditions, or
 551       * that it has an AND tree with one or more conditions.
 552       *
 553       * @param string|null $availability Current availability conditions
 554       * @param \stdClass $rec Object containing information from old table
 555       * @param bool $show True if 'show' option should be enabled
 556       * @return string New availability conditions
 557       */
 558      public static function add_legacy_availability_field_condition($availability, $rec, $show) {
 559          if (isset($rec->userfield)) {
 560              // Standard field.
 561              $fieldbit = ',"sf":' . json_encode($rec->userfield);
 562          } else {
 563              // Custom field.
 564              $fieldbit = ',"cf":' . json_encode($rec->shortname);
 565          }
 566          // Value is not included for certain operators.
 567          switch($rec->operator) {
 568              case 'isempty':
 569              case 'isnotempty':
 570                  $valuebit = '';
 571                  break;
 572  
 573              default:
 574                  $valuebit = ',"v":' . json_encode($rec->value);
 575                  break;
 576          }
 577          $condition = '{"type":"profile","op":"' . $rec->operator . '"' .
 578                  $fieldbit . $valuebit . '}';
 579  
 580          return self::add_legacy_condition($availability, $condition, $show);
 581      }
 582  
 583      /**
 584       * Adds a condition to an AND group.
 585       *
 586       * (For use during restore only.)
 587       *
 588       * This function assumes that the activity either has no conditions, or
 589       * that it has only conditions added by this function.
 590       *
 591       * @param string|null $availability Current availability conditions
 592       * @param string $condition Condition text '{...}'
 593       * @param bool $show True if 'show' option should be enabled
 594       * @return string New availability conditions
 595       */
 596      protected static function add_legacy_condition($availability, $condition, $show) {
 597          $showtext = ($show ? 'true' : 'false');
 598          if (is_null($availability)) {
 599              $availability = '{"op":"&","showc":[' . $showtext .
 600                      '],"c":[' . $condition . ']}';
 601          } else {
 602              $matches = array();
 603              if (!preg_match('~^({"op":"&","showc":\[(?:true|false)(?:,(?:true|false))*)' .
 604                      '(\],"c":\[.*)(\]})$~', $availability, $matches)) {
 605                  throw new \coding_exception('Unexpected availability value');
 606              }
 607              $availability = $matches[1] . ',' . $showtext . $matches[2] .
 608                      ',' . $condition . $matches[3];
 609          }
 610          return $availability;
 611      }
 612  
 613      /**
 614       * Tests against a user list. Users who cannot access the activity due to
 615       * availability restrictions will be removed from the list.
 616       *
 617       * Note this only includes availability restrictions (those handled within
 618       * this API) and not other ways of restricting access.
 619       *
 620       * This test ONLY includes conditions which are marked as being applied to
 621       * user lists. For example, group conditions are included but date
 622       * conditions are not included.
 623       *
 624       * The function operates reasonably efficiently i.e. should not do per-user
 625       * database queries. It is however likely to be fairly slow.
 626       *
 627       * @param array $users Array of userid => object
 628       * @return array Filtered version of input array
 629       */
 630      public function filter_user_list(array $users) {
 631          global $CFG;
 632          if (is_null($this->availability) || !$CFG->enableavailability) {
 633              return $users;
 634          }
 635          $tree = $this->get_availability_tree();
 636          $checker = new capability_checker($this->get_context());
 637  
 638          // Filter using availability tree.
 639          $this->modinfo = get_fast_modinfo($this->get_course());
 640          $filtered = $tree->filter_user_list($users, false, $this, $checker);
 641          $this->modinfo = null;
 642  
 643          // Include users in the result if they're either in the filtered list,
 644          // or they have viewhidden. This logic preserves ordering of the
 645          // passed users array.
 646          $result = array();
 647          $canviewhidden = $checker->get_users_by_capability($this->get_view_hidden_capability());
 648          foreach ($users as $userid => $data) {
 649              if (array_key_exists($userid, $filtered) || array_key_exists($userid, $canviewhidden)) {
 650                  $result[$userid] = $users[$userid];
 651              }
 652          }
 653  
 654          return $result;
 655      }
 656  
 657      /**
 658       * Gets the capability used to view hidden activities/sections (as
 659       * appropriate).
 660       *
 661       * @return string Name of capability used to view hidden items of this type
 662       */
 663      protected abstract function get_view_hidden_capability();
 664  
 665      /**
 666       * Obtains SQL that returns a list of enrolled users that has been filtered
 667       * by the conditions applied in the availability API, similar to calling
 668       * get_enrolled_users and then filter_user_list. As for filter_user_list,
 669       * this ONLY filters out users with conditions that are marked as applying
 670       * to user lists. For example, group conditions are included but date
 671       * conditions are not included.
 672       *
 673       * The returned SQL is a query that returns a list of user IDs. It does not
 674       * include brackets, so you neeed to add these to make it into a subquery.
 675       * You would normally use it in an SQL phrase like "WHERE u.id IN ($sql)".
 676       *
 677       * The function returns an array with '' and an empty array, if there are
 678       * no restrictions on users from these conditions.
 679       *
 680       * The SQL will be complex and may be slow. It uses named parameters (sorry,
 681       * I know they are annoying, but it was unavoidable here).
 682       *
 683       * @param bool $onlyactive True if including only active enrolments
 684       * @return array Array of SQL code (may be empty) and params
 685       */
 686      public function get_user_list_sql($onlyactive) {
 687          global $CFG;
 688          if (is_null($this->availability) || !$CFG->enableavailability) {
 689              return array('', array());
 690          }
 691  
 692          // Get SQL for the availability filter.
 693          $tree = $this->get_availability_tree();
 694          list ($filtersql, $filterparams) = $tree->get_user_list_sql(false, $this, $onlyactive);
 695          if ($filtersql === '') {
 696              // No restrictions, so return empty query.
 697              return array('', array());
 698          }
 699  
 700          // Get SQL for the view hidden list.
 701          list ($viewhiddensql, $viewhiddenparams) = get_enrolled_sql(
 702                  $this->get_context(), $this->get_view_hidden_capability(), 0, $onlyactive);
 703  
 704          // Result is a union of the two.
 705          return array('(' . $filtersql . ') UNION (' . $viewhiddensql . ')',
 706                  array_merge($filterparams, $viewhiddenparams));
 707      }
 708  
 709      /**
 710       * Formats the $cm->availableinfo string for display. This includes
 711       * filling in the names of any course-modules that might be mentioned.
 712       * Should be called immediately prior to display, or at least somewhere
 713       * that we can guarantee does not happen from within building the modinfo
 714       * object.
 715       *
 716       * @param \renderable|string $inforenderable Info string or renderable
 717       * @param int|\stdClass $courseorid
 718       * @return string Correctly formatted info string
 719       */
 720      public static function format_info($inforenderable, $courseorid) {
 721          global $PAGE;
 722  
 723          // Use renderer if required.
 724          if (is_string($inforenderable)) {
 725              $info = $inforenderable;
 726          } else {
 727              $renderer = $PAGE->get_renderer('core', 'availability');
 728              $info = $renderer->render($inforenderable);
 729          }
 730  
 731          // Don't waste time if there are no special tags.
 732          if (strpos($info, '<AVAILABILITY_') === false) {
 733              return $info;
 734          }
 735  
 736          // Handle CMNAME tags.
 737          $modinfo = get_fast_modinfo($courseorid);
 738          $context = \context_course::instance($modinfo->courseid);
 739          $info = preg_replace_callback('~<AVAILABILITY_CMNAME_([0-9]+)/>~',
 740                  function($matches) use($modinfo, $context) {
 741                      $cm = $modinfo->get_cm($matches[1]);
 742                      if ($cm->has_view() and $cm->get_user_visible()) {
 743                          // Help student by providing a link to the module which is preventing availability.
 744                          return \html_writer::link($cm->get_url(), format_string($cm->get_name(), true, ['context' => $context]));
 745                      } else {
 746                          return format_string($cm->get_name(), true, ['context' => $context]);
 747                      }
 748                  }, $info);
 749  
 750          return $info;
 751      }
 752  
 753      /**
 754       * Used in course/lib.php because we need to disable the completion tickbox
 755       * JS (using the non-JS version instead, which causes a page reload) if a
 756       * completion tickbox value may affect a conditional activity.
 757       *
 758       * @param \stdClass $course Moodle course object
 759       * @param int $cmid Course-module id
 760       * @return bool True if this is used in a condition, false otherwise
 761       */
 762      public static function completion_value_used($course, $cmid) {
 763          // Access all plugins. Normally only the completion plugin is going
 764          // to affect this value, but it's potentially possible that some other
 765          // plugin could also rely on the completion plugin.
 766          $pluginmanager = \core_plugin_manager::instance();
 767          $enabled = $pluginmanager->get_enabled_plugins('availability');
 768          $componentparams = new \stdClass();
 769          foreach ($enabled as $plugin => $info) {
 770              // Use the static method.
 771              $class = '\availability_' . $plugin . '\condition';
 772              if ($class::completion_value_used($course, $cmid)) {
 773                  return true;
 774              }
 775          }
 776          return false;
 777      }
 778  }