Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.
/lib/ -> accesslib.php (source)

Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 39 and 401] [Versions 400 and 401] [Versions 401 and 402] [Versions 401 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   * This file contains functions for managing user access
  19   *
  20   * <b>Public API vs internals</b>
  21   *
  22   * General users probably only care about
  23   *
  24   * Context handling
  25   * - context_course::instance($courseid), context_module::instance($cm->id), context_coursecat::instance($catid)
  26   * - context::instance_by_id($contextid)
  27   * - $context->get_parent_contexts();
  28   * - $context->get_child_contexts();
  29   *
  30   * Whether the user can do something...
  31   * - has_capability()
  32   * - has_any_capability()
  33   * - has_all_capabilities()
  34   * - require_capability()
  35   * - require_login() (from moodlelib)
  36   * - is_enrolled()
  37   * - is_viewing()
  38   * - is_guest()
  39   * - is_siteadmin()
  40   * - isguestuser()
  41   * - isloggedin()
  42   *
  43   * What courses has this user access to?
  44   * - get_enrolled_users()
  45   *
  46   * What users can do X in this context?
  47   * - get_enrolled_users() - at and bellow course context
  48   * - get_users_by_capability() - above course context
  49   *
  50   * Modify roles
  51   * - role_assign()
  52   * - role_unassign()
  53   * - role_unassign_all()
  54   *
  55   * Advanced - for internal use only
  56   * - load_all_capabilities()
  57   * - reload_all_capabilities()
  58   * - has_capability_in_accessdata()
  59   * - get_user_roles_sitewide_accessdata()
  60   * - etc.
  61   *
  62   * <b>Name conventions</b>
  63   *
  64   * "ctx" means context
  65   * "ra" means role assignment
  66   * "rdef" means role definition
  67   *
  68   * <b>accessdata</b>
  69   *
  70   * Access control data is held in the "accessdata" array
  71   * which - for the logged-in user, will be in $USER->access
  72   *
  73   * For other users can be generated and passed around (but may also be cached
  74   * against userid in $ACCESSLIB_PRIVATE->accessdatabyuser).
  75   *
  76   * $accessdata is a multidimensional array, holding
  77   * role assignments (RAs), role switches and initialization time.
  78   *
  79   * Things are keyed on "contextpaths" (the path field of
  80   * the context table) for fast walking up/down the tree.
  81   * <code>
  82   * $accessdata['ra'][$contextpath] = array($roleid=>$roleid)
  83   *                  [$contextpath] = array($roleid=>$roleid)
  84   *                  [$contextpath] = array($roleid=>$roleid)
  85   * </code>
  86   *
  87   * <b>Stale accessdata</b>
  88   *
  89   * For the logged-in user, accessdata is long-lived.
  90   *
  91   * On each pageload we load $ACCESSLIB_PRIVATE->dirtycontexts which lists
  92   * context paths affected by changes. Any check at-or-below
  93   * a dirty context will trigger a transparent reload of accessdata.
  94   *
  95   * Changes at the system level will force the reload for everyone.
  96   *
  97   * <b>Default role caps</b>
  98   * The default role assignment is not in the DB, so we
  99   * add it manually to accessdata.
 100   *
 101   * This means that functions that work directly off the
 102   * DB need to ensure that the default role caps
 103   * are dealt with appropriately.
 104   *
 105   * @package    core_access
 106   * @copyright  1999 onwards Martin Dougiamas  http://dougiamas.com
 107   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 108   */
 109  
 110  defined('MOODLE_INTERNAL') || die();
 111  
 112  /** No capability change */
 113  define('CAP_INHERIT', 0);
 114  /** Allow permission, overrides CAP_PREVENT defined in parent contexts */
 115  define('CAP_ALLOW', 1);
 116  /** Prevent permission, overrides CAP_ALLOW defined in parent contexts */
 117  define('CAP_PREVENT', -1);
 118  /** Prohibit permission, overrides everything in current and child contexts */
 119  define('CAP_PROHIBIT', -1000);
 120  
 121  /** System context level - only one instance in every system */
 122  define('CONTEXT_SYSTEM', 10);
 123  /** User context level -  one instance for each user describing what others can do to user */
 124  define('CONTEXT_USER', 30);
 125  /** Course category context level - one instance for each category */
 126  define('CONTEXT_COURSECAT', 40);
 127  /** Course context level - one instances for each course */
 128  define('CONTEXT_COURSE', 50);
 129  /** Course module context level - one instance for each course module */
 130  define('CONTEXT_MODULE', 70);
 131  /**
 132   * Block context level - one instance for each block, sticky blocks are tricky
 133   * because ppl think they should be able to override them at lower contexts.
 134   * Any other context level instance can be parent of block context.
 135   */
 136  define('CONTEXT_BLOCK', 80);
 137  
 138  /** Capability allow management of trusts - NOT IMPLEMENTED YET - see {@link https://moodledev.io/docs/apis/subsystems/roles} */
 139  define('RISK_MANAGETRUST', 0x0001);
 140  /** Capability allows changes in system configuration - see {@link https://moodledev.io/docs/apis/subsystems/roles} */
 141  define('RISK_CONFIG',      0x0002);
 142  /** Capability allows user to add scripted content - see {@link https://moodledev.io/docs/apis/subsystems/roles} */
 143  define('RISK_XSS',         0x0004);
 144  /** Capability allows access to personal user information - see {@link https://moodledev.io/docs/apis/subsystems/roles} */
 145  define('RISK_PERSONAL',    0x0008);
 146  /** Capability allows users to add content others may see - see {@link https://moodledev.io/docs/apis/subsystems/roles} */
 147  define('RISK_SPAM',        0x0010);
 148  /** capability allows mass delete of data belonging to other users - see {@link https://moodledev.io/docs/apis/subsystems/roles} */
 149  define('RISK_DATALOSS',    0x0020);
 150  
 151  /** rolename displays - the name as defined in the role definition, localised if name empty */
 152  define('ROLENAME_ORIGINAL', 0);
 153  /** rolename displays - the name as defined by a role alias at the course level, falls back to ROLENAME_ORIGINAL if alias not present */
 154  define('ROLENAME_ALIAS', 1);
 155  /** rolename displays - Both, like this:  Role alias (Original) */
 156  define('ROLENAME_BOTH', 2);
 157  /** rolename displays - the name as defined in the role definition and the shortname in brackets */
 158  define('ROLENAME_ORIGINALANDSHORT', 3);
 159  /** rolename displays - the name as defined by a role alias, in raw form suitable for editing */
 160  define('ROLENAME_ALIAS_RAW', 4);
 161  /** rolename displays - the name is simply short role name */
 162  define('ROLENAME_SHORT', 5);
 163  
 164  if (!defined('CONTEXT_CACHE_MAX_SIZE')) {
 165      /** maximum size of context cache - it is possible to tweak this config.php or in any script before inclusion of context.php */
 166      define('CONTEXT_CACHE_MAX_SIZE', 2500);
 167  }
 168  
 169  /**
 170   * Although this looks like a global variable, it isn't really.
 171   *
 172   * It is just a private implementation detail to accesslib that MUST NOT be used elsewhere.
 173   * It is used to cache various bits of data between function calls for performance reasons.
 174   * Sadly, a PHP global variable is the only way to implement this, without rewriting everything
 175   * as methods of a class, instead of functions.
 176   *
 177   * @access private
 178   * @global stdClass $ACCESSLIB_PRIVATE
 179   * @name $ACCESSLIB_PRIVATE
 180   */
 181  global $ACCESSLIB_PRIVATE;
 182  $ACCESSLIB_PRIVATE = new stdClass();
 183  $ACCESSLIB_PRIVATE->cacheroledefs    = array(); // Holds site-wide role definitions.
 184  $ACCESSLIB_PRIVATE->dirtycontexts    = null;    // Dirty contexts cache, loaded from DB once per page
 185  $ACCESSLIB_PRIVATE->dirtyusers       = null;    // Dirty users cache, loaded from DB once per $USER->id
 186  $ACCESSLIB_PRIVATE->accessdatabyuser = array(); // Holds the cache of $accessdata structure for users (including $USER)
 187  
 188  /**
 189   * Clears accesslib's private caches. ONLY BE USED BY UNIT TESTS
 190   *
 191   * This method should ONLY BE USED BY UNIT TESTS. It clears all of
 192   * accesslib's private caches. You need to do this before setting up test data,
 193   * and also at the end of the tests.
 194   *
 195   * @access private
 196   * @return void
 197   */
 198  function accesslib_clear_all_caches_for_unit_testing() {
 199      global $USER;
 200      if (!PHPUNIT_TEST) {
 201          throw new coding_exception('You must not call clear_all_caches outside of unit tests.');
 202      }
 203  
 204      accesslib_clear_all_caches(true);
 205      accesslib_reset_role_cache();
 206  
 207      unset($USER->access);
 208  }
 209  
 210  /**
 211   * Clears accesslib's private caches. ONLY BE USED FROM THIS LIBRARY FILE!
 212   *
 213   * This reset does not touch global $USER.
 214   *
 215   * @access private
 216   * @param bool $resetcontexts
 217   * @return void
 218   */
 219  function accesslib_clear_all_caches($resetcontexts) {
 220      global $ACCESSLIB_PRIVATE;
 221  
 222      $ACCESSLIB_PRIVATE->dirtycontexts    = null;
 223      $ACCESSLIB_PRIVATE->dirtyusers       = null;
 224      $ACCESSLIB_PRIVATE->accessdatabyuser = array();
 225  
 226      if ($resetcontexts) {
 227          context_helper::reset_caches();
 228      }
 229  }
 230  
 231  /**
 232   * Full reset of accesslib's private role cache. ONLY TO BE USED FROM THIS LIBRARY FILE!
 233   *
 234   * This reset does not touch global $USER.
 235   *
 236   * Note: Only use this when the roles that need a refresh are unknown.
 237   *
 238   * @see accesslib_clear_role_cache()
 239   *
 240   * @access private
 241   * @return void
 242   */
 243  function accesslib_reset_role_cache() {
 244      global $ACCESSLIB_PRIVATE;
 245  
 246      $ACCESSLIB_PRIVATE->cacheroledefs = array();
 247      $cache = cache::make('core', 'roledefs');
 248      $cache->purge();
 249  }
 250  
 251  /**
 252   * Clears accesslib's private cache of a specific role or roles. ONLY BE USED FROM THIS LIBRARY FILE!
 253   *
 254   * This reset does not touch global $USER.
 255   *
 256   * @access private
 257   * @param int|array $roles
 258   * @return void
 259   */
 260  function accesslib_clear_role_cache($roles) {
 261      global $ACCESSLIB_PRIVATE;
 262  
 263      if (!is_array($roles)) {
 264          $roles = [$roles];
 265      }
 266  
 267      foreach ($roles as $role) {
 268          if (isset($ACCESSLIB_PRIVATE->cacheroledefs[$role])) {
 269              unset($ACCESSLIB_PRIVATE->cacheroledefs[$role]);
 270          }
 271      }
 272  
 273      $cache = cache::make('core', 'roledefs');
 274      $cache->delete_many($roles);
 275  }
 276  
 277  /**
 278   * Role is assigned at system context.
 279   *
 280   * @access private
 281   * @param int $roleid
 282   * @return array
 283   */
 284  function get_role_access($roleid) {
 285      $accessdata = get_empty_accessdata();
 286      $accessdata['ra']['/'.SYSCONTEXTID] = array((int)$roleid => (int)$roleid);
 287      return $accessdata;
 288  }
 289  
 290  /**
 291   * Fetch raw "site wide" role definitions.
 292   * Even MUC static acceleration cache appears a bit slow for this.
 293   * Important as can be hit hundreds of times per page.
 294   *
 295   * @param array $roleids List of role ids to fetch definitions for.
 296   * @return array Complete definition for each requested role.
 297   */
 298  function get_role_definitions(array $roleids) {
 299      global $ACCESSLIB_PRIVATE;
 300  
 301      if (empty($roleids)) {
 302          return array();
 303      }
 304  
 305      // Grab all keys we have not yet got in our static cache.
 306      if ($uncached = array_diff($roleids, array_keys($ACCESSLIB_PRIVATE->cacheroledefs))) {
 307          $cache = cache::make('core', 'roledefs');
 308          foreach ($cache->get_many($uncached) as $roleid => $cachedroledef) {
 309              if (is_array($cachedroledef)) {
 310                  $ACCESSLIB_PRIVATE->cacheroledefs[$roleid] = $cachedroledef;
 311              }
 312          }
 313  
 314          // Check we have the remaining keys from the MUC.
 315          if ($uncached = array_diff($roleids, array_keys($ACCESSLIB_PRIVATE->cacheroledefs))) {
 316              $uncached = get_role_definitions_uncached($uncached);
 317              $ACCESSLIB_PRIVATE->cacheroledefs += $uncached;
 318              $cache->set_many($uncached);
 319          }
 320      }
 321  
 322      // Return just the roles we need.
 323      return array_intersect_key($ACCESSLIB_PRIVATE->cacheroledefs, array_flip($roleids));
 324  }
 325  
 326  /**
 327   * Query raw "site wide" role definitions.
 328   *
 329   * @param array $roleids List of role ids to fetch definitions for.
 330   * @return array Complete definition for each requested role.
 331   */
 332  function get_role_definitions_uncached(array $roleids) {
 333      global $DB;
 334  
 335      if (empty($roleids)) {
 336          return array();
 337      }
 338  
 339      // Create a blank results array: even if a role has no capabilities,
 340      // we need to ensure it is included in the results to show we have
 341      // loaded all the capabilities that there are.
 342      $rdefs = array();
 343      foreach ($roleids as $roleid) {
 344          $rdefs[$roleid] = array();
 345      }
 346  
 347      // Load all the capabilities for these roles in all contexts.
 348      list($sql, $params) = $DB->get_in_or_equal($roleids);
 349      $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
 350                FROM {role_capabilities} rc
 351                JOIN {context} ctx ON rc.contextid = ctx.id
 352                JOIN {capabilities} cap ON rc.capability = cap.name
 353               WHERE rc.roleid $sql";
 354      $rs = $DB->get_recordset_sql($sql, $params);
 355  
 356      // Store the capabilities into the expected data structure.
 357      foreach ($rs as $rd) {
 358          if (!isset($rdefs[$rd->roleid][$rd->path])) {
 359              $rdefs[$rd->roleid][$rd->path] = array();
 360          }
 361          $rdefs[$rd->roleid][$rd->path][$rd->capability] = (int) $rd->permission;
 362      }
 363  
 364      $rs->close();
 365  
 366      // Sometimes (e.g. get_user_capability_course_helper::get_capability_info_at_each_context)
 367      // we process role definitinons in a way that requires we see parent contexts
 368      // before child contexts. This sort ensures that works (and is faster than
 369      // sorting in the SQL query).
 370      foreach ($rdefs as $roleid => $rdef) {
 371          ksort($rdefs[$roleid]);
 372      }
 373  
 374      return $rdefs;
 375  }
 376  
 377  /**
 378   * Get the default guest role, this is used for guest account,
 379   * search engine spiders, etc.
 380   *
 381   * @return stdClass role record
 382   */
 383  function get_guest_role() {
 384      global $CFG, $DB;
 385  
 386      if (empty($CFG->guestroleid)) {
 387          if ($roles = $DB->get_records('role', array('archetype'=>'guest'))) {
 388              $guestrole = array_shift($roles);   // Pick the first one
 389              set_config('guestroleid', $guestrole->id);
 390              return $guestrole;
 391          } else {
 392              debugging('Can not find any guest role!');
 393              return false;
 394          }
 395      } else {
 396          if ($guestrole = $DB->get_record('role', array('id'=>$CFG->guestroleid))) {
 397              return $guestrole;
 398          } else {
 399              // somebody is messing with guest roles, remove incorrect setting and try to find a new one
 400              set_config('guestroleid', '');
 401              return get_guest_role();
 402          }
 403      }
 404  }
 405  
 406  /**
 407   * Check whether a user has a particular capability in a given context.
 408   *
 409   * For example:
 410   *      $context = context_module::instance($cm->id);
 411   *      has_capability('mod/forum:replypost', $context)
 412   *
 413   * By default checks the capabilities of the current user, but you can pass a
 414   * different userid. By default will return true for admin users, but you can override that with the fourth argument.
 415   *
 416   * Guest and not-logged-in users can never get any dangerous capability - that is any write capability
 417   * or capabilities with XSS, config or data loss risks.
 418   *
 419   * @category access
 420   *
 421   * @param string $capability the name of the capability to check. For example mod/forum:view
 422   * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
 423   * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
 424   * @param boolean $doanything If false, ignores effect of admin role assignment
 425   * @return boolean true if the user has this capability. Otherwise false.
 426   */
 427  function has_capability($capability, context $context, $user = null, $doanything = true) {
 428      global $USER, $CFG, $SCRIPT, $ACCESSLIB_PRIVATE;
 429  
 430      if (during_initial_install()) {
 431          if ($SCRIPT === "/$CFG->admin/index.php"
 432                  or $SCRIPT === "/$CFG->admin/cli/install.php"
 433                  or $SCRIPT === "/$CFG->admin/cli/install_database.php"
 434                  or (defined('BEHAT_UTIL') and BEHAT_UTIL)
 435                  or (defined('PHPUNIT_UTIL') and PHPUNIT_UTIL)) {
 436              // we are in an installer - roles can not work yet
 437              return true;
 438          } else {
 439              return false;
 440          }
 441      }
 442  
 443      if (strpos($capability, 'moodle/legacy:') === 0) {
 444          throw new coding_exception('Legacy capabilities can not be used any more!');
 445      }
 446  
 447      if (!is_bool($doanything)) {
 448          throw new coding_exception('Capability parameter "doanything" is wierd, only true or false is allowed. This has to be fixed in code.');
 449      }
 450  
 451      // capability must exist
 452      if (!$capinfo = get_capability_info($capability)) {
 453          debugging('Capability "'.$capability.'" was not found! This has to be fixed in code.');
 454          return false;
 455      }
 456  
 457      if (!isset($USER->id)) {
 458          // should never happen
 459          $USER->id = 0;
 460          debugging('Capability check being performed on a user with no ID.', DEBUG_DEVELOPER);
 461      }
 462  
 463      // make sure there is a real user specified
 464      if ($user === null) {
 465          $userid = $USER->id;
 466      } else {
 467          $userid = is_object($user) ? $user->id : $user;
 468      }
 469  
 470      // make sure forcelogin cuts off not-logged-in users if enabled
 471      if (!empty($CFG->forcelogin) and $userid == 0) {
 472          return false;
 473      }
 474  
 475      // make sure the guest account and not-logged-in users never get any risky caps no matter what the actual settings are.
 476      if (($capinfo->captype === 'write') or ($capinfo->riskbitmask & (RISK_XSS | RISK_CONFIG | RISK_DATALOSS))) {
 477          if (isguestuser($userid) or $userid == 0) {
 478              return false;
 479          }
 480      }
 481  
 482      // Check whether context locking is enabled.
 483      if (!empty($CFG->contextlocking)) {
 484          if ($capinfo->captype === 'write' && $context->locked) {
 485              // Context locking applies to any write capability in a locked context.
 486              // It does not apply to moodle/site:managecontextlocks - this is to allow context locking to be unlocked.
 487              if ($capinfo->name !== 'moodle/site:managecontextlocks') {
 488                  // It applies to all users who are not site admins.
 489                  // It also applies to site admins when contextlockappliestoadmin is set.
 490                  if (!is_siteadmin($userid) || !empty($CFG->contextlockappliestoadmin)) {
 491                      return false;
 492                  }
 493              }
 494          }
 495      }
 496  
 497      // somehow make sure the user is not deleted and actually exists
 498      if ($userid != 0) {
 499          if ($userid == $USER->id and isset($USER->deleted)) {
 500              // this prevents one query per page, it is a bit of cheating,
 501              // but hopefully session is terminated properly once user is deleted
 502              if ($USER->deleted) {
 503                  return false;
 504              }
 505          } else {
 506              if (!context_user::instance($userid, IGNORE_MISSING)) {
 507                  // no user context == invalid userid
 508                  return false;
 509              }
 510          }
 511      }
 512  
 513      // context path/depth must be valid
 514      if (empty($context->path) or $context->depth == 0) {
 515          // this should not happen often, each upgrade tries to rebuild the context paths
 516          debugging('Context id '.$context->id.' does not have valid path, please use context_helper::build_all_paths()');
 517          if (is_siteadmin($userid)) {
 518              return true;
 519          } else {
 520              return false;
 521          }
 522      }
 523  
 524      if (!empty($USER->loginascontext)) {
 525          // The current user is logged in as another user and can assume their identity at or below the `loginascontext`
 526          // defined in the USER session.
 527          // The user may not assume their identity at any other location.
 528          if (!$USER->loginascontext->is_parent_of($context, true)) {
 529              // The context being checked is not the specified context, or one of its children.
 530              return false;
 531          }
 532      }
 533  
 534      // Find out if user is admin - it is not possible to override the doanything in any way
 535      // and it is not possible to switch to admin role either.
 536      if ($doanything) {
 537          if (is_siteadmin($userid)) {
 538              if ($userid != $USER->id) {
 539                  return true;
 540              }
 541              // make sure switchrole is not used in this context
 542              if (empty($USER->access['rsw'])) {
 543                  return true;
 544              }
 545              $parts = explode('/', trim($context->path, '/'));
 546              $path = '';
 547              $switched = false;
 548              foreach ($parts as $part) {
 549                  $path .= '/' . $part;
 550                  if (!empty($USER->access['rsw'][$path])) {
 551                      $switched = true;
 552                      break;
 553                  }
 554              }
 555              if (!$switched) {
 556                  return true;
 557              }
 558              //ok, admin switched role in this context, let's use normal access control rules
 559          }
 560      }
 561  
 562      // Careful check for staleness...
 563      $context->reload_if_dirty();
 564  
 565      if ($USER->id == $userid) {
 566          if (!isset($USER->access)) {
 567              load_all_capabilities();
 568          }
 569          $access =& $USER->access;
 570  
 571      } else {
 572          // make sure user accessdata is really loaded
 573          get_user_accessdata($userid, true);
 574          $access =& $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
 575      }
 576  
 577      return has_capability_in_accessdata($capability, $context, $access);
 578  }
 579  
 580  /**
 581   * Check if the user has any one of several capabilities from a list.
 582   *
 583   * This is just a utility method that calls has_capability in a loop. Try to put
 584   * the capabilities that most users are likely to have first in the list for best
 585   * performance.
 586   *
 587   * @category access
 588   * @see has_capability()
 589   *
 590   * @param array $capabilities an array of capability names.
 591   * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
 592   * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
 593   * @param boolean $doanything If false, ignore effect of admin role assignment
 594   * @return boolean true if the user has any of these capabilities. Otherwise false.
 595   */
 596  function has_any_capability(array $capabilities, context $context, $user = null, $doanything = true) {
 597      foreach ($capabilities as $capability) {
 598          if (has_capability($capability, $context, $user, $doanything)) {
 599              return true;
 600          }
 601      }
 602      return false;
 603  }
 604  
 605  /**
 606   * Check if the user has all the capabilities in a list.
 607   *
 608   * This is just a utility method that calls has_capability in a loop. Try to put
 609   * the capabilities that fewest users are likely to have first in the list for best
 610   * performance.
 611   *
 612   * @category access
 613   * @see has_capability()
 614   *
 615   * @param array $capabilities an array of capability names.
 616   * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
 617   * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
 618   * @param boolean $doanything If false, ignore effect of admin role assignment
 619   * @return boolean true if the user has all of these capabilities. Otherwise false.
 620   */
 621  function has_all_capabilities(array $capabilities, context $context, $user = null, $doanything = true) {
 622      foreach ($capabilities as $capability) {
 623          if (!has_capability($capability, $context, $user, $doanything)) {
 624              return false;
 625          }
 626      }
 627      return true;
 628  }
 629  
 630  /**
 631   * Is course creator going to have capability in a new course?
 632   *
 633   * This is intended to be used in enrolment plugins before or during course creation,
 634   * do not use after the course is fully created.
 635   *
 636   * @category access
 637   *
 638   * @param string $capability the name of the capability to check.
 639   * @param context $context course or category context where is course going to be created
 640   * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
 641   * @return boolean true if the user will have this capability.
 642   *
 643   * @throws coding_exception if different type of context submitted
 644   */
 645  function guess_if_creator_will_have_course_capability($capability, context $context, $user = null) {
 646      global $CFG;
 647  
 648      if ($context->contextlevel != CONTEXT_COURSE and $context->contextlevel != CONTEXT_COURSECAT) {
 649          throw new coding_exception('Only course or course category context expected');
 650      }
 651  
 652      if (has_capability($capability, $context, $user)) {
 653          // User already has the capability, it could be only removed if CAP_PROHIBIT
 654          // was involved here, but we ignore that.
 655          return true;
 656      }
 657  
 658      if (!has_capability('moodle/course:create', $context, $user)) {
 659          return false;
 660      }
 661  
 662      if (!enrol_is_enabled('manual')) {
 663          return false;
 664      }
 665  
 666      if (empty($CFG->creatornewroleid)) {
 667          return false;
 668      }
 669  
 670      if ($context->contextlevel == CONTEXT_COURSE) {
 671          if (is_viewing($context, $user, 'moodle/role:assign') or is_enrolled($context, $user, 'moodle/role:assign')) {
 672              return false;
 673          }
 674      } else {
 675          if (has_capability('moodle/course:view', $context, $user) and has_capability('moodle/role:assign', $context, $user)) {
 676              return false;
 677          }
 678      }
 679  
 680      // Most likely they will be enrolled after the course creation is finished,
 681      // does the new role have the required capability?
 682      list($neededroles, $forbiddenroles) = get_roles_with_cap_in_context($context, $capability);
 683      return isset($neededroles[$CFG->creatornewroleid]);
 684  }
 685  
 686  /**
 687   * Check if the user is an admin at the site level.
 688   *
 689   * Please note that use of proper capabilities is always encouraged,
 690   * this function is supposed to be used from core or for temporary hacks.
 691   *
 692   * @category access
 693   *
 694   * @param  int|stdClass  $user_or_id user id or user object
 695   * @return bool true if user is one of the administrators, false otherwise
 696   */
 697  function is_siteadmin($user_or_id = null) {
 698      global $CFG, $USER;
 699  
 700      if ($user_or_id === null) {
 701          $user_or_id = $USER;
 702      }
 703  
 704      if (empty($user_or_id)) {
 705          return false;
 706      }
 707      if (!empty($user_or_id->id)) {
 708          $userid = $user_or_id->id;
 709      } else {
 710          $userid = $user_or_id;
 711      }
 712  
 713      // Because this script is called many times (150+ for course page) with
 714      // the same parameters, it is worth doing minor optimisations. This static
 715      // cache stores the value for a single userid, saving about 2ms from course
 716      // page load time without using significant memory. As the static cache
 717      // also includes the value it depends on, this cannot break unit tests.
 718      static $knownid, $knownresult, $knownsiteadmins;
 719      if ($knownid === $userid && $knownsiteadmins === $CFG->siteadmins) {
 720          return $knownresult;
 721      }
 722      $knownid = $userid;
 723      $knownsiteadmins = $CFG->siteadmins;
 724  
 725      $siteadmins = explode(',', $CFG->siteadmins);
 726      $knownresult = in_array($userid, $siteadmins);
 727      return $knownresult;
 728  }
 729  
 730  /**
 731   * Returns true if user has at least one role assign
 732   * of 'coursecontact' role (is potentially listed in some course descriptions).
 733   *
 734   * @param int $userid
 735   * @return bool
 736   */
 737  function has_coursecontact_role($userid) {
 738      global $DB, $CFG;
 739  
 740      if (empty($CFG->coursecontact)) {
 741          return false;
 742      }
 743      $sql = "SELECT 1
 744                FROM {role_assignments}
 745               WHERE userid = :userid AND roleid IN ($CFG->coursecontact)";
 746      return $DB->record_exists_sql($sql, array('userid'=>$userid));
 747  }
 748  
 749  /**
 750   * Does the user have a capability to do something?
 751   *
 752   * Walk the accessdata array and return true/false.
 753   * Deals with prohibits, role switching, aggregating
 754   * capabilities, etc.
 755   *
 756   * The main feature of here is being FAST and with no
 757   * side effects.
 758   *
 759   * Notes:
 760   *
 761   * Switch Role merges with default role
 762   * ------------------------------------
 763   * If you are a teacher in course X, you have at least
 764   * teacher-in-X + defaultloggedinuser-sitewide. So in the
 765   * course you'll have techer+defaultloggedinuser.
 766   * We try to mimic that in switchrole.
 767   *
 768   * Permission evaluation
 769   * ---------------------
 770   * Originally there was an extremely complicated way
 771   * to determine the user access that dealt with
 772   * "locality" or role assignments and role overrides.
 773   * Now we simply evaluate access for each role separately
 774   * and then verify if user has at least one role with allow
 775   * and at the same time no role with prohibit.
 776   *
 777   * @access private
 778   * @param string $capability
 779   * @param context $context
 780   * @param array $accessdata
 781   * @return bool
 782   */
 783  function has_capability_in_accessdata($capability, context $context, array &$accessdata) {
 784      global $CFG;
 785  
 786      // Build $paths as a list of current + all parent "paths" with order bottom-to-top
 787      $path = $context->path;
 788      $paths = array($path);
 789      while ($path = rtrim($path, '0123456789')) {
 790          $path = rtrim($path, '/');
 791          if ($path === '') {
 792              break;
 793          }
 794          $paths[] = $path;
 795      }
 796  
 797      $roles = array();
 798      $switchedrole = false;
 799  
 800      // Find out if role switched
 801      if (!empty($accessdata['rsw'])) {
 802          // From the bottom up...
 803          foreach ($paths as $path) {
 804              if (isset($accessdata['rsw'][$path])) {
 805                  // Found a switchrole assignment - check for that role _plus_ the default user role
 806                  $roles = array($accessdata['rsw'][$path]=>null, $CFG->defaultuserroleid=>null);
 807                  $switchedrole = true;
 808                  break;
 809              }
 810          }
 811      }
 812  
 813      if (!$switchedrole) {
 814          // get all users roles in this context and above
 815          foreach ($paths as $path) {
 816              if (isset($accessdata['ra'][$path])) {
 817                  foreach ($accessdata['ra'][$path] as $roleid) {
 818                      $roles[$roleid] = null;
 819                  }
 820              }
 821          }
 822      }
 823  
 824      // Now find out what access is given to each role, going bottom-->up direction
 825      $rdefs = get_role_definitions(array_keys($roles));
 826      $allowed = false;
 827  
 828      foreach ($roles as $roleid => $ignored) {
 829          foreach ($paths as $path) {
 830              if (isset($rdefs[$roleid][$path][$capability])) {
 831                  $perm = (int)$rdefs[$roleid][$path][$capability];
 832                  if ($perm === CAP_PROHIBIT) {
 833                      // any CAP_PROHIBIT found means no permission for the user
 834                      return false;
 835                  }
 836                  if (is_null($roles[$roleid])) {
 837                      $roles[$roleid] = $perm;
 838                  }
 839              }
 840          }
 841          // CAP_ALLOW in any role means the user has a permission, we continue only to detect prohibits
 842          $allowed = ($allowed or $roles[$roleid] === CAP_ALLOW);
 843      }
 844  
 845      return $allowed;
 846  }
 847  
 848  /**
 849   * A convenience function that tests has_capability, and displays an error if
 850   * the user does not have that capability.
 851   *
 852   * NOTE before Moodle 2.0, this function attempted to make an appropriate
 853   * require_login call before checking the capability. This is no longer the case.
 854   * You must call require_login (or one of its variants) if you want to check the
 855   * user is logged in, before you call this function.
 856   *
 857   * @see has_capability()
 858   *
 859   * @param string $capability the name of the capability to check. For example mod/forum:view
 860   * @param context $context the context to check the capability in. You normally get this with context_xxxx::instance().
 861   * @param int $userid A user id. By default (null) checks the permissions of the current user.
 862   * @param bool $doanything If false, ignore effect of admin role assignment
 863   * @param string $errormessage The error string to to user. Defaults to 'nopermissions'.
 864   * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
 865   * @return void terminates with an error if the user does not have the given capability.
 866   */
 867  function require_capability($capability, context $context, $userid = null, $doanything = true,
 868                              $errormessage = 'nopermissions', $stringfile = '') {
 869      if (!has_capability($capability, $context, $userid, $doanything)) {
 870          throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
 871      }
 872  }
 873  
 874  /**
 875   * A convenience function that tests has_capability for a list of capabilities, and displays an error if
 876   * the user does not have that capability.
 877   *
 878   * This is just a utility method that calls has_capability in a loop. Try to put
 879   * the capabilities that fewest users are likely to have first in the list for best
 880   * performance.
 881   *
 882   * @category access
 883   * @see has_capability()
 884   *
 885   * @param array $capabilities an array of capability names.
 886   * @param context $context the context to check the capability in. You normally get this with context_xxxx::instance().
 887   * @param int $userid A user id. By default (null) checks the permissions of the current user.
 888   * @param bool $doanything If false, ignore effect of admin role assignment
 889   * @param string $errormessage The error string to to user. Defaults to 'nopermissions'.
 890   * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
 891   * @return void terminates with an error if the user does not have the given capability.
 892   */
 893  function require_all_capabilities(array $capabilities, context $context, $userid = null, $doanything = true,
 894                                    $errormessage = 'nopermissions', $stringfile = ''): void {
 895      foreach ($capabilities as $capability) {
 896          if (!has_capability($capability, $context, $userid, $doanything)) {
 897              throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
 898          }
 899      }
 900  }
 901  
 902  /**
 903   * Return a nested array showing all role assignments for the user.
 904   * [ra] => [contextpath][roleid] = roleid
 905   *
 906   * @access private
 907   * @param int $userid - the id of the user
 908   * @return array access info array
 909   */
 910  function get_user_roles_sitewide_accessdata($userid) {
 911      global $CFG, $DB;
 912  
 913      $accessdata = get_empty_accessdata();
 914  
 915      // start with the default role
 916      if (!empty($CFG->defaultuserroleid)) {
 917          $syscontext = context_system::instance();
 918          $accessdata['ra'][$syscontext->path][(int)$CFG->defaultuserroleid] = (int)$CFG->defaultuserroleid;
 919      }
 920  
 921      // load the "default frontpage role"
 922      if (!empty($CFG->defaultfrontpageroleid)) {
 923          $frontpagecontext = context_course::instance(get_site()->id);
 924          if ($frontpagecontext->path) {
 925              $accessdata['ra'][$frontpagecontext->path][(int)$CFG->defaultfrontpageroleid] = (int)$CFG->defaultfrontpageroleid;
 926          }
 927      }
 928  
 929      // Preload every assigned role.
 930      $sql = "SELECT ctx.path, ra.roleid, ra.contextid
 931                FROM {role_assignments} ra
 932                JOIN {context} ctx ON ctx.id = ra.contextid
 933               WHERE ra.userid = :userid";
 934  
 935      $rs = $DB->get_recordset_sql($sql, array('userid' => $userid));
 936  
 937      foreach ($rs as $ra) {
 938          // RAs leafs are arrays to support multi-role assignments...
 939          $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
 940      }
 941  
 942      $rs->close();
 943  
 944      return $accessdata;
 945  }
 946  
 947  /**
 948   * Returns empty accessdata structure.
 949   *
 950   * @access private
 951   * @return array empt accessdata
 952   */
 953  function get_empty_accessdata() {
 954      $accessdata               = array(); // named list
 955      $accessdata['ra']         = array();
 956      $accessdata['time']       = time();
 957      $accessdata['rsw']        = array();
 958  
 959      return $accessdata;
 960  }
 961  
 962  /**
 963   * Get accessdata for a given user.
 964   *
 965   * @access private
 966   * @param int $userid
 967   * @param bool $preloadonly true means do not return access array
 968   * @return array accessdata
 969   */
 970  function get_user_accessdata($userid, $preloadonly=false) {
 971      global $CFG, $ACCESSLIB_PRIVATE, $USER;
 972  
 973      if (isset($USER->access)) {
 974          $ACCESSLIB_PRIVATE->accessdatabyuser[$USER->id] = $USER->access;
 975      }
 976  
 977      if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
 978          if (empty($userid)) {
 979              if (!empty($CFG->notloggedinroleid)) {
 980                  $accessdata = get_role_access($CFG->notloggedinroleid);
 981              } else {
 982                  // weird
 983                  return get_empty_accessdata();
 984              }
 985  
 986          } else if (isguestuser($userid)) {
 987              if ($guestrole = get_guest_role()) {
 988                  $accessdata = get_role_access($guestrole->id);
 989              } else {
 990                  //weird
 991                  return get_empty_accessdata();
 992              }
 993  
 994          } else {
 995              // Includes default role and frontpage role.
 996              $accessdata = get_user_roles_sitewide_accessdata($userid);
 997          }
 998  
 999          $ACCESSLIB_PRIVATE->accessdatabyuser[$userid] = $accessdata;
1000      }
1001  
1002      if ($preloadonly) {
1003          return;
1004      } else {
1005          return $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
1006      }
1007  }
1008  
1009  /**
1010   * A convenience function to completely load all the capabilities
1011   * for the current user. It is called from has_capability() and functions change permissions.
1012   *
1013   * Call it only _after_ you've setup $USER and called check_enrolment_plugins();
1014   * @see check_enrolment_plugins()
1015   *
1016   * @access private
1017   * @return void
1018   */
1019  function load_all_capabilities() {
1020      global $USER;
1021  
1022      // roles not installed yet - we are in the middle of installation
1023      if (during_initial_install()) {
1024          return;
1025      }
1026  
1027      if (!isset($USER->id)) {
1028          // this should not happen
1029          $USER->id = 0;
1030      }
1031  
1032      unset($USER->access);
1033      $USER->access = get_user_accessdata($USER->id);
1034  
1035      // Clear to force a refresh
1036      unset($USER->mycourses);
1037  
1038      // init/reset internal enrol caches - active course enrolments and temp access
1039      $USER->enrol = array('enrolled'=>array(), 'tempguest'=>array());
1040  }
1041  
1042  /**
1043   * A convenience function to completely reload all the capabilities
1044   * for the current user when roles have been updated in a relevant
1045   * context -- but PRESERVING switchroles and loginas.
1046   * This function resets all accesslib and context caches.
1047   *
1048   * That is - completely transparent to the user.
1049   *
1050   * Note: reloads $USER->access completely.
1051   *
1052   * @access private
1053   * @return void
1054   */
1055  function reload_all_capabilities() {
1056      global $USER, $DB, $ACCESSLIB_PRIVATE;
1057  
1058      // copy switchroles
1059      $sw = array();
1060      if (!empty($USER->access['rsw'])) {
1061          $sw = $USER->access['rsw'];
1062      }
1063  
1064      accesslib_clear_all_caches(true);
1065      unset($USER->access);
1066  
1067      // Prevent dirty flags refetching on this page.
1068      $ACCESSLIB_PRIVATE->dirtycontexts = array();
1069      $ACCESSLIB_PRIVATE->dirtyusers    = array($USER->id => false);
1070  
1071      load_all_capabilities();
1072  
1073      foreach ($sw as $path => $roleid) {
1074          if ($record = $DB->get_record('context', array('path'=>$path))) {
1075              $context = context::instance_by_id($record->id);
1076              if (has_capability('moodle/role:switchroles', $context)) {
1077                  role_switch($roleid, $context);
1078              }
1079          }
1080      }
1081  }
1082  
1083  /**
1084   * Adds a temp role to current USER->access array.
1085   *
1086   * Useful for the "temporary guest" access we grant to logged-in users.
1087   * This is useful for enrol plugins only.
1088   *
1089   * @since Moodle 2.2
1090   * @param context_course $coursecontext
1091   * @param int $roleid
1092   * @return void
1093   */
1094  function load_temp_course_role(context_course $coursecontext, $roleid) {
1095      global $USER, $SITE;
1096  
1097      if (empty($roleid)) {
1098          debugging('invalid role specified in load_temp_course_role()');
1099          return;
1100      }
1101  
1102      if ($coursecontext->instanceid == $SITE->id) {
1103          debugging('Can not use temp roles on the frontpage');
1104          return;
1105      }
1106  
1107      if (!isset($USER->access)) {
1108          load_all_capabilities();
1109      }
1110  
1111      $coursecontext->reload_if_dirty();
1112  
1113      if (isset($USER->access['ra'][$coursecontext->path][$roleid])) {
1114          return;
1115      }
1116  
1117      $USER->access['ra'][$coursecontext->path][(int)$roleid] = (int)$roleid;
1118  }
1119  
1120  /**
1121   * Removes any extra guest roles from current USER->access array.
1122   * This is useful for enrol plugins only.
1123   *
1124   * @since Moodle 2.2
1125   * @param context_course $coursecontext
1126   * @return void
1127   */
1128  function remove_temp_course_roles(context_course $coursecontext) {
1129      global $DB, $USER, $SITE;
1130  
1131      if ($coursecontext->instanceid == $SITE->id) {
1132          debugging('Can not use temp roles on the frontpage');
1133          return;
1134      }
1135  
1136      if (empty($USER->access['ra'][$coursecontext->path])) {
1137          //no roles here, weird
1138          return;
1139      }
1140  
1141      $sql = "SELECT DISTINCT ra.roleid AS id
1142                FROM {role_assignments} ra
1143               WHERE ra.contextid = :contextid AND ra.userid = :userid";
1144      $ras = $DB->get_records_sql($sql, array('contextid'=>$coursecontext->id, 'userid'=>$USER->id));
1145  
1146      $USER->access['ra'][$coursecontext->path] = array();
1147      foreach ($ras as $r) {
1148          $USER->access['ra'][$coursecontext->path][(int)$r->id] = (int)$r->id;
1149      }
1150  }
1151  
1152  /**
1153   * Returns array of all role archetypes.
1154   *
1155   * @return array
1156   */
1157  function get_role_archetypes() {
1158      return array(
1159          'manager'        => 'manager',
1160          'coursecreator'  => 'coursecreator',
1161          'editingteacher' => 'editingteacher',
1162          'teacher'        => 'teacher',
1163          'student'        => 'student',
1164          'guest'          => 'guest',
1165          'user'           => 'user',
1166          'frontpage'      => 'frontpage'
1167      );
1168  }
1169  
1170  /**
1171   * Assign the defaults found in this capability definition to roles that have
1172   * the corresponding legacy capabilities assigned to them.
1173   *
1174   * @param string $capability
1175   * @param array $legacyperms an array in the format (example):
1176   *                      'guest' => CAP_PREVENT,
1177   *                      'student' => CAP_ALLOW,
1178   *                      'teacher' => CAP_ALLOW,
1179   *                      'editingteacher' => CAP_ALLOW,
1180   *                      'coursecreator' => CAP_ALLOW,
1181   *                      'manager' => CAP_ALLOW
1182   * @return boolean success or failure.
1183   */
1184  function assign_legacy_capabilities($capability, $legacyperms) {
1185  
1186      $archetypes = get_role_archetypes();
1187  
1188      foreach ($legacyperms as $type => $perm) {
1189  
1190          $systemcontext = context_system::instance();
1191          if ($type === 'admin') {
1192              debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
1193              $type = 'manager';
1194          }
1195  
1196          if (!array_key_exists($type, $archetypes)) {
1197              throw new \moodle_exception('invalidlegacy', '', '', $type);
1198          }
1199  
1200          if ($roles = get_archetype_roles($type)) {
1201              foreach ($roles as $role) {
1202                  // Assign a site level capability.
1203                  if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1204                      return false;
1205                  }
1206              }
1207          }
1208      }
1209      return true;
1210  }
1211  
1212  /**
1213   * Verify capability risks.
1214   *
1215   * @param stdClass $capability a capability - a row from the capabilities table.
1216   * @return boolean whether this capability is safe - that is, whether people with the
1217   *      safeoverrides capability should be allowed to change it.
1218   */
1219  function is_safe_capability($capability) {
1220      return !((RISK_DATALOSS | RISK_MANAGETRUST | RISK_CONFIG | RISK_XSS | RISK_PERSONAL) & $capability->riskbitmask);
1221  }
1222  
1223  /**
1224   * Get the local override (if any) for a given capability in a role in a context
1225   *
1226   * @param int $roleid
1227   * @param int $contextid
1228   * @param string $capability
1229   * @return stdClass local capability override
1230   */
1231  function get_local_override($roleid, $contextid, $capability) {
1232      global $DB;
1233  
1234      return $DB->get_record_sql("
1235          SELECT rc.*
1236            FROM {role_capabilities} rc
1237            JOIN {capability} cap ON rc.capability = cap.name
1238           WHERE rc.roleid = :roleid AND rc.capability = :capability AND rc.contextid = :contextid", [
1239              'roleid' => $roleid,
1240              'contextid' => $contextid,
1241              'capability' => $capability,
1242  
1243          ]);
1244  }
1245  
1246  /**
1247   * Returns context instance plus related course and cm instances
1248   *
1249   * @param int $contextid
1250   * @return array of ($context, $course, $cm)
1251   */
1252  function get_context_info_array($contextid) {
1253      global $DB;
1254  
1255      $context = context::instance_by_id($contextid, MUST_EXIST);
1256      $course  = null;
1257      $cm      = null;
1258  
1259      if ($context->contextlevel == CONTEXT_COURSE) {
1260          $course = $DB->get_record('course', array('id'=>$context->instanceid), '*', MUST_EXIST);
1261  
1262      } else if ($context->contextlevel == CONTEXT_MODULE) {
1263          $cm = get_coursemodule_from_id('', $context->instanceid, 0, false, MUST_EXIST);
1264          $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1265  
1266      } else if ($context->contextlevel == CONTEXT_BLOCK) {
1267          $parent = $context->get_parent_context();
1268  
1269          if ($parent->contextlevel == CONTEXT_COURSE) {
1270              $course = $DB->get_record('course', array('id'=>$parent->instanceid), '*', MUST_EXIST);
1271          } else if ($parent->contextlevel == CONTEXT_MODULE) {
1272              $cm = get_coursemodule_from_id('', $parent->instanceid, 0, false, MUST_EXIST);
1273              $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1274          }
1275      }
1276  
1277      return array($context, $course, $cm);
1278  }
1279  
1280  /**
1281   * Function that creates a role
1282   *
1283   * @param string $name role name
1284   * @param string $shortname role short name
1285   * @param string $description role description
1286   * @param string $archetype
1287   * @return int id or dml_exception
1288   */
1289  function create_role($name, $shortname, $description, $archetype = '') {
1290      global $DB;
1291  
1292      if (strpos($archetype, 'moodle/legacy:') !== false) {
1293          throw new coding_exception('Use new role archetype parameter in create_role() instead of old legacy capabilities.');
1294      }
1295  
1296      // verify role archetype actually exists
1297      $archetypes = get_role_archetypes();
1298      if (empty($archetypes[$archetype])) {
1299          $archetype = '';
1300      }
1301  
1302      // Insert the role record.
1303      $role = new stdClass();
1304      $role->name        = $name;
1305      $role->shortname   = $shortname;
1306      $role->description = $description;
1307      $role->archetype   = $archetype;
1308  
1309      //find free sortorder number
1310      $role->sortorder = $DB->get_field('role', 'MAX(sortorder) + 1', array());
1311      if (empty($role->sortorder)) {
1312          $role->sortorder = 1;
1313      }
1314      $id = $DB->insert_record('role', $role);
1315  
1316      return $id;
1317  }
1318  
1319  /**
1320   * Function that deletes a role and cleanups up after it
1321   *
1322   * @param int $roleid id of role to delete
1323   * @return bool always true
1324   */
1325  function delete_role($roleid) {
1326      global $DB;
1327  
1328      // first unssign all users
1329      role_unassign_all(array('roleid'=>$roleid));
1330  
1331      // cleanup all references to this role, ignore errors
1332      $DB->delete_records('role_capabilities',   array('roleid'=>$roleid));
1333      $DB->delete_records('role_allow_assign',   array('roleid'=>$roleid));
1334      $DB->delete_records('role_allow_assign',   array('allowassign'=>$roleid));
1335      $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
1336      $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
1337      $DB->delete_records('role_names',          array('roleid'=>$roleid));
1338      $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
1339  
1340      // Get role record before it's deleted.
1341      $role = $DB->get_record('role', array('id'=>$roleid));
1342  
1343      // Finally delete the role itself.
1344      $DB->delete_records('role', array('id'=>$roleid));
1345  
1346      // Trigger event.
1347      $event = \core\event\role_deleted::create(
1348          array(
1349              'context' => context_system::instance(),
1350              'objectid' => $roleid,
1351              'other' =>
1352                  array(
1353                      'shortname' => $role->shortname,
1354                      'description' => $role->description,
1355                      'archetype' => $role->archetype
1356                  )
1357              )
1358          );
1359      $event->add_record_snapshot('role', $role);
1360      $event->trigger();
1361  
1362      // Reset any cache of this role, including MUC.
1363      accesslib_clear_role_cache($roleid);
1364  
1365      return true;
1366  }
1367  
1368  /**
1369   * Function to write context specific overrides, or default capabilities.
1370   *
1371   * @param string $capability string name
1372   * @param int $permission CAP_ constants
1373   * @param int $roleid role id
1374   * @param int|context $contextid context id
1375   * @param bool $overwrite
1376   * @return bool always true or exception
1377   */
1378  function assign_capability($capability, $permission, $roleid, $contextid, $overwrite = false) {
1379      global $USER, $DB;
1380  
1381      if ($contextid instanceof context) {
1382          $context = $contextid;
1383      } else {
1384          $context = context::instance_by_id($contextid);
1385      }
1386  
1387      // Capability must exist.
1388      if (!$capinfo = get_capability_info($capability)) {
1389          throw new coding_exception("Capability '{$capability}' was not found! This has to be fixed in code.");
1390      }
1391  
1392      if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
1393          unassign_capability($capability, $roleid, $context->id);
1394          return true;
1395      }
1396  
1397      $existing = $DB->get_record('role_capabilities', array('contextid'=>$context->id, 'roleid'=>$roleid, 'capability'=>$capability));
1398  
1399      if ($existing and !$overwrite) {   // We want to keep whatever is there already
1400          return true;
1401      }
1402  
1403      $cap = new stdClass();
1404      $cap->contextid    = $context->id;
1405      $cap->roleid       = $roleid;
1406      $cap->capability   = $capability;
1407      $cap->permission   = $permission;
1408      $cap->timemodified = time();
1409      $cap->modifierid   = empty($USER->id) ? 0 : $USER->id;
1410  
1411      if ($existing) {
1412          $cap->id = $existing->id;
1413          $DB->update_record('role_capabilities', $cap);
1414      } else {
1415          if ($DB->record_exists('context', array('id'=>$context->id))) {
1416              $DB->insert_record('role_capabilities', $cap);
1417          }
1418      }
1419  
1420      // Trigger capability_assigned event.
1421      \core\event\capability_assigned::create([
1422          'userid' => $cap->modifierid,
1423          'context' => $context,
1424          'objectid' => $roleid,
1425          'other' => [
1426              'capability' => $capability,
1427              'oldpermission' => $existing->permission ?? CAP_INHERIT,
1428              'permission' => $permission
1429          ]
1430      ])->trigger();
1431  
1432      // Reset any cache of this role, including MUC.
1433      accesslib_clear_role_cache($roleid);
1434  
1435      return true;
1436  }
1437  
1438  /**
1439   * Unassign a capability from a role.
1440   *
1441   * @param string $capability the name of the capability
1442   * @param int $roleid the role id
1443   * @param int|context $contextid null means all contexts
1444   * @return boolean true or exception
1445   */
1446  function unassign_capability($capability, $roleid, $contextid = null) {
1447      global $DB, $USER;
1448  
1449      // Capability must exist.
1450      if (!$capinfo = get_capability_info($capability)) {
1451          throw new coding_exception("Capability '{$capability}' was not found! This has to be fixed in code.");
1452      }
1453  
1454      if (!empty($contextid)) {
1455          if ($contextid instanceof context) {
1456              $context = $contextid;
1457          } else {
1458              $context = context::instance_by_id($contextid);
1459          }
1460          // delete from context rel, if this is the last override in this context
1461          $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$context->id));
1462      } else {
1463          $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
1464      }
1465  
1466      // Trigger capability_assigned event.
1467      \core\event\capability_unassigned::create([
1468          'userid' => $USER->id,
1469          'context' => $context ?? context_system::instance(),
1470          'objectid' => $roleid,
1471          'other' => [
1472              'capability' => $capability,
1473          ]
1474      ])->trigger();
1475  
1476      // Reset any cache of this role, including MUC.
1477      accesslib_clear_role_cache($roleid);
1478  
1479      return true;
1480  }
1481  
1482  /**
1483   * Get the roles that have a given capability assigned to it
1484   *
1485   * This function does not resolve the actual permission of the capability.
1486   * It just checks for permissions and overrides.
1487   * Use get_roles_with_cap_in_context() if resolution is required.
1488   *
1489   * @param string $capability capability name (string)
1490   * @param string $permission optional, the permission defined for this capability
1491   *                      either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to null which means any.
1492   * @param stdClass $context null means any
1493   * @return array of role records
1494   */
1495  function get_roles_with_capability($capability, $permission = null, $context = null) {
1496      global $DB;
1497  
1498      if ($context) {
1499          $contexts = $context->get_parent_context_ids(true);
1500          list($insql, $params) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED, 'ctx');
1501          $contextsql = "AND rc.contextid $insql";
1502      } else {
1503          $params = array();
1504          $contextsql = '';
1505      }
1506  
1507      if ($permission) {
1508          $permissionsql = " AND rc.permission = :permission";
1509          $params['permission'] = $permission;
1510      } else {
1511          $permissionsql = '';
1512      }
1513  
1514      $sql = "SELECT r.*
1515                FROM {role} r
1516               WHERE r.id IN (SELECT rc.roleid
1517                                FROM {role_capabilities} rc
1518                                JOIN {capabilities} cap ON rc.capability = cap.name
1519                               WHERE rc.capability = :capname
1520                                     $contextsql
1521                                     $permissionsql)";
1522      $params['capname'] = $capability;
1523  
1524  
1525      return $DB->get_records_sql($sql, $params);
1526  }
1527  
1528  /**
1529   * This function makes a role-assignment (a role for a user in a particular context)
1530   *
1531   * @param int $roleid the role of the id
1532   * @param int $userid userid
1533   * @param int|context $contextid id of the context
1534   * @param string $component example 'enrol_ldap', defaults to '' which means manual assignment,
1535   * @param int $itemid id of enrolment/auth plugin
1536   * @param string $timemodified defaults to current time
1537   * @return int new/existing id of the assignment
1538   */
1539  function role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '') {
1540      global $USER, $DB;
1541  
1542      // first of all detect if somebody is using old style parameters
1543      if ($contextid === 0 or is_numeric($component)) {
1544          throw new coding_exception('Invalid call to role_assign(), code needs to be updated to use new order of parameters');
1545      }
1546  
1547      // now validate all parameters
1548      if (empty($roleid)) {
1549          throw new coding_exception('Invalid call to role_assign(), roleid can not be empty');
1550      }
1551  
1552      if (empty($userid)) {
1553          throw new coding_exception('Invalid call to role_assign(), userid can not be empty');
1554      }
1555  
1556      if ($itemid) {
1557          if (strpos($component, '_') === false) {
1558              throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as"enrol_" when itemid specified', 'component:'.$component);
1559          }
1560      } else {
1561          $itemid = 0;
1562          if ($component !== '' and strpos($component, '_') === false) {
1563              throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1564          }
1565      }
1566  
1567      if (!$DB->record_exists('user', array('id'=>$userid, 'deleted'=>0))) {
1568          throw new coding_exception('User ID does not exist or is deleted!', 'userid:'.$userid);
1569      }
1570  
1571      if ($contextid instanceof context) {
1572          $context = $contextid;
1573      } else {
1574          $context = context::instance_by_id($contextid, MUST_EXIST);
1575      }
1576  
1577      if (!$timemodified) {
1578          $timemodified = time();
1579      }
1580  
1581      // Check for existing entry
1582      $ras = $DB->get_records('role_assignments', array('roleid'=>$roleid, 'contextid'=>$context->id, 'userid'=>$userid, 'component'=>$component, 'itemid'=>$itemid), 'id');
1583  
1584      if ($ras) {
1585          // role already assigned - this should not happen
1586          if (count($ras) > 1) {
1587              // very weird - remove all duplicates!
1588              $ra = array_shift($ras);
1589              foreach ($ras as $r) {
1590                  $DB->delete_records('role_assignments', array('id'=>$r->id));
1591              }
1592          } else {
1593              $ra = reset($ras);
1594          }
1595  
1596          // actually there is no need to update, reset anything or trigger any event, so just return
1597          return $ra->id;
1598      }
1599  
1600      // Create a new entry
1601      $ra = new stdClass();
1602      $ra->roleid       = $roleid;
1603      $ra->contextid    = $context->id;
1604      $ra->userid       = $userid;
1605      $ra->component    = $component;
1606      $ra->itemid       = $itemid;
1607      $ra->timemodified = $timemodified;
1608      $ra->modifierid   = empty($USER->id) ? 0 : $USER->id;
1609      $ra->sortorder    = 0;
1610  
1611      $ra->id = $DB->insert_record('role_assignments', $ra);
1612  
1613      // Role assignments have changed, so mark user as dirty.
1614      mark_user_dirty($userid);
1615  
1616      core_course_category::role_assignment_changed($roleid, $context);
1617  
1618      $event = \core\event\role_assigned::create(array(
1619          'context' => $context,
1620          'objectid' => $ra->roleid,
1621          'relateduserid' => $ra->userid,
1622          'other' => array(
1623              'id' => $ra->id,
1624              'component' => $ra->component,
1625              'itemid' => $ra->itemid
1626          )
1627      ));
1628      $event->add_record_snapshot('role_assignments', $ra);
1629      $event->trigger();
1630  
1631      return $ra->id;
1632  }
1633  
1634  /**
1635   * Removes one role assignment
1636   *
1637   * @param int $roleid
1638   * @param int  $userid
1639   * @param int  $contextid
1640   * @param string $component
1641   * @param int  $itemid
1642   * @return void
1643   */
1644  function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
1645      // first make sure the params make sense
1646      if ($roleid == 0 or $userid == 0 or $contextid == 0) {
1647          throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
1648      }
1649  
1650      if ($itemid) {
1651          if (strpos($component, '_') === false) {
1652              throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
1653          }
1654      } else {
1655          $itemid = 0;
1656          if ($component !== '' and strpos($component, '_') === false) {
1657              throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1658          }
1659      }
1660  
1661      role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
1662  }
1663  
1664  /**
1665   * Removes multiple role assignments, parameters may contain:
1666   *   'roleid', 'userid', 'contextid', 'component', 'enrolid'.
1667   *
1668   * @param array $params role assignment parameters
1669   * @param bool $subcontexts unassign in subcontexts too
1670   * @param bool $includemanual include manual role assignments too
1671   * @return void
1672   */
1673  function role_unassign_all(array $params, $subcontexts = false, $includemanual = false) {
1674      global $USER, $CFG, $DB;
1675  
1676      if (!$params) {
1677          throw new coding_exception('Missing parameters in role_unsassign_all() call');
1678      }
1679  
1680      $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
1681      foreach ($params as $key=>$value) {
1682          if (!in_array($key, $allowed)) {
1683              throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
1684          }
1685      }
1686  
1687      if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
1688          throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
1689      }
1690  
1691      if ($includemanual) {
1692          if (!isset($params['component']) or $params['component'] === '') {
1693              throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
1694          }
1695      }
1696  
1697      if ($subcontexts) {
1698          if (empty($params['contextid'])) {
1699              throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
1700          }
1701      }
1702  
1703      $ras = $DB->get_records('role_assignments', $params);
1704      foreach ($ras as $ra) {
1705          $DB->delete_records('role_assignments', array('id'=>$ra->id));
1706          if ($context = context::instance_by_id($ra->contextid, IGNORE_MISSING)) {
1707              // Role assignments have changed, so mark user as dirty.
1708              mark_user_dirty($ra->userid);
1709  
1710              $event = \core\event\role_unassigned::create(array(
1711                  'context' => $context,
1712                  'objectid' => $ra->roleid,
1713                  'relateduserid' => $ra->userid,
1714                  'other' => array(
1715                      'id' => $ra->id,
1716                      'component' => $ra->component,
1717                      'itemid' => $ra->itemid
1718                  )
1719              ));
1720              $event->add_record_snapshot('role_assignments', $ra);
1721              $event->trigger();
1722              core_course_category::role_assignment_changed($ra->roleid, $context);
1723          }
1724      }
1725      unset($ras);
1726  
1727      // process subcontexts
1728      if ($subcontexts and $context = context::instance_by_id($params['contextid'], IGNORE_MISSING)) {
1729          if ($params['contextid'] instanceof context) {
1730              $context = $params['contextid'];
1731          } else {
1732              $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
1733          }
1734  
1735          if ($context) {
1736              $contexts = $context->get_child_contexts();
1737              $mparams = $params;
1738              foreach ($contexts as $context) {
1739                  $mparams['contextid'] = $context->id;
1740                  $ras = $DB->get_records('role_assignments', $mparams);
1741                  foreach ($ras as $ra) {
1742                      $DB->delete_records('role_assignments', array('id'=>$ra->id));
1743                      // Role assignments have changed, so mark user as dirty.
1744                      mark_user_dirty($ra->userid);
1745  
1746                      $event = \core\event\role_unassigned::create(
1747                          array('context'=>$context, 'objectid'=>$ra->roleid, 'relateduserid'=>$ra->userid,
1748                              'other'=>array('id'=>$ra->id, 'component'=>$ra->component, 'itemid'=>$ra->itemid)));
1749                      $event->add_record_snapshot('role_assignments', $ra);
1750                      $event->trigger();
1751                      core_course_category::role_assignment_changed($ra->roleid, $context);
1752                  }
1753              }
1754          }
1755      }
1756  
1757      // do this once more for all manual role assignments
1758      if ($includemanual) {
1759          $params['component'] = '';
1760          role_unassign_all($params, $subcontexts, false);
1761      }
1762  }
1763  
1764  /**
1765   * Mark a user as dirty (with timestamp) so as to force reloading of the user session.
1766   *
1767   * @param int $userid
1768   * @return void
1769   */
1770  function mark_user_dirty($userid) {
1771      global $CFG, $ACCESSLIB_PRIVATE;
1772  
1773      if (during_initial_install()) {
1774          return;
1775      }
1776  
1777      // Throw exception if invalid userid is provided.
1778      if (empty($userid)) {
1779          throw new coding_exception('Invalid user parameter supplied for mark_user_dirty() function!');
1780      }
1781  
1782      // Set dirty flag in database, set dirty field locally, and clear local accessdata cache.
1783      set_cache_flag('accesslib/dirtyusers', $userid, 1, time() + $CFG->sessiontimeout);
1784      $ACCESSLIB_PRIVATE->dirtyusers[$userid] = 1;
1785      unset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid]);
1786  }
1787  
1788  /**
1789   * Determines if a user is currently logged in
1790   *
1791   * @category   access
1792   *
1793   * @return bool
1794   */
1795  function isloggedin() {
1796      global $USER;
1797  
1798      return (!empty($USER->id));
1799  }
1800  
1801  /**
1802   * Determines if a user is logged in as real guest user with username 'guest'.
1803   *
1804   * @category   access
1805   *
1806   * @param int|object $user mixed user object or id, $USER if not specified
1807   * @return bool true if user is the real guest user, false if not logged in or other user
1808   */
1809  function isguestuser($user = null) {
1810      global $USER, $DB, $CFG;
1811  
1812      // make sure we have the user id cached in config table, because we are going to use it a lot
1813      if (empty($CFG->siteguest)) {
1814          if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
1815              // guest does not exist yet, weird
1816              return false;
1817          }
1818          set_config('siteguest', $guestid);
1819      }
1820      if ($user === null) {
1821          $user = $USER;
1822      }
1823  
1824      if ($user === null) {
1825          // happens when setting the $USER
1826          return false;
1827  
1828      } else if (is_numeric($user)) {
1829          return ($CFG->siteguest == $user);
1830  
1831      } else if (is_object($user)) {
1832          if (empty($user->id)) {
1833              return false; // not logged in means is not be guest
1834          } else {
1835              return ($CFG->siteguest == $user->id);
1836          }
1837  
1838      } else {
1839          throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
1840      }
1841  }
1842  
1843  /**
1844   * Does user have a (temporary or real) guest access to course?
1845   *
1846   * @category   access
1847   *
1848   * @param context $context
1849   * @param stdClass|int $user
1850   * @return bool
1851   */
1852  function is_guest(context $context, $user = null) {
1853      global $USER;
1854  
1855      // first find the course context
1856      $coursecontext = $context->get_course_context();
1857  
1858      // make sure there is a real user specified
1859      if ($user === null) {
1860          $userid = isset($USER->id) ? $USER->id : 0;
1861      } else {
1862          $userid = is_object($user) ? $user->id : $user;
1863      }
1864  
1865      if (isguestuser($userid)) {
1866          // can not inspect or be enrolled
1867          return true;
1868      }
1869  
1870      if (has_capability('moodle/course:view', $coursecontext, $user)) {
1871          // viewing users appear out of nowhere, they are neither guests nor participants
1872          return false;
1873      }
1874  
1875      // consider only real active enrolments here
1876      if (is_enrolled($coursecontext, $user, '', true)) {
1877          return false;
1878      }
1879  
1880      return true;
1881  }
1882  
1883  /**
1884   * Returns true if the user has moodle/course:view capability in the course,
1885   * this is intended for admins, managers (aka small admins), inspectors, etc.
1886   *
1887   * @category   access
1888   *
1889   * @param context $context
1890   * @param int|stdClass $user if null $USER is used
1891   * @param string $withcapability extra capability name
1892   * @return bool
1893   */
1894  function is_viewing(context $context, $user = null, $withcapability = '') {
1895      // first find the course context
1896      $coursecontext = $context->get_course_context();
1897  
1898      if (isguestuser($user)) {
1899          // can not inspect
1900          return false;
1901      }
1902  
1903      if (!has_capability('moodle/course:view', $coursecontext, $user)) {
1904          // admins are allowed to inspect courses
1905          return false;
1906      }
1907  
1908      if ($withcapability and !has_capability($withcapability, $context, $user)) {
1909          // site admins always have the capability, but the enrolment above blocks
1910          return false;
1911      }
1912  
1913      return true;
1914  }
1915  
1916  /**
1917   * Returns true if the user is able to access the course.
1918   *
1919   * This function is in no way, shape, or form a substitute for require_login.
1920   * It should only be used in circumstances where it is not possible to call require_login
1921   * such as the navigation.
1922   *
1923   * This function checks many of the methods of access to a course such as the view
1924   * capability, enrollments, and guest access. It also makes use of the cache
1925   * generated by require_login for guest access.
1926   *
1927   * The flags within the $USER object that are used here should NEVER be used outside
1928   * of this function can_access_course and require_login. Doing so WILL break future
1929   * versions.
1930   *
1931   * @param stdClass $course record
1932   * @param stdClass|int|null $user user record or id, current user if null
1933   * @param string $withcapability Check for this capability as well.
1934   * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1935   * @return boolean Returns true if the user is able to access the course
1936   */
1937  function can_access_course(stdClass $course, $user = null, $withcapability = '', $onlyactive = false) {
1938      global $DB, $USER;
1939  
1940      // this function originally accepted $coursecontext parameter
1941      if ($course instanceof context) {
1942          if ($course instanceof context_course) {
1943              debugging('deprecated context parameter, please use $course record');
1944              $coursecontext = $course;
1945              $course = $DB->get_record('course', array('id'=>$coursecontext->instanceid));
1946          } else {
1947              debugging('Invalid context parameter, please use $course record');
1948              return false;
1949          }
1950      } else {
1951          $coursecontext = context_course::instance($course->id);
1952      }
1953  
1954      if (!isset($USER->id)) {
1955          // should never happen
1956          $USER->id = 0;
1957          debugging('Course access check being performed on a user with no ID.', DEBUG_DEVELOPER);
1958      }
1959  
1960      // make sure there is a user specified
1961      if ($user === null) {
1962          $userid = $USER->id;
1963      } else {
1964          $userid = is_object($user) ? $user->id : $user;
1965      }
1966      unset($user);
1967  
1968      if ($withcapability and !has_capability($withcapability, $coursecontext, $userid)) {
1969          return false;
1970      }
1971  
1972      if ($userid == $USER->id) {
1973          if (!empty($USER->access['rsw'][$coursecontext->path])) {
1974              // the fact that somebody switched role means they can access the course no matter to what role they switched
1975              return true;
1976          }
1977      }
1978  
1979      if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext, $userid)) {
1980          return false;
1981      }
1982  
1983      if (is_viewing($coursecontext, $userid)) {
1984          return true;
1985      }
1986  
1987      if ($userid != $USER->id) {
1988          // for performance reasons we do not verify temporary guest access for other users, sorry...
1989          return is_enrolled($coursecontext, $userid, '', $onlyactive);
1990      }
1991  
1992      // === from here we deal only with $USER ===
1993  
1994      $coursecontext->reload_if_dirty();
1995  
1996      if (isset($USER->enrol['enrolled'][$course->id])) {
1997          if ($USER->enrol['enrolled'][$course->id] > time()) {
1998              return true;
1999          }
2000      }
2001      if (isset($USER->enrol['tempguest'][$course->id])) {
2002          if ($USER->enrol['tempguest'][$course->id] > time()) {
2003              return true;
2004          }
2005      }
2006  
2007      if (is_enrolled($coursecontext, $USER, '', $onlyactive)) {
2008          return true;
2009      }
2010  
2011      if (!core_course_category::can_view_course_info($course)) {
2012          // No guest access if user does not have capability to browse courses.
2013          return false;
2014      }
2015  
2016      // if not enrolled try to gain temporary guest access
2017      $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2018      $enrols = enrol_get_plugins(true);
2019      foreach ($instances as $instance) {
2020          if (!isset($enrols[$instance->enrol])) {
2021              continue;
2022          }
2023          // Get a duration for the guest access, a timestamp in the future, 0 (always) or false.
2024          $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2025          if ($until !== false and $until > time()) {
2026              $USER->enrol['tempguest'][$course->id] = $until;
2027              return true;
2028          }
2029      }
2030      if (isset($USER->enrol['tempguest'][$course->id])) {
2031          unset($USER->enrol['tempguest'][$course->id]);
2032          remove_temp_course_roles($coursecontext);
2033      }
2034  
2035      return false;
2036  }
2037  
2038  /**
2039   * Loads the capability definitions for the component (from file).
2040   *
2041   * Loads the capability definitions for the component (from file). If no
2042   * capabilities are defined for the component, we simply return an empty array.
2043   *
2044   * @access private
2045   * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
2046   * @return array array of capabilities
2047   */
2048  function load_capability_def($component) {
2049      $defpath = core_component::get_component_directory($component).'/db/access.php';
2050  
2051      $capabilities = array();
2052      if (file_exists($defpath)) {
2053          require($defpath);
2054          if (!empty(${$component.'_capabilities'})) {
2055              // BC capability array name
2056              // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
2057              debugging('componentname_capabilities array is deprecated, please use $capabilities array only in access.php files');
2058              $capabilities = ${$component.'_capabilities'};
2059          }
2060      }
2061  
2062      return $capabilities;
2063  }
2064  
2065  /**
2066   * Gets the capabilities that have been cached in the database for this component.
2067   *
2068   * @access private
2069   * @param string $component - examples: 'moodle', 'mod_forum'
2070   * @return array array of capabilities
2071   */
2072  function get_cached_capabilities($component = 'moodle') {
2073      global $DB;
2074      $caps = get_all_capabilities();
2075      $componentcaps = array();
2076      foreach ($caps as $cap) {
2077          if ($cap['component'] == $component) {
2078              $componentcaps[] = (object) $cap;
2079          }
2080      }
2081      return $componentcaps;
2082  }
2083  
2084  /**
2085   * Returns default capabilities for given role archetype.
2086   *
2087   * @param string $archetype role archetype
2088   * @return array
2089   */
2090  function get_default_capabilities($archetype) {
2091      global $DB;
2092  
2093      if (!$archetype) {
2094          return array();
2095      }
2096  
2097      $alldefs = array();
2098      $defaults = array();
2099      $components = array();
2100      $allcaps = get_all_capabilities();
2101  
2102      foreach ($allcaps as $cap) {
2103          if (!in_array($cap['component'], $components)) {
2104              $components[] = $cap['component'];
2105              $alldefs = array_merge($alldefs, load_capability_def($cap['component']));
2106          }
2107      }
2108      foreach ($alldefs as $name=>$def) {
2109          // Use array 'archetypes if available. Only if not specified, use 'legacy'.
2110          if (isset($def['archetypes'])) {
2111              if (isset($def['archetypes'][$archetype])) {
2112                  $defaults[$name] = $def['archetypes'][$archetype];
2113              }
2114          // 'legacy' is for backward compatibility with 1.9 access.php
2115          } else {
2116              if (isset($def['legacy'][$archetype])) {
2117                  $defaults[$name] = $def['legacy'][$archetype];
2118              }
2119          }
2120      }
2121  
2122      return $defaults;
2123  }
2124  
2125  /**
2126   * Return default roles that can be assigned, overridden or switched
2127   * by give role archetype.
2128   *
2129   * @param string $type  assign|override|switch|view
2130   * @param string $archetype
2131   * @return array of role ids
2132   */
2133  function get_default_role_archetype_allows($type, $archetype) {
2134      global $DB;
2135  
2136      if (empty($archetype)) {
2137          return array();
2138      }
2139  
2140      $roles = $DB->get_records('role');
2141      $archetypemap = array();
2142      foreach ($roles as $role) {
2143          if ($role->archetype) {
2144              $archetypemap[$role->archetype][$role->id] = $role->id;
2145          }
2146      }
2147  
2148      $defaults = array(
2149          'assign' => array(
2150              'manager'        => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student'),
2151              'coursecreator'  => array(),
2152              'editingteacher' => array('teacher', 'student'),
2153              'teacher'        => array(),
2154              'student'        => array(),
2155              'guest'          => array(),
2156              'user'           => array(),
2157              'frontpage'      => array(),
2158          ),
2159          'override' => array(
2160              'manager'        => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest', 'user', 'frontpage'),
2161              'coursecreator'  => array(),
2162              'editingteacher' => array('teacher', 'student', 'guest'),
2163              'teacher'        => array(),
2164              'student'        => array(),
2165              'guest'          => array(),
2166              'user'           => array(),
2167              'frontpage'      => array(),
2168          ),
2169          'switch' => array(
2170              'manager'        => array('editingteacher', 'teacher', 'student', 'guest'),
2171              'coursecreator'  => array(),
2172              'editingteacher' => array('teacher', 'student', 'guest'),
2173              'teacher'        => array('student', 'guest'),
2174              'student'        => array(),
2175              'guest'          => array(),
2176              'user'           => array(),
2177              'frontpage'      => array(),
2178          ),
2179          'view' => array(
2180              'manager'        => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest', 'user', 'frontpage'),
2181              'coursecreator'  => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2182              'editingteacher' => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2183              'teacher'        => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2184              'student'        => array('coursecreator', 'editingteacher', 'teacher', 'student'),
2185              'guest'          => array(),
2186              'user'           => array(),
2187              'frontpage'      => array(),
2188          ),
2189      );
2190  
2191      if (!isset($defaults[$type][$archetype])) {
2192          debugging("Unknown type '$type'' or archetype '$archetype''");
2193          return array();
2194      }
2195  
2196      $return = array();
2197      foreach ($defaults[$type][$archetype] as $at) {
2198          if (isset($archetypemap[$at])) {
2199              foreach ($archetypemap[$at] as $roleid) {
2200                  $return[$roleid] = $roleid;
2201              }
2202          }
2203      }
2204  
2205      return $return;
2206  }
2207  
2208  /**
2209   * Reset role capabilities to default according to selected role archetype.
2210   * If no archetype selected, removes all capabilities.
2211   *
2212   * This applies to capabilities that are assigned to the role (that you could
2213   * edit in the 'define roles' interface), and not to any capability overrides
2214   * in different locations.
2215   *
2216   * @param int $roleid ID of role to reset capabilities for
2217   */
2218  function reset_role_capabilities($roleid) {
2219      global $DB;
2220  
2221      $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST);
2222      $defaultcaps = get_default_capabilities($role->archetype);
2223  
2224      $systemcontext = context_system::instance();
2225  
2226      $DB->delete_records('role_capabilities',
2227              array('roleid' => $roleid, 'contextid' => $systemcontext->id));
2228  
2229      foreach ($defaultcaps as $cap=>$permission) {
2230          assign_capability($cap, $permission, $roleid, $systemcontext->id);
2231      }
2232  
2233      // Reset any cache of this role, including MUC.
2234      accesslib_clear_role_cache($roleid);
2235  }
2236  
2237  /**
2238   * Updates the capabilities table with the component capability definitions.
2239   * If no parameters are given, the function updates the core moodle
2240   * capabilities.
2241   *
2242   * Note that the absence of the db/access.php capabilities definition file
2243   * will cause any stored capabilities for the component to be removed from
2244   * the database.
2245   *
2246   * @access private
2247   * @param string $component examples: 'moodle', 'mod_forum', 'block_activity_results'
2248   * @return boolean true if success, exception in case of any problems
2249   */
2250  function update_capabilities($component = 'moodle') {
2251      global $DB, $OUTPUT;
2252  
2253      $storedcaps = array();
2254  
2255      $filecaps = load_capability_def($component);
2256      foreach ($filecaps as $capname=>$unused) {
2257          if (!preg_match('|^[a-z]+/[a-z_0-9]+:[a-z_0-9]+$|', $capname)) {
2258              debugging("Coding problem: Invalid capability name '$capname', use 'clonepermissionsfrom' field for migration.");
2259          }
2260      }
2261  
2262      // It is possible somebody directly modified the DB (according to accesslib_test anyway).
2263      // So ensure our updating is based on fresh data.
2264      cache::make('core', 'capabilities')->delete('core_capabilities');
2265  
2266      $cachedcaps = get_cached_capabilities($component);
2267      if ($cachedcaps) {
2268          foreach ($cachedcaps as $cachedcap) {
2269              array_push($storedcaps, $cachedcap->name);
2270              // update risk bitmasks and context levels in existing capabilities if needed
2271              if (array_key_exists($cachedcap->name, $filecaps)) {
2272                  if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2273                      $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
2274                  }
2275                  if ($cachedcap->captype != $filecaps[$cachedcap->name]['captype']) {
2276                      $updatecap = new stdClass();
2277                      $updatecap->id = $cachedcap->id;
2278                      $updatecap->captype = $filecaps[$cachedcap->name]['captype'];
2279                      $DB->update_record('capabilities', $updatecap);
2280                  }
2281                  if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
2282                      $updatecap = new stdClass();
2283                      $updatecap->id = $cachedcap->id;
2284                      $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2285                      $DB->update_record('capabilities', $updatecap);
2286                  }
2287  
2288                  if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2289                      $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2290                  }
2291                  if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2292                      $updatecap = new stdClass();
2293                      $updatecap->id = $cachedcap->id;
2294                      $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2295                      $DB->update_record('capabilities', $updatecap);
2296                  }
2297              }
2298          }
2299      }
2300  
2301      // Flush the cached again, as we have changed DB.
2302      cache::make('core', 'capabilities')->delete('core_capabilities');
2303  
2304      // Are there new capabilities in the file definition?
2305      $newcaps = array();
2306  
2307      foreach ($filecaps as $filecap => $def) {
2308          if (!$storedcaps ||
2309                  ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2310              if (!array_key_exists('riskbitmask', $def)) {
2311                  $def['riskbitmask'] = 0; // no risk if not specified
2312              }
2313              $newcaps[$filecap] = $def;
2314          }
2315      }
2316      // Add new capabilities to the stored definition.
2317      $existingcaps = $DB->get_records_menu('capabilities', array(), 'id', 'id, name');
2318      foreach ($newcaps as $capname => $capdef) {
2319          $capability = new stdClass();
2320          $capability->name         = $capname;
2321          $capability->captype      = $capdef['captype'];
2322          $capability->contextlevel = $capdef['contextlevel'];
2323          $capability->component    = $component;
2324          $capability->riskbitmask  = $capdef['riskbitmask'];
2325  
2326          $DB->insert_record('capabilities', $capability, false);
2327  
2328          // Flush the cached, as we have changed DB.
2329          cache::make('core', 'capabilities')->delete('core_capabilities');
2330  
2331          if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $existingcaps)){
2332              if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
2333                  foreach ($rolecapabilities as $rolecapability){
2334                      //assign_capability will update rather than insert if capability exists
2335                      if (!assign_capability($capname, $rolecapability->permission,
2336                                              $rolecapability->roleid, $rolecapability->contextid, true)){
2337                           echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
2338                      }
2339                  }
2340              }
2341          // we ignore archetype key if we have cloned permissions
2342          } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
2343              assign_legacy_capabilities($capname, $capdef['archetypes']);
2344          // 'legacy' is for backward compatibility with 1.9 access.php
2345          } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
2346              assign_legacy_capabilities($capname, $capdef['legacy']);
2347          }
2348      }
2349      // Are there any capabilities that have been removed from the file
2350      // definition that we need to delete from the stored capabilities and
2351      // role assignments?
2352      capabilities_cleanup($component, $filecaps);
2353  
2354      // reset static caches
2355      accesslib_reset_role_cache();
2356  
2357      // Flush the cached again, as we have changed DB.
2358      cache::make('core', 'capabilities')->delete('core_capabilities');
2359  
2360      return true;
2361  }
2362  
2363  /**
2364   * Deletes cached capabilities that are no longer needed by the component.
2365   * Also unassigns these capabilities from any roles that have them.
2366   * NOTE: this function is called from lib/db/upgrade.php
2367   *
2368   * @access private
2369   * @param string $component examples: 'moodle', 'mod_forum', 'block_activity_results'
2370   * @param array $newcapdef array of the new capability definitions that will be
2371   *                     compared with the cached capabilities
2372   * @return int number of deprecated capabilities that have been removed
2373   */
2374  function capabilities_cleanup($component, $newcapdef = null) {
2375      global $DB;
2376  
2377      $removedcount = 0;
2378  
2379      if ($cachedcaps = get_cached_capabilities($component)) {
2380          foreach ($cachedcaps as $cachedcap) {
2381              if (empty($newcapdef) ||
2382                          array_key_exists($cachedcap->name, $newcapdef) === false) {
2383  
2384                  // Delete from roles.
2385                  if ($roles = get_roles_with_capability($cachedcap->name)) {
2386                      foreach ($roles as $role) {
2387                          if (!unassign_capability($cachedcap->name, $role->id)) {
2388                              throw new \moodle_exception('cannotunassigncap', 'error', '',
2389                                  (object)array('cap' => $cachedcap->name, 'role' => $role->name));
2390                          }
2391                      }
2392                  }
2393  
2394                  // Remove from role_capabilities for any old ones.
2395                  $DB->delete_records('role_capabilities', array('capability' => $cachedcap->name));
2396  
2397                  // Remove from capabilities cache.
2398                  $DB->delete_records('capabilities', array('name' => $cachedcap->name));
2399                  $removedcount++;
2400              } // End if.
2401          }
2402      }
2403      if ($removedcount) {
2404          cache::make('core', 'capabilities')->delete('core_capabilities');
2405      }
2406      return $removedcount;
2407  }
2408  
2409  /**
2410   * Returns an array of all the known types of risk
2411   * The array keys can be used, for example as CSS class names, or in calls to
2412   * print_risk_icon. The values are the corresponding RISK_ constants.
2413   *
2414   * @return array all the known types of risk.
2415   */
2416  function get_all_risks() {
2417      return array(
2418          'riskmanagetrust' => RISK_MANAGETRUST,
2419          'riskconfig'      => RISK_CONFIG,
2420          'riskxss'         => RISK_XSS,
2421          'riskpersonal'    => RISK_PERSONAL,
2422          'riskspam'        => RISK_SPAM,
2423          'riskdataloss'    => RISK_DATALOSS,
2424      );
2425  }
2426  
2427  /**
2428   * Return a link to moodle docs for a given capability name
2429   *
2430   * @param stdClass $capability a capability - a row from the mdl_capabilities table.
2431   * @return string the human-readable capability name as a link to Moodle Docs.
2432   */
2433  function get_capability_docs_link($capability) {
2434      $url = get_docs_url('Capabilities/' . $capability->name);
2435      return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name) . '</a>';
2436  }
2437  
2438  /**
2439   * This function pulls out all the resolved capabilities (overrides and
2440   * defaults) of a role used in capability overrides in contexts at a given
2441   * context.
2442   *
2443   * @param int $roleid
2444   * @param context $context
2445   * @param string $cap capability, optional, defaults to ''
2446   * @return array Array of capabilities
2447   */
2448  function role_context_capabilities($roleid, context $context, $cap = '') {
2449      global $DB;
2450  
2451      $contexts = $context->get_parent_context_ids(true);
2452      $contexts = '('.implode(',', $contexts).')';
2453  
2454      $params = array($roleid);
2455  
2456      if ($cap) {
2457          $search = " AND rc.capability = ? ";
2458          $params[] = $cap;
2459      } else {
2460          $search = '';
2461      }
2462  
2463      $sql = "SELECT rc.*
2464                FROM {role_capabilities} rc
2465                JOIN {context} c ON rc.contextid = c.id
2466                JOIN {capabilities} cap ON rc.capability = cap.name
2467               WHERE rc.contextid in $contexts
2468                     AND rc.roleid = ?
2469                     $search
2470            ORDER BY c.contextlevel DESC, rc.capability DESC";
2471  
2472      $capabilities = array();
2473  
2474      if ($records = $DB->get_records_sql($sql, $params)) {
2475          // We are traversing via reverse order.
2476          foreach ($records as $record) {
2477              // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2478              if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2479                  $capabilities[$record->capability] = $record->permission;
2480              }
2481          }
2482      }
2483      return $capabilities;
2484  }
2485  
2486  /**
2487   * Constructs array with contextids as first parameter and context paths,
2488   * in both cases bottom top including self.
2489   *
2490   * @access private
2491   * @param context $context
2492   * @return array
2493   */
2494  function get_context_info_list(context $context) {
2495      $contextids = explode('/', ltrim($context->path, '/'));
2496      $contextpaths = array();
2497      $contextids2 = $contextids;
2498      while ($contextids2) {
2499          $contextpaths[] = '/' . implode('/', $contextids2);
2500          array_pop($contextids2);
2501      }
2502      return array($contextids, $contextpaths);
2503  }
2504  
2505  /**
2506   * Check if context is the front page context or a context inside it
2507   *
2508   * Returns true if this context is the front page context, or a context inside it,
2509   * otherwise false.
2510   *
2511   * @param context $context a context object.
2512   * @return bool
2513   */
2514  function is_inside_frontpage(context $context) {
2515      $frontpagecontext = context_course::instance(SITEID);
2516      return strpos($context->path . '/', $frontpagecontext->path . '/') === 0;
2517  }
2518  
2519  /**
2520   * Returns capability information (cached)
2521   *
2522   * @param string $capabilityname
2523   * @return stdClass or null if capability not found
2524   */
2525  function get_capability_info($capabilityname) {
2526      $caps = get_all_capabilities();
2527  
2528      // Check for deprecated capability.
2529      if ($deprecatedinfo = get_deprecated_capability_info($capabilityname)) {
2530          if (!empty($deprecatedinfo['replacement'])) {
2531              // Let's try again with this capability if it exists.
2532              if (isset($caps[$deprecatedinfo['replacement']])) {
2533                  $capabilityname = $deprecatedinfo['replacement'];
2534              } else {
2535                  debugging("Capability '{$capabilityname}' was supposed to be replaced with ".
2536                      "'{$deprecatedinfo['replacement']}', which does not exist !");
2537              }
2538          }
2539          $fullmessage = $deprecatedinfo['fullmessage'];
2540          debugging($fullmessage, DEBUG_DEVELOPER);
2541      }
2542      if (!isset($caps[$capabilityname])) {
2543          return null;
2544      }
2545  
2546      return (object) $caps[$capabilityname];
2547  }
2548  
2549  /**
2550   * Returns deprecation info for this particular capabilty (cached)
2551   *
2552   * Do not use this function except in the get_capability_info
2553   *
2554   * @param string $capabilityname
2555   * @return stdClass|null with deprecation message and potential replacement if not null
2556   */
2557  function get_deprecated_capability_info($capabilityname) {
2558      $cache = cache::make('core', 'capabilities');
2559      $alldeprecatedcaps = $cache->get('deprecated_capabilities');
2560      if ($alldeprecatedcaps === false) {
2561          // Look for deprecated capabilities in each component.
2562          $allcaps = get_all_capabilities();
2563          $components = [];
2564          $alldeprecatedcaps = [];
2565          foreach ($allcaps as $cap) {
2566              if (!in_array($cap['component'], $components)) {
2567                  $components[] = $cap['component'];
2568                  $defpath = core_component::get_component_directory($cap['component']).'/db/access.php';
2569                  if (file_exists($defpath)) {
2570                      $deprecatedcapabilities = [];
2571                      require($defpath);
2572                      if (!empty($deprecatedcapabilities)) {
2573                          foreach ($deprecatedcapabilities as $cname => $cdef) {
2574                              $alldeprecatedcaps[$cname] = $cdef;
2575                          }
2576                      }
2577                  }
2578              }
2579          }
2580          $cache->set('deprecated_capabilities', $alldeprecatedcaps);
2581      }
2582  
2583      if (!isset($alldeprecatedcaps[$capabilityname])) {
2584          return null;
2585      }
2586      $deprecatedinfo = $alldeprecatedcaps[$capabilityname];
2587      $deprecatedinfo['fullmessage'] = "The capability '{$capabilityname}' is deprecated.";
2588      if (!empty($deprecatedinfo['message'])) {
2589          $deprecatedinfo['fullmessage'] .= $deprecatedinfo['message'];
2590      }
2591      if (!empty($deprecatedinfo['replacement'])) {
2592          $deprecatedinfo['fullmessage'] .=
2593              "It will be replaced by '{$deprecatedinfo['replacement']}'.";
2594      }
2595      return $deprecatedinfo;
2596  }
2597  
2598  /**
2599   * Returns all capabilitiy records, preferably from MUC and not database.
2600   *
2601   * @return array All capability records indexed by capability name
2602   */
2603  function get_all_capabilities() {
2604      global $DB;
2605      $cache = cache::make('core', 'capabilities');
2606      if (!$allcaps = $cache->get('core_capabilities')) {
2607          $rs = $DB->get_recordset('capabilities');
2608          $allcaps = array();
2609          foreach ($rs as $capability) {
2610              $capability->riskbitmask = (int) $capability->riskbitmask;
2611              $allcaps[$capability->name] = (array) $capability;
2612          }
2613          $rs->close();
2614          $cache->set('core_capabilities', $allcaps);
2615      }
2616      return $allcaps;
2617  }
2618  
2619  /**
2620   * Returns the human-readable, translated version of the capability.
2621   * Basically a big switch statement.
2622   *
2623   * @param string $capabilityname e.g. mod/choice:readresponses
2624   * @return string
2625   */
2626  function get_capability_string($capabilityname) {
2627  
2628      // Typical capability name is 'plugintype/pluginname:capabilityname'
2629      list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
2630  
2631      if ($type === 'moodle') {
2632          $component = 'core_role';
2633      } else if ($type === 'quizreport') {
2634          //ugly hack!!
2635          $component = 'quiz_'.$name;
2636      } else {
2637          $component = $type.'_'.$name;
2638      }
2639  
2640      $stringname = $name.':'.$capname;
2641  
2642      if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
2643          return get_string($stringname, $component);
2644      }
2645  
2646      $dir = core_component::get_component_directory($component);
2647      if (!isset($dir) || !file_exists($dir)) {
2648          // plugin broken or does not exist, do not bother with printing of debug message
2649          return $capabilityname.' ???';
2650      }
2651  
2652      // something is wrong in plugin, better print debug
2653      return get_string($stringname, $component);
2654  }
2655  
2656  /**
2657   * This gets the mod/block/course/core etc strings.
2658   *
2659   * @param string $component
2660   * @param int $contextlevel
2661   * @return string|bool String is success, false if failed
2662   */
2663  function get_component_string($component, $contextlevel) {
2664  
2665      if ($component === 'moodle' || $component === 'core') {
2666          return context_helper::get_level_name($contextlevel);
2667      }
2668  
2669      list($type, $name) = core_component::normalize_component($component);
2670      $dir = core_component::get_plugin_directory($type, $name);
2671      if (!isset($dir) || !file_exists($dir)) {
2672          // plugin not installed, bad luck, there is no way to find the name
2673          return $component . ' ???';
2674      }
2675  
2676      // Some plugin types need an extra prefix to make the name easy to understand.
2677      switch ($type) {
2678          case 'quiz':
2679              $prefix = get_string('quizreport', 'quiz') . ': ';
2680              break;
2681          case 'repository':
2682              $prefix = get_string('repository', 'repository') . ': ';
2683              break;
2684          case 'gradeimport':
2685              $prefix = get_string('gradeimport', 'grades') . ': ';
2686              break;
2687          case 'gradeexport':
2688              $prefix = get_string('gradeexport', 'grades') . ': ';
2689              break;
2690          case 'gradereport':
2691              $prefix = get_string('gradereport', 'grades') . ': ';
2692              break;
2693          case 'webservice':
2694              $prefix = get_string('webservice', 'webservice') . ': ';
2695              break;
2696          case 'block':
2697              $prefix = get_string('block') . ': ';
2698              break;
2699          case 'mod':
2700              $prefix = get_string('activity') . ': ';
2701              break;
2702  
2703          // Default case, just use the plugin name.
2704          default:
2705              $prefix = '';
2706      }
2707      return $prefix . get_string('pluginname', $component);
2708  }
2709  
2710  /**
2711   * Gets the list of roles assigned to this context and up (parents)
2712   * from the aggregation of:
2713   * a) the list of roles that are visible on user profile page and participants page (profileroles setting) and;
2714   * b) if applicable, those roles that are assigned in the context.
2715   *
2716   * @param context $context
2717   * @return array
2718   */
2719  function get_profile_roles(context $context) {
2720      global $CFG, $DB;
2721      // If the current user can assign roles, then they can see all roles on the profile and participants page,
2722      // provided the roles are assigned to at least 1 user in the context. If not, only the policy-defined roles.
2723      if (has_capability('moodle/role:assign', $context)) {
2724          $rolesinscope = array_keys(get_all_roles($context));
2725      } else {
2726          $rolesinscope = empty($CFG->profileroles) ? [] : array_map('trim', explode(',', $CFG->profileroles));
2727      }
2728  
2729      if (empty($rolesinscope)) {
2730          return [];
2731      }
2732  
2733      list($rallowed, $params) = $DB->get_in_or_equal($rolesinscope, SQL_PARAMS_NAMED, 'a');
2734      list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2735      $params = array_merge($params, $cparams);
2736  
2737      if ($coursecontext = $context->get_course_context(false)) {
2738          $params['coursecontext'] = $coursecontext->id;
2739      } else {
2740          $params['coursecontext'] = 0;
2741      }
2742  
2743      $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2744                FROM {role_assignments} ra, {role} r
2745           LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2746               WHERE r.id = ra.roleid
2747                     AND ra.contextid $contextlist
2748                     AND r.id $rallowed
2749            ORDER BY r.sortorder ASC";
2750  
2751      return $DB->get_records_sql($sql, $params);
2752  }
2753  
2754  /**
2755   * Gets the list of roles assigned to this context and up (parents)
2756   *
2757   * @param context $context
2758   * @param boolean $includeparents, false means without parents.
2759   * @return array
2760   */
2761  function get_roles_used_in_context(context $context, $includeparents = true) {
2762      global $DB;
2763  
2764      if ($includeparents === true) {
2765          list($contextlist, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'cl');
2766      } else {
2767          list($contextlist, $params) = $DB->get_in_or_equal($context->id, SQL_PARAMS_NAMED, 'cl');
2768      }
2769  
2770      if ($coursecontext = $context->get_course_context(false)) {
2771          $params['coursecontext'] = $coursecontext->id;
2772      } else {
2773          $params['coursecontext'] = 0;
2774      }
2775  
2776      $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2777                FROM {role_assignments} ra, {role} r
2778           LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2779               WHERE r.id = ra.roleid
2780                     AND ra.contextid $contextlist
2781            ORDER BY r.sortorder ASC";
2782  
2783      return $DB->get_records_sql($sql, $params);
2784  }
2785  
2786  /**
2787   * This function is used to print roles column in user profile page.
2788   * It is using the CFG->profileroles to limit the list to only interesting roles.
2789   * (The permission tab has full details of user role assignments.)
2790   *
2791   * @param int $userid
2792   * @param int $courseid
2793   * @return string
2794   */
2795  function get_user_roles_in_course($userid, $courseid) {
2796      global $CFG, $DB;
2797      if ($courseid == SITEID) {
2798          $context = context_system::instance();
2799      } else {
2800          $context = context_course::instance($courseid);
2801      }
2802      // If the current user can assign roles, then they can see all roles on the profile and participants page,
2803      // provided the roles are assigned to at least 1 user in the context. If not, only the policy-defined roles.
2804      if (has_capability('moodle/role:assign', $context)) {
2805          $rolesinscope = array_keys(get_all_roles($context));
2806      } else {
2807          $rolesinscope = empty($CFG->profileroles) ? [] : array_map('trim', explode(',', $CFG->profileroles));
2808      }
2809      if (empty($rolesinscope)) {
2810          return '';
2811      }
2812  
2813      list($rallowed, $params) = $DB->get_in_or_equal($rolesinscope, SQL_PARAMS_NAMED, 'a');
2814      list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2815      $params = array_merge($params, $cparams);
2816  
2817      if ($coursecontext = $context->get_course_context(false)) {
2818          $params['coursecontext'] = $coursecontext->id;
2819      } else {
2820          $params['coursecontext'] = 0;
2821      }
2822  
2823      $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2824                FROM {role_assignments} ra, {role} r
2825           LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2826               WHERE r.id = ra.roleid
2827                     AND ra.contextid $contextlist
2828                     AND r.id $rallowed
2829                     AND ra.userid = :userid
2830            ORDER BY r.sortorder ASC";
2831      $params['userid'] = $userid;
2832  
2833      $rolestring = '';
2834  
2835      if ($roles = $DB->get_records_sql($sql, $params)) {
2836          $viewableroles = get_viewable_roles($context, $userid);
2837  
2838          $rolenames = array();
2839          foreach ($roles as $roleid => $unused) {
2840              if (isset($viewableroles[$roleid])) {
2841                  $url = new moodle_url('/user/index.php', ['contextid' => $context->id, 'roleid' => $roleid]);
2842                  $rolenames[] = '<a href="' . $url . '">' . $viewableroles[$roleid] . '</a>';
2843              }
2844          }
2845          $rolestring = implode(', ', $rolenames);
2846      }
2847  
2848      return $rolestring;
2849  }
2850  
2851  /**
2852   * Checks if a user can assign users to a particular role in this context
2853   *
2854   * @param context $context
2855   * @param int $targetroleid - the id of the role you want to assign users to
2856   * @return boolean
2857   */
2858  function user_can_assign(context $context, $targetroleid) {
2859      global $DB;
2860  
2861      // First check to see if the user is a site administrator.
2862      if (is_siteadmin()) {
2863          return true;
2864      }
2865  
2866      // Check if user has override capability.
2867      // If not return false.
2868      if (!has_capability('moodle/role:assign', $context)) {
2869          return false;
2870      }
2871      // pull out all active roles of this user from this context(or above)
2872      if ($userroles = get_user_roles($context)) {
2873          foreach ($userroles as $userrole) {
2874              // if any in the role_allow_override table, then it's ok
2875              if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid, 'allowassign'=>$targetroleid))) {
2876                  return true;
2877              }
2878          }
2879      }
2880  
2881      return false;
2882  }
2883  
2884  /**
2885   * Returns all site roles in correct sort order.
2886   *
2887   * Note: this method does not localise role names or descriptions,
2888   *       use role_get_names() if you need role names.
2889   *
2890   * @param context $context optional context for course role name aliases
2891   * @return array of role records with optional coursealias property
2892   */
2893  function get_all_roles(context $context = null) {
2894      global $DB;
2895  
2896      if (!$context or !$coursecontext = $context->get_course_context(false)) {
2897          $coursecontext = null;
2898      }
2899  
2900      if ($coursecontext) {
2901          $sql = "SELECT r.*, rn.name AS coursealias
2902                    FROM {role} r
2903               LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2904                ORDER BY r.sortorder ASC";
2905          return $DB->get_records_sql($sql, array('coursecontext'=>$coursecontext->id));
2906  
2907      } else {
2908          return $DB->get_records('role', array(), 'sortorder ASC');
2909      }
2910  }
2911  
2912  /**
2913   * Returns roles of a specified archetype
2914   *
2915   * @param string $archetype
2916   * @return array of full role records
2917   */
2918  function get_archetype_roles($archetype) {
2919      global $DB;
2920      return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
2921  }
2922  
2923  /**
2924   * Gets all the user roles assigned in this context, or higher contexts for a list of users.
2925   *
2926   * If you try using the combination $userids = [], $checkparentcontexts = true then this is likely
2927   * to cause an out-of-memory error on large Moodle sites, so this combination is deprecated and
2928   * outputs a warning, even though it is the default.
2929   *
2930   * @param context $context
2931   * @param array $userids. An empty list means fetch all role assignments for the context.
2932   * @param bool $checkparentcontexts defaults to true
2933   * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
2934   * @return array
2935   */
2936  function get_users_roles(context $context, $userids = [], $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
2937      global $DB;
2938  
2939      if (!$userids && $checkparentcontexts) {
2940          debugging('Please do not call get_users_roles() with $checkparentcontexts = true ' .
2941                  'and $userids array not set. This combination causes large Moodle sites ' .
2942                  'with lots of site-wide role assignemnts to run out of memory.', DEBUG_DEVELOPER);
2943      }
2944  
2945      if ($checkparentcontexts) {
2946          $contextids = $context->get_parent_context_ids();
2947      } else {
2948          $contextids = array();
2949      }
2950      $contextids[] = $context->id;
2951  
2952      list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
2953  
2954      // If userids was passed as an empty array, we fetch all role assignments for the course.
2955      if (empty($userids)) {
2956          $useridlist = ' IS NOT NULL ';
2957          $uparams = [];
2958      } else {
2959          list($useridlist, $uparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'uids');
2960      }
2961  
2962      $sql = "SELECT ra.*, r.name, r.shortname, ra.userid
2963                FROM {role_assignments} ra, {role} r, {context} c
2964               WHERE ra.userid $useridlist
2965                     AND ra.roleid = r.id
2966                     AND ra.contextid = c.id
2967                     AND ra.contextid $contextids
2968            ORDER BY $order";
2969  
2970      $all = $DB->get_records_sql($sql , array_merge($params, $uparams));
2971  
2972      // Return results grouped by userid.
2973      $result = [];
2974      foreach ($all as $id => $record) {
2975          if (!isset($result[$record->userid])) {
2976              $result[$record->userid] = [];
2977          }
2978          $result[$record->userid][$record->id] = $record;
2979      }
2980  
2981      // Make sure all requested users are included in the result, even if they had no role assignments.
2982      foreach ($userids as $id) {
2983          if (!isset($result[$id])) {
2984              $result[$id] = [];
2985          }
2986      }
2987  
2988      return $result;
2989  }
2990  
2991  
2992  /**
2993   * Gets all the user roles assigned in this context, or higher contexts
2994   * this is mainly used when checking if a user can assign a role, or overriding a role
2995   * i.e. we need to know what this user holds, in order to verify against allow_assign and
2996   * allow_override tables
2997   *
2998   * @param context $context
2999   * @param int $userid
3000   * @param bool $checkparentcontexts defaults to true
3001   * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
3002   * @return array
3003   */
3004  function get_user_roles(context $context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
3005      global $USER, $DB;
3006  
3007      if (empty($userid)) {
3008          if (empty($USER->id)) {
3009              return array();
3010          }
3011          $userid = $USER->id;
3012      }
3013  
3014      if ($checkparentcontexts) {
3015          $contextids = $context->get_parent_context_ids();
3016      } else {
3017          $contextids = array();
3018      }
3019      $contextids[] = $context->id;
3020  
3021      list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM);
3022  
3023      array_unshift($params, $userid);
3024  
3025      $sql = "SELECT ra.*, r.name, r.shortname
3026                FROM {role_assignments} ra, {role} r, {context} c
3027               WHERE ra.userid = ?
3028                     AND ra.roleid = r.id
3029                     AND ra.contextid = c.id
3030                     AND ra.contextid $contextids
3031            ORDER BY $order";
3032  
3033      return $DB->get_records_sql($sql ,$params);
3034  }
3035  
3036  /**
3037   * Like get_user_roles, but adds in the authenticated user role, and the front
3038   * page roles, if applicable.
3039   *
3040   * @param context $context the context.
3041   * @param int $userid optional. Defaults to $USER->id
3042   * @return array of objects with fields ->userid, ->contextid and ->roleid.
3043   */
3044  function get_user_roles_with_special(context $context, $userid = 0) {
3045      global $CFG, $USER;
3046  
3047      if (empty($userid)) {
3048          if (empty($USER->id)) {
3049              return array();
3050          }
3051          $userid = $USER->id;
3052      }
3053  
3054      $ras = get_user_roles($context, $userid);
3055  
3056      // Add front-page role if relevant.
3057      $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3058      $isfrontpage = ($context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID) ||
3059              is_inside_frontpage($context);
3060      if ($defaultfrontpageroleid && $isfrontpage) {
3061          $frontpagecontext = context_course::instance(SITEID);
3062          $ra = new stdClass();
3063          $ra->userid = $userid;
3064          $ra->contextid = $frontpagecontext->id;
3065          $ra->roleid = $defaultfrontpageroleid;
3066          $ras[] = $ra;
3067      }
3068  
3069      // Add authenticated user role if relevant.
3070      $defaultuserroleid      = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3071      if ($defaultuserroleid && !isguestuser($userid)) {
3072          $systemcontext = context_system::instance();
3073          $ra = new stdClass();
3074          $ra->userid = $userid;
3075          $ra->contextid = $systemcontext->id;
3076          $ra->roleid = $defaultuserroleid;
3077          $ras[] = $ra;
3078      }
3079  
3080      return $ras;
3081  }
3082  
3083  /**
3084   * Creates a record in the role_allow_override table
3085   *
3086   * @param int $fromroleid source roleid
3087   * @param int $targetroleid target roleid
3088   * @return void
3089   */
3090  function core_role_set_override_allowed($fromroleid, $targetroleid) {
3091      global $DB;
3092  
3093      $record = new stdClass();
3094      $record->roleid        = $fromroleid;
3095      $record->allowoverride = $targetroleid;
3096      $DB->insert_record('role_allow_override', $record);
3097  }
3098  
3099  /**
3100   * Creates a record in the role_allow_assign table
3101   *
3102   * @param int $fromroleid source roleid
3103   * @param int $targetroleid target roleid
3104   * @return void
3105   */
3106  function core_role_set_assign_allowed($fromroleid, $targetroleid) {
3107      global $DB;
3108  
3109      $record = new stdClass();
3110      $record->roleid      = $fromroleid;
3111      $record->allowassign = $targetroleid;
3112      $DB->insert_record('role_allow_assign', $record);
3113  }
3114  
3115  /**
3116   * Creates a record in the role_allow_switch table
3117   *
3118   * @param int $fromroleid source roleid
3119   * @param int $targetroleid target roleid
3120   * @return void
3121   */
3122  function core_role_set_switch_allowed($fromroleid, $targetroleid) {
3123      global $DB;
3124  
3125      $record = new stdClass();
3126      $record->roleid      = $fromroleid;
3127      $record->allowswitch = $targetroleid;
3128      $DB->insert_record('role_allow_switch', $record);
3129  }
3130  
3131  /**
3132   * Creates a record in the role_allow_view table
3133   *
3134   * @param int $fromroleid source roleid
3135   * @param int $targetroleid target roleid
3136   * @return void
3137   */
3138  function core_role_set_view_allowed($fromroleid, $targetroleid) {
3139      global $DB;
3140  
3141      $record = new stdClass();
3142      $record->roleid      = $fromroleid;
3143      $record->allowview = $targetroleid;
3144      $DB->insert_record('role_allow_view', $record);
3145  }
3146  
3147  /**
3148   * Gets a list of roles that this user can assign in this context
3149   *
3150   * @param context $context the context.
3151   * @param int $rolenamedisplay the type of role name to display. One of the
3152   *      ROLENAME_X constants. Default ROLENAME_ALIAS.
3153   * @param bool $withusercounts if true, count the number of users with each role.
3154   * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
3155   * @return array if $withusercounts is false, then an array $roleid => $rolename.
3156   *      if $withusercounts is true, returns a list of three arrays,
3157   *      $rolenames, $rolecounts, and $nameswithcounts.
3158   */
3159  function get_assignable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withusercounts = false, $user = null) {
3160      global $USER, $DB;
3161  
3162      // make sure there is a real user specified
3163      if ($user === null) {
3164          $userid = isset($USER->id) ? $USER->id : 0;
3165      } else {
3166          $userid = is_object($user) ? $user->id : $user;
3167      }
3168  
3169      if (!has_capability('moodle/role:assign', $context, $userid)) {
3170          if ($withusercounts) {
3171              return array(array(), array(), array());
3172          } else {
3173              return array();
3174          }
3175      }
3176  
3177      $params = array();
3178      $extrafields = '';
3179  
3180      if ($withusercounts) {
3181          $extrafields = ', (SELECT COUNT(DISTINCT u.id)
3182                               FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
3183                              WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
3184                            ) AS usercount';
3185          $params['conid'] = $context->id;
3186      }
3187  
3188      if (is_siteadmin($userid)) {
3189          // show all roles allowed in this context to admins
3190          $assignrestriction = "";
3191      } else {
3192          $parents = $context->get_parent_context_ids(true);
3193          $contexts = implode(',' , $parents);
3194          $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
3195                                        FROM {role_allow_assign} raa
3196                                        JOIN {role_assignments} ra ON ra.roleid = raa.roleid
3197                                       WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3198                                     ) ar ON ar.id = r.id";
3199          $params['userid'] = $userid;
3200      }
3201      $params['contextlevel'] = $context->contextlevel;
3202  
3203      if ($coursecontext = $context->get_course_context(false)) {
3204          $params['coursecontext'] = $coursecontext->id;
3205      } else {
3206          $params['coursecontext'] = 0; // no course aliases
3207          $coursecontext = null;
3208      }
3209      $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias $extrafields
3210                FROM {role} r
3211                $assignrestriction
3212                JOIN {role_context_levels} rcl ON (rcl.contextlevel = :contextlevel AND r.id = rcl.roleid)
3213           LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3214            ORDER BY r.sortorder ASC";
3215      $roles = $DB->get_records_sql($sql, $params);
3216  
3217      $rolenames = role_fix_names($roles, $coursecontext, $rolenamedisplay, true);
3218  
3219      if (!$withusercounts) {
3220          return $rolenames;
3221      }
3222  
3223      $rolecounts = array();
3224      $nameswithcounts = array();
3225      foreach ($roles as $role) {
3226          $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->usercount . ')';
3227          $rolecounts[$role->id] = $roles[$role->id]->usercount;
3228      }
3229      return array($rolenames, $rolecounts, $nameswithcounts);
3230  }
3231  
3232  /**
3233   * Gets a list of roles that this user can switch to in a context
3234   *
3235   * Gets a list of roles that this user can switch to in a context, for the switchrole menu.
3236   * This function just process the contents of the role_allow_switch table. You also need to
3237   * test the moodle/role:switchroles to see if the user is allowed to switch in the first place.
3238   *
3239   * @param context $context a context.
3240   * @param int $rolenamedisplay the type of role name to display. One of the
3241   *      ROLENAME_X constants. Default ROLENAME_ALIAS.
3242   * @return array an array $roleid => $rolename.
3243   */
3244  function get_switchable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS) {
3245      global $USER, $DB;
3246  
3247      // You can't switch roles without this capability.
3248      if (!has_capability('moodle/role:switchroles', $context)) {
3249          return [];
3250      }
3251  
3252      $params = array();
3253      $extrajoins = '';
3254      $extrawhere = '';
3255      if (!is_siteadmin()) {
3256          // Admins are allowed to switch to any role with.
3257          // Others are subject to the additional constraint that the switch-to role must be allowed by
3258          // 'role_allow_switch' for some role they have assigned in this context or any parent.
3259          $parents = $context->get_parent_context_ids(true);
3260          $contexts = implode(',' , $parents);
3261  
3262          $extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
3263          JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3264          $extrawhere = "WHERE ra.userid = :userid AND ra.contextid IN ($contexts)";
3265          $params['userid'] = $USER->id;
3266      }
3267  
3268      if ($coursecontext = $context->get_course_context(false)) {
3269          $params['coursecontext'] = $coursecontext->id;
3270      } else {
3271          $params['coursecontext'] = 0; // no course aliases
3272          $coursecontext = null;
3273      }
3274  
3275      $query = "
3276          SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3277            FROM (SELECT DISTINCT rc.roleid
3278                    FROM {role_capabilities} rc
3279  
3280                    $extrajoins
3281                    $extrawhere) idlist
3282            JOIN {role} r ON r.id = idlist.roleid
3283       LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3284        ORDER BY r.sortorder";
3285      $roles = $DB->get_records_sql($query, $params);
3286  
3287      return role_fix_names($roles, $context, $rolenamedisplay, true);
3288  }
3289  
3290  /**
3291   * Gets a list of roles that this user can view in a context
3292   *
3293   * @param context $context a context.
3294   * @param int $userid id of user.
3295   * @param int $rolenamedisplay the type of role name to display. One of the
3296   *      ROLENAME_X constants. Default ROLENAME_ALIAS.
3297   * @return array an array $roleid => $rolename.
3298   */
3299  function get_viewable_roles(context $context, $userid = null, $rolenamedisplay = ROLENAME_ALIAS) {
3300      global $USER, $DB;
3301  
3302      if ($userid == null) {
3303          $userid = $USER->id;
3304      }
3305  
3306      $params = array();
3307      $extrajoins = '';
3308      $extrawhere = '';
3309      if (!is_siteadmin()) {
3310          // Admins are allowed to view any role.
3311          // Others are subject to the additional constraint that the view role must be allowed by
3312          // 'role_allow_view' for some role they have assigned in this context or any parent.
3313          $contexts = $context->get_parent_context_ids(true);
3314          list($insql, $inparams) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED);
3315  
3316          $extrajoins = "JOIN {role_allow_view} ras ON ras.allowview = r.id
3317                         JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3318          $extrawhere = "WHERE ra.userid = :userid AND ra.contextid $insql";
3319  
3320          $params += $inparams;
3321          $params['userid'] = $userid;
3322      }
3323  
3324      if ($coursecontext = $context->get_course_context(false)) {
3325          $params['coursecontext'] = $coursecontext->id;
3326      } else {
3327          $params['coursecontext'] = 0; // No course aliases.
3328          $coursecontext = null;
3329      }
3330  
3331      $query = "
3332          SELECT r.id, r.name, r.shortname, rn.name AS coursealias, r.sortorder
3333            FROM {role} r
3334            $extrajoins
3335       LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3336            $extrawhere
3337        GROUP BY r.id, r.name, r.shortname, rn.name, r.sortorder
3338        ORDER BY r.sortorder";
3339      $roles = $DB->get_records_sql($query, $params);
3340  
3341      return role_fix_names($roles, $context, $rolenamedisplay, true);
3342  }
3343  
3344  /**
3345   * Gets a list of roles that this user can override in this context.
3346   *
3347   * @param context $context the context.
3348   * @param int $rolenamedisplay the type of role name to display. One of the
3349   *      ROLENAME_X constants. Default ROLENAME_ALIAS.
3350   * @param bool $withcounts if true, count the number of overrides that are set for each role.
3351   * @return array if $withcounts is false, then an array $roleid => $rolename.
3352   *      if $withusercounts is true, returns a list of three arrays,
3353   *      $rolenames, $rolecounts, and $nameswithcounts.
3354   */
3355  function get_overridable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withcounts = false) {
3356      global $USER, $DB;
3357  
3358      if (!has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context)) {
3359          if ($withcounts) {
3360              return array(array(), array(), array());
3361          } else {
3362              return array();
3363          }
3364      }
3365  
3366      $parents = $context->get_parent_context_ids(true);
3367      $contexts = implode(',' , $parents);
3368  
3369      $params = array();
3370      $extrafields = '';
3371  
3372      $params['userid'] = $USER->id;
3373      if ($withcounts) {
3374          $extrafields = ', (SELECT COUNT(rc.id) FROM {role_capabilities} rc
3375                  WHERE rc.roleid = ro.id AND rc.contextid = :conid) AS overridecount';
3376          $params['conid'] = $context->id;
3377      }
3378  
3379      if ($coursecontext = $context->get_course_context(false)) {
3380          $params['coursecontext'] = $coursecontext->id;
3381      } else {
3382          $params['coursecontext'] = 0; // no course aliases
3383          $coursecontext = null;
3384      }
3385  
3386      if (is_siteadmin()) {
3387          // show all roles to admins
3388          $roles = $DB->get_records_sql("
3389              SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3390                FROM {role} ro
3391           LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3392            ORDER BY ro.sortorder ASC", $params);
3393  
3394      } else {
3395          $roles = $DB->get_records_sql("
3396              SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3397                FROM {role} ro
3398                JOIN (SELECT DISTINCT r.id
3399                        FROM {role} r
3400                        JOIN {role_allow_override} rao ON r.id = rao.allowoverride
3401                        JOIN {role_assignments} ra ON rao.roleid = ra.roleid
3402                       WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3403                     ) inline_view ON ro.id = inline_view.id
3404           LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3405            ORDER BY ro.sortorder ASC", $params);
3406      }
3407  
3408      $rolenames = role_fix_names($roles, $context, $rolenamedisplay, true);
3409  
3410      if (!$withcounts) {
3411          return $rolenames;
3412      }
3413  
3414      $rolecounts = array();
3415      $nameswithcounts = array();
3416      foreach ($roles as $role) {
3417          $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->overridecount . ')';
3418          $rolecounts[$role->id] = $roles[$role->id]->overridecount;
3419      }
3420      return array($rolenames, $rolecounts, $nameswithcounts);
3421  }
3422  
3423  /**
3424   * Create a role menu suitable for default role selection in enrol plugins.
3425   *
3426   * @package    core_enrol
3427   *
3428   * @param context $context
3429   * @param int $addroleid current or default role - always added to list
3430   * @return array roleid=>localised role name
3431   */
3432  function get_default_enrol_roles(context $context, $addroleid = null) {
3433      global $DB;
3434  
3435      $params = array('contextlevel'=>CONTEXT_COURSE);
3436  
3437      if ($coursecontext = $context->get_course_context(false)) {
3438          $params['coursecontext'] = $coursecontext->id;
3439      } else {
3440          $params['coursecontext'] = 0; // no course names
3441          $coursecontext = null;
3442      }
3443  
3444      if ($addroleid) {
3445          $addrole = "OR r.id = :addroleid";
3446          $params['addroleid'] = $addroleid;
3447      } else {
3448          $addrole = "";
3449      }
3450  
3451      $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3452                FROM {role} r
3453           LEFT JOIN {role_context_levels} rcl ON (rcl.roleid = r.id AND rcl.contextlevel = :contextlevel)
3454           LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3455               WHERE rcl.id IS NOT NULL $addrole
3456            ORDER BY sortorder DESC";
3457  
3458      $roles = $DB->get_records_sql($sql, $params);
3459  
3460      return role_fix_names($roles, $context, ROLENAME_BOTH, true);
3461  }
3462  
3463  /**
3464   * Return context levels where this role is assignable.
3465   *
3466   * @param integer $roleid the id of a role.
3467   * @return array list of the context levels at which this role may be assigned.
3468   */
3469  function get_role_contextlevels($roleid) {
3470      global $DB;
3471      return $DB->get_records_menu('role_context_levels', array('roleid' => $roleid),
3472              'contextlevel', 'id,contextlevel');
3473  }
3474  
3475  /**
3476   * Return roles suitable for assignment at the specified context level.
3477   *
3478   * NOTE: this function name looks like a typo, should be probably get_roles_for_contextlevel()
3479   *
3480   * @param integer $contextlevel a contextlevel.
3481   * @return array list of role ids that are assignable at this context level.
3482   */
3483  function get_roles_for_contextlevels($contextlevel) {
3484      global $DB;
3485      return $DB->get_records_menu('role_context_levels', array('contextlevel' => $contextlevel),
3486              '', 'id,roleid');
3487  }
3488  
3489  /**
3490   * Returns default context levels where roles can be assigned.
3491   *
3492   * @param string $rolearchetype one of the role archetypes - that is, one of the keys
3493   *      from the array returned by get_role_archetypes();
3494   * @return array list of the context levels at which this type of role may be assigned by default.
3495   */
3496  function get_default_contextlevels($rolearchetype) {
3497      static $defaults = array(
3498          'manager'        => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE),
3499          'coursecreator'  => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT),
3500          'editingteacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3501          'teacher'        => array(CONTEXT_COURSE, CONTEXT_MODULE),
3502          'student'        => array(CONTEXT_COURSE, CONTEXT_MODULE),
3503          'guest'          => array(),
3504          'user'           => array(),
3505          'frontpage'      => array());
3506  
3507      if (isset($defaults[$rolearchetype])) {
3508          return $defaults[$rolearchetype];
3509      } else {
3510          return array();
3511      }
3512  }
3513  
3514  /**
3515   * Set the context levels at which a particular role can be assigned.
3516   * Throws exceptions in case of error.
3517   *
3518   * @param integer $roleid the id of a role.
3519   * @param array $contextlevels the context levels at which this role should be assignable,
3520   *      duplicate levels are removed.
3521   * @return void
3522   */
3523  function set_role_contextlevels($roleid, array $contextlevels) {
3524      global $DB;
3525      $DB->delete_records('role_context_levels', array('roleid' => $roleid));
3526      $rcl = new stdClass();
3527      $rcl->roleid = $roleid;
3528      $contextlevels = array_unique($contextlevels);
3529      foreach ($contextlevels as $level) {
3530          $rcl->contextlevel = $level;
3531          $DB->insert_record('role_context_levels', $rcl, false, true);
3532      }
3533  }
3534  
3535  /**
3536   * Gets sql joins for finding users with capability in the given context.
3537   *
3538   * @param context $context Context for the join.
3539   * @param string|array $capability Capability name or array of names.
3540   *      If an array is provided then this is the equivalent of a logical 'OR',
3541   *      i.e. the user needs to have one of these capabilities.
3542   * @param string $useridcolumn e.g. 'u.id'.
3543   * @return \core\dml\sql_join Contains joins, wheres, params.
3544   *      This function will set ->cannotmatchanyrows if applicable.
3545   *      This may let you skip doing a DB query.
3546   */
3547  function get_with_capability_join(context $context, $capability, $useridcolumn) {
3548      global $CFG, $DB;
3549  
3550      // Add a unique prefix to param names to ensure they are unique.
3551      static $i = 0;
3552      $i++;
3553      $paramprefix = 'eu' . $i . '_';
3554  
3555      $defaultuserroleid      = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3556      $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3557  
3558      $ctxids = trim($context->path, '/');
3559      $ctxids = str_replace('/', ',', $ctxids);
3560  
3561      // Context is the frontpage
3562      $isfrontpage = $context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID;
3563      $isfrontpage = $isfrontpage || is_inside_frontpage($context);
3564  
3565      $caps = (array) $capability;
3566  
3567      // Construct list of context paths bottom --> top.
3568      list($contextids, $paths) = get_context_info_list($context);
3569  
3570      // We need to find out all roles that have these capabilities either in definition or in overrides.
3571      $defs = [];
3572      list($incontexts, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, $paramprefix . 'con');
3573      list($incaps, $params2) = $DB->get_in_or_equal($caps, SQL_PARAMS_NAMED, $paramprefix . 'cap');
3574  
3575      // Check whether context locking is enabled.
3576      // Filter out any write capability if this is the case.
3577      $excludelockedcaps = '';
3578      $excludelockedcapsparams = [];
3579      if (!empty($CFG->contextlocking) && $context->locked) {
3580          $excludelockedcaps = 'AND (cap.captype = :capread OR cap.name = :managelockscap)';
3581          $excludelockedcapsparams['capread'] = 'read';
3582          $excludelockedcapsparams['managelockscap'] = 'moodle/site:managecontextlocks';
3583      }
3584  
3585      $params = array_merge($params, $params2, $excludelockedcapsparams);
3586      $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability, ctx.path
3587                FROM {role_capabilities} rc
3588                JOIN {capabilities} cap ON rc.capability = cap.name
3589                JOIN {context} ctx on rc.contextid = ctx.id
3590               WHERE rc.contextid $incontexts AND rc.capability $incaps $excludelockedcaps";
3591  
3592      $rcs = $DB->get_records_sql($sql, $params);
3593      foreach ($rcs as $rc) {
3594          $defs[$rc->capability][$rc->path][$rc->roleid] = $rc->permission;
3595      }
3596  
3597      // Go through the permissions bottom-->top direction to evaluate the current permission,
3598      // first one wins (prohibit is an exception that always wins).
3599      $access = [];
3600      foreach ($caps as $cap) {
3601          foreach ($paths as $path) {
3602              if (empty($defs[$cap][$path])) {
3603                  continue;
3604              }
3605              foreach ($defs[$cap][$path] as $roleid => $perm) {
3606                  if ($perm == CAP_PROHIBIT) {
3607                      $access[$cap][$roleid] = CAP_PROHIBIT;
3608                      continue;
3609                  }
3610                  if (!isset($access[$cap][$roleid])) {
3611                      $access[$cap][$roleid] = (int)$perm;
3612                  }
3613              }
3614          }
3615      }
3616  
3617      // Make lists of roles that are needed and prohibited in this context.
3618      $needed = []; // One of these is enough.
3619      $prohibited = []; // Must not have any of these.
3620      foreach ($caps as $cap) {
3621          if (empty($access[$cap])) {
3622              continue;
3623          }
3624          foreach ($access[$cap] as $roleid => $perm) {
3625              if ($perm == CAP_PROHIBIT) {
3626                  unset($needed[$cap][$roleid]);
3627                  $prohibited[$cap][$roleid] = true;
3628              } else if ($perm == CAP_ALLOW and empty($prohibited[$cap][$roleid])) {
3629                  $needed[$cap][$roleid] = true;
3630              }
3631          }
3632          if (empty($needed[$cap]) or !empty($prohibited[$cap][$defaultuserroleid])) {
3633              // Easy, nobody has the permission.
3634              unset($needed[$cap]);
3635              unset($prohibited[$cap]);
3636          } else if ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid])) {
3637              // Everybody is disqualified on the frontpage.
3638              unset($needed[$cap]);
3639              unset($prohibited[$cap]);
3640          }
3641          if (empty($prohibited[$cap])) {
3642              unset($prohibited[$cap]);
3643          }
3644      }
3645  
3646      if (empty($needed)) {
3647          // There can not be anybody if no roles match this request.
3648          return new \core\dml\sql_join('', '1 = 2', [], true);
3649      }
3650  
3651      if (empty($prohibited)) {
3652          // We can compact the needed roles.
3653          $n = [];
3654          foreach ($needed as $cap) {
3655              foreach ($cap as $roleid => $unused) {
3656                  $n[$roleid] = true;
3657              }
3658          }
3659          $needed = ['any' => $n];
3660          unset($n);
3661      }
3662  
3663      // Prepare query clauses.
3664      $wherecond = [];
3665      $params    = [];
3666      $joins     = [];
3667      $cannotmatchanyrows = false;
3668  
3669      // We never return deleted users or guest account.
3670      // Use a hack to get the deleted user column without an API change.
3671      $deletedusercolumn = substr($useridcolumn, 0, -2) . 'deleted';
3672      $wherecond[] = "$deletedusercolumn = 0 AND $useridcolumn <> :{$paramprefix}guestid";
3673      $params[$paramprefix . 'guestid'] = $CFG->siteguest;
3674  
3675      // Now add the needed and prohibited roles conditions as joins.
3676      if (!empty($needed['any'])) {
3677          // Simple case - there are no prohibits involved.
3678          if (!empty($needed['any'][$defaultuserroleid]) ||
3679                  ($isfrontpage && !empty($needed['any'][$defaultfrontpageroleid]))) {
3680              // Everybody.
3681          } else {
3682              $joins[] = "JOIN (SELECT DISTINCT userid
3683                                  FROM {role_assignments}
3684                                 WHERE contextid IN ($ctxids)
3685                                       AND roleid IN (" . implode(',', array_keys($needed['any'])) . ")
3686                               ) ra ON ra.userid = $useridcolumn";
3687          }
3688      } else {
3689          $unions = [];
3690          $everybody = false;
3691          foreach ($needed as $cap => $unused) {
3692              if (empty($prohibited[$cap])) {
3693                  if (!empty($needed[$cap][$defaultuserroleid]) ||
3694                          ($isfrontpage && !empty($needed[$cap][$defaultfrontpageroleid]))) {
3695                      $everybody = true;
3696                      break;
3697                  } else {
3698                      $unions[] = "SELECT userid
3699                                     FROM {role_assignments}
3700                                    WHERE contextid IN ($ctxids)
3701                                          AND roleid IN (".implode(',', array_keys($needed[$cap])) .")";
3702                  }
3703              } else {
3704                  if (!empty($prohibited[$cap][$defaultuserroleid]) ||
3705                          ($isfrontpage && !empty($prohibited[$cap][$defaultfrontpageroleid]))) {
3706                      // Nobody can have this cap because it is prohibited in default roles.
3707                      continue;
3708  
3709                  } else if (!empty($needed[$cap][$defaultuserroleid]) ||
3710                          ($isfrontpage && !empty($needed[$cap][$defaultfrontpageroleid]))) {
3711                      // Everybody except the prohibited - hiding does not matter.
3712                      $unions[] = "SELECT id AS userid
3713                                     FROM {user}
3714                                    WHERE id NOT IN (SELECT userid
3715                                                       FROM {role_assignments}
3716                                                      WHERE contextid IN ($ctxids)
3717                                                            AND roleid IN (" . implode(',', array_keys($prohibited[$cap])) . "))";
3718  
3719                  } else {
3720                      $unions[] = "SELECT userid
3721                                     FROM {role_assignments}
3722                                    WHERE contextid IN ($ctxids) AND roleid IN (" . implode(',', array_keys($needed[$cap])) . ")
3723                                          AND userid NOT IN (
3724                                              SELECT userid
3725                                                FROM {role_assignments}
3726                                               WHERE contextid IN ($ctxids)
3727                                                     AND roleid IN (" . implode(',', array_keys($prohibited[$cap])) . "))";
3728                  }
3729              }
3730          }
3731  
3732          if (!$everybody) {
3733              if ($unions) {
3734                  $joins[] = "JOIN (
3735                                    SELECT DISTINCT userid
3736                                      FROM (
3737                                              " . implode("\n UNION \n", $unions) . "
3738                                           ) us
3739                                   ) ra ON ra.userid = $useridcolumn";
3740              } else {
3741                  // Only prohibits found - nobody can be matched.
3742                  $wherecond[] = "1 = 2";
3743                  $cannotmatchanyrows = true;
3744              }
3745          }
3746      }
3747  
3748      return new \core\dml\sql_join(implode("\n", $joins), implode(" AND ", $wherecond), $params, $cannotmatchanyrows);
3749  }
3750  
3751  /**
3752   * Who has this capability in this context?
3753   *
3754   * This can be a very expensive call - use sparingly and keep
3755   * the results if you are going to need them again soon.
3756   *
3757   * Note if $fields is empty this function attempts to get u.*
3758   * which can get rather large - and has a serious perf impact
3759   * on some DBs.
3760   *
3761   * @param context $context
3762   * @param string|array $capability - capability name(s)
3763   * @param string $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
3764   * @param string $sort - the sort order. Default is lastaccess time.
3765   * @param mixed $limitfrom - number of records to skip (offset)
3766   * @param mixed $limitnum - number of records to fetch
3767   * @param string|array $groups - single group or array of groups - only return
3768   *               users who are in one of these group(s).
3769   * @param string|array $exceptions - list of users to exclude, comma separated or array
3770   * @param bool $notuseddoanything not used any more, admin accounts are never returned
3771   * @param bool $notusedview - use get_enrolled_sql() instead
3772   * @param bool $useviewallgroups if $groups is set the return users who
3773   *               have capability both $capability and moodle/site:accessallgroups
3774   *               in this context, as well as users who have $capability and who are
3775   *               in $groups.
3776   * @return array of user records
3777   */
3778  function get_users_by_capability(context $context, $capability, $fields = '', $sort = '', $limitfrom = '', $limitnum = '',
3779          $groups = '', $exceptions = '', $notuseddoanything = null, $notusedview = null, $useviewallgroups = false) {
3780      global $CFG, $DB;
3781  
3782      // Context is a course page other than the frontpage.
3783      $iscoursepage = $context->contextlevel == CONTEXT_COURSE && $context->instanceid != SITEID;
3784  
3785      // Set up default fields list if necessary.
3786      if (empty($fields)) {
3787          if ($iscoursepage) {
3788              $fields = 'u.*, ul.timeaccess AS lastaccess';
3789          } else {
3790              $fields = 'u.*';
3791          }
3792      } else {
3793          if ($CFG->debugdeveloper && strpos($fields, 'u.*') === false && strpos($fields, 'u.id') === false) {
3794              debugging('u.id must be included in the list of fields passed to get_users_by_capability().', DEBUG_DEVELOPER);
3795          }
3796      }
3797  
3798      // Set up default sort if necessary.
3799      if (empty($sort)) { // default to course lastaccess or just lastaccess
3800          if ($iscoursepage) {
3801              $sort = 'ul.timeaccess';
3802          } else {
3803              $sort = 'u.lastaccess';
3804          }
3805      }
3806  
3807      // Get the bits of SQL relating to capabilities.
3808      $sqljoin = get_with_capability_join($context, $capability, 'u.id');
3809      if ($sqljoin->cannotmatchanyrows) {
3810          return [];
3811      }
3812  
3813      // Prepare query clauses.
3814      $wherecond = [$sqljoin->wheres];
3815      $params    = $sqljoin->params;
3816      $joins     = [$sqljoin->joins];
3817  
3818      // Add user lastaccess JOIN, if required.
3819      if ((strpos($sort, 'ul.timeaccess') === false) and (strpos($fields, 'ul.timeaccess') === false)) {
3820           // Here user_lastaccess is not required MDL-13810.
3821      } else {
3822          if ($iscoursepage) {
3823              $joins[] = "LEFT OUTER JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
3824          } else {
3825              throw new coding_exception('Invalid sort in get_users_by_capability(), ul.timeaccess allowed only for course contexts.');
3826          }
3827      }
3828  
3829      // Groups.
3830      if ($groups) {
3831          $groups = (array)$groups;
3832          list($grouptest, $grpparams) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grp');
3833          $joins[] = "LEFT OUTER JOIN (SELECT DISTINCT userid
3834                                         FROM {groups_members}
3835                                        WHERE groupid $grouptest
3836                                      ) gm ON gm.userid = u.id";
3837  
3838          $params = array_merge($params, $grpparams);
3839  
3840          $grouptest = 'gm.userid IS NOT NULL';
3841          if ($useviewallgroups) {
3842              $viewallgroupsusers = get_users_by_capability($context, 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
3843              if (!empty($viewallgroupsusers)) {
3844                  $grouptest .= ' OR u.id IN (' . implode(',', array_keys($viewallgroupsusers)) . ')';
3845              }
3846          }
3847          $wherecond[] = "($grouptest)";
3848      }
3849  
3850      // User exceptions.
3851      if (!empty($exceptions)) {
3852          $exceptions = (array)$exceptions;
3853          list($exsql, $exparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'exc', false);
3854          $params = array_merge($params, $exparams);
3855          $wherecond[] = "u.id $exsql";
3856      }
3857  
3858      // Collect WHERE conditions and needed joins.
3859      $where = implode(' AND ', $wherecond);
3860      if ($where !== '') {
3861          $where = 'WHERE ' . $where;
3862      }
3863      $joins = implode("\n", $joins);
3864  
3865      // Finally! we have all the bits, run the query.
3866      $sql = "SELECT $fields
3867                FROM {user} u
3868              $joins
3869              $where
3870            ORDER BY $sort";
3871  
3872      return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3873  }
3874  
3875  /**
3876   * Re-sort a users array based on a sorting policy
3877   *
3878   * Will re-sort a $users results array (from get_users_by_capability(), usually)
3879   * based on a sorting policy. This is to support the odd practice of
3880   * sorting teachers by 'authority', where authority was "lowest id of the role
3881   * assignment".
3882   *
3883   * Will execute 1 database query. Only suitable for small numbers of users, as it
3884   * uses an u.id IN() clause.
3885   *
3886   * Notes about the sorting criteria.
3887   *
3888   * As a default, we cannot rely on role.sortorder because then
3889   * admins/coursecreators will always win. That is why the sane
3890   * rule "is locality matters most", with sortorder as 2nd
3891   * consideration.
3892   *
3893   * If you want role.sortorder, use the 'sortorder' policy, and
3894   * name explicitly what roles you want to cover. It's probably
3895   * a good idea to see what roles have the capabilities you want
3896   * (array_diff() them against roiles that have 'can-do-anything'
3897   * to weed out admin-ish roles. Or fetch a list of roles from
3898   * variables like $CFG->coursecontact .
3899   *
3900   * @param array $users Users array, keyed on userid
3901   * @param context $context
3902   * @param array $roles ids of the roles to include, optional
3903   * @param string $sortpolicy defaults to locality, more about
3904   * @return array sorted copy of the array
3905   */
3906  function sort_by_roleassignment_authority($users, context $context, $roles = array(), $sortpolicy = 'locality') {
3907      global $DB;
3908  
3909      $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
3910      $contextwhere = 'AND ra.contextid IN ('.str_replace('/', ',',substr($context->path, 1)).')';
3911      if (empty($roles)) {
3912          $roleswhere = '';
3913      } else {
3914          $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
3915      }
3916  
3917      $sql = "SELECT ra.userid
3918                FROM {role_assignments} ra
3919                JOIN {role} r
3920                     ON ra.roleid=r.id
3921                JOIN {context} ctx
3922                     ON ra.contextid=ctx.id
3923               WHERE $userswhere
3924                     $contextwhere
3925                     $roleswhere";
3926  
3927      // Default 'locality' policy -- read PHPDoc notes
3928      // about sort policies...
3929      $orderby = 'ORDER BY '
3930                      .'ctx.depth DESC, '  /* locality wins */
3931                      .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3932                      .'ra.id';            /* role assignment order tie-breaker */
3933      if ($sortpolicy === 'sortorder') {
3934          $orderby = 'ORDER BY '
3935                          .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3936                          .'ra.id';            /* role assignment order tie-breaker */
3937      }
3938  
3939      $sortedids = $DB->get_fieldset_sql($sql . $orderby);
3940      $sortedusers = array();
3941      $seen = array();
3942  
3943      foreach ($sortedids as $id) {
3944          // Avoid duplicates
3945          if (isset($seen[$id])) {
3946              continue;
3947          }
3948          $seen[$id] = true;
3949  
3950          // assign
3951          $sortedusers[$id] = $users[$id];
3952      }
3953      return $sortedusers;
3954  }
3955  
3956  /**
3957   * Gets all the users assigned this role in this context or higher
3958   *
3959   * Note that moodle is based on capabilities and it is usually better
3960   * to check permissions than to check role ids as the capabilities
3961   * system is more flexible. If you really need, you can to use this
3962   * function but consider has_capability() as a possible substitute.
3963   *
3964   * All $sort fields are added into $fields if not present there yet.
3965   *
3966   * If $roleid is an array or is empty (all roles) you need to set $fields
3967   * (and $sort by extension) params according to it, as the first field
3968   * returned by the database should be unique (ra.id is the best candidate).
3969   *
3970   * @param int $roleid (can also be an array of ints!)
3971   * @param context $context
3972   * @param bool $parent if true, get list of users assigned in higher context too
3973   * @param string $fields fields from user (u.) , role assignment (ra) or role (r.)
3974   * @param string $sort sort from user (u.) , role assignment (ra.) or role (r.).
3975   *      null => use default sort from users_order_by_sql.
3976   * @param bool $all true means all, false means limit to enrolled users
3977   * @param string $group defaults to ''
3978   * @param mixed $limitfrom defaults to ''
3979   * @param mixed $limitnum defaults to ''
3980   * @param string $extrawheretest defaults to ''
3981   * @param array $whereorsortparams any paramter values used by $sort or $extrawheretest.
3982   * @return array
3983   */
3984  function get_role_users($roleid, context $context, $parent = false, $fields = '',
3985          $sort = null, $all = true, $group = '',
3986          $limitfrom = '', $limitnum = '', $extrawheretest = '', $whereorsortparams = array()) {
3987      global $DB;
3988  
3989      if (empty($fields)) {
3990          $userfieldsapi = \core_user\fields::for_name();
3991          $allnames = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
3992          $fields = 'u.id, u.confirmed, u.username, '. $allnames . ', ' .
3993                    'u.maildisplay, u.mailformat, u.maildigest, u.email, u.emailstop, u.city, '.
3994                    'u.country, u.picture, u.idnumber, u.department, u.institution, '.
3995                    'u.lang, u.timezone, u.lastaccess, u.mnethostid, r.name AS rolename, r.sortorder, '.
3996                    'r.shortname AS roleshortname, rn.name AS rolecoursealias';
3997      }
3998  
3999      // Prevent wrong function uses.
4000      if ((empty($roleid) || is_array($roleid)) && strpos($fields, 'ra.id') !== 0) {
4001          debugging('get_role_users() without specifying one single roleid needs to be called prefixing ' .
4002              'role assignments id (ra.id) as unique field, you can use $fields param for it.');
4003  
4004          if (!empty($roleid)) {
4005              // Solving partially the issue when specifying multiple roles.
4006              $users = array();
4007              foreach ($roleid as $id) {
4008                  // Ignoring duplicated keys keeping the first user appearance.
4009                  $users = $users + get_role_users($id, $context, $parent, $fields, $sort, $all, $group,
4010                      $limitfrom, $limitnum, $extrawheretest, $whereorsortparams);
4011              }
4012              return $users;
4013          }
4014      }
4015  
4016      $parentcontexts = '';
4017      if ($parent) {
4018          $parentcontexts = substr($context->path, 1); // kill leading slash
4019          $parentcontexts = str_replace('/', ',', $parentcontexts);
4020          if ($parentcontexts !== '') {
4021              $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
4022          }
4023      }
4024  
4025      if ($roleid) {
4026          list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_NAMED, 'r');
4027          $roleselect = "AND ra.roleid $rids";
4028      } else {
4029          $params = array();
4030          $roleselect = '';
4031      }
4032  
4033      if ($coursecontext = $context->get_course_context(false)) {
4034          $params['coursecontext'] = $coursecontext->id;
4035      } else {
4036          $params['coursecontext'] = 0;
4037      }
4038  
4039      if ($group) {
4040          $groupjoin   = "JOIN {groups_members} gm ON gm.userid = u.id";
4041          $groupselect = " AND gm.groupid = :groupid ";
4042          $params['groupid'] = $group;
4043      } else {
4044          $groupjoin   = '';
4045          $groupselect = '';
4046      }
4047  
4048      $params['contextid'] = $context->id;
4049  
4050      if ($extrawheretest) {
4051          $extrawheretest = ' AND ' . $extrawheretest;
4052      }
4053  
4054      if ($whereorsortparams) {
4055          $params = array_merge($params, $whereorsortparams);
4056      }
4057  
4058      if (!$sort) {
4059          list($sort, $sortparams) = users_order_by_sql('u');
4060          $params = array_merge($params, $sortparams);
4061      }
4062  
4063      // Adding the fields from $sort that are not present in $fields.
4064      $sortarray = preg_split('/,\s*/', $sort);
4065      $fieldsarray = preg_split('/,\s*/', $fields);
4066  
4067      // Discarding aliases from the fields.
4068      $fieldnames = array();
4069      foreach ($fieldsarray as $key => $field) {
4070          list($fieldnames[$key]) = explode(' ', $field);
4071      }
4072  
4073      $addedfields = array();
4074      foreach ($sortarray as $sortfield) {
4075          // Throw away any additional arguments to the sort (e.g. ASC/DESC).
4076          list($sortfield) = explode(' ', $sortfield);
4077          list($tableprefix) = explode('.', $sortfield);
4078          $fieldpresent = false;
4079          foreach ($fieldnames as $fieldname) {
4080              if ($fieldname === $sortfield || $fieldname === $tableprefix.'.*') {
4081                  $fieldpresent = true;
4082                  break;
4083              }
4084          }
4085  
4086          if (!$fieldpresent) {
4087              $fieldsarray[] = $sortfield;
4088              $addedfields[] = $sortfield;
4089          }
4090      }
4091  
4092      $fields = implode(', ', $fieldsarray);
4093      if (!empty($addedfields)) {
4094          $addedfields = implode(', ', $addedfields);
4095          debugging('get_role_users() adding '.$addedfields.' to the query result because they were required by $sort but missing in $fields');
4096      }
4097  
4098      if ($all === null) {
4099          // Previously null was used to indicate that parameter was not used.
4100          $all = true;
4101      }
4102      if (!$all and $coursecontext) {
4103          // Do not use get_enrolled_sql() here for performance reasons.
4104          $ejoin = "JOIN {user_enrolments} ue ON ue.userid = u.id
4105                    JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :ecourseid)";
4106          $params['ecourseid'] = $coursecontext->instanceid;
4107      } else {
4108          $ejoin = "";
4109      }
4110  
4111      $sql = "SELECT DISTINCT $fields, ra.roleid
4112                FROM {role_assignments} ra
4113                JOIN {user} u ON u.id = ra.userid
4114                JOIN {role} r ON ra.roleid = r.id
4115              $ejoin
4116           LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
4117          $groupjoin
4118               WHERE (ra.contextid = :contextid $parentcontexts)
4119                     $roleselect
4120                     $groupselect
4121                     $extrawheretest
4122            ORDER BY $sort";                  // join now so that we can just use fullname() later
4123  
4124      return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
4125  }
4126  
4127  /**
4128   * Counts all the users assigned this role in this context or higher
4129   *
4130   * @param int|array $roleid either int or an array of ints
4131   * @param context $context
4132   * @param bool $parent if true, get list of users assigned in higher context too
4133   * @return int Returns the result count
4134   */
4135  function count_role_users($roleid, context $context, $parent = false) {
4136      global $DB;
4137  
4138      if ($parent) {
4139          if ($contexts = $context->get_parent_context_ids()) {
4140              $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
4141          } else {
4142              $parentcontexts = '';
4143          }
4144      } else {
4145          $parentcontexts = '';
4146      }
4147  
4148      if ($roleid) {
4149          list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM);
4150          $roleselect = "AND r.roleid $rids";
4151      } else {
4152          $params = array();
4153          $roleselect = '';
4154      }
4155  
4156      array_unshift($params, $context->id);
4157  
4158      $sql = "SELECT COUNT(DISTINCT u.id)
4159                FROM {role_assignments} r
4160                JOIN {user} u ON u.id = r.userid
4161               WHERE (r.contextid = ? $parentcontexts)
4162                     $roleselect
4163                     AND u.deleted = 0";
4164  
4165      return $DB->count_records_sql($sql, $params);
4166  }
4167  
4168  /**
4169   * This function gets the list of course and course category contexts that this user has a particular capability in.
4170   *
4171   * It is now reasonably efficient, but bear in mind that if there are users who have the capability
4172   * everywhere, it may return an array of all contexts.
4173   *
4174   * @param string $capability Capability in question
4175   * @param int $userid User ID or null for current user
4176   * @param bool $getcategories Wether to return also course_categories
4177   * @param bool $doanything True if 'doanything' is permitted (default)
4178   * @param string $coursefieldsexceptid Leave blank if you only need 'id' in the course records;
4179   *   otherwise use a comma-separated list of the fields you require, not including id.
4180   *   Add ctxid, ctxpath, ctxdepth etc to return course context information for preloading.
4181   * @param string $categoryfieldsexceptid Leave blank if you only need 'id' in the course records;
4182   *   otherwise use a comma-separated list of the fields you require, not including id.
4183   *   Add ctxid, ctxpath, ctxdepth etc to return course context information for preloading.
4184   * @param string $courseorderby If set, use a comma-separated list of fields from course
4185   *   table with sql modifiers (DESC) if needed
4186   * @param string $categoryorderby If set, use a comma-separated list of fields from course_category
4187   *   table with sql modifiers (DESC) if needed
4188   * @param int $limit Limit the number of courses to return on success. Zero equals all entries.
4189   * @return array Array of categories and courses.
4190   */
4191  function get_user_capability_contexts(string $capability, bool $getcategories, $userid = null, $doanything = true,
4192                                        $coursefieldsexceptid = '', $categoryfieldsexceptid = '', $courseorderby = '',
4193                                        $categoryorderby = '', $limit = 0): array {
4194      global $DB, $USER;
4195  
4196      // Default to current user.
4197      if (!$userid) {
4198          $userid = $USER->id;
4199      }
4200  
4201      if (!$capinfo = get_capability_info($capability)) {
4202          debugging('Capability "'.$capability.'" was not found! This has to be fixed in code.');
4203          return [false, false];
4204      }
4205  
4206      if ($doanything && is_siteadmin($userid)) {
4207          // If the user is a site admin and $doanything is enabled then there is no need to restrict
4208          // the list of courses.
4209          $contextlimitsql = '';
4210          $contextlimitparams = [];
4211      } else {
4212          // Gets SQL to limit contexts ('x' table) to those where the user has this capability.
4213          list ($contextlimitsql, $contextlimitparams) = \core\access\get_user_capability_course_helper::get_sql(
4214              $userid, $capinfo->name);
4215          if (!$contextlimitsql) {
4216              // If the does not have this capability in any context, return false without querying.
4217              return [false, false];
4218          }
4219  
4220          $contextlimitsql = 'WHERE' . $contextlimitsql;
4221      }
4222  
4223      $categories = [];
4224      if ($getcategories) {
4225          $fieldlist = \core\access\get_user_capability_course_helper::map_fieldnames($categoryfieldsexceptid);
4226          if ($categoryorderby) {
4227              $fields = explode(',', $categoryorderby);
4228              $categoryorderby = '';
4229              foreach ($fields as $field) {
4230                  if ($categoryorderby) {
4231                      $categoryorderby .= ',';
4232                  }
4233                  $categoryorderby .= 'c.'.$field;
4234              }
4235              $categoryorderby = 'ORDER BY '.$categoryorderby;
4236          }
4237          $rs = $DB->get_recordset_sql("
4238              SELECT c.id $fieldlist
4239                FROM {course_categories} c
4240                 JOIN {context} x ON c.id = x.instanceid AND x.contextlevel = ?
4241              $contextlimitsql
4242              $categoryorderby", array_merge([CONTEXT_COURSECAT], $contextlimitparams));
4243          $basedlimit = $limit;
4244          foreach ($rs as $category) {
4245              $categories[] = $category;
4246              $basedlimit--;
4247              if ($basedlimit == 0) {
4248                  break;
4249              }
4250          }
4251          $rs->close();
4252      }
4253  
4254      $courses = [];
4255      $fieldlist = \core\access\get_user_capability_course_helper::map_fieldnames($coursefieldsexceptid);
4256      if ($courseorderby) {
4257          $fields = explode(',', $courseorderby);
4258          $courseorderby = '';
4259          foreach ($fields as $field) {
4260              if ($courseorderby) {
4261                  $courseorderby .= ',';
4262              }
4263              $courseorderby .= 'c.'.$field;
4264          }
4265          $courseorderby = 'ORDER BY '.$courseorderby;
4266      }
4267      $rs = $DB->get_recordset_sql("
4268              SELECT c.id $fieldlist
4269                FROM {course} c
4270                 JOIN {context} x ON c.id = x.instanceid AND x.contextlevel = ?
4271              $contextlimitsql
4272              $courseorderby", array_merge([CONTEXT_COURSE], $contextlimitparams));
4273      foreach ($rs as $course) {
4274          $courses[] = $course;
4275          $limit--;
4276          if ($limit == 0) {
4277              break;
4278          }
4279      }
4280      $rs->close();
4281      return [$categories, $courses];
4282  }
4283  
4284  /**
4285   * This function gets the list of courses that this user has a particular capability in.
4286   *
4287   * It is now reasonably efficient, but bear in mind that if there are users who have the capability
4288   * everywhere, it may return an array of all courses.
4289   *
4290   * @param string $capability Capability in question
4291   * @param int $userid User ID or null for current user
4292   * @param bool $doanything True if 'doanything' is permitted (default)
4293   * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
4294   *   otherwise use a comma-separated list of the fields you require, not including id.
4295   *   Add ctxid, ctxpath, ctxdepth etc to return course context information for preloading.
4296   * @param string $orderby If set, use a comma-separated list of fields from course
4297   *   table with sql modifiers (DESC) if needed
4298   * @param int $limit Limit the number of courses to return on success. Zero equals all entries.
4299   * @return array|bool Array of courses, if none found false is returned.
4300   */
4301  function get_user_capability_course($capability, $userid = null, $doanything = true, $fieldsexceptid = '',
4302                                      $orderby = '', $limit = 0) {
4303      list($categories, $courses) = get_user_capability_contexts(
4304          $capability,
4305          false,
4306          $userid,
4307          $doanything,
4308          $fieldsexceptid,
4309          '',
4310          $orderby,
4311          '',
4312          $limit
4313      );
4314      return $courses;
4315  }
4316  
4317  /**
4318   * Switches the current user to another role for the current session and only
4319   * in the given context.
4320   *
4321   * The caller *must* check
4322   * - that this op is allowed
4323   * - that the requested role can be switched to in this context (use get_switchable_roles)
4324   * - that the requested role is NOT $CFG->defaultuserroleid
4325   *
4326   * To "unswitch" pass 0 as the roleid.
4327   *
4328   * This function *will* modify $USER->access - beware
4329   *
4330   * @param integer $roleid the role to switch to.
4331   * @param context $context the context in which to perform the switch.
4332   * @return bool success or failure.
4333   */
4334  function role_switch($roleid, context $context) {
4335      global $USER;
4336  
4337      // Add the ghost RA to $USER->access as $USER->access['rsw'][$path] = $roleid.
4338      // To un-switch just unset($USER->access['rsw'][$path]).
4339      //
4340      // Note: it is not possible to switch to roles that do not have course:view
4341  
4342      if (!isset($USER->access)) {
4343          load_all_capabilities();
4344      }
4345  
4346      // Make sure that course index is refreshed.
4347      if ($coursecontext = $context->get_course_context()) {
4348          core_courseformat\base::session_cache_reset(get_course($coursecontext->instanceid));
4349      }
4350  
4351      // Add the switch RA
4352      if ($roleid == 0) {
4353          unset($USER->access['rsw'][$context->path]);
4354          return true;
4355      }
4356  
4357      $USER->access['rsw'][$context->path] = $roleid;
4358  
4359      return true;
4360  }
4361  
4362  /**
4363   * Checks if the user has switched roles within the given course.
4364   *
4365   * Note: You can only switch roles within the course, hence it takes a course id
4366   * rather than a context. On that note Petr volunteered to implement this across
4367   * all other contexts, all requests for this should be forwarded to him ;)
4368   *
4369   * @param int $courseid The id of the course to check
4370   * @return bool True if the user has switched roles within the course.
4371   */
4372  function is_role_switched($courseid) {
4373      global $USER;
4374      $context = context_course::instance($courseid, MUST_EXIST);
4375      return (!empty($USER->access['rsw'][$context->path]));
4376  }
4377  
4378  /**
4379   * Get any role that has an override on exact context
4380   *
4381   * @param context $context The context to check
4382   * @return array An array of roles
4383   */
4384  function get_roles_with_override_on_context(context $context) {
4385      global $DB;
4386  
4387      return $DB->get_records_sql("SELECT r.*
4388                                     FROM {role_capabilities} rc, {role} r
4389                                    WHERE rc.roleid = r.id AND rc.contextid = ?",
4390                                  array($context->id));
4391  }
4392  
4393  /**
4394   * Get all capabilities for this role on this context (overrides)
4395   *
4396   * @param stdClass $role
4397   * @param context $context
4398   * @return array
4399   */
4400  function get_capabilities_from_role_on_context($role, context $context) {
4401      global $DB;
4402  
4403      return $DB->get_records_sql("SELECT *
4404                                     FROM {role_capabilities}
4405                                    WHERE contextid = ? AND roleid = ?",
4406                                  array($context->id, $role->id));
4407  }
4408  
4409  /**
4410   * Find all user assignment of users for this role, on this context
4411   *
4412   * @param stdClass $role
4413   * @param context $context
4414   * @return array
4415   */
4416  function get_users_from_role_on_context($role, context $context) {
4417      global $DB;
4418  
4419      return $DB->get_records_sql("SELECT *
4420                                     FROM {role_assignments}
4421                                    WHERE contextid = ? AND roleid = ?",
4422                                  array($context->id, $role->id));
4423  }
4424  
4425  /**
4426   * Simple function returning a boolean true if user has roles
4427   * in context or parent contexts, otherwise false.
4428   *
4429   * @param int $userid
4430   * @param int $roleid
4431   * @param int $contextid empty means any context
4432   * @return bool
4433   */
4434  function user_has_role_assignment($userid, $roleid, $contextid = 0) {
4435      global $DB;
4436  
4437      if ($contextid) {
4438          if (!$context = context::instance_by_id($contextid, IGNORE_MISSING)) {
4439              return false;
4440          }
4441          $parents = $context->get_parent_context_ids(true);
4442          list($contexts, $params) = $DB->get_in_or_equal($parents, SQL_PARAMS_NAMED, 'r');
4443          $params['userid'] = $userid;
4444          $params['roleid'] = $roleid;
4445  
4446          $sql = "SELECT COUNT(ra.id)
4447                    FROM {role_assignments} ra
4448                   WHERE ra.userid = :userid AND ra.roleid = :roleid AND ra.contextid $contexts";
4449  
4450          $count = $DB->get_field_sql($sql, $params);
4451          return ($count > 0);
4452  
4453      } else {
4454          return $DB->record_exists('role_assignments', array('userid'=>$userid, 'roleid'=>$roleid));
4455      }
4456  }
4457  
4458  /**
4459   * Get localised role name or alias if exists and format the text.
4460   *
4461   * @param stdClass $role role object
4462   *      - optional 'coursealias' property should be included for performance reasons if course context used
4463   *      - description property is not required here
4464   * @param context|bool $context empty means system context
4465   * @param int $rolenamedisplay type of role name
4466   * @return string localised role name or course role name alias
4467   */
4468  function role_get_name(stdClass $role, $context = null, $rolenamedisplay = ROLENAME_ALIAS) {
4469      global $DB;
4470  
4471      if ($rolenamedisplay == ROLENAME_SHORT) {
4472          return $role->shortname;
4473      }
4474  
4475      if (!$context or !$coursecontext = $context->get_course_context(false)) {
4476          $coursecontext = null;
4477      }
4478  
4479      if ($coursecontext and !property_exists($role, 'coursealias') and ($rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH or $rolenamedisplay == ROLENAME_ALIAS_RAW)) {
4480          $role = clone($role); // Do not modify parameters.
4481          if ($r = $DB->get_record('role_names', array('roleid'=>$role->id, 'contextid'=>$coursecontext->id))) {
4482              $role->coursealias = $r->name;
4483          } else {
4484              $role->coursealias = null;
4485          }
4486      }
4487  
4488      if ($rolenamedisplay == ROLENAME_ALIAS_RAW) {
4489          if ($coursecontext) {
4490              return $role->coursealias;
4491          } else {
4492              return null;
4493          }
4494      }
4495  
4496      if (trim($role->name) !== '') {
4497          // For filtering always use context where was the thing defined - system for roles here.
4498          $original = format_string($role->name, true, array('context'=>context_system::instance()));
4499  
4500      } else {
4501          // Empty role->name means we want to see localised role name based on shortname,
4502          // only default roles are supposed to be localised.
4503          switch ($role->shortname) {
4504              case 'manager':         $original = get_string('manager', 'role'); break;
4505              case 'coursecreator':   $original = get_string('coursecreators'); break;
4506              case 'editingteacher':  $original = get_string('defaultcourseteacher'); break;
4507              case 'teacher':         $original = get_string('noneditingteacher'); break;
4508              case 'student':         $original = get_string('defaultcoursestudent'); break;
4509              case 'guest':           $original = get_string('guest'); break;
4510              case 'user':            $original = get_string('authenticateduser'); break;
4511              case 'frontpage':       $original = get_string('frontpageuser', 'role'); break;
4512              // We should not get here, the role UI should require the name for custom roles!
4513              default:                $original = $role->shortname; break;
4514          }
4515      }
4516  
4517      if ($rolenamedisplay == ROLENAME_ORIGINAL) {
4518          return $original;
4519      }
4520  
4521      if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
4522          return "$original ($role->shortname)";
4523      }
4524  
4525      if ($rolenamedisplay == ROLENAME_ALIAS) {
4526          if ($coursecontext && $role->coursealias && trim($role->coursealias) !== '') {
4527              return format_string($role->coursealias, true, array('context'=>$coursecontext));
4528          } else {
4529              return $original;
4530          }
4531      }
4532  
4533      if ($rolenamedisplay == ROLENAME_BOTH) {
4534          if ($coursecontext && $role->coursealias && trim($role->coursealias) !== '') {
4535              return format_string($role->coursealias, true, array('context'=>$coursecontext)) . " ($original)";
4536          } else {
4537              return $original;
4538          }
4539      }
4540  
4541      throw new coding_exception('Invalid $rolenamedisplay parameter specified in role_get_name()');
4542  }
4543  
4544  /**
4545   * Returns localised role description if available.
4546   * If the name is empty it tries to find the default role name using
4547   * hardcoded list of default role names or other methods in the future.
4548   *
4549   * @param stdClass $role
4550   * @return string localised role name
4551   */
4552  function role_get_description(stdClass $role) {
4553      if (!html_is_blank($role->description)) {
4554          return format_text($role->description, FORMAT_HTML, array('context'=>context_system::instance()));
4555      }
4556  
4557      switch ($role->shortname) {
4558          case 'manager':         return get_string('managerdescription', 'role');
4559          case 'coursecreator':   return get_string('coursecreatorsdescription');
4560          case 'editingteacher':  return get_string('defaultcourseteacherdescription');
4561          case 'teacher':         return get_string('noneditingteacherdescription');
4562          case 'student':         return get_string('defaultcoursestudentdescription');
4563          case 'guest':           return get_string('guestdescription');
4564          case 'user':            return get_string('authenticateduserdescription');
4565          case 'frontpage':       return get_string('frontpageuserdescription', 'role');
4566          default:                return '';
4567      }
4568  }
4569  
4570  /**
4571   * Get all the localised role names for a context.
4572   *
4573   * In new installs default roles have empty names, this function
4574   * add localised role names using current language pack.
4575   *
4576   * @param context $context the context, null means system context
4577   * @param array of role objects with a ->localname field containing the context-specific role name.
4578   * @param int $rolenamedisplay
4579   * @param bool $returnmenu true means id=>localname, false means id=>rolerecord
4580   * @return array Array of context-specific role names, or role objects with a ->localname field added.
4581   */
4582  function role_get_names(context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4583      return role_fix_names(get_all_roles($context), $context, $rolenamedisplay, $returnmenu);
4584  }
4585  
4586  /**
4587   * Prepare list of roles for display, apply aliases and localise default role names.
4588   *
4589   * @param array $roleoptions array roleid => roleobject (with optional coursealias), strings are accepted for backwards compatibility only
4590   * @param context $context the context, null means system context
4591   * @param int $rolenamedisplay
4592   * @param bool $returnmenu null means keep the same format as $roleoptions, true means id=>localname, false means id=>rolerecord
4593   * @return array Array of context-specific role names, or role objects with a ->localname field added.
4594   */
4595  function role_fix_names($roleoptions, context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4596      global $DB;
4597  
4598      if (empty($roleoptions)) {
4599          return array();
4600      }
4601  
4602      if (!$context or !$coursecontext = $context->get_course_context(false)) {
4603          $coursecontext = null;
4604      }
4605  
4606      // We usually need all role columns...
4607      $first = reset($roleoptions);
4608      if ($returnmenu === null) {
4609          $returnmenu = !is_object($first);
4610      }
4611  
4612      if (!is_object($first) or !property_exists($first, 'shortname')) {
4613          $allroles = get_all_roles($context);
4614          foreach ($roleoptions as $rid => $unused) {
4615              $roleoptions[$rid] = $allroles[$rid];
4616          }
4617      }
4618  
4619      // Inject coursealias if necessary.
4620      if ($coursecontext and ($rolenamedisplay == ROLENAME_ALIAS_RAW or $rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH)) {
4621          $first = reset($roleoptions);
4622          if (!property_exists($first, 'coursealias')) {
4623              $aliasnames = $DB->get_records('role_names', array('contextid'=>$coursecontext->id));
4624              foreach ($aliasnames as $alias) {
4625                  if (isset($roleoptions[$alias->roleid])) {
4626                      $roleoptions[$alias->roleid]->coursealias = $alias->name;
4627                  }
4628              }
4629          }
4630      }
4631  
4632      // Add localname property.
4633      foreach ($roleoptions as $rid => $role) {
4634          $roleoptions[$rid]->localname = role_get_name($role, $coursecontext, $rolenamedisplay);
4635      }
4636  
4637      if (!$returnmenu) {
4638          return $roleoptions;
4639      }
4640  
4641      $menu = array();
4642      foreach ($roleoptions as $rid => $role) {
4643          $menu[$rid] = $role->localname;
4644      }
4645  
4646      return $menu;
4647  }
4648  
4649  /**
4650   * Aids in detecting if a new line is required when reading a new capability
4651   *
4652   * This function helps admin/roles/manage.php etc to detect if a new line should be printed
4653   * when we read in a new capability.
4654   * Most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
4655   * but when we are in grade, all reports/import/export capabilities should be together
4656   *
4657   * @param string $cap component string a
4658   * @param string $comp component string b
4659   * @param int $contextlevel
4660   * @return bool whether 2 component are in different "sections"
4661   */
4662  function component_level_changed($cap, $comp, $contextlevel) {
4663  
4664      if (strstr($cap->component, '/') && strstr($comp, '/')) {
4665          $compsa = explode('/', $cap->component);
4666          $compsb = explode('/', $comp);
4667  
4668          // list of system reports
4669          if (($compsa[0] == 'report') && ($compsb[0] == 'report')) {
4670              return false;
4671          }
4672  
4673          // we are in gradebook, still
4674          if (($compsa[0] == 'gradeexport' || $compsa[0] == 'gradeimport' || $compsa[0] == 'gradereport') &&
4675              ($compsb[0] == 'gradeexport' || $compsb[0] == 'gradeimport' || $compsb[0] == 'gradereport')) {
4676              return false;
4677          }
4678  
4679          if (($compsa[0] == 'coursereport') && ($compsb[0] == 'coursereport')) {
4680              return false;
4681          }
4682      }
4683  
4684      return ($cap->component != $comp || $cap->contextlevel != $contextlevel);
4685  }
4686  
4687  /**
4688   * Fix the roles.sortorder field in the database, so it contains sequential integers,
4689   * and return an array of roleids in order.
4690   *
4691   * @param array $allroles array of roles, as returned by get_all_roles();
4692   * @return array $role->sortorder =-> $role->id with the keys in ascending order.
4693   */
4694  function fix_role_sortorder($allroles) {
4695      global $DB;
4696  
4697      $rolesort = array();
4698      $i = 0;
4699      foreach ($allroles as $role) {
4700          $rolesort[$i] = $role->id;
4701          if ($role->sortorder != $i) {
4702              $r = new stdClass();
4703              $r->id = $role->id;
4704              $r->sortorder = $i;
4705              $DB->update_record('role', $r);
4706              $allroles[$role->id]->sortorder = $i;
4707          }
4708          $i++;
4709      }
4710      return $rolesort;
4711  }
4712  
4713  /**
4714   * Switch the sort order of two roles (used in admin/roles/manage.php).
4715   *
4716   * @param stdClass $first The first role. Actually, only ->sortorder is used.
4717   * @param stdClass $second The second role. Actually, only ->sortorder is used.
4718   * @return boolean success or failure
4719   */
4720  function switch_roles($first, $second) {
4721      global $DB;
4722      $temp = $DB->get_field('role', 'MAX(sortorder) + 1', array());
4723      $result = $DB->set_field('role', 'sortorder', $temp, array('sortorder' => $first->sortorder));
4724      $result = $result && $DB->set_field('role', 'sortorder', $first->sortorder, array('sortorder' => $second->sortorder));
4725      $result = $result && $DB->set_field('role', 'sortorder', $second->sortorder, array('sortorder' => $temp));
4726      return $result;
4727  }
4728  
4729  /**
4730   * Duplicates all the base definitions of a role
4731   *
4732   * @param stdClass $sourcerole role to copy from
4733   * @param int $targetrole id of role to copy to
4734   */
4735  function role_cap_duplicate($sourcerole, $targetrole) {
4736      global $DB;
4737  
4738      $systemcontext = context_system::instance();
4739      $caps = $DB->get_records_sql("SELECT *
4740                                      FROM {role_capabilities}
4741                                     WHERE roleid = ? AND contextid = ?",
4742                                   array($sourcerole->id, $systemcontext->id));
4743      // adding capabilities
4744      foreach ($caps as $cap) {
4745          unset($cap->id);
4746          $cap->roleid = $targetrole;
4747          $DB->insert_record('role_capabilities', $cap);
4748      }
4749  
4750      // Reset any cache of this role, including MUC.
4751      accesslib_clear_role_cache($targetrole);
4752  }
4753  
4754  /**
4755   * Returns two lists, this can be used to find out if user has capability.
4756   * Having any needed role and no forbidden role in this context means
4757   * user has this capability in this context.
4758   * Use get_role_names_with_cap_in_context() if you need role names to display in the UI
4759   *
4760   * @param stdClass $context
4761   * @param string $capability
4762   * @return array($neededroles, $forbiddenroles)
4763   */
4764  function get_roles_with_cap_in_context($context, $capability) {
4765      global $DB;
4766  
4767      $ctxids = trim($context->path, '/'); // kill leading slash
4768      $ctxids = str_replace('/', ',', $ctxids);
4769  
4770      $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.depth
4771                FROM {role_capabilities} rc
4772                JOIN {context} ctx ON ctx.id = rc.contextid
4773                JOIN {capabilities} cap ON rc.capability = cap.name
4774               WHERE rc.capability = :cap AND ctx.id IN ($ctxids)
4775            ORDER BY rc.roleid ASC, ctx.depth DESC";
4776      $params = array('cap'=>$capability);
4777  
4778      if (!$capdefs = $DB->get_records_sql($sql, $params)) {
4779          // no cap definitions --> no capability
4780          return array(array(), array());
4781      }
4782  
4783      $forbidden = array();
4784      $needed    = array();
4785      foreach ($capdefs as $def) {
4786          if (isset($forbidden[$def->roleid])) {
4787              continue;
4788          }
4789          if ($def->permission == CAP_PROHIBIT) {
4790              $forbidden[$def->roleid] = $def->roleid;
4791              unset($needed[$def->roleid]);
4792              continue;
4793          }
4794          if (!isset($needed[$def->roleid])) {
4795              if ($def->permission == CAP_ALLOW) {
4796                  $needed[$def->roleid] = true;
4797              } else if ($def->permission == CAP_PREVENT) {
4798                  $needed[$def->roleid] = false;
4799              }
4800          }
4801      }
4802      unset($capdefs);
4803  
4804      // remove all those roles not allowing
4805      foreach ($needed as $key=>$value) {
4806          if (!$value) {
4807              unset($needed[$key]);
4808          } else {
4809              $needed[$key] = $key;
4810          }
4811      }
4812  
4813      return array($needed, $forbidden);
4814  }
4815  
4816  /**
4817   * Returns an array of role IDs that have ALL of the the supplied capabilities
4818   * Uses get_roles_with_cap_in_context(). Returns $allowed minus $forbidden
4819   *
4820   * @param stdClass $context
4821   * @param array $capabilities An array of capabilities
4822   * @return array of roles with all of the required capabilities
4823   */
4824  function get_roles_with_caps_in_context($context, $capabilities) {
4825      $neededarr = array();
4826      $forbiddenarr = array();
4827      foreach ($capabilities as $caprequired) {
4828          list($neededarr[], $forbiddenarr[]) = get_roles_with_cap_in_context($context, $caprequired);
4829      }
4830  
4831      $rolesthatcanrate = array();
4832      if (!empty($neededarr)) {
4833          foreach ($neededarr as $needed) {
4834              if (empty($rolesthatcanrate)) {
4835                  $rolesthatcanrate = $needed;
4836              } else {
4837                  //only want roles that have all caps
4838                  $rolesthatcanrate = array_intersect_key($rolesthatcanrate,$needed);
4839              }
4840          }
4841      }
4842      if (!empty($forbiddenarr) && !empty($rolesthatcanrate)) {
4843          foreach ($forbiddenarr as $forbidden) {
4844             //remove any roles that are forbidden any of the caps
4845             $rolesthatcanrate = array_diff($rolesthatcanrate, $forbidden);
4846          }
4847      }
4848      return $rolesthatcanrate;
4849  }
4850  
4851  /**
4852   * Returns an array of role names that have ALL of the the supplied capabilities
4853   * Uses get_roles_with_caps_in_context(). Returns $allowed minus $forbidden
4854   *
4855   * @param stdClass $context
4856   * @param array $capabilities An array of capabilities
4857   * @return array of roles with all of the required capabilities
4858   */
4859  function get_role_names_with_caps_in_context($context, $capabilities) {
4860      global $DB;
4861  
4862      $rolesthatcanrate = get_roles_with_caps_in_context($context, $capabilities);
4863      $allroles = $DB->get_records('role', null, 'sortorder DESC');
4864  
4865      $roles = array();
4866      foreach ($rolesthatcanrate as $r) {
4867          $roles[$r] = $allroles[$r];
4868      }
4869  
4870      return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
4871  }
4872  
4873  /**
4874   * This function verifies the prohibit comes from this context
4875   * and there are no more prohibits in parent contexts.
4876   *
4877   * @param int $roleid
4878   * @param context $context
4879   * @param string $capability name
4880   * @return bool
4881   */
4882  function prohibit_is_removable($roleid, context $context, $capability) {
4883      global $DB;
4884  
4885      $ctxids = trim($context->path, '/'); // kill leading slash
4886      $ctxids = str_replace('/', ',', $ctxids);
4887  
4888      $params = array('roleid'=>$roleid, 'cap'=>$capability, 'prohibit'=>CAP_PROHIBIT);
4889  
4890      $sql = "SELECT ctx.id
4891                FROM {role_capabilities} rc
4892                JOIN {context} ctx ON ctx.id = rc.contextid
4893                JOIN {capabilities} cap ON rc.capability = cap.name
4894               WHERE rc.roleid = :roleid AND rc.permission = :prohibit AND rc.capability = :cap AND ctx.id IN ($ctxids)
4895            ORDER BY ctx.depth DESC";
4896  
4897      if (!$prohibits = $DB->get_records_sql($sql, $params)) {
4898          // no prohibits == nothing to remove
4899          return true;
4900      }
4901  
4902      if (count($prohibits) > 1) {
4903          // more prohibits can not be removed
4904          return false;
4905      }
4906  
4907      return !empty($prohibits[$context->id]);
4908  }
4909  
4910  /**
4911   * More user friendly role permission changing,
4912   * it should produce as few overrides as possible.
4913   *
4914   * @param int $roleid
4915   * @param stdClass $context
4916   * @param string $capname capability name
4917   * @param int $permission
4918   * @return void
4919   */
4920  function role_change_permission($roleid, $context, $capname, $permission) {
4921      global $DB;
4922  
4923      if ($permission == CAP_INHERIT) {
4924          unassign_capability($capname, $roleid, $context->id);
4925          return;
4926      }
4927  
4928      $ctxids = trim($context->path, '/'); // kill leading slash
4929      $ctxids = str_replace('/', ',', $ctxids);
4930  
4931      $params = array('roleid'=>$roleid, 'cap'=>$capname);
4932  
4933      $sql = "SELECT ctx.id, rc.permission, ctx.depth
4934                FROM {role_capabilities} rc
4935                JOIN {context} ctx ON ctx.id = rc.contextid
4936                JOIN {capabilities} cap ON rc.capability = cap.name
4937               WHERE rc.roleid = :roleid AND rc.capability = :cap AND ctx.id IN ($ctxids)
4938            ORDER BY ctx.depth DESC";
4939  
4940      if ($existing = $DB->get_records_sql($sql, $params)) {
4941          foreach ($existing as $e) {
4942              if ($e->permission == CAP_PROHIBIT) {
4943                  // prohibit can not be overridden, no point in changing anything
4944                  return;
4945              }
4946          }
4947          $lowest = array_shift($existing);
4948          if ($lowest->permission == $permission) {
4949              // permission already set in this context or parent - nothing to do
4950              return;
4951          }
4952          if ($existing) {
4953              $parent = array_shift($existing);
4954              if ($parent->permission == $permission) {
4955                  // permission already set in parent context or parent - just unset in this context
4956                  // we do this because we want as few overrides as possible for performance reasons
4957                  unassign_capability($capname, $roleid, $context->id);
4958                  return;
4959              }
4960          }
4961  
4962      } else {
4963          if ($permission == CAP_PREVENT) {
4964              // nothing means role does not have permission
4965              return;
4966          }
4967      }
4968  
4969      // assign the needed capability
4970      assign_capability($capname, $permission, $roleid, $context->id, true);
4971  }
4972  
4973  
4974  /**
4975   * Basic moodle context abstraction class.
4976   *
4977   * Google confirms that no other important framework is using "context" class,
4978   * we could use something else like mcontext or moodle_context, but we need to type
4979   * this very often which would be annoying and it would take too much space...
4980   *
4981   * This class is derived from stdClass for backwards compatibility with
4982   * odl $context record that was returned from DML $DB->get_record()
4983   *
4984   * @package   core_access
4985   * @category  access
4986   * @copyright Petr Skoda {@link http://skodak.org}
4987   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4988   * @since     Moodle 2.2
4989   *
4990   * @property-read int $id context id
4991   * @property-read int $contextlevel CONTEXT_SYSTEM, CONTEXT_COURSE, etc.
4992   * @property-read int $instanceid id of related instance in each context
4993   * @property-read string $path path to context, starts with system context
4994   * @property-read int $depth
4995   */
4996  abstract class context extends stdClass implements IteratorAggregate {
4997  
4998      /** @var string Default sorting of capabilities in {@see get_capabilities} */
4999      protected const DEFAULT_CAPABILITY_SORT = 'contextlevel, component, name';
5000  
5001      /**
5002       * The context id
5003       * Can be accessed publicly through $context->id
5004       * @var int
5005       */
5006      protected $_id;
5007  
5008      /**
5009       * The context level
5010       * Can be accessed publicly through $context->contextlevel
5011       * @var int One of CONTEXT_* e.g. CONTEXT_COURSE, CONTEXT_MODULE
5012       */
5013      protected $_contextlevel;
5014  
5015      /**
5016       * Id of the item this context is related to e.g. COURSE_CONTEXT => course.id
5017       * Can be accessed publicly through $context->instanceid
5018       * @var int
5019       */
5020      protected $_instanceid;
5021  
5022      /**
5023       * The path to the context always starting from the system context
5024       * Can be accessed publicly through $context->path
5025       * @var string
5026       */
5027      protected $_path;
5028  
5029      /**
5030       * The depth of the context in relation to parent contexts
5031       * Can be accessed publicly through $context->depth
5032       * @var int
5033       */
5034      protected $_depth;
5035  
5036      /**
5037       * Whether this context is locked or not.
5038       *
5039       * Can be accessed publicly through $context->locked.
5040       *
5041       * @var int
5042       */
5043      protected $_locked;
5044  
5045      /**
5046       * @var array Context caching info
5047       */
5048      private static $cache_contextsbyid = array();
5049  
5050      /**
5051       * @var array Context caching info
5052       */
5053      private static $cache_contexts     = array();
5054  
5055      /**
5056       * Context count
5057       * Why do we do count contexts? Because count($array) is horribly slow for large arrays
5058       * @var int
5059       */
5060      protected static $cache_count      = 0;
5061  
5062      /**
5063       * @var array Context caching info
5064       */
5065      protected static $cache_preloaded  = array();
5066  
5067      /**
5068       * @var context_system The system context once initialised
5069       */
5070      protected static $systemcontext    = null;
5071  
5072      /**
5073       * Resets the cache to remove all data.
5074       * @static
5075       */
5076      protected static function reset_caches() {
5077          self::$cache_contextsbyid = array();
5078          self::$cache_contexts     = array();
5079          self::$cache_count        = 0;
5080          self::$cache_preloaded    = array();
5081  
5082          self::$systemcontext = null;
5083      }
5084  
5085      /**
5086       * Adds a context to the cache. If the cache is full, discards a batch of
5087       * older entries.
5088       *
5089       * @static
5090       * @param context $context New context to add
5091       * @return void
5092       */
5093      protected static function cache_add(context $context) {
5094          if (isset(self::$cache_contextsbyid[$context->id])) {
5095              // already cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
5096              return;
5097          }
5098  
5099          if (self::$cache_count >= CONTEXT_CACHE_MAX_SIZE) {
5100              $i = 0;
5101              foreach (self::$cache_contextsbyid as $ctx) {
5102                  $i++;
5103                  if ($i <= 100) {
5104                      // we want to keep the first contexts to be loaded on this page, hopefully they will be needed again later
5105                      continue;
5106                  }
5107                  if ($i > (CONTEXT_CACHE_MAX_SIZE / 3)) {
5108                      // we remove oldest third of the contexts to make room for more contexts
5109                      break;
5110                  }
5111                  unset(self::$cache_contextsbyid[$ctx->id]);
5112                  unset(self::$cache_contexts[$ctx->contextlevel][$ctx->instanceid]);
5113                  self::$cache_count--;
5114              }
5115          }
5116  
5117          self::$cache_contexts[$context->contextlevel][$context->instanceid] = $context;
5118          self::$cache_contextsbyid[$context->id] = $context;
5119          self::$cache_count++;
5120      }
5121  
5122      /**
5123       * Removes a context from the cache.
5124       *
5125       * @static
5126       * @param context $context Context object to remove
5127       * @return void
5128       */
5129      protected static function cache_remove(context $context) {
5130          if (!isset(self::$cache_contextsbyid[$context->id])) {
5131              // not cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
5132              return;
5133          }
5134          unset(self::$cache_contexts[$context->contextlevel][$context->instanceid]);
5135          unset(self::$cache_contextsbyid[$context->id]);
5136  
5137          self::$cache_count--;
5138  
5139          if (self::$cache_count < 0) {
5140              self::$cache_count = 0;
5141          }
5142      }
5143  
5144      /**
5145       * Gets a context from the cache.
5146       *
5147       * @static
5148       * @param int $contextlevel Context level
5149       * @param int $instance Instance ID
5150       * @return context|bool Context or false if not in cache
5151       */
5152      protected static function cache_get($contextlevel, $instance) {
5153          if (isset(self::$cache_contexts[$contextlevel][$instance])) {
5154              return self::$cache_contexts[$contextlevel][$instance];
5155          }
5156          return false;
5157      }
5158  
5159      /**
5160       * Gets a context from the cache based on its id.
5161       *
5162       * @static
5163       * @param int $id Context ID
5164       * @return context|bool Context or false if not in cache
5165       */
5166      protected static function cache_get_by_id($id) {
5167          if (isset(self::$cache_contextsbyid[$id])) {
5168              return self::$cache_contextsbyid[$id];
5169          }
5170          return false;
5171      }
5172  
5173      /**
5174       * Preloads context information from db record and strips the cached info.
5175       *
5176       * @static
5177       * @param stdClass $rec
5178       * @return void (modifies $rec)
5179       */
5180      protected static function preload_from_record(stdClass $rec) {
5181          $notenoughdata = false;
5182          $notenoughdata = $notenoughdata || empty($rec->ctxid);
5183          $notenoughdata = $notenoughdata || empty($rec->ctxlevel);
5184          $notenoughdata = $notenoughdata || !isset($rec->ctxinstance);
5185          $notenoughdata = $notenoughdata || empty($rec->ctxpath);
5186          $notenoughdata = $notenoughdata || empty($rec->ctxdepth);
5187          $notenoughdata = $notenoughdata || !isset($rec->ctxlocked);
5188          if ($notenoughdata) {
5189              // The record does not have enough data, passed here repeatedly or context does not exist yet.
5190              if (isset($rec->ctxid) && !isset($rec->ctxlocked)) {
5191                  debugging('Locked value missing. Code is possibly not usings the getter properly.', DEBUG_DEVELOPER);
5192              }
5193              return;
5194          }
5195  
5196          $record = (object) [
5197              'id'            => $rec->ctxid,
5198              'contextlevel'  => $rec->ctxlevel,
5199              'instanceid'    => $rec->ctxinstance,
5200              'path'          => $rec->ctxpath,
5201              'depth'         => $rec->ctxdepth,
5202              'locked'        => $rec->ctxlocked,
5203          ];
5204  
5205          unset($rec->ctxid);
5206          unset($rec->ctxlevel);
5207          unset($rec->ctxinstance);
5208          unset($rec->ctxpath);
5209          unset($rec->ctxdepth);
5210          unset($rec->ctxlocked);
5211  
5212          return context::create_instance_from_record($record);
5213      }
5214  
5215  
5216      // ====== magic methods =======
5217  
5218      /**
5219       * Magic setter method, we do not want anybody to modify properties from the outside
5220       * @param string $name
5221       * @param mixed $value
5222       */
5223      public function __set($name, $value) {
5224          debugging('Can not change context instance properties!');
5225      }
5226  
5227      /**
5228       * Magic method getter, redirects to read only values.
5229       * @param string $name
5230       * @return mixed
5231       */
5232      public function __get($name) {
5233          switch ($name) {
5234              case 'id':
5235                  return $this->_id;
5236              case 'contextlevel':
5237                  return $this->_contextlevel;
5238              case 'instanceid':
5239                  return $this->_instanceid;
5240              case 'path':
5241                  return $this->_path;
5242              case 'depth':
5243                  return $this->_depth;
5244              case 'locked':
5245                  return $this->is_locked();
5246  
5247              default:
5248                  debugging('Invalid context property accessed! '.$name);
5249                  return null;
5250          }
5251      }
5252  
5253      /**
5254       * Full support for isset on our magic read only properties.
5255       * @param string $name
5256       * @return bool
5257       */
5258      public function __isset($name) {
5259          switch ($name) {
5260              case 'id':
5261                  return isset($this->_id);
5262              case 'contextlevel':
5263                  return isset($this->_contextlevel);
5264              case 'instanceid':
5265                  return isset($this->_instanceid);
5266              case 'path':
5267                  return isset($this->_path);
5268              case 'depth':
5269                  return isset($this->_depth);
5270              case 'locked':
5271                  // Locked is always set.
5272                  return true;
5273              default:
5274                  return false;
5275          }
5276      }
5277  
5278      /**
5279       * All properties are read only, sorry.
5280       * @param string $name
5281       */
5282      public function __unset($name) {
5283          debugging('Can not unset context instance properties!');
5284      }
5285  
5286      // ====== implementing method from interface IteratorAggregate ======
5287  
5288      /**
5289       * Create an iterator because magic vars can't be seen by 'foreach'.
5290       *
5291       * Now we can convert context object to array using convert_to_array(),
5292       * and feed it properly to json_encode().
5293       */
5294      public function getIterator(): Traversable {
5295          $ret = array(
5296              'id'           => $this->id,
5297              'contextlevel' => $this->contextlevel,
5298              'instanceid'   => $this->instanceid,
5299              'path'         => $this->path,
5300              'depth'        => $this->depth,
5301              'locked'       => $this->locked,
5302          );
5303          return new ArrayIterator($ret);
5304      }
5305  
5306      // ====== general context methods ======
5307  
5308      /**
5309       * Constructor is protected so that devs are forced to
5310       * use context_xxx::instance() or context::instance_by_id().
5311       *
5312       * @param stdClass $record
5313       */
5314      protected function __construct(stdClass $record) {
5315          $this->_id           = (int)$record->id;
5316          $this->_contextlevel = (int)$record->contextlevel;
5317          $this->_instanceid   = $record->instanceid;
5318          $this->_path         = $record->path;
5319          $this->_depth        = $record->depth;
5320  
5321          if (isset($record->locked)) {
5322              $this->_locked = $record->locked;
5323          } else if (!during_initial_install() && !moodle_needs_upgrading()) {
5324              debugging('Locked value missing. Code is possibly not usings the getter properly.', DEBUG_DEVELOPER);
5325          }
5326      }
5327  
5328      /**
5329       * This function is also used to work around 'protected' keyword problems in context_helper.
5330       * @static
5331       * @param stdClass $record
5332       * @return context instance
5333       */
5334      protected static function create_instance_from_record(stdClass $record) {
5335          $classname = context_helper::get_class_for_level($record->contextlevel);
5336  
5337          if ($context = context::cache_get_by_id($record->id)) {
5338              return $context;
5339          }
5340  
5341          $context = new $classname($record);
5342          context::cache_add($context);
5343  
5344          return $context;
5345      }
5346  
5347      /**
5348       * Copy prepared new contexts from temp table to context table,
5349       * we do this in db specific way for perf reasons only.
5350       * @static
5351       */
5352      protected static function merge_context_temp_table() {
5353          global $DB;
5354  
5355          /* MDL-11347:
5356           *  - mysql does not allow to use FROM in UPDATE statements
5357           *  - using two tables after UPDATE works in mysql, but might give unexpected
5358           *    results in pg 8 (depends on configuration)
5359           *  - using table alias in UPDATE does not work in pg < 8.2
5360           *
5361           * Different code for each database - mostly for performance reasons
5362           */
5363  
5364          $dbfamily = $DB->get_dbfamily();
5365          if ($dbfamily == 'mysql') {
5366              $updatesql = "UPDATE {context} ct, {context_temp} temp
5367                               SET ct.path     = temp.path,
5368                                   ct.depth    = temp.depth,
5369                                   ct.locked   = temp.locked
5370                             WHERE ct.id = temp.id";
5371          } else if ($dbfamily == 'oracle') {
5372              $updatesql = "UPDATE {context} ct
5373                               SET (ct.path, ct.depth, ct.locked) =
5374                                   (SELECT temp.path, temp.depth, temp.locked
5375                                      FROM {context_temp} temp
5376                                     WHERE temp.id=ct.id)
5377                             WHERE EXISTS (SELECT 'x'
5378                                             FROM {context_temp} temp
5379                                             WHERE temp.id = ct.id)";
5380          } else if ($dbfamily == 'postgres' or $dbfamily == 'mssql') {
5381              $updatesql = "UPDATE {context}
5382                               SET path     = temp.path,
5383                                   depth    = temp.depth,
5384                                   locked   = temp.locked
5385                              FROM {context_temp} temp
5386                             WHERE temp.id={context}.id";
5387          } else {
5388              // sqlite and others
5389              $updatesql = "UPDATE {context}
5390                               SET path     = (SELECT path FROM {context_temp} WHERE id = {context}.id),
5391                                   depth    = (SELECT depth FROM {context_temp} WHERE id = {context}.id),
5392                                   locked   = (SELECT locked FROM {context_temp} WHERE id = {context}.id)
5393                               WHERE id IN (SELECT id FROM {context_temp})";
5394          }
5395  
5396          $DB->execute($updatesql);
5397      }
5398  
5399     /**
5400      * Get a context instance as an object, from a given context id.
5401      *
5402      * @static
5403      * @param int $id context id
5404      * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
5405      *                        MUST_EXIST means throw exception if no record found
5406      * @return context|bool the context object or false if not found
5407      */
5408      public static function instance_by_id($id, $strictness = MUST_EXIST) {
5409          global $DB;
5410  
5411          if (get_called_class() !== 'context' and get_called_class() !== 'context_helper') {
5412              // some devs might confuse context->id and instanceid, better prevent these mistakes completely
5413              throw new coding_exception('use only context::instance_by_id() for real context levels use ::instance() methods');
5414          }
5415  
5416          if ($id == SYSCONTEXTID) {
5417              return context_system::instance(0, $strictness);
5418          }
5419  
5420          if (is_array($id) or is_object($id) or empty($id)) {
5421              throw new coding_exception('Invalid context id specified context::instance_by_id()');
5422          }
5423  
5424          if ($context = context::cache_get_by_id($id)) {
5425              return $context;
5426          }
5427  
5428          if ($record = $DB->get_record('context', array('id'=>$id), '*', $strictness)) {
5429              return context::create_instance_from_record($record);
5430          }
5431  
5432          return false;
5433      }
5434  
5435      /**
5436       * Update context info after moving context in the tree structure.
5437       *
5438       * @param context $newparent
5439       * @return void
5440       */
5441      public function update_moved(context $newparent) {
5442          global $DB;
5443  
5444          $frompath = $this->_path;
5445          $newpath  = $newparent->path . '/' . $this->_id;
5446  
5447          $trans = $DB->start_delegated_transaction();
5448  
5449          $setdepth = '';
5450          if (($newparent->depth +1) != $this->_depth) {
5451              $diff = $newparent->depth - $this->_depth + 1;
5452              $setdepth = ", depth = depth + $diff";
5453          }
5454          $sql = "UPDATE {context}
5455                     SET path = ?
5456                         $setdepth
5457                   WHERE id = ?";
5458          $params = array($newpath, $this->_id);
5459          $DB->execute($sql, $params);
5460  
5461          $this->_path  = $newpath;
5462          $this->_depth = $newparent->depth + 1;
5463  
5464          $sql = "UPDATE {context}
5465                     SET path = ".$DB->sql_concat("?", $DB->sql_substr("path", strlen($frompath)+1))."
5466                         $setdepth
5467                   WHERE path LIKE ?";
5468          $params = array($newpath, "{$frompath}/%");
5469          $DB->execute($sql, $params);
5470  
5471          $this->mark_dirty();
5472  
5473          context::reset_caches();
5474  
5475          $trans->allow_commit();
5476      }
5477  
5478      /**
5479       * Set whether this context has been locked or not.
5480       *
5481       * @param   bool    $locked
5482       * @return  $this
5483       */
5484      public function set_locked(bool $locked) {
5485          global $DB;
5486  
5487          if ($this->_locked == $locked) {
5488              return $this;
5489          }
5490  
5491          $this->_locked = $locked;
5492          $DB->set_field('context', 'locked', (int) $locked, ['id' => $this->id]);
5493          $this->mark_dirty();
5494  
5495          if ($locked) {
5496              $eventname = '\\core\\event\\context_locked';
5497          } else {
5498              $eventname = '\\core\\event\\context_unlocked';
5499          }
5500          $event = $eventname::create(['context' => $this, 'objectid' => $this->id]);
5501          $event->trigger();
5502  
5503          self::reset_caches();
5504  
5505          return $this;
5506      }
5507  
5508      /**
5509       * Remove all context path info and optionally rebuild it.
5510       *
5511       * @param bool $rebuild
5512       * @return void
5513       */
5514      public function reset_paths($rebuild = true) {
5515          global $DB;
5516  
5517          if ($this->_path) {
5518              $this->mark_dirty();
5519          }
5520          $DB->set_field_select('context', 'depth', 0, "path LIKE '%/$this->_id/%'");
5521          $DB->set_field_select('context', 'path', NULL, "path LIKE '%/$this->_id/%'");
5522          if ($this->_contextlevel != CONTEXT_SYSTEM) {
5523              $DB->set_field('context', 'depth', 0, array('id'=>$this->_id));
5524              $DB->set_field('context', 'path', NULL, array('id'=>$this->_id));
5525              $this->_depth = 0;
5526              $this->_path = null;
5527          }
5528  
5529          if ($rebuild) {
5530              context_helper::build_all_paths(false);
5531          }
5532  
5533          context::reset_caches();
5534      }
5535  
5536      /**
5537       * Delete all data linked to content, do not delete the context record itself
5538       */
5539      public function delete_content() {
5540          global $CFG, $DB;
5541  
5542          blocks_delete_all_for_context($this->_id);
5543          filter_delete_all_for_context($this->_id);
5544  
5545          require_once($CFG->dirroot . '/comment/lib.php');
5546          comment::delete_comments(array('contextid'=>$this->_id));
5547  
5548          require_once($CFG->dirroot.'/rating/lib.php');
5549          $delopt = new stdclass();
5550          $delopt->contextid = $this->_id;
5551          $rm = new rating_manager();
5552          $rm->delete_ratings($delopt);
5553  
5554          // delete all files attached to this context
5555          $fs = get_file_storage();
5556          $fs->delete_area_files($this->_id);
5557  
5558          // Delete all repository instances attached to this context.
5559          require_once($CFG->dirroot . '/repository/lib.php');
5560          repository::delete_all_for_context($this->_id);
5561  
5562          // delete all advanced grading data attached to this context
5563          require_once($CFG->dirroot.'/grade/grading/lib.php');
5564          grading_manager::delete_all_for_context($this->_id);
5565  
5566          // now delete stuff from role related tables, role_unassign_all
5567          // and unenrol should be called earlier to do proper cleanup
5568          $DB->delete_records('role_assignments', array('contextid'=>$this->_id));
5569          $DB->delete_records('role_names', array('contextid'=>$this->_id));
5570          $this->delete_capabilities();
5571      }
5572  
5573      /**
5574       * Unassign all capabilities from a context.
5575       */
5576      public function delete_capabilities() {
5577          global $DB;
5578  
5579          $ids = $DB->get_fieldset_select('role_capabilities', 'DISTINCT roleid', 'contextid = ?', array($this->_id));
5580          if ($ids) {
5581              $DB->delete_records('role_capabilities', array('contextid' => $this->_id));
5582  
5583              // Reset any cache of these roles, including MUC.
5584              accesslib_clear_role_cache($ids);
5585          }
5586      }
5587  
5588      /**
5589       * Delete the context content and the context record itself
5590       */
5591      public function delete() {
5592          global $DB;
5593  
5594          if ($this->_contextlevel <= CONTEXT_SYSTEM) {
5595              throw new coding_exception('Cannot delete system context');
5596          }
5597  
5598          // double check the context still exists
5599          if (!$DB->record_exists('context', array('id'=>$this->_id))) {
5600              context::cache_remove($this);
5601              return;
5602          }
5603  
5604          $this->delete_content();
5605          $DB->delete_records('context', array('id'=>$this->_id));
5606          // purge static context cache if entry present
5607          context::cache_remove($this);
5608  
5609          // Inform search engine to delete data related to this context.
5610          \core_search\manager::context_deleted($this);
5611      }
5612  
5613      // ====== context level related methods ======
5614  
5615      /**
5616       * Utility method for context creation
5617       *
5618       * @static
5619       * @param int $contextlevel
5620       * @param int $instanceid
5621       * @param string $parentpath
5622       * @return stdClass context record
5623       */
5624      protected static function insert_context_record($contextlevel, $instanceid, $parentpath) {
5625          global $DB;
5626  
5627          $record = new stdClass();
5628          $record->contextlevel = $contextlevel;
5629          $record->instanceid   = $instanceid;
5630          $record->depth        = 0;
5631          $record->path         = null; //not known before insert
5632          $record->locked       = 0;
5633  
5634          $record->id = $DB->insert_record('context', $record);
5635  
5636          // now add path if known - it can be added later
5637          if (!is_null($parentpath)) {
5638              $record->path = $parentpath.'/'.$record->id;
5639              $record->depth = substr_count($record->path, '/');
5640              $DB->update_record('context', $record);
5641          }
5642  
5643          return $record;
5644      }
5645  
5646      /**
5647       * Returns human readable context identifier.
5648       *
5649       * @param boolean $withprefix whether to prefix the name of the context with the
5650       *      type of context, e.g. User, Course, Forum, etc.
5651       * @param boolean $short whether to use the short name of the thing. Only applies
5652       *      to course contexts
5653       * @param boolean $escape Whether the returned name of the thing is to be
5654       *      HTML escaped or not.
5655       * @return string the human readable context name.
5656       */
5657      public function get_context_name($withprefix = true, $short = false, $escape = true) {
5658          // must be implemented in all context levels
5659          throw new coding_exception('can not get name of abstract context');
5660      }
5661  
5662      /**
5663       * Whether the current context is locked.
5664       *
5665       * @return  bool
5666       */
5667      public function is_locked() {
5668          if ($this->_locked) {
5669              return true;
5670          }
5671  
5672          if ($parent = $this->get_parent_context()) {
5673              return $parent->is_locked();
5674          }
5675  
5676          return false;
5677      }
5678  
5679      /**
5680       * Returns the most relevant URL for this context.
5681       *
5682       * @return moodle_url
5683       */
5684      public abstract function get_url();
5685  
5686      /**
5687       * Returns array of relevant context capability records.
5688       *
5689       * @param string $sort SQL order by snippet for sorting returned capabilities sensibly for display
5690       * @return array
5691       */
5692      public abstract function get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT);
5693  
5694      /**
5695       * Recursive function which, given a context, find all its children context ids.
5696       *
5697       * For course category contexts it will return immediate children and all subcategory contexts.
5698       * It will NOT recurse into courses or subcategories categories.
5699       * If you want to do that, call it on the returned courses/categories.
5700       *
5701       * When called for a course context, it will return the modules and blocks
5702       * displayed in the course page and blocks displayed on the module pages.
5703       *
5704       * If called on a user/course/module context it _will_ populate the cache with the appropriate
5705       * contexts ;-)
5706       *
5707       * @return array Array of child records
5708       */
5709      public function get_child_contexts() {
5710          global $DB;
5711  
5712          if (empty($this->_path) or empty($this->_depth)) {
5713              debugging('Can not find child contexts of context '.$this->_id.' try rebuilding of context paths');
5714              return array();
5715          }
5716  
5717          $sql = "SELECT ctx.*
5718                    FROM {context} ctx
5719                   WHERE ctx.path LIKE ?";
5720          $params = array($this->_path.'/%');
5721          $records = $DB->get_records_sql($sql, $params);
5722  
5723          $result = array();
5724          foreach ($records as $record) {
5725              $result[$record->id] = context::create_instance_from_record($record);
5726          }
5727  
5728          return $result;
5729      }
5730  
5731      /**
5732       * Determine if the current context is a parent of the possible child.
5733       *
5734       * @param   context $possiblechild
5735       * @param   bool $includeself Whether to check the current context
5736       * @return  bool
5737       */
5738      public function is_parent_of(context $possiblechild, bool $includeself): bool {
5739          // A simple substring check is used on the context path.
5740          // The possible child's path is used as a haystack, with the current context as the needle.
5741          // The path is prefixed with '+' to ensure that the parent always starts at the top.
5742          // It is suffixed with '+' to ensure that parents are not included.
5743          // The needle always suffixes with a '/' to ensure that the contextid uses a complete match (i.e. 142/ instead of 14).
5744          // The haystack is suffixed with '/+' if $includeself is true to allow the current context to match.
5745          // The haystack is suffixed with '+' if $includeself is false to prevent the current context from matching.
5746          $haystacksuffix = $includeself ? '/+' : '+';
5747  
5748          $strpos = strpos(
5749              "+{$possiblechild->path}{$haystacksuffix}",
5750              "+{$this->path}/"
5751          );
5752          return $strpos === 0;
5753      }
5754  
5755      /**
5756       * Returns parent contexts of this context in reversed order, i.e. parent first,
5757       * then grand parent, etc.
5758       *
5759       * @param bool $includeself true means include self too
5760       * @return array of context instances
5761       */
5762      public function get_parent_contexts($includeself = false) {
5763          if (!$contextids = $this->get_parent_context_ids($includeself)) {
5764              return array();
5765          }
5766  
5767          // Preload the contexts to reduce DB calls.
5768          context_helper::preload_contexts_by_id($contextids);
5769  
5770          $result = array();
5771          foreach ($contextids as $contextid) {
5772              $parent = context::instance_by_id($contextid, MUST_EXIST);
5773              $result[$parent->id] = $parent;
5774          }
5775  
5776          return $result;
5777      }
5778  
5779      /**
5780       * Determine if the current context is a child of the possible parent.
5781       *
5782       * @param   context $possibleparent
5783       * @param   bool $includeself Whether to check the current context
5784       * @return  bool
5785       */
5786      public function is_child_of(context $possibleparent, bool $includeself): bool {
5787          // A simple substring check is used on the context path.
5788          // The current context is used as a haystack, with the possible parent as the needle.
5789          // The path is prefixed with '+' to ensure that the parent always starts at the top.
5790          // It is suffixed with '+' to ensure that children are not included.
5791          // The needle always suffixes with a '/' to ensure that the contextid uses a complete match (i.e. 142/ instead of 14).
5792          // The haystack is suffixed with '/+' if $includeself is true to allow the current context to match.
5793          // The haystack is suffixed with '+' if $includeself is false to prevent the current context from matching.
5794          $haystacksuffix = $includeself ? '/+' : '+';
5795  
5796          $strpos = strpos(
5797              "+{$this->path}{$haystacksuffix}",
5798              "+{$possibleparent->path}/"
5799          );
5800          return $strpos === 0;
5801      }
5802  
5803      /**
5804       * Returns parent context ids of this context in reversed order, i.e. parent first,
5805       * then grand parent, etc.
5806       *
5807       * @param bool $includeself true means include self too
5808       * @return array of context ids
5809       */
5810      public function get_parent_context_ids($includeself = false) {
5811          if (empty($this->_path)) {
5812              return array();
5813          }
5814  
5815          $parentcontexts = trim($this->_path, '/'); // kill leading slash
5816          $parentcontexts = explode('/', $parentcontexts);
5817          if (!$includeself) {
5818              array_pop($parentcontexts); // and remove its own id
5819          }
5820  
5821          return array_reverse($parentcontexts);
5822      }
5823  
5824      /**
5825       * Returns parent context paths of this context.
5826       *
5827       * @param bool $includeself true means include self too
5828       * @return array of context paths
5829       */
5830      public function get_parent_context_paths($includeself = false) {
5831          if (empty($this->_path)) {
5832              return array();
5833          }
5834  
5835          $contextids = explode('/', $this->_path);
5836  
5837          $path = '';
5838          $paths = array();
5839          foreach ($contextids as $contextid) {
5840              if ($contextid) {
5841                  $path .= '/' . $contextid;
5842                  $paths[$contextid] = $path;
5843              }
5844          }
5845  
5846          if (!$includeself) {
5847              unset($paths[$this->_id]);
5848          }
5849  
5850          return $paths;
5851      }
5852  
5853      /**
5854       * Returns parent context
5855       *
5856       * @return context
5857       */
5858      public function get_parent_context() {
5859          if (empty($this->_path) or $this->_id == SYSCONTEXTID) {
5860              return false;
5861          }
5862  
5863          $parentcontexts = trim($this->_path, '/'); // kill leading slash
5864          $parentcontexts = explode('/', $parentcontexts);
5865          array_pop($parentcontexts); // self
5866          $contextid = array_pop($parentcontexts); // immediate parent
5867  
5868          return context::instance_by_id($contextid, MUST_EXIST);
5869      }
5870  
5871      /**
5872       * Is this context part of any course? If yes return course context.
5873       *
5874       * @param bool $strict true means throw exception if not found, false means return false if not found
5875       * @return context_course context of the enclosing course, null if not found or exception
5876       */
5877      public function get_course_context($strict = true) {
5878          if ($strict) {
5879              throw new coding_exception('Context does not belong to any course.');
5880          } else {
5881              return false;
5882          }
5883      }
5884  
5885      /**
5886       * Returns sql necessary for purging of stale context instances.
5887       *
5888       * @static
5889       * @return string cleanup SQL
5890       */
5891      protected static function get_cleanup_sql() {
5892          throw new coding_exception('get_cleanup_sql() method must be implemented in all context levels');
5893      }
5894  
5895      /**
5896       * Rebuild context paths and depths at context level.
5897       *
5898       * @static
5899       * @param bool $force
5900       * @return void
5901       */
5902      protected static function build_paths($force) {
5903          throw new coding_exception('build_paths() method must be implemented in all context levels');
5904      }
5905  
5906      /**
5907       * Create missing context instances at given level
5908       *
5909       * @static
5910       * @return void
5911       */
5912      protected static function create_level_instances() {
5913          throw new coding_exception('create_level_instances() method must be implemented in all context levels');
5914      }
5915  
5916      /**
5917       * Reset all cached permissions and definitions if the necessary.
5918       * @return void
5919       */
5920      public function reload_if_dirty() {
5921          global $ACCESSLIB_PRIVATE, $USER;
5922  
5923          // Load dirty contexts list if needed
5924          if (CLI_SCRIPT) {
5925              if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5926                  // we do not load dirty flags in CLI and cron
5927                  $ACCESSLIB_PRIVATE->dirtycontexts = array();
5928              }
5929          } else {
5930              if (!isset($USER->access['time'])) {
5931                  // Nothing has been loaded yet, so we do not need to check dirty flags now.
5932                  return;
5933              }
5934  
5935              // From skodak: No idea why -2 is there, server cluster time difference maybe...
5936              $changedsince = $USER->access['time'] - 2;
5937  
5938              if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5939                  $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $changedsince);
5940              }
5941  
5942              if (!isset($ACCESSLIB_PRIVATE->dirtyusers[$USER->id])) {
5943                  $ACCESSLIB_PRIVATE->dirtyusers[$USER->id] = get_cache_flag('accesslib/dirtyusers', $USER->id, $changedsince);
5944              }
5945          }
5946  
5947          $dirty = false;
5948  
5949          if (!empty($ACCESSLIB_PRIVATE->dirtyusers[$USER->id])) {
5950              $dirty = true;
5951          } else if (!empty($ACCESSLIB_PRIVATE->dirtycontexts)) {
5952              $paths = $this->get_parent_context_paths(true);
5953  
5954              foreach ($paths as $path) {
5955                  if (isset($ACCESSLIB_PRIVATE->dirtycontexts[$path])) {
5956                      $dirty = true;
5957                      break;
5958                  }
5959              }
5960          }
5961  
5962          if ($dirty) {
5963              // Reload all capabilities of USER and others - preserving loginas, roleswitches, etc.
5964              // Then cleanup any marks of dirtyness... at least from our short term memory!
5965              reload_all_capabilities();
5966          }
5967      }
5968  
5969      /**
5970       * Mark a context as dirty (with timestamp) so as to force reloading of the context.
5971       */
5972      public function mark_dirty() {
5973          global $CFG, $USER, $ACCESSLIB_PRIVATE;
5974  
5975          if (during_initial_install()) {
5976              return;
5977          }
5978  
5979          // only if it is a non-empty string
5980          if (is_string($this->_path) && $this->_path !== '') {
5981              set_cache_flag('accesslib/dirtycontexts', $this->_path, 1, time()+$CFG->sessiontimeout);
5982              if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5983                  $ACCESSLIB_PRIVATE->dirtycontexts[$this->_path] = 1;
5984              } else {
5985                  if (CLI_SCRIPT) {
5986                      $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5987                  } else {
5988                      if (isset($USER->access['time'])) {
5989                          $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5990                      } else {
5991                          $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5992                      }
5993                      // flags not loaded yet, it will be done later in $context->reload_if_dirty()
5994                  }
5995              }
5996          }
5997      }
5998  }
5999  
6000  
6001  /**
6002   * Context maintenance and helper methods.
6003   *
6004   * This is "extends context" is a bloody hack that tires to work around the deficiencies
6005   * in the "protected" keyword in PHP, this helps us to hide all the internals of context
6006   * level implementation from the rest of code, the code completion returns what developers need.
6007   *
6008   * Thank you Tim Hunt for helping me with this nasty trick.
6009   *
6010   * @package   core_access
6011   * @category  access
6012   * @copyright Petr Skoda {@link http://skodak.org}
6013   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6014   * @since     Moodle 2.2
6015   */
6016  class context_helper extends context {
6017  
6018      /**
6019       * @var array An array mapping context levels to classes
6020       */
6021      private static $alllevels;
6022  
6023      /**
6024       * Instance does not make sense here, only static use
6025       */
6026      protected function __construct() {
6027      }
6028  
6029      /**
6030       * Reset internal context levels array.
6031       */
6032      public static function reset_levels() {
6033          self::$alllevels = null;
6034      }
6035  
6036      /**
6037       * Initialise context levels, call before using self::$alllevels.
6038       */
6039      private static function init_levels() {
6040          global $CFG;
6041  
6042          if (isset(self::$alllevels)) {
6043              return;
6044          }
6045          self::$alllevels = array(
6046              CONTEXT_SYSTEM    => 'context_system',
6047              CONTEXT_USER      => 'context_user',
6048              CONTEXT_COURSECAT => 'context_coursecat',
6049              CONTEXT_COURSE    => 'context_course',
6050              CONTEXT_MODULE    => 'context_module',
6051              CONTEXT_BLOCK     => 'context_block',
6052          );
6053  
6054          if (empty($CFG->custom_context_classes)) {
6055              return;
6056          }
6057  
6058          $levels = $CFG->custom_context_classes;
6059          if (!is_array($levels)) {
6060              $levels = @unserialize($levels);
6061          }
6062          if (!is_array($levels)) {
6063              debugging('Invalid $CFG->custom_context_classes detected, value ignored.', DEBUG_DEVELOPER);
6064              return;
6065          }
6066  
6067          // Unsupported custom levels, use with care!!!
6068          foreach ($levels as $level => $classname) {
6069              self::$alllevels[$level] = $classname;
6070          }
6071          ksort(self::$alllevels);
6072      }
6073  
6074      /**
6075       * Returns a class name of the context level class
6076       *
6077       * @static
6078       * @param int $contextlevel (CONTEXT_SYSTEM, etc.)
6079       * @return string class name of the context class
6080       */
6081      public static function get_class_for_level($contextlevel) {
6082          self::init_levels();
6083          if (isset(self::$alllevels[$contextlevel])) {
6084              return self::$alllevels[$contextlevel];
6085          } else {
6086              throw new coding_exception('Invalid context level specified');
6087          }
6088      }
6089  
6090      /**
6091       * Returns a list of all context levels
6092       *
6093       * @static
6094       * @return array int=>string (level=>level class name)
6095       */
6096      public static function get_all_levels() {
6097          self::init_levels();
6098          return self::$alllevels;
6099      }
6100  
6101      /**
6102       * Remove stale contexts that belonged to deleted instances.
6103       * Ideally all code should cleanup contexts properly, unfortunately accidents happen...
6104       *
6105       * @static
6106       * @return void
6107       */
6108      public static function cleanup_instances() {
6109          global $DB;
6110          self::init_levels();
6111  
6112          $sqls = array();
6113          foreach (self::$alllevels as $level=>$classname) {
6114              $sqls[] = $classname::get_cleanup_sql();
6115          }
6116  
6117          $sql = implode(" UNION ", $sqls);
6118  
6119          // it is probably better to use transactions, it might be faster too
6120          $transaction = $DB->start_delegated_transaction();
6121  
6122          $rs = $DB->get_recordset_sql($sql);
6123          foreach ($rs as $record) {
6124              $context = context::create_instance_from_record($record);
6125              $context->delete();
6126          }
6127          $rs->close();
6128  
6129          $transaction->allow_commit();
6130      }
6131  
6132      /**
6133       * Create all context instances at the given level and above.
6134       *
6135       * @static
6136       * @param int $contextlevel null means all levels
6137       * @param bool $buildpaths
6138       * @return void
6139       */
6140      public static function create_instances($contextlevel = null, $buildpaths = true) {
6141          self::init_levels();
6142          foreach (self::$alllevels as $level=>$classname) {
6143              if ($contextlevel and $level > $contextlevel) {
6144                  // skip potential sub-contexts
6145                  continue;
6146              }
6147              $classname::create_level_instances();
6148              if ($buildpaths) {
6149                  $classname::build_paths(false);
6150              }
6151          }
6152      }
6153  
6154      /**
6155       * Rebuild paths and depths in all context levels.
6156       *
6157       * @static
6158       * @param bool $force false means add missing only
6159       * @return void
6160       */
6161      public static function build_all_paths($force = false) {
6162          self::init_levels();
6163          foreach (self::$alllevels as $classname) {
6164              $classname::build_paths($force);
6165          }
6166  
6167          // reset static course cache - it might have incorrect cached data
6168          accesslib_clear_all_caches(true);
6169      }
6170  
6171      /**
6172       * Resets the cache to remove all data.
6173       * @static
6174       */
6175      public static function reset_caches() {
6176          context::reset_caches();
6177      }
6178  
6179      /**
6180       * Returns all fields necessary for context preloading from user $rec.
6181       *
6182       * This helps with performance when dealing with hundreds of contexts.
6183       *
6184       * @static
6185       * @param string $tablealias context table alias in the query
6186       * @return array (table.column=>alias, ...)
6187       */
6188      public static function get_preload_record_columns($tablealias) {
6189          return [
6190              "$tablealias.id" => "ctxid",
6191              "$tablealias.path" => "ctxpath",
6192              "$tablealias.depth" => "ctxdepth",
6193              "$tablealias.contextlevel" => "ctxlevel",
6194              "$tablealias.instanceid" => "ctxinstance",
6195              "$tablealias.locked" => "ctxlocked",
6196          ];
6197      }
6198  
6199      /**
6200       * Returns all fields necessary for context preloading from user $rec.
6201       *
6202       * This helps with performance when dealing with hundreds of contexts.
6203       *
6204       * @static
6205       * @param string $tablealias context table alias in the query
6206       * @return string
6207       */
6208      public static function get_preload_record_columns_sql($tablealias) {
6209          return "$tablealias.id AS ctxid, " .
6210                 "$tablealias.path AS ctxpath, " .
6211                 "$tablealias.depth AS ctxdepth, " .
6212                 "$tablealias.contextlevel AS ctxlevel, " .
6213                 "$tablealias.instanceid AS ctxinstance, " .
6214                 "$tablealias.locked AS ctxlocked";
6215      }
6216  
6217      /**
6218       * Preloads context cache with information from db record and strips the cached info.
6219       *
6220       * The db request has to contain all columns from context_helper::get_preload_record_columns().
6221       *
6222       * @static
6223       * @param stdClass $rec
6224       * @return void This is intentional. See MDL-37115. You will need to get the context
6225       *      in the normal way, but it is now cached, so that will be fast.
6226       */
6227       public static function preload_from_record(stdClass $rec) {
6228           context::preload_from_record($rec);
6229       }
6230  
6231      /**
6232       * Preload a set of contexts using their contextid.
6233       *
6234       * @param   array $contextids
6235       */
6236      public static function preload_contexts_by_id(array $contextids) {
6237          global $DB;
6238  
6239          // Determine which contexts are not already cached.
6240          $tofetch = [];
6241          foreach ($contextids as $contextid) {
6242              if (!self::cache_get_by_id($contextid)) {
6243                  $tofetch[] = $contextid;
6244              }
6245          }
6246  
6247          if (count($tofetch) > 1) {
6248              // There are at least two to fetch.
6249              // There is no point only fetching a single context as this would be no more efficient than calling the existing code.
6250              list($insql, $inparams) = $DB->get_in_or_equal($tofetch, SQL_PARAMS_NAMED);
6251              $ctxs = $DB->get_records_select('context', "id {$insql}", $inparams, '',
6252                      \context_helper::get_preload_record_columns_sql('{context}'));
6253              foreach ($ctxs as $ctx) {
6254                  self::preload_from_record($ctx);
6255              }
6256          }
6257      }
6258  
6259      /**
6260       * Preload all contexts instances from course.
6261       *
6262       * To be used if you expect multiple queries for course activities...
6263       *
6264       * @static
6265       * @param int $courseid
6266       */
6267      public static function preload_course($courseid) {
6268          // Users can call this multiple times without doing any harm
6269          if (isset(context::$cache_preloaded[$courseid])) {
6270              return;
6271          }
6272          $coursecontext = context_course::instance($courseid);
6273          $coursecontext->get_child_contexts();
6274  
6275          context::$cache_preloaded[$courseid] = true;
6276      }
6277  
6278      /**
6279       * Delete context instance
6280       *
6281       * @static
6282       * @param int $contextlevel
6283       * @param int $instanceid
6284       * @return void
6285       */
6286      public static function delete_instance($contextlevel, $instanceid) {
6287          global $DB;
6288  
6289          // double check the context still exists
6290          if ($record = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
6291              $context = context::create_instance_from_record($record);
6292              $context->delete();
6293          } else {
6294              // we should try to purge the cache anyway
6295          }
6296      }
6297  
6298      /**
6299       * Returns the name of specified context level
6300       *
6301       * @static
6302       * @param int $contextlevel
6303       * @return string name of the context level
6304       */
6305      public static function get_level_name($contextlevel) {
6306          $classname = context_helper::get_class_for_level($contextlevel);
6307          return $classname::get_level_name();
6308      }
6309  
6310      /**
6311       * Gets the current context to be used for navigation tree filtering.
6312       *
6313       * @param context|null $context The current context to be checked against.
6314       * @return context|null the context that navigation tree filtering should use.
6315       */
6316      public static function get_navigation_filter_context(?context $context): ?context {
6317          global $CFG;
6318          if (!empty($CFG->filternavigationwithsystemcontext)) {
6319              return context_system::instance();
6320          } else {
6321              return $context;
6322          }
6323      }
6324  
6325      /**
6326       * not used
6327       */
6328      public function get_url() {
6329      }
6330  
6331      /**
6332       * not used
6333       *
6334       * @param string $sort
6335       */
6336      public function get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT) {
6337      }
6338  }
6339  
6340  
6341  /**
6342   * System context class
6343   *
6344   * @package   core_access
6345   * @category  access
6346   * @copyright Petr Skoda {@link http://skodak.org}
6347   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6348   * @since     Moodle 2.2
6349   */
6350  class context_system extends context {
6351      /**
6352       * Please use context_system::instance() if you need the instance of context.
6353       *
6354       * @param stdClass $record
6355       */
6356      protected function __construct(stdClass $record) {
6357          parent::__construct($record);
6358          if ($record->contextlevel != CONTEXT_SYSTEM) {
6359              throw new coding_exception('Invalid $record->contextlevel in context_system constructor.');
6360          }
6361      }
6362  
6363      /**
6364       * Returns human readable context level name.
6365       *
6366       * @static
6367       * @return string the human readable context level name.
6368       */
6369      public static function get_level_name() {
6370          return get_string('coresystem');
6371      }
6372  
6373      /**
6374       * Returns human readable context identifier.
6375       *
6376       * @param boolean $withprefix does not apply to system context
6377       * @param boolean $short does not apply to system context
6378       * @param boolean $escape does not apply to system context
6379       * @return string the human readable context name.
6380       */
6381      public function get_context_name($withprefix = true, $short = false, $escape = true) {
6382          return self::get_level_name();
6383      }
6384  
6385      /**
6386       * Returns the most relevant URL for this context.
6387       *
6388       * @return moodle_url
6389       */
6390      public function get_url() {
6391          return new moodle_url('/');
6392      }
6393  
6394      /**
6395       * Returns array of relevant context capability records.
6396       *
6397       * @param string $sort
6398       * @return array
6399       */
6400      public function get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT) {
6401          global $DB;
6402  
6403          return $DB->get_records('capabilities', [], $sort);
6404      }
6405  
6406      /**
6407       * Create missing context instances at system context
6408       * @static
6409       */
6410      protected static function create_level_instances() {
6411          // nothing to do here, the system context is created automatically in installer
6412          self::instance(0);
6413      }
6414  
6415      /**
6416       * Returns system context instance.
6417       *
6418       * @static
6419       * @param int $instanceid should be 0
6420       * @param int $strictness
6421       * @param bool $cache
6422       * @return context_system context instance
6423       */
6424      public static function instance($instanceid = 0, $strictness = MUST_EXIST, $cache = true) {
6425          global $DB;
6426  
6427          if ($instanceid != 0) {
6428              debugging('context_system::instance(): invalid $id parameter detected, should be 0');
6429          }
6430  
6431          // SYSCONTEXTID is cached in local cache to eliminate 1 query per page.
6432          if (defined('SYSCONTEXTID') and $cache) {
6433              if (!isset(context::$systemcontext)) {
6434                  $record = new stdClass();
6435                  $record->id           = SYSCONTEXTID;
6436                  $record->contextlevel = CONTEXT_SYSTEM;
6437                  $record->instanceid   = 0;
6438                  $record->path         = '/'.SYSCONTEXTID;
6439                  $record->depth        = 1;
6440                  $record->locked       = 0;
6441                  context::$systemcontext = new context_system($record);
6442              }
6443              return context::$systemcontext;
6444          }
6445  
6446          try {
6447              // We ignore the strictness completely because system context must exist except during install.
6448              $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
6449          } catch (dml_exception $e) {
6450              //table or record does not exist
6451              if (!during_initial_install()) {
6452                  // do not mess with system context after install, it simply must exist
6453                  throw $e;
6454              }
6455              $record = null;
6456          }
6457  
6458          if (!$record) {
6459              $record = new stdClass();
6460              $record->contextlevel = CONTEXT_SYSTEM;
6461              $record->instanceid   = 0;
6462              $record->depth        = 1;
6463              $record->path         = null; // Not known before insert.
6464              $record->locked       = 0;
6465  
6466              try {
6467                  if ($DB->count_records('context')) {
6468                      // contexts already exist, this is very weird, system must be first!!!
6469                      return null;
6470                  }
6471                  if (defined('SYSCONTEXTID')) {
6472                      // this would happen only in unittest on sites that went through weird 1.7 upgrade
6473                      $record->id = SYSCONTEXTID;
6474                      $DB->import_record('context', $record);
6475                      $DB->get_manager()->reset_sequence('context');
6476                  } else {
6477                      $record->id = $DB->insert_record('context', $record);
6478                  }
6479              } catch (dml_exception $e) {
6480                  // can not create context - table does not exist yet, sorry
6481                  return null;
6482              }
6483          }
6484  
6485          if ($record->instanceid != 0) {
6486              // this is very weird, somebody must be messing with context table
6487              debugging('Invalid system context detected');
6488          }
6489  
6490          if ($record->depth != 1 or $record->path != '/'.$record->id) {
6491              // fix path if necessary, initial install or path reset
6492              $record->depth = 1;
6493              $record->path  = '/'.$record->id;
6494              $DB->update_record('context', $record);
6495          }
6496  
6497          if (empty($record->locked)) {
6498              $record->locked = 0;
6499          }
6500  
6501          if (!defined('SYSCONTEXTID')) {
6502              define('SYSCONTEXTID', $record->id);
6503          }
6504  
6505          context::$systemcontext = new context_system($record);
6506          return context::$systemcontext;
6507      }
6508  
6509      /**
6510       * Returns all site contexts except the system context, DO NOT call on production servers!!
6511       *
6512       * Contexts are not cached.
6513       *
6514       * @return array
6515       */
6516      public function get_child_contexts() {
6517          global $DB;
6518  
6519          debugging('Fetching of system context child courses is strongly discouraged on production servers (it may eat all available memory)!');
6520  
6521          // Just get all the contexts except for CONTEXT_SYSTEM level
6522          // and hope we don't OOM in the process - don't cache
6523          $sql = "SELECT c.*
6524                    FROM {context} c
6525                   WHERE contextlevel > ".CONTEXT_SYSTEM;
6526          $records = $DB->get_records_sql($sql);
6527  
6528          $result = array();
6529          foreach ($records as $record) {
6530              $result[$record->id] = context::create_instance_from_record($record);
6531          }
6532  
6533          return $result;
6534      }
6535  
6536      /**
6537       * Returns sql necessary for purging of stale context instances.
6538       *
6539       * @static
6540       * @return string cleanup SQL
6541       */
6542      protected static function get_cleanup_sql() {
6543          $sql = "
6544                    SELECT c.*
6545                      FROM {context} c
6546                     WHERE 1=2
6547                 ";
6548  
6549          return $sql;
6550      }
6551  
6552      /**
6553       * Rebuild context paths and depths at system context level.
6554       *
6555       * @static
6556       * @param bool $force
6557       */
6558      protected static function build_paths($force) {
6559          global $DB;
6560  
6561          /* note: ignore $force here, we always do full test of system context */
6562  
6563          // exactly one record must exist
6564          $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
6565  
6566          if ($record->instanceid != 0) {
6567              debugging('Invalid system context detected');
6568          }
6569  
6570          if (defined('SYSCONTEXTID') and $record->id != SYSCONTEXTID) {
6571              debugging('Invalid SYSCONTEXTID detected');
6572          }
6573  
6574          if ($record->depth != 1 or $record->path != '/'.$record->id) {
6575              // fix path if necessary, initial install or path reset
6576              $record->depth    = 1;
6577              $record->path     = '/'.$record->id;
6578              $DB->update_record('context', $record);
6579          }
6580      }
6581  
6582      /**
6583       * Set whether this context has been locked or not.
6584       *
6585       * @param   bool    $locked
6586       * @return  $this
6587       */
6588      public function set_locked(bool $locked) {
6589          throw new \coding_exception('It is not possible to lock the system context');
6590  
6591          return $this;
6592      }
6593  }
6594  
6595  
6596  /**
6597   * User context class
6598   *
6599   * @package   core_access
6600   * @category  access
6601   * @copyright Petr Skoda {@link http://skodak.org}
6602   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6603   * @since     Moodle 2.2
6604   */
6605  class context_user extends context {
6606      /**
6607       * Please use context_user::instance($userid) if you need the instance of context.
6608       * Alternatively if you know only the context id use context::instance_by_id($contextid)
6609       *
6610       * @param stdClass $record
6611       */
6612      protected function __construct(stdClass $record) {
6613          parent::__construct($record);
6614          if ($record->contextlevel != CONTEXT_USER) {
6615              throw new coding_exception('Invalid $record->contextlevel in context_user constructor.');
6616          }
6617      }
6618  
6619      /**
6620       * Returns human readable context level name.
6621       *
6622       * @static
6623       * @return string the human readable context level name.
6624       */
6625      public static function get_level_name() {
6626          return get_string('user');
6627      }
6628  
6629      /**
6630       * Returns human readable context identifier.
6631       *
6632       * @param boolean $withprefix whether to prefix the name of the context with User
6633       * @param boolean $short does not apply to user context
6634       * @param boolean $escape does not apply to user context
6635       * @return string the human readable context name.
6636       */
6637      public function get_context_name($withprefix = true, $short = false, $escape = true) {
6638          global $DB;
6639  
6640          $name = '';
6641          if ($user = $DB->get_record('user', array('id'=>$this->_instanceid, 'deleted'=>0))) {
6642              if ($withprefix){
6643                  $name = get_string('user').': ';
6644              }
6645              $name .= fullname($user);
6646          }
6647          return $name;
6648      }
6649  
6650      /**
6651       * Returns the most relevant URL for this context.
6652       *
6653       * @return moodle_url
6654       */
6655      public function get_url() {
6656          global $COURSE;
6657  
6658          if ($COURSE->id == SITEID) {
6659              $url = new moodle_url('/user/profile.php', array('id'=>$this->_instanceid));
6660          } else {
6661              $url = new moodle_url('/user/view.php', array('id'=>$this->_instanceid, 'courseid'=>$COURSE->id));
6662          }
6663          return $url;
6664      }
6665  
6666      /**
6667       * Returns array of relevant context capability records.
6668       *
6669       * @param string $sort
6670       * @return array
6671       */
6672      public function get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT) {
6673          global $DB;
6674  
6675          $extracaps = array('moodle/grade:viewall');
6676          list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
6677  
6678          return $DB->get_records_select('capabilities', "contextlevel = :level OR name {$extra}",
6679              $params + ['level' => CONTEXT_USER], $sort);
6680      }
6681  
6682      /**
6683       * Returns user context instance.
6684       *
6685       * @static
6686       * @param int $userid id from {user} table
6687       * @param int $strictness
6688       * @return context_user context instance
6689       */
6690      public static function instance($userid, $strictness = MUST_EXIST) {
6691          global $DB;
6692  
6693          if ($context = context::cache_get(CONTEXT_USER, $userid)) {
6694              return $context;
6695          }
6696  
6697          if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_USER, 'instanceid' => $userid))) {
6698              if ($user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0), 'id', $strictness)) {
6699                  $record = context::insert_context_record(CONTEXT_USER, $user->id, '/'.SYSCONTEXTID, 0);
6700              }
6701          }
6702  
6703          if ($record) {
6704              $context = new context_user($record);
6705              context::cache_add($context);
6706              return $context;
6707          }
6708  
6709          return false;
6710      }
6711  
6712      /**
6713       * Create missing context instances at user context level
6714       * @static
6715       */
6716      protected static function create_level_instances() {
6717          global $DB;
6718  
6719          $sql = "SELECT ".CONTEXT_USER.", u.id
6720                    FROM {user} u
6721                   WHERE u.deleted = 0
6722                         AND NOT EXISTS (SELECT 'x'
6723                                           FROM {context} cx
6724                                          WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER.")";
6725          $contextdata = $DB->get_recordset_sql($sql);
6726          foreach ($contextdata as $context) {
6727              context::insert_context_record(CONTEXT_USER, $context->id, null);
6728          }
6729          $contextdata->close();
6730      }
6731  
6732      /**
6733       * Returns sql necessary for purging of stale context instances.
6734       *
6735       * @static
6736       * @return string cleanup SQL
6737       */
6738      protected static function get_cleanup_sql() {
6739          $sql = "
6740                    SELECT c.*
6741                      FROM {context} c
6742           LEFT OUTER JOIN {user} u ON (c.instanceid = u.id AND u.deleted = 0)
6743                     WHERE u.id IS NULL AND c.contextlevel = ".CONTEXT_USER."
6744                 ";
6745  
6746          return $sql;
6747      }
6748  
6749      /**
6750       * Rebuild context paths and depths at user context level.
6751       *
6752       * @static
6753       * @param bool $force
6754       */
6755      protected static function build_paths($force) {
6756          global $DB;
6757  
6758          // First update normal users.
6759          $path = $DB->sql_concat('?', 'id');
6760          $pathstart = '/' . SYSCONTEXTID . '/';
6761          $params = array($pathstart);
6762  
6763          if ($force) {
6764              $where = "depth <> 2 OR path IS NULL OR path <> ({$path})";
6765              $params[] = $pathstart;
6766          } else {
6767              $where = "depth = 0 OR path IS NULL";
6768          }
6769  
6770          $sql = "UPDATE {context}
6771                     SET depth = 2,
6772                         path = {$path}
6773                   WHERE contextlevel = " . CONTEXT_USER . "
6774                     AND ($where)";
6775          $DB->execute($sql, $params);
6776      }
6777  }
6778  
6779  
6780  /**
6781   * Course category context class
6782   *
6783   * @package   core_access
6784   * @category  access
6785   * @copyright Petr Skoda {@link http://skodak.org}
6786   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6787   * @since     Moodle 2.2
6788   */
6789  class context_coursecat extends context {
6790      /**
6791       * Please use context_coursecat::instance($coursecatid) if you need the instance of context.
6792       * Alternatively if you know only the context id use context::instance_by_id($contextid)
6793       *
6794       * @param stdClass $record
6795       */
6796      protected function __construct(stdClass $record) {
6797          parent::__construct($record);
6798          if ($record->contextlevel != CONTEXT_COURSECAT) {
6799              throw new coding_exception('Invalid $record->contextlevel in context_coursecat constructor.');
6800          }
6801      }
6802  
6803      /**
6804       * Returns human readable context level name.
6805       *
6806       * @static
6807       * @return string the human readable context level name.
6808       */
6809      public static function get_level_name() {
6810          return get_string('category');
6811      }
6812  
6813      /**
6814       * Returns human readable context identifier.
6815       *
6816       * @param boolean $withprefix whether to prefix the name of the context with Category
6817       * @param boolean $short does not apply to course categories
6818       * @param boolean $escape Whether the returned name of the context is to be HTML escaped or not.
6819       * @return string the human readable context name.
6820       */
6821      public function get_context_name($withprefix = true, $short = false, $escape = true) {
6822          global $DB;
6823  
6824          $name = '';
6825          if ($category = $DB->get_record('course_categories', array('id'=>$this->_instanceid))) {
6826              if ($withprefix){
6827                  $name = get_string('category').': ';
6828              }
6829              if (!$escape) {
6830                  $name .= format_string($category->name, true, array('context' => $this, 'escape' => false));
6831              } else {
6832                  $name .= format_string($category->name, true, array('context' => $this));
6833              }
6834          }
6835          return $name;
6836      }
6837  
6838      /**
6839       * Returns the most relevant URL for this context.
6840       *
6841       * @return moodle_url
6842       */
6843      public function get_url() {
6844          return new moodle_url('/course/index.php', array('categoryid' => $this->_instanceid));
6845      }
6846  
6847      /**
6848       * Returns array of relevant context capability records.
6849       *
6850       * @param string $sort
6851       * @return array
6852       */
6853      public function get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT) {
6854          global $DB;
6855  
6856          return $DB->get_records_list('capabilities', 'contextlevel', [
6857              CONTEXT_COURSECAT,
6858              CONTEXT_COURSE,
6859              CONTEXT_MODULE,
6860              CONTEXT_BLOCK,
6861          ], $sort);
6862      }
6863  
6864      /**
6865       * Returns course category context instance.
6866       *
6867       * @static
6868       * @param int $categoryid id from {course_categories} table
6869       * @param int $strictness
6870       * @return context_coursecat context instance
6871       */
6872      public static function instance($categoryid, $strictness = MUST_EXIST) {
6873          global $DB;
6874  
6875          if ($context = context::cache_get(CONTEXT_COURSECAT, $categoryid)) {
6876              return $context;
6877          }
6878  
6879          if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_COURSECAT, 'instanceid' => $categoryid))) {
6880              if ($category = $DB->get_record('course_categories', array('id' => $categoryid), 'id,parent', $strictness)) {
6881                  if ($category->parent) {
6882                      $parentcontext = context_coursecat::instance($category->parent);
6883                      $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, $parentcontext->path);
6884                  } else {
6885                      $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, '/'.SYSCONTEXTID, 0);
6886                  }
6887              }
6888          }
6889  
6890          if ($record) {
6891              $context = new context_coursecat($record);
6892              context::cache_add($context);
6893              return $context;
6894          }
6895  
6896          return false;
6897      }
6898  
6899      /**
6900       * Returns immediate child contexts of category and all subcategories,
6901       * children of subcategories and courses are not returned.
6902       *
6903       * @return array
6904       */
6905      public function get_child_contexts() {
6906          global $DB;
6907  
6908          if (empty($this->_path) or empty($this->_depth)) {
6909              debugging('Can not find child contexts of context '.$this->_id.' try rebuilding of context paths');
6910              return array();
6911          }
6912  
6913          $sql = "SELECT ctx.*
6914                    FROM {context} ctx
6915                   WHERE ctx.path LIKE ? AND (ctx.depth = ? OR ctx.contextlevel = ?)";
6916          $params = array($this->_path.'/%', $this->depth+1, CONTEXT_COURSECAT);
6917          $records = $DB->get_records_sql($sql, $params);
6918  
6919          $result = array();
6920          foreach ($records as $record) {
6921              $result[$record->id] = context::create_instance_from_record($record);
6922          }
6923  
6924          return $result;
6925      }
6926  
6927      /**
6928       * Create missing context instances at course category context level
6929       * @static
6930       */
6931      protected static function create_level_instances() {
6932          global $DB;
6933  
6934          $sql = "SELECT ".CONTEXT_COURSECAT.", cc.id
6935                    FROM {course_categories} cc
6936                   WHERE NOT EXISTS (SELECT 'x'
6937                                       FROM {context} cx
6938                                      WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
6939          $contextdata = $DB->get_recordset_sql($sql);
6940          foreach ($contextdata as $context) {
6941              context::insert_context_record(CONTEXT_COURSECAT, $context->id, null);
6942          }
6943          $contextdata->close();
6944      }
6945  
6946      /**
6947       * Returns sql necessary for purging of stale context instances.
6948       *
6949       * @static
6950       * @return string cleanup SQL
6951       */
6952      protected static function get_cleanup_sql() {
6953          $sql = "
6954                    SELECT c.*
6955                      FROM {context} c
6956           LEFT OUTER JOIN {course_categories} cc ON c.instanceid = cc.id
6957                     WHERE cc.id IS NULL AND c.contextlevel = ".CONTEXT_COURSECAT."
6958                 ";
6959  
6960          return $sql;
6961      }
6962  
6963      /**
6964       * Rebuild context paths and depths at course category context level.
6965       *
6966       * @static
6967       * @param bool $force
6968       */
6969      protected static function build_paths($force) {
6970          global $DB;
6971  
6972          if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSECAT." AND (depth = 0 OR path IS NULL)")) {
6973              if ($force) {
6974                  $ctxemptyclause = $emptyclause = '';
6975              } else {
6976                  $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6977                  $emptyclause    = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6978              }
6979  
6980              $base = '/'.SYSCONTEXTID;
6981  
6982              // Normal top level categories
6983              $sql = "UPDATE {context}
6984                         SET depth=2,
6985                             path=".$DB->sql_concat("'$base/'", 'id')."
6986                       WHERE contextlevel=".CONTEXT_COURSECAT."
6987                             AND EXISTS (SELECT 'x'
6988                                           FROM {course_categories} cc
6989                                          WHERE cc.id = {context}.instanceid AND cc.depth=1)
6990                             $emptyclause";
6991              $DB->execute($sql);
6992  
6993              // Deeper categories - one query per depthlevel
6994              $maxdepth = $DB->get_field_sql("SELECT MAX(depth) FROM {course_categories}");
6995              for ($n=2; $n<=$maxdepth; $n++) {
6996                  $sql = "INSERT INTO {context_temp} (id, path, depth, locked)
6997                          SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1, ctx.locked
6998                            FROM {context} ctx
6999                            JOIN {course_categories} cc ON (cc.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSECAT." AND cc.depth = $n)
7000                            JOIN {context} pctx ON (pctx.instanceid = cc.parent AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
7001                           WHERE pctx.path IS NOT NULL AND pctx.depth > 0
7002                                 $ctxemptyclause";
7003                  $trans = $DB->start_delegated_transaction();
7004                  $DB->delete_records('context_temp');
7005                  $DB->execute($sql);
7006                  context::merge_context_temp_table();
7007                  $DB->delete_records('context_temp');
7008                  $trans->allow_commit();
7009  
7010              }
7011          }
7012      }
7013  }
7014  
7015  
7016  /**
7017   * Course context class
7018   *
7019   * @package   core_access
7020   * @category  access
7021   * @copyright Petr Skoda {@link http://skodak.org}
7022   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7023   * @since     Moodle 2.2
7024   */
7025  class context_course extends context {
7026      /**
7027       * Please use context_course::instance($courseid) if you need the instance of context.
7028       * Alternatively if you know only the context id use context::instance_by_id($contextid)
7029       *
7030       * @param stdClass $record
7031       */
7032      protected function __construct(stdClass $record) {
7033          parent::__construct($record);
7034          if ($record->contextlevel != CONTEXT_COURSE) {
7035              throw new coding_exception('Invalid $record->contextlevel in context_course constructor.');
7036          }
7037      }
7038  
7039      /**
7040       * Returns human readable context level name.
7041       *
7042       * @static
7043       * @return string the human readable context level name.
7044       */
7045      public static function get_level_name() {
7046          return get_string('course');
7047      }
7048  
7049      /**
7050       * Returns human readable context identifier.
7051       *
7052       * @param boolean $withprefix whether to prefix the name of the context with Course
7053       * @param boolean $short whether to use the short name of the thing.
7054       * @param bool $escape Whether the returned category name is to be HTML escaped or not.
7055       * @return string the human readable context name.
7056       */
7057      public function get_context_name($withprefix = true, $short = false, $escape = true) {
7058          global $DB;
7059  
7060          $name = '';
7061          if ($this->_instanceid == SITEID) {
7062              $name = get_string('frontpage', 'admin');
7063          } else {
7064              if ($course = $DB->get_record('course', array('id'=>$this->_instanceid))) {
7065                  if ($withprefix){
7066                      $name = get_string('course').': ';
7067                  }
7068                  if ($short){
7069                      if (!$escape) {
7070                          $name .= format_string($course->shortname, true, array('context' => $this, 'escape' => false));
7071                      } else {
7072                          $name .= format_string($course->shortname, true, array('context' => $this));
7073                      }
7074                  } else {
7075                      if (!$escape) {
7076                          $name .= format_string(get_course_display_name_for_list($course), true, array('context' => $this,
7077                              'escape' => false));
7078                      } else {
7079                          $name .= format_string(get_course_display_name_for_list($course), true, array('context' => $this));
7080                      }
7081                  }
7082              }
7083          }
7084          return $name;
7085      }
7086  
7087      /**
7088       * Returns the most relevant URL for this context.
7089       *
7090       * @return moodle_url
7091       */
7092      public function get_url() {
7093          if ($this->_instanceid != SITEID) {
7094              return new moodle_url('/course/view.php', array('id'=>$this->_instanceid));
7095          }
7096  
7097          return new moodle_url('/');
7098      }
7099  
7100      /**
7101       * Returns array of relevant context capability records.
7102       *
7103       * @param string $sort
7104       * @return array
7105       */
7106      public function get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT) {
7107          global $DB;
7108  
7109          return $DB->get_records_list('capabilities', 'contextlevel', [
7110              CONTEXT_COURSE,
7111              CONTEXT_MODULE,
7112              CONTEXT_BLOCK,
7113          ], $sort);
7114      }
7115  
7116      /**
7117       * Is this context part of any course? If yes return course context.
7118       *
7119       * @param bool $strict true means throw exception if not found, false means return false if not found
7120       * @return context_course context of the enclosing course, null if not found or exception
7121       */
7122      public function get_course_context($strict = true) {
7123          return $this;
7124      }
7125  
7126      /**
7127       * Returns course context instance.
7128       *
7129       * @static
7130       * @param int $courseid id from {course} table
7131       * @param int $strictness
7132       * @return context_course context instance
7133       */
7134      public static function instance($courseid, $strictness = MUST_EXIST) {
7135          global $DB;
7136  
7137          if ($context = context::cache_get(CONTEXT_COURSE, $courseid)) {
7138              return $context;
7139          }
7140  
7141          if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_COURSE, 'instanceid' => $courseid))) {
7142              if ($course = $DB->get_record('course', array('id' => $courseid), 'id,category', $strictness)) {
7143                  if ($course->category) {
7144                      $parentcontext = context_coursecat::instance($course->category);
7145                      $record = context::insert_context_record(CONTEXT_COURSE, $course->id, $parentcontext->path);
7146                  } else {
7147                      $record = context::insert_context_record(CONTEXT_COURSE, $course->id, '/'.SYSCONTEXTID, 0);
7148                  }
7149              }
7150          }
7151  
7152          if ($record) {
7153              $context = new context_course($record);
7154              context::cache_add($context);
7155              return $context;
7156          }
7157  
7158          return false;
7159      }
7160  
7161      /**
7162       * Create missing context instances at course context level
7163       * @static
7164       */
7165      protected static function create_level_instances() {
7166          global $DB;
7167  
7168          $sql = "SELECT ".CONTEXT_COURSE.", c.id
7169                    FROM {course} c
7170                   WHERE NOT EXISTS (SELECT 'x'
7171                                       FROM {context} cx
7172                                      WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE.")";
7173          $contextdata = $DB->get_recordset_sql($sql);
7174          foreach ($contextdata as $context) {
7175              context::insert_context_record(CONTEXT_COURSE, $context->id, null);
7176          }
7177          $contextdata->close();
7178      }
7179  
7180      /**
7181       * Returns sql necessary for purging of stale context instances.
7182       *
7183       * @static
7184       * @return string cleanup SQL
7185       */
7186      protected static function get_cleanup_sql() {
7187          $sql = "
7188                    SELECT c.*
7189                      FROM {context} c
7190           LEFT OUTER JOIN {course} co ON c.instanceid = co.id
7191                     WHERE co.id IS NULL AND c.contextlevel = ".CONTEXT_COURSE."
7192                 ";
7193  
7194          return $sql;
7195      }
7196  
7197      /**
7198       * Rebuild context paths and depths at course context level.
7199       *
7200       * @static
7201       * @param bool $force
7202       */
7203      protected static function build_paths($force) {
7204          global $DB;
7205  
7206          if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSE." AND (depth = 0 OR path IS NULL)")) {
7207              if ($force) {
7208                  $ctxemptyclause = $emptyclause = '';
7209              } else {
7210                  $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7211                  $emptyclause    = "AND ({context}.path IS NULL OR {context}.depth = 0)";
7212              }
7213  
7214              $base = '/'.SYSCONTEXTID;
7215  
7216              // Standard frontpage
7217              $sql = "UPDATE {context}
7218                         SET depth = 2,
7219                             path = ".$DB->sql_concat("'$base/'", 'id')."
7220                       WHERE contextlevel = ".CONTEXT_COURSE."
7221                             AND EXISTS (SELECT 'x'
7222                                           FROM {course} c
7223                                          WHERE c.id = {context}.instanceid AND c.category = 0)
7224                             $emptyclause";
7225              $DB->execute($sql);
7226  
7227              // standard courses
7228              $sql = "INSERT INTO {context_temp} (id, path, depth, locked)
7229                      SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1, ctx.locked
7230                        FROM {context} ctx
7231                        JOIN {course} c ON (c.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSE." AND c.category <> 0)
7232                        JOIN {context} pctx ON (pctx.instanceid = c.category AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
7233                       WHERE pctx.path IS NOT NULL AND pctx.depth > 0
7234                             $ctxemptyclause";
7235              $trans = $DB->start_delegated_transaction();
7236              $DB->delete_records('context_temp');
7237              $DB->execute($sql);
7238              context::merge_context_temp_table();
7239              $DB->delete_records('context_temp');
7240              $trans->allow_commit();
7241          }
7242      }
7243  }
7244  
7245  
7246  /**
7247   * Course module context class
7248   *
7249   * @package   core_access
7250   * @category  access
7251   * @copyright Petr Skoda {@link http://skodak.org}
7252   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7253   * @since     Moodle 2.2
7254   */
7255  class context_module extends context {
7256      /**
7257       * Please use context_module::instance($cmid) if you need the instance of context.
7258       * Alternatively if you know only the context id use context::instance_by_id($contextid)
7259       *
7260       * @param stdClass $record
7261       */
7262      protected function __construct(stdClass $record) {
7263          parent::__construct($record);
7264          if ($record->contextlevel != CONTEXT_MODULE) {
7265              throw new coding_exception('Invalid $record->contextlevel in context_module constructor.');
7266          }
7267      }
7268  
7269      /**
7270       * Returns human readable context level name.
7271       *
7272       * @static
7273       * @return string the human readable context level name.
7274       */
7275      public static function get_level_name() {
7276          return get_string('activitymodule');
7277      }
7278  
7279      /**
7280       * Returns human readable context identifier.
7281       *
7282       * @param boolean $withprefix whether to prefix the name of the context with the
7283       *      module name, e.g. Forum, Glossary, etc.
7284       * @param boolean $short does not apply to module context
7285       * @param boolean $escape Whether the returned name of the context is to be HTML escaped or not.
7286       * @return string the human readable context name.
7287       */
7288      public function get_context_name($withprefix = true, $short = false, $escape = true) {
7289          global $DB;
7290  
7291          $name = '';
7292          if ($cm = $DB->get_record_sql("SELECT cm.*, md.name AS modname
7293                                           FROM {course_modules} cm
7294                                           JOIN {modules} md ON md.id = cm.module
7295                                          WHERE cm.id = ?", array($this->_instanceid))) {
7296              if ($mod = $DB->get_record($cm->modname, array('id' => $cm->instance))) {
7297                      if ($withprefix){
7298                          $name = get_string('modulename', $cm->modname).': ';
7299                      }
7300                      if (!$escape) {
7301                          $name .= format_string($mod->name, true, array('context' => $this, 'escape' => false));
7302                      } else {
7303                          $name .= format_string($mod->name, true, array('context' => $this));
7304                      }
7305                  }
7306              }
7307          return $name;
7308      }
7309  
7310      /**
7311       * Returns the most relevant URL for this context.
7312       *
7313       * @return moodle_url
7314       */
7315      public function get_url() {
7316          global $DB;
7317  
7318          if ($modname = $DB->get_field_sql("SELECT md.name AS modname
7319                                               FROM {course_modules} cm
7320                                               JOIN {modules} md ON md.id = cm.module
7321                                              WHERE cm.id = ?", array($this->_instanceid))) {
7322              return new moodle_url('/mod/' . $modname . '/view.php', array('id'=>$this->_instanceid));
7323          }
7324  
7325          return new moodle_url('/');
7326      }
7327  
7328      /**
7329       * Returns array of relevant context capability records.
7330       *
7331       * @param string $sort
7332       * @return array
7333       */
7334      public function get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT) {
7335          global $DB, $CFG;
7336  
7337          $cm = $DB->get_record('course_modules', array('id'=>$this->_instanceid));
7338          $module = $DB->get_record('modules', array('id'=>$cm->module));
7339  
7340          $subcaps = array();
7341  
7342          $modulepath = "{$CFG->dirroot}/mod/{$module->name}";
7343          if (file_exists("{$modulepath}/db/subplugins.json")) {
7344              $subplugins = (array) json_decode(file_get_contents("{$modulepath}/db/subplugins.json"))->plugintypes;
7345          } else if (file_exists("{$modulepath}/db/subplugins.php")) {
7346              debugging('Use of subplugins.php has been deprecated. ' .
7347                      'Please update your plugin to provide a subplugins.json file instead.',
7348                      DEBUG_DEVELOPER);
7349              $subplugins = array();  // should be redefined in the file
7350              include("{$modulepath}/db/subplugins.php");
7351          }
7352  
7353          if (!empty($subplugins)) {
7354              foreach (array_keys($subplugins) as $subplugintype) {
7355                  foreach (array_keys(core_component::get_plugin_list($subplugintype)) as $subpluginname) {
7356                      $subcaps = array_merge($subcaps, array_keys(load_capability_def($subplugintype.'_'.$subpluginname)));
7357                  }
7358              }
7359          }
7360  
7361          $modfile = "{$modulepath}/lib.php";
7362          $extracaps = array();
7363          if (file_exists($modfile)) {
7364              include_once($modfile);
7365              $modfunction = $module->name.'_get_extra_capabilities';
7366              if (function_exists($modfunction)) {
7367                  $extracaps = $modfunction();
7368              }
7369          }
7370  
7371          $extracaps = array_merge($subcaps, $extracaps);
7372          $extra = '';
7373          list($extra, $params) = $DB->get_in_or_equal(
7374              $extracaps, SQL_PARAMS_NAMED, 'cap0', true, '');
7375          if (!empty($extra)) {
7376              $extra = "OR name $extra";
7377          }
7378  
7379          // Fetch the list of modules, and remove this one.
7380          $components = \core_component::get_component_list();
7381          $componentnames = $components['mod'];
7382          unset($componentnames["mod_{$module->name}"]);
7383          $componentnames = array_keys($componentnames);
7384  
7385          // Exclude all other modules.
7386          list($notcompsql, $notcompparams) = $DB->get_in_or_equal($componentnames, SQL_PARAMS_NAMED, 'notcomp', false);
7387          $params = array_merge($params, $notcompparams);
7388  
7389  
7390          // Exclude other component submodules.
7391          $i = 0;
7392          $ignorecomponents = [];
7393          foreach ($componentnames as $mod) {
7394              if ($subplugins = \core_component::get_subplugins($mod)) {
7395                  foreach (array_keys($subplugins) as $subplugintype) {
7396                      $paramname = "notlike{$i}";
7397                      $ignorecomponents[] = $DB->sql_like('component', ":{$paramname}", true, true, true);
7398                      $params[$paramname] = "{$subplugintype}_%";
7399                      $i++;
7400                  }
7401              }
7402          }
7403          $notlikesql = "(" . implode(' AND ', $ignorecomponents) . ")";
7404  
7405          $sql = "SELECT *
7406                    FROM {capabilities}
7407                   WHERE (contextlevel = ".CONTEXT_MODULE."
7408                     AND component {$notcompsql}
7409                     AND {$notlikesql})
7410                         $extra
7411                ORDER BY $sort";
7412  
7413          return $DB->get_records_sql($sql, $params);
7414      }
7415  
7416      /**
7417       * Is this context part of any course? If yes return course context.
7418       *
7419       * @param bool $strict true means throw exception if not found, false means return false if not found
7420       * @return context_course context of the enclosing course, null if not found or exception
7421       */
7422      public function get_course_context($strict = true) {
7423          return $this->get_parent_context();
7424      }
7425  
7426      /**
7427       * Returns module context instance.
7428       *
7429       * @static
7430       * @param int $cmid id of the record from {course_modules} table; pass cmid there, NOT id in the instance column
7431       * @param int $strictness
7432       * @return context_module context instance
7433       */
7434      public static function instance($cmid, $strictness = MUST_EXIST) {
7435          global $DB;
7436  
7437          if ($context = context::cache_get(CONTEXT_MODULE, $cmid)) {
7438              return $context;
7439          }
7440  
7441          if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_MODULE, 'instanceid' => $cmid))) {
7442              if ($cm = $DB->get_record('course_modules', array('id' => $cmid), 'id,course', $strictness)) {
7443                  $parentcontext = context_course::instance($cm->course);
7444                  $record = context::insert_context_record(CONTEXT_MODULE, $cm->id, $parentcontext->path);
7445              }
7446          }
7447  
7448          if ($record) {
7449              $context = new context_module($record);
7450              context::cache_add($context);
7451              return $context;
7452          }
7453  
7454          return false;
7455      }
7456  
7457      /**
7458       * Create missing context instances at module context level
7459       * @static
7460       */
7461      protected static function create_level_instances() {
7462          global $DB;
7463  
7464          $sql = "SELECT ".CONTEXT_MODULE.", cm.id
7465                    FROM {course_modules} cm
7466                   WHERE NOT EXISTS (SELECT 'x'
7467                                       FROM {context} cx
7468                                      WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE.")";
7469          $contextdata = $DB->get_recordset_sql($sql);
7470          foreach ($contextdata as $context) {
7471              context::insert_context_record(CONTEXT_MODULE, $context->id, null);
7472          }
7473          $contextdata->close();
7474      }
7475  
7476      /**
7477       * Returns sql necessary for purging of stale context instances.
7478       *
7479       * @static
7480       * @return string cleanup SQL
7481       */
7482      protected static function get_cleanup_sql() {
7483          $sql = "
7484                    SELECT c.*
7485                      FROM {context} c
7486           LEFT OUTER JOIN {course_modules} cm ON c.instanceid = cm.id
7487                     WHERE cm.id IS NULL AND c.contextlevel = ".CONTEXT_MODULE."
7488                 ";
7489  
7490          return $sql;
7491      }
7492  
7493      /**
7494       * Rebuild context paths and depths at module context level.
7495       *
7496       * @static
7497       * @param bool $force
7498       */
7499      protected static function build_paths($force) {
7500          global $DB;
7501  
7502          if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_MODULE." AND (depth = 0 OR path IS NULL)")) {
7503              if ($force) {
7504                  $ctxemptyclause = '';
7505              } else {
7506                  $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7507              }
7508  
7509              $sql = "INSERT INTO {context_temp} (id, path, depth, locked)
7510                      SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1, ctx.locked
7511                        FROM {context} ctx
7512                        JOIN {course_modules} cm ON (cm.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_MODULE.")
7513                        JOIN {context} pctx ON (pctx.instanceid = cm.course AND pctx.contextlevel = ".CONTEXT_COURSE.")
7514                       WHERE pctx.path IS NOT NULL AND pctx.depth > 0
7515                             $ctxemptyclause";
7516              $trans = $DB->start_delegated_transaction();
7517              $DB->delete_records('context_temp');
7518              $DB->execute($sql);
7519              context::merge_context_temp_table();
7520              $DB->delete_records('context_temp');
7521              $trans->allow_commit();
7522          }
7523      }
7524  }
7525  
7526  
7527  /**
7528   * Block context class
7529   *
7530   * @package   core_access
7531   * @category  access
7532   * @copyright Petr Skoda {@link http://skodak.org}
7533   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7534   * @since     Moodle 2.2
7535   */
7536  class context_block extends context {
7537      /**
7538       * Please use context_block::instance($blockinstanceid) if you need the instance of context.
7539       * Alternatively if you know only the context id use context::instance_by_id($contextid)
7540       *
7541       * @param stdClass $record
7542       */
7543      protected function __construct(stdClass $record) {
7544          parent::__construct($record);
7545          if ($record->contextlevel != CONTEXT_BLOCK) {
7546              throw new coding_exception('Invalid $record->contextlevel in context_block constructor');
7547          }
7548      }
7549  
7550      /**
7551       * Returns human readable context level name.
7552       *
7553       * @static
7554       * @return string the human readable context level name.
7555       */
7556      public static function get_level_name() {
7557          return get_string('block');
7558      }
7559  
7560      /**
7561       * Returns human readable context identifier.
7562       *
7563       * @param boolean $withprefix whether to prefix the name of the context with Block
7564       * @param boolean $short does not apply to block context
7565       * @param boolean $escape does not apply to block context
7566       * @return string the human readable context name.
7567       */
7568      public function get_context_name($withprefix = true, $short = false, $escape = true) {
7569          global $DB, $CFG;
7570  
7571          $name = '';
7572          if ($blockinstance = $DB->get_record('block_instances', array('id'=>$this->_instanceid))) {
7573              global $CFG;
7574              require_once("$CFG->dirroot/blocks/moodleblock.class.php");
7575              require_once("$CFG->dirroot/blocks/$blockinstance->blockname/block_$blockinstance->blockname.php");
7576              $blockname = "block_$blockinstance->blockname";
7577              if ($blockobject = new $blockname()) {
7578                  if ($withprefix){
7579                      $name = get_string('block').': ';
7580                  }
7581                  $name .= $blockobject->title;
7582              }
7583          }
7584  
7585          return $name;
7586      }
7587  
7588      /**
7589       * Returns the most relevant URL for this context.
7590       *
7591       * @return moodle_url
7592       */
7593      public function get_url() {
7594          $parentcontexts = $this->get_parent_context();
7595          return $parentcontexts->get_url();
7596      }
7597  
7598      /**
7599       * Returns array of relevant context capability records.
7600       *
7601       * @param string $sort
7602       * @return array
7603       */
7604      public function get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT) {
7605          global $DB;
7606  
7607          $bi = $DB->get_record('block_instances', array('id' => $this->_instanceid));
7608  
7609          $select = '(contextlevel = :level AND component = :component)';
7610          $params = [
7611              'level' => CONTEXT_BLOCK,
7612              'component' => 'block_' . $bi->blockname,
7613          ];
7614  
7615          $extracaps = block_method_result($bi->blockname, 'get_extra_capabilities');
7616          if ($extracaps) {
7617              list($extra, $extraparams) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
7618              $select .= " OR name $extra";
7619              $params = array_merge($params, $extraparams);
7620          }
7621  
7622          return $DB->get_records_select('capabilities', $select, $params, $sort);
7623      }
7624  
7625      /**
7626       * Is this context part of any course? If yes return course context.
7627       *
7628       * @param bool $strict true means throw exception if not found, false means return false if not found
7629       * @return context_course context of the enclosing course, null if not found or exception
7630       */
7631      public function get_course_context($strict = true) {
7632          $parentcontext = $this->get_parent_context();
7633          return $parentcontext->get_course_context($strict);
7634      }
7635  
7636      /**
7637       * Returns block context instance.
7638       *
7639       * @static
7640       * @param int $blockinstanceid id from {block_instances} table.
7641       * @param int $strictness
7642       * @return context_block context instance
7643       */
7644      public static function instance($blockinstanceid, $strictness = MUST_EXIST) {
7645          global $DB;
7646  
7647          if ($context = context::cache_get(CONTEXT_BLOCK, $blockinstanceid)) {
7648              return $context;
7649          }
7650  
7651          if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_BLOCK, 'instanceid' => $blockinstanceid))) {
7652              if ($bi = $DB->get_record('block_instances', array('id' => $blockinstanceid), 'id,parentcontextid', $strictness)) {
7653                  $parentcontext = context::instance_by_id($bi->parentcontextid);
7654                  $record = context::insert_context_record(CONTEXT_BLOCK, $bi->id, $parentcontext->path);
7655              }
7656          }
7657  
7658          if ($record) {
7659              $context = new context_block($record);
7660              context::cache_add($context);
7661              return $context;
7662          }
7663  
7664          return false;
7665      }
7666  
7667      /**
7668       * Block do not have child contexts...
7669       * @return array
7670       */
7671      public function get_child_contexts() {
7672          return array();
7673      }
7674  
7675      /**
7676       * Create missing context instances at block context level
7677       * @static
7678       */
7679      protected static function create_level_instances() {
7680          global $DB;
7681  
7682          $sql = <<<EOF
7683              INSERT INTO {context} (
7684                  contextlevel,
7685                  instanceid
7686              ) SELECT
7687                  :contextlevel,
7688                  bi.id as instanceid
7689                 FROM {block_instances} bi
7690                 WHERE NOT EXISTS (
7691                     SELECT 'x' FROM {context} cx WHERE bi.id = cx.instanceid AND cx.contextlevel = :existingcontextlevel
7692                 )
7693          EOF;
7694  
7695          $DB->execute($sql, [
7696              'contextlevel' => CONTEXT_BLOCK,
7697              'existingcontextlevel' => CONTEXT_BLOCK,
7698          ]);
7699      }
7700  
7701      /**
7702       * Returns sql necessary for purging of stale context instances.
7703       *
7704       * @static
7705       * @return string cleanup SQL
7706       */
7707      protected static function get_cleanup_sql() {
7708          $sql = "
7709                    SELECT c.*
7710                      FROM {context} c
7711           LEFT OUTER JOIN {block_instances} bi ON c.instanceid = bi.id
7712                     WHERE bi.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK."
7713                 ";
7714  
7715          return $sql;
7716      }
7717  
7718      /**
7719       * Rebuild context paths and depths at block context level.
7720       *
7721       * @static
7722       * @param bool $force
7723       */
7724      protected static function build_paths($force) {
7725          global $DB;
7726  
7727          if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_BLOCK." AND (depth = 0 OR path IS NULL)")) {
7728              if ($force) {
7729                  $ctxemptyclause = '';
7730              } else {
7731                  $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7732              }
7733  
7734              // pctx.path IS NOT NULL prevents fatal problems with broken block instances that point to invalid context parent
7735              $sql = "INSERT INTO {context_temp} (id, path, depth, locked)
7736                      SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1, ctx.locked
7737                        FROM {context} ctx
7738                        JOIN {block_instances} bi ON (bi.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_BLOCK.")
7739                        JOIN {context} pctx ON (pctx.id = bi.parentcontextid)
7740                       WHERE (pctx.path IS NOT NULL AND pctx.depth > 0)
7741                             $ctxemptyclause";
7742              $trans = $DB->start_delegated_transaction();
7743              $DB->delete_records('context_temp');
7744              $DB->execute($sql);
7745              context::merge_context_temp_table();
7746              $DB->delete_records('context_temp');
7747              $trans->allow_commit();
7748          }
7749      }
7750  }
7751  
7752  
7753  // ============== DEPRECATED FUNCTIONS ==========================================
7754  // Old context related functions were deprecated in 2.0, it is recommended
7755  // to use context classes in new code. Old function can be used when
7756  // creating patches that are supposed to be backported to older stable branches.
7757  // These deprecated functions will not be removed in near future,
7758  // before removing devs will be warned with a debugging message first,
7759  // then we will add error message and only after that we can remove the functions
7760  // completely.
7761  
7762  /**
7763   * Runs get_records select on context table and returns the result
7764   * Does get_records_select on the context table, and returns the results ordered
7765   * by contextlevel, and then the natural sort order within each level.
7766   * for the purpose of $select, you need to know that the context table has been
7767   * aliased to ctx, so for example, you can call get_sorted_contexts('ctx.depth = 3');
7768   *
7769   * @param string $select the contents of the WHERE clause. Remember to do ctx.fieldname.
7770   * @param array $params any parameters required by $select.
7771   * @return array the requested context records.
7772   */
7773  function get_sorted_contexts($select, $params = array()) {
7774  
7775      //TODO: we should probably rewrite all the code that is using this thing, the trouble is we MUST NOT modify the context instances...
7776  
7777      global $DB;
7778      if ($select) {
7779          $select = 'WHERE ' . $select;
7780      }
7781      return $DB->get_records_sql("
7782              SELECT ctx.*
7783                FROM {context} ctx
7784                LEFT JOIN {user} u ON ctx.contextlevel = " . CONTEXT_USER . " AND u.id = ctx.instanceid
7785                LEFT JOIN {course_categories} cat ON ctx.contextlevel = " . CONTEXT_COURSECAT . " AND cat.id = ctx.instanceid
7786                LEFT JOIN {course} c ON ctx.contextlevel = " . CONTEXT_COURSE . " AND c.id = ctx.instanceid
7787                LEFT JOIN {course_modules} cm ON ctx.contextlevel = " . CONTEXT_MODULE . " AND cm.id = ctx.instanceid
7788                LEFT JOIN {block_instances} bi ON ctx.contextlevel = " . CONTEXT_BLOCK . " AND bi.id = ctx.instanceid
7789             $select
7790            ORDER BY ctx.contextlevel, bi.defaultregion, COALESCE(cat.sortorder, c.sortorder, cm.section, bi.defaultweight), u.lastname, u.firstname, cm.id
7791              ", $params);
7792  }
7793  
7794  /**
7795   * Given context and array of users, returns array of users whose enrolment status is suspended,
7796   * or enrolment has expired or has not started. Also removes those users from the given array
7797   *
7798   * @param context $context context in which suspended users should be extracted.
7799   * @param array $users list of users.
7800   * @param array $ignoreusers array of user ids to ignore, e.g. guest
7801   * @return array list of suspended users.
7802   */
7803  function extract_suspended_users($context, &$users, $ignoreusers=array()) {
7804      global $DB;
7805  
7806      // Get active enrolled users.
7807      list($sql, $params) = get_enrolled_sql($context, null, null, true);
7808      $activeusers = $DB->get_records_sql($sql, $params);
7809  
7810      // Move suspended users to a separate array & remove from the initial one.
7811      $susers = array();
7812      if (sizeof($activeusers)) {
7813          foreach ($users as $userid => $user) {
7814              if (!array_key_exists($userid, $activeusers) && !in_array($userid, $ignoreusers)) {
7815                  $susers[$userid] = $user;
7816                  unset($users[$userid]);
7817              }
7818          }
7819      }
7820      return $susers;
7821  }
7822  
7823  /**
7824   * Given context and array of users, returns array of user ids whose enrolment status is suspended,
7825   * or enrolment has expired or not started.
7826   *
7827   * @param context $context context in which user enrolment is checked.
7828   * @param bool $usecache Enable or disable (default) the request cache
7829   * @return array list of suspended user id's.
7830   */
7831  function get_suspended_userids(context $context, $usecache = false) {
7832      global $DB;
7833  
7834      if ($usecache) {
7835          $cache = cache::make('core', 'suspended_userids');
7836          $susers = $cache->get($context->id);
7837          if ($susers !== false) {
7838              return $susers;
7839          }
7840      }
7841  
7842      $coursecontext = $context->get_course_context();
7843      $susers = array();
7844  
7845      // Front page users are always enrolled, so suspended list is empty.
7846      if ($coursecontext->instanceid != SITEID) {
7847          list($sql, $params) = get_enrolled_sql($context, null, null, false, true);
7848          $susers = $DB->get_fieldset_sql($sql, $params);
7849          $susers = array_combine($susers, $susers);
7850      }
7851  
7852      // Cache results for the remainder of this request.
7853      if ($usecache) {
7854          $cache->set($context->id, $susers);
7855      }
7856  
7857      return $susers;
7858  }
7859  
7860  /**
7861   * Gets sql for finding users with capability in the given context
7862   *
7863   * @param context $context
7864   * @param string|array $capability Capability name or array of names.
7865   *      If an array is provided then this is the equivalent of a logical 'OR',
7866   *      i.e. the user needs to have one of these capabilities.
7867   * @return array($sql, $params)
7868   */
7869  function get_with_capability_sql(context $context, $capability) {
7870      static $i = 0;
7871      $i++;
7872      $prefix = 'cu' . $i . '_';
7873  
7874      $capjoin = get_with_capability_join($context, $capability, $prefix . 'u.id');
7875  
7876      $sql = "SELECT DISTINCT {$prefix}u.id
7877                FROM {user} {$prefix}u
7878              $capjoin->joins
7879               WHERE {$prefix}u.deleted = 0 AND $capjoin->wheres";
7880  
7881      return array($sql, $capjoin->params);
7882  }