Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

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

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

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  /**
  18   * 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 http://docs.moodle.org/dev/Hardening_new_Roles_system} */
 139  define('RISK_MANAGETRUST', 0x0001);
 140  /** Capability allows changes in system configuration - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
 141  define('RISK_CONFIG',      0x0002);
 142  /** Capability allows user to add scripted content - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
 143  define('RISK_XSS',         0x0004);
 144  /** Capability allows access to personal user information - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
 145  define('RISK_PERSONAL',    0x0008);
 146  /** Capability allows users to add content others may see - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
 147  define('RISK_SPAM',        0x0010);
 148  /** capability allows mass delete of data belonging to other users - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
 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              print_error('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_quiz_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_quiz_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                              print_error('cannotunassigncap', 'error', '', (object)array('cap'=>$cachedcap->name, 'role'=>$role->name));
2389                          }
2390                      }
2391                  }
2392  
2393                  // Remove from role_capabilities for any old ones.
2394                  $DB->delete_records('role_capabilities', array('capability' => $cachedcap->name));
2395  
2396                  // Remove from capabilities cache.
2397                  $DB->delete_records('capabilities', array('name' => $cachedcap->name));
2398                  $removedcount++;
2399              } // End if.
2400          }
2401      }
2402      if ($removedcount) {
2403          cache::make('core', 'capabilities')->delete('core_capabilities');
2404      }
2405      return $removedcount;
2406  }
2407  
2408  /**
2409   * Returns an array of all the known types of risk
2410   * The array keys can be used, for example as CSS class names, or in calls to
2411   * print_risk_icon. The values are the corresponding RISK_ constants.
2412   *
2413   * @return array all the known types of risk.
2414   */
2415  function get_all_risks() {
2416      return array(
2417          'riskmanagetrust' => RISK_MANAGETRUST,
2418          'riskconfig'      => RISK_CONFIG,
2419          'riskxss'         => RISK_XSS,
2420          'riskpersonal'    => RISK_PERSONAL,
2421          'riskspam'        => RISK_SPAM,
2422          'riskdataloss'    => RISK_DATALOSS,
2423      );
2424  }
2425  
2426  /**
2427   * Return a link to moodle docs for a given capability name
2428   *
2429   * @param stdClass $capability a capability - a row from the mdl_capabilities table.
2430   * @return string the human-readable capability name as a link to Moodle Docs.
2431   */
2432  function get_capability_docs_link($capability) {
2433      $url = get_docs_url('Capabilities/' . $capability->name);
2434      return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name) . '</a>';
2435  }
2436  
2437  /**
2438   * This function pulls out all the resolved capabilities (overrides and
2439   * defaults) of a role used in capability overrides in contexts at a given
2440   * context.
2441   *
2442   * @param int $roleid
2443   * @param context $context
2444   * @param string $cap capability, optional, defaults to ''
2445   * @return array Array of capabilities
2446   */
2447  function role_context_capabilities($roleid, context $context, $cap = '') {
2448      global $DB;
2449  
2450      $contexts = $context->get_parent_context_ids(true);
2451      $contexts = '('.implode(',', $contexts).')';
2452  
2453      $params = array($roleid);
2454  
2455      if ($cap) {
2456          $search = " AND rc.capability = ? ";
2457          $params[] = $cap;
2458      } else {
2459          $search = '';
2460      }
2461  
2462      $sql = "SELECT rc.*
2463                FROM {role_capabilities} rc
2464                JOIN {context} c ON rc.contextid = c.id
2465                JOIN {capabilities} cap ON rc.capability = cap.name
2466               WHERE rc.contextid in $contexts
2467                     AND rc.roleid = ?
2468                     $search
2469            ORDER BY c.contextlevel DESC, rc.capability DESC";
2470  
2471      $capabilities = array();
2472  
2473      if ($records = $DB->get_records_sql($sql, $params)) {
2474          // We are traversing via reverse order.
2475          foreach ($records as $record) {
2476              // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2477              if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2478                  $capabilities[$record->capability] = $record->permission;
2479              }
2480          }
2481      }
2482      return $capabilities;
2483  }
2484  
2485  /**
2486   * Constructs array with contextids as first parameter and context paths,
2487   * in both cases bottom top including self.
2488   *
2489   * @access private
2490   * @param context $context
2491   * @return array
2492   */
2493  function get_context_info_list(context $context) {
2494      $contextids = explode('/', ltrim($context->path, '/'));
2495      $contextpaths = array();
2496      $contextids2 = $contextids;
2497      while ($contextids2) {
2498          $contextpaths[] = '/' . implode('/', $contextids2);
2499          array_pop($contextids2);
2500      }
2501      return array($contextids, $contextpaths);
2502  }
2503  
2504  /**
2505   * Check if context is the front page context or a context inside it
2506   *
2507   * Returns true if this context is the front page context, or a context inside it,
2508   * otherwise false.
2509   *
2510   * @param context $context a context object.
2511   * @return bool
2512   */
2513  function is_inside_frontpage(context $context) {
2514      $frontpagecontext = context_course::instance(SITEID);
2515      return strpos($context->path . '/', $frontpagecontext->path . '/') === 0;
2516  }
2517  
2518  /**
2519   * Returns capability information (cached)
2520   *
2521   * @param string $capabilityname
2522   * @return stdClass or null if capability not found
2523   */
2524  function get_capability_info($capabilityname) {
2525      $caps = get_all_capabilities();
2526  
2527      if (!isset($caps[$capabilityname])) {
2528          return null;
2529      }
2530  
2531      return (object) $caps[$capabilityname];
2532  }
2533  
2534  /**
2535   * Returns all capabilitiy records, preferably from MUC and not database.
2536   *
2537   * @return array All capability records indexed by capability name
2538   */
2539  function get_all_capabilities() {
2540      global $DB;
2541      $cache = cache::make('core', 'capabilities');
2542      if (!$allcaps = $cache->get('core_capabilities')) {
2543          $rs = $DB->get_recordset('capabilities');
2544          $allcaps = array();
2545          foreach ($rs as $capability) {
2546              $capability->riskbitmask = (int) $capability->riskbitmask;
2547              $allcaps[$capability->name] = (array) $capability;
2548          }
2549          $rs->close();
2550          $cache->set('core_capabilities', $allcaps);
2551      }
2552      return $allcaps;
2553  }
2554  
2555  /**
2556   * Returns the human-readable, translated version of the capability.
2557   * Basically a big switch statement.
2558   *
2559   * @param string $capabilityname e.g. mod/choice:readresponses
2560   * @return string
2561   */
2562  function get_capability_string($capabilityname) {
2563  
2564      // Typical capability name is 'plugintype/pluginname:capabilityname'
2565      list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
2566  
2567      if ($type === 'moodle') {
2568          $component = 'core_role';
2569      } else if ($type === 'quizreport') {
2570          //ugly hack!!
2571          $component = 'quiz_'.$name;
2572      } else {
2573          $component = $type.'_'.$name;
2574      }
2575  
2576      $stringname = $name.':'.$capname;
2577  
2578      if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
2579          return get_string($stringname, $component);
2580      }
2581  
2582      $dir = core_component::get_component_directory($component);
2583      if (!file_exists($dir)) {
2584          // plugin broken or does not exist, do not bother with printing of debug message
2585          return $capabilityname.' ???';
2586      }
2587  
2588      // something is wrong in plugin, better print debug
2589      return get_string($stringname, $component);
2590  }
2591  
2592  /**
2593   * This gets the mod/block/course/core etc strings.
2594   *
2595   * @param string $component
2596   * @param int $contextlevel
2597   * @return string|bool String is success, false if failed
2598   */
2599  function get_component_string($component, $contextlevel) {
2600  
2601      if ($component === 'moodle' || $component === 'core') {
2602          return context_helper::get_level_name($contextlevel);
2603      }
2604  
2605      list($type, $name) = core_component::normalize_component($component);
2606      $dir = core_component::get_plugin_directory($type, $name);
2607      if (!file_exists($dir)) {
2608          // plugin not installed, bad luck, there is no way to find the name
2609          return $component . ' ???';
2610      }
2611  
2612      // Some plugin types need an extra prefix to make the name easy to understand.
2613      switch ($type) {
2614          case 'quiz':
2615              $prefix = get_string('quizreport', 'quiz') . ': ';
2616              break;
2617          case 'repository':
2618              $prefix = get_string('repository', 'repository') . ': ';
2619              break;
2620          case 'gradeimport':
2621              $prefix = get_string('gradeimport', 'grades') . ': ';
2622              break;
2623          case 'gradeexport':
2624              $prefix = get_string('gradeexport', 'grades') . ': ';
2625              break;
2626          case 'gradereport':
2627              $prefix = get_string('gradereport', 'grades') . ': ';
2628              break;
2629          case 'webservice':
2630              $prefix = get_string('webservice', 'webservice') . ': ';
2631              break;
2632          case 'block':
2633              $prefix = get_string('block') . ': ';
2634              break;
2635          case 'mod':
2636              $prefix = get_string('activity') . ': ';
2637              break;
2638  
2639          // Default case, just use the plugin name.
2640          default:
2641              $prefix = '';
2642      }
2643      return $prefix . get_string('pluginname', $component);
2644  }
2645  
2646  /**
2647   * Gets the list of roles assigned to this context and up (parents)
2648   * from the aggregation of:
2649   * a) the list of roles that are visible on user profile page and participants page (profileroles setting) and;
2650   * b) if applicable, those roles that are assigned in the context.
2651   *
2652   * @param context $context
2653   * @return array
2654   */
2655  function get_profile_roles(context $context) {
2656      global $CFG, $DB;
2657      // If the current user can assign roles, then they can see all roles on the profile and participants page,
2658      // provided the roles are assigned to at least 1 user in the context. If not, only the policy-defined roles.
2659      if (has_capability('moodle/role:assign', $context)) {
2660          $rolesinscope = array_keys(get_all_roles($context));
2661      } else {
2662          $rolesinscope = empty($CFG->profileroles) ? [] : array_map('trim', explode(',', $CFG->profileroles));
2663      }
2664  
2665      if (empty($rolesinscope)) {
2666          return [];
2667      }
2668  
2669      list($rallowed, $params) = $DB->get_in_or_equal($rolesinscope, SQL_PARAMS_NAMED, 'a');
2670      list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2671      $params = array_merge($params, $cparams);
2672  
2673      if ($coursecontext = $context->get_course_context(false)) {
2674          $params['coursecontext'] = $coursecontext->id;
2675      } else {
2676          $params['coursecontext'] = 0;
2677      }
2678  
2679      $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2680                FROM {role_assignments} ra, {role} r
2681           LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2682               WHERE r.id = ra.roleid
2683                     AND ra.contextid $contextlist
2684                     AND r.id $rallowed
2685            ORDER BY r.sortorder ASC";
2686  
2687      return $DB->get_records_sql($sql, $params);
2688  }
2689  
2690  /**
2691   * Gets the list of roles assigned to this context and up (parents)
2692   *
2693   * @param context $context
2694   * @param boolean $includeparents, false means without parents.
2695   * @return array
2696   */
2697  function get_roles_used_in_context(context $context, $includeparents = true) {
2698      global $DB;
2699  
2700      if ($includeparents === true) {
2701          list($contextlist, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'cl');
2702      } else {
2703          list($contextlist, $params) = $DB->get_in_or_equal($context->id, SQL_PARAMS_NAMED, 'cl');
2704      }
2705  
2706      if ($coursecontext = $context->get_course_context(false)) {
2707          $params['coursecontext'] = $coursecontext->id;
2708      } else {
2709          $params['coursecontext'] = 0;
2710      }
2711  
2712      $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2713                FROM {role_assignments} ra, {role} r
2714           LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2715               WHERE r.id = ra.roleid
2716                     AND ra.contextid $contextlist
2717            ORDER BY r.sortorder ASC";
2718  
2719      return $DB->get_records_sql($sql, $params);
2720  }
2721  
2722  /**
2723   * This function is used to print roles column in user profile page.
2724   * It is using the CFG->profileroles to limit the list to only interesting roles.
2725   * (The permission tab has full details of user role assignments.)
2726   *
2727   * @param int $userid
2728   * @param int $courseid
2729   * @return string
2730   */
2731  function get_user_roles_in_course($userid, $courseid) {
2732      global $CFG, $DB;
2733      if ($courseid == SITEID) {
2734          $context = context_system::instance();
2735      } else {
2736          $context = context_course::instance($courseid);
2737      }
2738      // If the current user can assign roles, then they can see all roles on the profile and participants page,
2739      // provided the roles are assigned to at least 1 user in the context. If not, only the policy-defined roles.
2740      if (has_capability('moodle/role:assign', $context)) {
2741          $rolesinscope = array_keys(get_all_roles($context));
2742      } else {
2743          $rolesinscope = empty($CFG->profileroles) ? [] : array_map('trim', explode(',', $CFG->profileroles));
2744      }
2745      if (empty($rolesinscope)) {
2746          return '';
2747      }
2748  
2749      list($rallowed, $params) = $DB->get_in_or_equal($rolesinscope, SQL_PARAMS_NAMED, 'a');
2750      list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2751      $params = array_merge($params, $cparams);
2752  
2753      if ($coursecontext = $context->get_course_context(false)) {
2754          $params['coursecontext'] = $coursecontext->id;
2755      } else {
2756          $params['coursecontext'] = 0;
2757      }
2758  
2759      $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2760                FROM {role_assignments} ra, {role} r
2761           LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2762               WHERE r.id = ra.roleid
2763                     AND ra.contextid $contextlist
2764                     AND r.id $rallowed
2765                     AND ra.userid = :userid
2766            ORDER BY r.sortorder ASC";
2767      $params['userid'] = $userid;
2768  
2769      $rolestring = '';
2770  
2771      if ($roles = $DB->get_records_sql($sql, $params)) {
2772          $viewableroles = get_viewable_roles($context, $userid);
2773  
2774          $rolenames = array();
2775          foreach ($roles as $roleid => $unused) {
2776              if (isset($viewableroles[$roleid])) {
2777                  $url = new moodle_url('/user/index.php', ['contextid' => $context->id, 'roleid' => $roleid]);
2778                  $rolenames[] = '<a href="' . $url . '">' . $viewableroles[$roleid] . '</a>';
2779              }
2780          }
2781          $rolestring = implode(', ', $rolenames);
2782      }
2783  
2784      return $rolestring;
2785  }
2786  
2787  /**
2788   * Checks if a user can assign users to a particular role in this context
2789   *
2790   * @param context $context
2791   * @param int $targetroleid - the id of the role you want to assign users to
2792   * @return boolean
2793   */
2794  function user_can_assign(context $context, $targetroleid) {
2795      global $DB;
2796  
2797      // First check to see if the user is a site administrator.
2798      if (is_siteadmin()) {
2799          return true;
2800      }
2801  
2802      // Check if user has override capability.
2803      // If not return false.
2804      if (!has_capability('moodle/role:assign', $context)) {
2805          return false;
2806      }
2807      // pull out all active roles of this user from this context(or above)
2808      if ($userroles = get_user_roles($context)) {
2809          foreach ($userroles as $userrole) {
2810              // if any in the role_allow_override table, then it's ok
2811              if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid, 'allowassign'=>$targetroleid))) {
2812                  return true;
2813              }
2814          }
2815      }
2816  
2817      return false;
2818  }
2819  
2820  /**
2821   * Returns all site roles in correct sort order.
2822   *
2823   * Note: this method does not localise role names or descriptions,
2824   *       use role_get_names() if you need role names.
2825   *
2826   * @param context $context optional context for course role name aliases
2827   * @return array of role records with optional coursealias property
2828   */
2829  function get_all_roles(context $context = null) {
2830      global $DB;
2831  
2832      if (!$context or !$coursecontext = $context->get_course_context(false)) {
2833          $coursecontext = null;
2834      }
2835  
2836      if ($coursecontext) {
2837          $sql = "SELECT r.*, rn.name AS coursealias
2838                    FROM {role} r
2839               LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2840                ORDER BY r.sortorder ASC";
2841          return $DB->get_records_sql($sql, array('coursecontext'=>$coursecontext->id));
2842  
2843      } else {
2844          return $DB->get_records('role', array(), 'sortorder ASC');
2845      }
2846  }
2847  
2848  /**
2849   * Returns roles of a specified archetype
2850   *
2851   * @param string $archetype
2852   * @return array of full role records
2853   */
2854  function get_archetype_roles($archetype) {
2855      global $DB;
2856      return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
2857  }
2858  
2859  /**
2860   * Gets all the user roles assigned in this context, or higher contexts for a list of users.
2861   *
2862   * If you try using the combination $userids = [], $checkparentcontexts = true then this is likely
2863   * to cause an out-of-memory error on large Moodle sites, so this combination is deprecated and
2864   * outputs a warning, even though it is the default.
2865   *
2866   * @param context $context
2867   * @param array $userids. An empty list means fetch all role assignments for the context.
2868   * @param bool $checkparentcontexts defaults to true
2869   * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
2870   * @return array
2871   */
2872  function get_users_roles(context $context, $userids = [], $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
2873      global $DB;
2874  
2875      if (!$userids && $checkparentcontexts) {
2876          debugging('Please do not call get_users_roles() with $checkparentcontexts = true ' .
2877                  'and $userids array not set. This combination causes large Moodle sites ' .
2878                  'with lots of site-wide role assignemnts to run out of memory.', DEBUG_DEVELOPER);
2879      }
2880  
2881      if ($checkparentcontexts) {
2882          $contextids = $context->get_parent_context_ids();
2883      } else {
2884          $contextids = array();
2885      }
2886      $contextids[] = $context->id;
2887  
2888      list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
2889  
2890      // If userids was passed as an empty array, we fetch all role assignments for the course.
2891      if (empty($userids)) {
2892          $useridlist = ' IS NOT NULL ';
2893          $uparams = [];
2894      } else {
2895          list($useridlist, $uparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'uids');
2896      }
2897  
2898      $sql = "SELECT ra.*, r.name, r.shortname, ra.userid
2899                FROM {role_assignments} ra, {role} r, {context} c
2900               WHERE ra.userid $useridlist
2901                     AND ra.roleid = r.id
2902                     AND ra.contextid = c.id
2903                     AND ra.contextid $contextids
2904            ORDER BY $order";
2905  
2906      $all = $DB->get_records_sql($sql , array_merge($params, $uparams));
2907  
2908      // Return results grouped by userid.
2909      $result = [];
2910      foreach ($all as $id => $record) {
2911          if (!isset($result[$record->userid])) {
2912              $result[$record->userid] = [];
2913          }
2914          $result[$record->userid][$record->id] = $record;
2915      }
2916  
2917      // Make sure all requested users are included in the result, even if they had no role assignments.
2918      foreach ($userids as $id) {
2919          if (!isset($result[$id])) {
2920              $result[$id] = [];
2921          }
2922      }
2923  
2924      return $result;
2925  }
2926  
2927  
2928  /**
2929   * Gets all the user roles assigned in this context, or higher contexts
2930   * this is mainly used when checking if a user can assign a role, or overriding a role
2931   * i.e. we need to know what this user holds, in order to verify against allow_assign and
2932   * allow_override tables
2933   *
2934   * @param context $context
2935   * @param int $userid
2936   * @param bool $checkparentcontexts defaults to true
2937   * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
2938   * @return array
2939   */
2940  function get_user_roles(context $context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
2941      global $USER, $DB;
2942  
2943      if (empty($userid)) {
2944          if (empty($USER->id)) {
2945              return array();
2946          }
2947          $userid = $USER->id;
2948      }
2949  
2950      if ($checkparentcontexts) {
2951          $contextids = $context->get_parent_context_ids();
2952      } else {
2953          $contextids = array();
2954      }
2955      $contextids[] = $context->id;
2956  
2957      list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM);
2958  
2959      array_unshift($params, $userid);
2960  
2961      $sql = "SELECT ra.*, r.name, r.shortname
2962                FROM {role_assignments} ra, {role} r, {context} c
2963               WHERE ra.userid = ?
2964                     AND ra.roleid = r.id
2965                     AND ra.contextid = c.id
2966                     AND ra.contextid $contextids
2967            ORDER BY $order";
2968  
2969      return $DB->get_records_sql($sql ,$params);
2970  }
2971  
2972  /**
2973   * Like get_user_roles, but adds in the authenticated user role, and the front
2974   * page roles, if applicable.
2975   *
2976   * @param context $context the context.
2977   * @param int $userid optional. Defaults to $USER->id
2978   * @return array of objects with fields ->userid, ->contextid and ->roleid.
2979   */
2980  function get_user_roles_with_special(context $context, $userid = 0) {
2981      global $CFG, $USER;
2982  
2983      if (empty($userid)) {
2984          if (empty($USER->id)) {
2985              return array();
2986          }
2987          $userid = $USER->id;
2988      }
2989  
2990      $ras = get_user_roles($context, $userid);
2991  
2992      // Add front-page role if relevant.
2993      $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
2994      $isfrontpage = ($context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID) ||
2995              is_inside_frontpage($context);
2996      if ($defaultfrontpageroleid && $isfrontpage) {
2997          $frontpagecontext = context_course::instance(SITEID);
2998          $ra = new stdClass();
2999          $ra->userid = $userid;
3000          $ra->contextid = $frontpagecontext->id;
3001          $ra->roleid = $defaultfrontpageroleid;
3002          $ras[] = $ra;
3003      }
3004  
3005      // Add authenticated user role if relevant.
3006      $defaultuserroleid      = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3007      if ($defaultuserroleid && !isguestuser($userid)) {
3008          $systemcontext = context_system::instance();
3009          $ra = new stdClass();
3010          $ra->userid = $userid;
3011          $ra->contextid = $systemcontext->id;
3012          $ra->roleid = $defaultuserroleid;
3013          $ras[] = $ra;
3014      }
3015  
3016      return $ras;
3017  }
3018  
3019  /**
3020   * Creates a record in the role_allow_override table
3021   *
3022   * @param int $fromroleid source roleid
3023   * @param int $targetroleid target roleid
3024   * @return void
3025   */
3026  function core_role_set_override_allowed($fromroleid, $targetroleid) {
3027      global $DB;
3028  
3029      $record = new stdClass();
3030      $record->roleid        = $fromroleid;
3031      $record->allowoverride = $targetroleid;
3032      $DB->insert_record('role_allow_override', $record);
3033  }
3034  
3035  /**
3036   * Creates a record in the role_allow_assign table
3037   *
3038   * @param int $fromroleid source roleid
3039   * @param int $targetroleid target roleid
3040   * @return void
3041   */
3042  function core_role_set_assign_allowed($fromroleid, $targetroleid) {
3043      global $DB;
3044  
3045      $record = new stdClass();
3046      $record->roleid      = $fromroleid;
3047      $record->allowassign = $targetroleid;
3048      $DB->insert_record('role_allow_assign', $record);
3049  }
3050  
3051  /**
3052   * Creates a record in the role_allow_switch table
3053   *
3054   * @param int $fromroleid source roleid
3055   * @param int $targetroleid target roleid
3056   * @return void
3057   */
3058  function core_role_set_switch_allowed($fromroleid, $targetroleid) {
3059      global $DB;
3060  
3061      $record = new stdClass();
3062      $record->roleid      = $fromroleid;
3063      $record->allowswitch = $targetroleid;
3064      $DB->insert_record('role_allow_switch', $record);
3065  }
3066  
3067  /**
3068   * Creates a record in the role_allow_view table
3069   *
3070   * @param int $fromroleid source roleid
3071   * @param int $targetroleid target roleid
3072   * @return void
3073   */
3074  function core_role_set_view_allowed($fromroleid, $targetroleid) {
3075      global $DB;
3076  
3077      $record = new stdClass();
3078      $record->roleid      = $fromroleid;
3079      $record->allowview = $targetroleid;
3080      $DB->insert_record('role_allow_view', $record);
3081  }
3082  
3083  /**
3084   * Gets a list of roles that this user can assign in this context
3085   *
3086   * @param context $context the context.
3087   * @param int $rolenamedisplay the type of role name to display. One of the
3088   *      ROLENAME_X constants. Default ROLENAME_ALIAS.
3089   * @param bool $withusercounts if true, count the number of users with each role.
3090   * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
3091   * @return array if $withusercounts is false, then an array $roleid => $rolename.
3092   *      if $withusercounts is true, returns a list of three arrays,
3093   *      $rolenames, $rolecounts, and $nameswithcounts.
3094   */
3095  function get_assignable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withusercounts = false, $user = null) {
3096      global $USER, $DB;
3097  
3098      // make sure there is a real user specified
3099      if ($user === null) {
3100          $userid = isset($USER->id) ? $USER->id : 0;
3101      } else {
3102          $userid = is_object($user) ? $user->id : $user;
3103      }
3104  
3105      if (!has_capability('moodle/role:assign', $context, $userid)) {
3106          if ($withusercounts) {
3107              return array(array(), array(), array());
3108          } else {
3109              return array();
3110          }
3111      }
3112  
3113      $params = array();
3114      $extrafields = '';
3115  
3116      if ($withusercounts) {
3117          $extrafields = ', (SELECT COUNT(DISTINCT u.id)
3118                               FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
3119                              WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
3120                            ) AS usercount';
3121          $params['conid'] = $context->id;
3122      }
3123  
3124      if (is_siteadmin($userid)) {
3125          // show all roles allowed in this context to admins
3126          $assignrestriction = "";
3127      } else {
3128          $parents = $context->get_parent_context_ids(true);
3129          $contexts = implode(',' , $parents);
3130          $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
3131                                        FROM {role_allow_assign} raa
3132                                        JOIN {role_assignments} ra ON ra.roleid = raa.roleid
3133                                       WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3134                                     ) ar ON ar.id = r.id";
3135          $params['userid'] = $userid;
3136      }
3137      $params['contextlevel'] = $context->contextlevel;
3138  
3139      if ($coursecontext = $context->get_course_context(false)) {
3140          $params['coursecontext'] = $coursecontext->id;
3141      } else {
3142          $params['coursecontext'] = 0; // no course aliases
3143          $coursecontext = null;
3144      }
3145      $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias $extrafields
3146                FROM {role} r
3147                $assignrestriction
3148                JOIN {role_context_levels} rcl ON (rcl.contextlevel = :contextlevel AND r.id = rcl.roleid)
3149           LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3150            ORDER BY r.sortorder ASC";
3151      $roles = $DB->get_records_sql($sql, $params);
3152  
3153      $rolenames = role_fix_names($roles, $coursecontext, $rolenamedisplay, true);
3154  
3155      if (!$withusercounts) {
3156          return $rolenames;
3157      }
3158  
3159      $rolecounts = array();
3160      $nameswithcounts = array();
3161      foreach ($roles as $role) {
3162          $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->usercount . ')';
3163          $rolecounts[$role->id] = $roles[$role->id]->usercount;
3164      }
3165      return array($rolenames, $rolecounts, $nameswithcounts);
3166  }
3167  
3168  /**
3169   * Gets a list of roles that this user can switch to in a context
3170   *
3171   * Gets a list of roles that this user can switch to in a context, for the switchrole menu.
3172   * This function just process the contents of the role_allow_switch table. You also need to
3173   * test the moodle/role:switchroles to see if the user is allowed to switch in the first place.
3174   *
3175   * @param context $context a context.
3176   * @return array an array $roleid => $rolename.
3177   */
3178  function get_switchable_roles(context $context) {
3179      global $USER, $DB;
3180  
3181      // You can't switch roles without this capability.
3182      if (!has_capability('moodle/role:switchroles', $context)) {
3183          return [];
3184      }
3185  
3186      $params = array();
3187      $extrajoins = '';
3188      $extrawhere = '';
3189      if (!is_siteadmin()) {
3190          // Admins are allowed to switch to any role with.
3191          // Others are subject to the additional constraint that the switch-to role must be allowed by
3192          // 'role_allow_switch' for some role they have assigned in this context or any parent.
3193          $parents = $context->get_parent_context_ids(true);
3194          $contexts = implode(',' , $parents);
3195  
3196          $extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
3197          JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3198          $extrawhere = "WHERE ra.userid = :userid AND ra.contextid IN ($contexts)";
3199          $params['userid'] = $USER->id;
3200      }
3201  
3202      if ($coursecontext = $context->get_course_context(false)) {
3203          $params['coursecontext'] = $coursecontext->id;
3204      } else {
3205          $params['coursecontext'] = 0; // no course aliases
3206          $coursecontext = null;
3207      }
3208  
3209      $query = "
3210          SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3211            FROM (SELECT DISTINCT rc.roleid
3212                    FROM {role_capabilities} rc
3213  
3214                    $extrajoins
3215                    $extrawhere) idlist
3216            JOIN {role} r ON r.id = idlist.roleid
3217       LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3218        ORDER BY r.sortorder";
3219      $roles = $DB->get_records_sql($query, $params);
3220  
3221      return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
3222  }
3223  
3224  /**
3225   * Gets a list of roles that this user can view in a context
3226   *
3227   * @param context $context a context.
3228   * @param int $userid id of user.
3229   * @return array an array $roleid => $rolename.
3230   */
3231  function get_viewable_roles(context $context, $userid = null) {
3232      global $USER, $DB;
3233  
3234      if ($userid == null) {
3235          $userid = $USER->id;
3236      }
3237  
3238      $params = array();
3239      $extrajoins = '';
3240      $extrawhere = '';
3241      if (!is_siteadmin()) {
3242          // Admins are allowed to view any role.
3243          // Others are subject to the additional constraint that the view role must be allowed by
3244          // 'role_allow_view' for some role they have assigned in this context or any parent.
3245          $contexts = $context->get_parent_context_ids(true);
3246          list($insql, $inparams) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED);
3247  
3248          $extrajoins = "JOIN {role_allow_view} ras ON ras.allowview = r.id
3249                         JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3250          $extrawhere = "WHERE ra.userid = :userid AND ra.contextid $insql";
3251  
3252          $params += $inparams;
3253          $params['userid'] = $userid;
3254      }
3255  
3256      if ($coursecontext = $context->get_course_context(false)) {
3257          $params['coursecontext'] = $coursecontext->id;
3258      } else {
3259          $params['coursecontext'] = 0; // No course aliases.
3260          $coursecontext = null;
3261      }
3262  
3263      $query = "
3264          SELECT r.id, r.name, r.shortname, rn.name AS coursealias, r.sortorder
3265            FROM {role} r
3266            $extrajoins
3267       LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3268            $extrawhere
3269        GROUP BY r.id, r.name, r.shortname, rn.name, r.sortorder
3270        ORDER BY r.sortorder";
3271      $roles = $DB->get_records_sql($query, $params);
3272  
3273      return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
3274  }
3275  
3276  /**
3277   * Gets a list of roles that this user can override in this context.
3278   *
3279   * @param context $context the context.
3280   * @param int $rolenamedisplay the type of role name to display. One of the
3281   *      ROLENAME_X constants. Default ROLENAME_ALIAS.
3282   * @param bool $withcounts if true, count the number of overrides that are set for each role.
3283   * @return array if $withcounts is false, then an array $roleid => $rolename.
3284   *      if $withusercounts is true, returns a list of three arrays,
3285   *      $rolenames, $rolecounts, and $nameswithcounts.
3286   */
3287  function get_overridable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withcounts = false) {
3288      global $USER, $DB;
3289  
3290      if (!has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context)) {
3291          if ($withcounts) {
3292              return array(array(), array(), array());
3293          } else {
3294              return array();
3295          }
3296      }
3297  
3298      $parents = $context->get_parent_context_ids(true);
3299      $contexts = implode(',' , $parents);
3300  
3301      $params = array();
3302      $extrafields = '';
3303  
3304      $params['userid'] = $USER->id;
3305      if ($withcounts) {
3306          $extrafields = ', (SELECT COUNT(rc.id) FROM {role_capabilities} rc
3307                  WHERE rc.roleid = ro.id AND rc.contextid = :conid) AS overridecount';
3308          $params['conid'] = $context->id;
3309      }
3310  
3311      if ($coursecontext = $context->get_course_context(false)) {
3312          $params['coursecontext'] = $coursecontext->id;
3313      } else {
3314          $params['coursecontext'] = 0; // no course aliases
3315          $coursecontext = null;
3316      }
3317  
3318      if (is_siteadmin()) {
3319          // show all roles to admins
3320          $roles = $DB->get_records_sql("
3321              SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3322                FROM {role} ro
3323           LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3324            ORDER BY ro.sortorder ASC", $params);
3325  
3326      } else {
3327          $roles = $DB->get_records_sql("
3328              SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3329                FROM {role} ro
3330                JOIN (SELECT DISTINCT r.id
3331                        FROM {role} r
3332                        JOIN {role_allow_override} rao ON r.id = rao.allowoverride
3333                        JOIN {role_assignments} ra ON rao.roleid = ra.roleid
3334                       WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3335                     ) inline_view ON ro.id = inline_view.id
3336           LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3337            ORDER BY ro.sortorder ASC", $params);
3338      }
3339  
3340      $rolenames = role_fix_names($roles, $context, $rolenamedisplay, true);
3341  
3342      if (!$withcounts) {
3343          return $rolenames;
3344      }
3345  
3346      $rolecounts = array();
3347      $nameswithcounts = array();
3348      foreach ($roles as $role) {
3349          $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->overridecount . ')';
3350          $rolecounts[$role->id] = $roles[$role->id]->overridecount;
3351      }
3352      return array($rolenames, $rolecounts, $nameswithcounts);
3353  }
3354  
3355  /**
3356   * Create a role menu suitable for default role selection in enrol plugins.
3357   *
3358   * @package    core_enrol
3359   *
3360   * @param context $context
3361   * @param int $addroleid current or default role - always added to list
3362   * @return array roleid=>localised role name
3363   */
3364  function get_default_enrol_roles(context $context, $addroleid = null) {
3365      global $DB;
3366  
3367      $params = array('contextlevel'=>CONTEXT_COURSE);
3368  
3369      if ($coursecontext = $context->get_course_context(false)) {
3370          $params['coursecontext'] = $coursecontext->id;
3371      } else {
3372          $params['coursecontext'] = 0; // no course names
3373          $coursecontext = null;
3374      }
3375  
3376      if ($addroleid) {
3377          $addrole = "OR r.id = :addroleid";
3378          $params['addroleid'] = $addroleid;
3379      } else {
3380          $addrole = "";
3381      }
3382  
3383      $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3384                FROM {role} r
3385           LEFT JOIN {role_context_levels} rcl ON (rcl.roleid = r.id AND rcl.contextlevel = :contextlevel)
3386           LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3387               WHERE rcl.id IS NOT NULL $addrole
3388            ORDER BY sortorder DESC";
3389  
3390      $roles = $DB->get_records_sql($sql, $params);
3391  
3392      return role_fix_names($roles, $context, ROLENAME_BOTH, true);
3393  }
3394  
3395  /**
3396   * Return context levels where this role is assignable.
3397   *
3398   * @param integer $roleid the id of a role.
3399   * @return array list of the context levels at which this role may be assigned.
3400   */
3401  function get_role_contextlevels($roleid) {
3402      global $DB;
3403      return $DB->get_records_menu('role_context_levels', array('roleid' => $roleid),
3404              'contextlevel', 'id,contextlevel');
3405  }
3406  
3407  /**
3408   * Return roles suitable for assignment at the specified context level.
3409   *
3410   * NOTE: this function name looks like a typo, should be probably get_roles_for_contextlevel()
3411   *
3412   * @param integer $contextlevel a contextlevel.
3413   * @return array list of role ids that are assignable at this context level.
3414   */
3415  function get_roles_for_contextlevels($contextlevel) {
3416      global $DB;
3417      return $DB->get_records_menu('role_context_levels', array('contextlevel' => $contextlevel),
3418              '', 'id,roleid');
3419  }
3420  
3421  /**
3422   * Returns default context levels where roles can be assigned.
3423   *
3424   * @param string $rolearchetype one of the role archetypes - that is, one of the keys
3425   *      from the array returned by get_role_archetypes();
3426   * @return array list of the context levels at which this type of role may be assigned by default.
3427   */
3428  function get_default_contextlevels($rolearchetype) {
3429      static $defaults = array(
3430          'manager'        => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE),
3431          'coursecreator'  => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT),
3432          'editingteacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3433          'teacher'        => array(CONTEXT_COURSE, CONTEXT_MODULE),
3434          'student'        => array(CONTEXT_COURSE, CONTEXT_MODULE),
3435          'guest'          => array(),
3436          'user'           => array(),
3437          'frontpage'      => array());
3438  
3439      if (isset($defaults[$rolearchetype])) {
3440          return $defaults[$rolearchetype];
3441      } else {
3442          return array();
3443      }
3444  }
3445  
3446  /**
3447   * Set the context levels at which a particular role can be assigned.
3448   * Throws exceptions in case of error.
3449   *
3450   * @param integer $roleid the id of a role.
3451   * @param array $contextlevels the context levels at which this role should be assignable,
3452   *      duplicate levels are removed.
3453   * @return void
3454   */
3455  function set_role_contextlevels($roleid, array $contextlevels) {
3456      global $DB;
3457      $DB->delete_records('role_context_levels', array('roleid' => $roleid));
3458      $rcl = new stdClass();
3459      $rcl->roleid = $roleid;
3460      $contextlevels = array_unique($contextlevels);
3461      foreach ($contextlevels as $level) {
3462          $rcl->contextlevel = $level;
3463          $DB->insert_record('role_context_levels', $rcl, false, true);
3464      }
3465  }
3466  
3467  /**
3468   * Gets sql joins for finding users with capability in the given context.
3469   *
3470   * @param context $context Context for the join.
3471   * @param string|array $capability Capability name or array of names.
3472   *      If an array is provided then this is the equivalent of a logical 'OR',
3473   *      i.e. the user needs to have one of these capabilities.
3474   * @param string $useridcolumn e.g. 'u.id'.
3475   * @return \core\dml\sql_join Contains joins, wheres, params.
3476   *      This function will set ->cannotmatchanyrows if applicable.
3477   *      This may let you skip doing a DB query.
3478   */
3479  function get_with_capability_join(context $context, $capability, $useridcolumn) {
3480      global $CFG, $DB;
3481  
3482      // Add a unique prefix to param names to ensure they are unique.
3483      static $i = 0;
3484      $i++;
3485      $paramprefix = 'eu' . $i . '_';
3486  
3487      $defaultuserroleid      = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3488      $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3489  
3490      $ctxids = trim($context->path, '/');
3491      $ctxids = str_replace('/', ',', $ctxids);
3492  
3493      // Context is the frontpage
3494      $isfrontpage = $context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID;
3495      $isfrontpage = $isfrontpage || is_inside_frontpage($context);
3496  
3497      $caps = (array) $capability;
3498  
3499      // Construct list of context paths bottom --> top.
3500      list($contextids, $paths) = get_context_info_list($context);
3501  
3502      // We need to find out all roles that have these capabilities either in definition or in overrides.
3503      $defs = [];
3504      list($incontexts, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, $paramprefix . 'con');
3505      list($incaps, $params2) = $DB->get_in_or_equal($caps, SQL_PARAMS_NAMED, $paramprefix . 'cap');
3506  
3507      // Check whether context locking is enabled.
3508      // Filter out any write capability if this is the case.
3509      $excludelockedcaps = '';
3510      $excludelockedcapsparams = [];
3511      if (!empty($CFG->contextlocking) && $context->locked) {
3512          $excludelockedcaps = 'AND (cap.captype = :capread OR cap.name = :managelockscap)';
3513          $excludelockedcapsparams['capread'] = 'read';
3514          $excludelockedcapsparams['managelockscap'] = 'moodle/site:managecontextlocks';
3515      }
3516  
3517      $params = array_merge($params, $params2, $excludelockedcapsparams);
3518      $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability, ctx.path
3519                FROM {role_capabilities} rc
3520                JOIN {capabilities} cap ON rc.capability = cap.name
3521                JOIN {context} ctx on rc.contextid = ctx.id
3522               WHERE rc.contextid $incontexts AND rc.capability $incaps $excludelockedcaps";
3523  
3524      $rcs = $DB->get_records_sql($sql, $params);
3525      foreach ($rcs as $rc) {
3526          $defs[$rc->capability][$rc->path][$rc->roleid] = $rc->permission;
3527      }
3528  
3529      // Go through the permissions bottom-->top direction to evaluate the current permission,
3530      // first one wins (prohibit is an exception that always wins).
3531      $access = [];
3532      foreach ($caps as $cap) {
3533          foreach ($paths as $path) {
3534              if (empty($defs[$cap][$path])) {
3535                  continue;
3536              }
3537              foreach ($defs[$cap][$path] as $roleid => $perm) {
3538                  if ($perm == CAP_PROHIBIT) {
3539                      $access[$cap][$roleid] = CAP_PROHIBIT;
3540                      continue;
3541                  }
3542                  if (!isset($access[$cap][$roleid])) {
3543                      $access[$cap][$roleid] = (int)$perm;
3544                  }
3545              }
3546          }
3547      }
3548  
3549      // Make lists of roles that are needed and prohibited in this context.
3550      $needed = []; // One of these is enough.
3551      $prohibited = []; // Must not have any of these.
3552      foreach ($caps as $cap) {
3553          if (empty($access[$cap])) {
3554              continue;
3555          }
3556          foreach ($access[$cap] as $roleid => $perm) {
3557              if ($perm == CAP_PROHIBIT) {
3558                  unset($needed[$cap][$roleid]);
3559                  $prohibited[$cap][$roleid] = true;
3560              } else if ($perm == CAP_ALLOW and empty($prohibited[$cap][$roleid])) {
3561                  $needed[$cap][$roleid] = true;
3562              }
3563          }
3564          if (empty($needed[$cap]) or !empty($prohibited[$cap][$defaultuserroleid])) {
3565              // Easy, nobody has the permission.
3566              unset($needed[$cap]);
3567              unset($prohibited[$cap]);
3568          } else if ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid])) {
3569              // Everybody is disqualified on the frontpage.
3570              unset($needed[$cap]);
3571              unset($prohibited[$cap]);
3572          }
3573          if (empty($prohibited[$cap])) {
3574              unset($prohibited[$cap]);
3575          }
3576      }
3577  
3578      if (empty($needed)) {
3579          // There can not be anybody if no roles match this request.
3580          return new \core\dml\sql_join('', '1 = 2', [], true);
3581      }
3582  
3583      if (empty($prohibited)) {
3584          // We can compact the needed roles.
3585          $n = [];
3586          foreach ($needed as $cap) {
3587              foreach ($cap as $roleid => $unused) {
3588                  $n[$roleid] = true;
3589              }
3590          }
3591          $needed = ['any' => $n];
3592          unset($n);
3593      }
3594  
3595      // Prepare query clauses.
3596      $wherecond = [];
3597      $params    = [];
3598      $joins     = [];
3599      $cannotmatchanyrows = false;
3600  
3601      // We never return deleted users or guest account.
3602      // Use a hack to get the deleted user column without an API change.
3603      $deletedusercolumn = substr($useridcolumn, 0, -2) . 'deleted';
3604      $wherecond[] = "$deletedusercolumn = 0 AND $useridcolumn <> :{$paramprefix}guestid";
3605      $params[$paramprefix . 'guestid'] = $CFG->siteguest;
3606  
3607      // Now add the needed and prohibited roles conditions as joins.
3608      if (!empty($needed['any'])) {
3609          // Simple case - there are no prohibits involved.
3610          if (!empty($needed['any'][$defaultuserroleid]) ||
3611                  ($isfrontpage && !empty($needed['any'][$defaultfrontpageroleid]))) {
3612              // Everybody.
3613          } else {
3614              $joins[] = "JOIN (SELECT DISTINCT userid
3615                                  FROM {role_assignments}
3616                                 WHERE contextid IN ($ctxids)
3617                                       AND roleid IN (" . implode(',', array_keys($needed['any'])) . ")
3618                               ) ra ON ra.userid = $useridcolumn";
3619          }
3620      } else {
3621          $unions = [];
3622          $everybody = false;
3623          foreach ($needed as $cap => $unused) {
3624              if (empty($prohibited[$cap])) {
3625                  if (!empty($needed[$cap][$defaultuserroleid]) ||
3626                          ($isfrontpage && !empty($needed[$cap][$defaultfrontpageroleid]))) {
3627                      $everybody = true;
3628                      break;
3629                  } else {
3630                      $unions[] = "SELECT userid
3631                                     FROM {role_assignments}
3632                                    WHERE contextid IN ($ctxids)
3633                                          AND roleid IN (".implode(',', array_keys($needed[$cap])) .")";
3634                  }
3635              } else {
3636                  if (!empty($prohibited[$cap][$defaultuserroleid]) ||
3637                          ($isfrontpage && !empty($prohibited[$cap][$defaultfrontpageroleid]))) {
3638                      // Nobody can have this cap because it is prohibited in default roles.
3639                      continue;
3640  
3641                  } else if (!empty($needed[$cap][$defaultuserroleid]) ||
3642                          ($isfrontpage && !empty($needed[$cap][$defaultfrontpageroleid]))) {
3643                      // Everybody except the prohibited - hiding does not matter.
3644                      $unions[] = "SELECT id AS userid
3645                                     FROM {user}
3646                                    WHERE id NOT IN (SELECT userid
3647                                                       FROM {role_assignments}
3648                                                      WHERE contextid IN ($ctxids)
3649                                                            AND roleid IN (" . implode(',', array_keys($prohibited[$cap])) . "))";
3650  
3651                  } else {
3652                      $unions[] = "SELECT userid
3653                                     FROM {role_assignments}
3654                                    WHERE contextid IN ($ctxids) AND roleid IN (" . implode(',', array_keys($needed[$cap])) . ")
3655                                          AND userid NOT IN (
3656                                              SELECT userid
3657                                                FROM {role_assignments}
3658                                               WHERE contextid IN ($ctxids)
3659                                                     AND roleid IN (" . implode(',', array_keys($prohibited[$cap])) . "))";
3660                  }
3661              }
3662          }
3663  
3664          if (!$everybody) {
3665              if ($unions) {
3666                  $joins[] = "JOIN (
3667                                    SELECT DISTINCT userid
3668                                      FROM (
3669                                              " . implode("\n UNION \n", $unions) . "
3670                                           ) us
3671                                   ) ra ON ra.userid = $useridcolumn";
3672              } else {
3673                  // Only prohibits found - nobody can be matched.
3674                  $wherecond[] = "1 = 2";
3675                  $cannotmatchanyrows = true;
3676              }
3677          }
3678      }
3679  
3680      return new \core\dml\sql_join(implode("\n", $joins), implode(" AND ", $wherecond), $params, $cannotmatchanyrows);
3681  }
3682  
3683  /**
3684   * Who has this capability in this context?
3685   *
3686   * This can be a very expensive call - use sparingly and keep
3687   * the results if you are going to need them again soon.
3688   *
3689   * Note if $fields is empty this function attempts to get u.*
3690   * which can get rather large - and has a serious perf impact
3691   * on some DBs.
3692   *
3693   * @param context $context
3694   * @param string|array $capability - capability name(s)
3695   * @param string $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
3696   * @param string $sort - the sort order. Default is lastaccess time.
3697   * @param mixed $limitfrom - number of records to skip (offset)
3698   * @param mixed $limitnum - number of records to fetch
3699   * @param string|array $groups - single group or array of groups - only return
3700   *               users who are in one of these group(s).
3701   * @param string|array $exceptions - list of users to exclude, comma separated or array
3702   * @param bool $notuseddoanything not used any more, admin accounts are never returned
3703   * @param bool $notusedview - use get_enrolled_sql() instead
3704   * @param bool $useviewallgroups if $groups is set the return users who
3705   *               have capability both $capability and moodle/site:accessallgroups
3706   *               in this context, as well as users who have $capability and who are
3707   *               in $groups.
3708   * @return array of user records
3709   */
3710  function get_users_by_capability(context $context, $capability, $fields = '', $sort = '', $limitfrom = '', $limitnum = '',
3711          $groups = '', $exceptions = '', $notuseddoanything = null, $notusedview = null, $useviewallgroups = false) {
3712      global $CFG, $DB;
3713  
3714      // Context is a course page other than the frontpage.
3715      $iscoursepage = $context->contextlevel == CONTEXT_COURSE && $context->instanceid != SITEID;
3716  
3717      // Set up default fields list if necessary.
3718      if (empty($fields)) {
3719          if ($iscoursepage) {
3720              $fields = 'u.*, ul.timeaccess AS lastaccess';
3721          } else {
3722              $fields = 'u.*';
3723          }
3724      } else {
3725          if ($CFG->debugdeveloper && strpos($fields, 'u.*') === false && strpos($fields, 'u.id') === false) {
3726              debugging('u.id must be included in the list of fields passed to get_users_by_capability().', DEBUG_DEVELOPER);
3727          }
3728      }
3729  
3730      // Set up default sort if necessary.
3731      if (empty($sort)) { // default to course lastaccess or just lastaccess
3732          if ($iscoursepage) {
3733              $sort = 'ul.timeaccess';
3734          } else {
3735              $sort = 'u.lastaccess';
3736          }
3737      }
3738  
3739      // Get the bits of SQL relating to capabilities.
3740      $sqljoin = get_with_capability_join($context, $capability, 'u.id');
3741      if ($sqljoin->cannotmatchanyrows) {
3742          return [];
3743      }
3744  
3745      // Prepare query clauses.
3746      $wherecond = [$sqljoin->wheres];
3747      $params    = $sqljoin->params;
3748      $joins     = [$sqljoin->joins];
3749  
3750      // Add user lastaccess JOIN, if required.
3751      if ((strpos($sort, 'ul.timeaccess') === false) and (strpos($fields, 'ul.timeaccess') === false)) {
3752           // Here user_lastaccess is not required MDL-13810.
3753      } else {
3754          if ($iscoursepage) {
3755              $joins[] = "LEFT OUTER JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
3756          } else {
3757              throw new coding_exception('Invalid sort in get_users_by_capability(), ul.timeaccess allowed only for course contexts.');
3758          }
3759      }
3760  
3761      // Groups.
3762      if ($groups) {
3763          $groups = (array)$groups;
3764          list($grouptest, $grpparams) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grp');
3765          $joins[] = "LEFT OUTER JOIN (SELECT DISTINCT userid
3766                                         FROM {groups_members}
3767                                        WHERE groupid $grouptest
3768                                      ) gm ON gm.userid = u.id";
3769  
3770          $params = array_merge($params, $grpparams);
3771  
3772          $grouptest = 'gm.userid IS NOT NULL';
3773          if ($useviewallgroups) {
3774              $viewallgroupsusers = get_users_by_capability($context, 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
3775              if (!empty($viewallgroupsusers)) {
3776                  $grouptest .= ' OR u.id IN (' . implode(',', array_keys($viewallgroupsusers)) . ')';
3777              }
3778          }
3779          $wherecond[] = "($grouptest)";
3780      }
3781  
3782      // User exceptions.
3783      if (!empty($exceptions)) {
3784          $exceptions = (array)$exceptions;
3785          list($exsql, $exparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'exc', false);
3786          $params = array_merge($params, $exparams);
3787          $wherecond[] = "u.id $exsql";
3788      }
3789  
3790      // Collect WHERE conditions and needed joins.
3791      $where = implode(' AND ', $wherecond);
3792      if ($where !== '') {
3793          $where = 'WHERE ' . $where;
3794      }
3795      $joins = implode("\n", $joins);
3796  
3797      // Finally! we have all the bits, run the query.
3798      $sql = "SELECT $fields
3799                FROM {user} u
3800              $joins
3801              $where
3802            ORDER BY $sort";
3803  
3804      return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3805  }
3806  
3807  /**
3808   * Re-sort a users array based on a sorting policy
3809   *
3810   * Will re-sort a $users results array (from get_users_by_capability(), usually)
3811   * based on a sorting policy. This is to support the odd practice of
3812   * sorting teachers by 'authority', where authority was "lowest id of the role
3813   * assignment".
3814   *
3815   * Will execute 1 database query. Only suitable for small numbers of users, as it
3816   * uses an u.id IN() clause.
3817   *
3818   * Notes about the sorting criteria.
3819   *
3820   * As a default, we cannot rely on role.sortorder because then
3821   * admins/coursecreators will always win. That is why the sane
3822   * rule "is locality matters most", with sortorder as 2nd
3823   * consideration.
3824   *
3825   * If you want role.sortorder, use the 'sortorder' policy, and
3826   * name explicitly what roles you want to cover. It's probably
3827   * a good idea to see what roles have the capabilities you want
3828   * (array_diff() them against roiles that have 'can-do-anything'
3829   * to weed out admin-ish roles. Or fetch a list of roles from
3830   * variables like $CFG->coursecontact .
3831   *
3832   * @param array $users Users array, keyed on userid
3833   * @param context $context
3834   * @param array $roles ids of the roles to include, optional
3835   * @param string $sortpolicy defaults to locality, more about
3836   * @return array sorted copy of the array
3837   */
3838  function sort_by_roleassignment_authority($users, context $context, $roles = array(), $sortpolicy = 'locality') {
3839      global $DB;
3840  
3841      $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
3842      $contextwhere = 'AND ra.contextid IN ('.str_replace('/', ',',substr($context->path, 1)).')';
3843      if (empty($roles)) {
3844          $roleswhere = '';
3845      } else {
3846          $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
3847      }
3848  
3849      $sql = "SELECT ra.userid
3850                FROM {role_assignments} ra
3851                JOIN {role} r
3852                     ON ra.roleid=r.id
3853                JOIN {context} ctx
3854                     ON ra.contextid=ctx.id
3855               WHERE $userswhere
3856                     $contextwhere
3857                     $roleswhere";
3858  
3859      // Default 'locality' policy -- read PHPDoc notes
3860      // about sort policies...
3861      $orderby = 'ORDER BY '
3862                      .'ctx.depth DESC, '  /* locality wins */
3863                      .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3864                      .'ra.id';            /* role assignment order tie-breaker */
3865      if ($sortpolicy === 'sortorder') {
3866          $orderby = 'ORDER BY '
3867                          .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3868                          .'ra.id';            /* role assignment order tie-breaker */
3869      }
3870  
3871      $sortedids = $DB->get_fieldset_sql($sql . $orderby);
3872      $sortedusers = array();
3873      $seen = array();
3874  
3875      foreach ($sortedids as $id) {
3876          // Avoid duplicates
3877          if (isset($seen[$id])) {
3878              continue;
3879          }
3880          $seen[$id] = true;
3881  
3882          // assign
3883          $sortedusers[$id] = $users[$id];
3884      }
3885      return $sortedusers;
3886  }
3887  
3888  /**
3889   * Gets all the users assigned this role in this context or higher
3890   *
3891   * Note that moodle is based on capabilities and it is usually better
3892   * to check permissions than to check role ids as the capabilities
3893   * system is more flexible. If you really need, you can to use this
3894   * function but consider has_capability() as a possible substitute.
3895   *
3896   * All $sort fields are added into $fields if not present there yet.
3897   *
3898   * If $roleid is an array or is empty (all roles) you need to set $fields
3899   * (and $sort by extension) params according to it, as the first field
3900   * returned by the database should be unique (ra.id is the best candidate).
3901   *
3902   * @param int $roleid (can also be an array of ints!)
3903   * @param context $context
3904   * @param bool $parent if true, get list of users assigned in higher context too
3905   * @param string $fields fields from user (u.) , role assignment (ra) or role (r.)
3906   * @param string $sort sort from user (u.) , role assignment (ra.) or role (r.).
3907   *      null => use default sort from users_order_by_sql.
3908   * @param bool $all true means all, false means limit to enrolled users
3909   * @param string $group defaults to ''
3910   * @param mixed $limitfrom defaults to ''
3911   * @param mixed $limitnum defaults to ''
3912   * @param string $extrawheretest defaults to ''
3913   * @param array $whereorsortparams any paramter values used by $sort or $extrawheretest.
3914   * @return array
3915   */
3916  function get_role_users($roleid, context $context, $parent = false, $fields = '',
3917          $sort = null, $all = true, $group = '',
3918          $limitfrom = '', $limitnum = '', $extrawheretest = '', $whereorsortparams = array()) {
3919      global $DB;
3920  
3921      if (empty($fields)) {
3922          $allnames = get_all_user_name_fields(true, 'u');
3923          $fields = 'u.id, u.confirmed, u.username, '. $allnames . ', ' .
3924                    'u.maildisplay, u.mailformat, u.maildigest, u.email, u.emailstop, u.city, '.
3925                    'u.country, u.picture, u.idnumber, u.department, u.institution, '.
3926                    'u.lang, u.timezone, u.lastaccess, u.mnethostid, r.name AS rolename, r.sortorder, '.
3927                    'r.shortname AS roleshortname, rn.name AS rolecoursealias';
3928      }
3929  
3930      // Prevent wrong function uses.
3931      if ((empty($roleid) || is_array($roleid)) && strpos($fields, 'ra.id') !== 0) {
3932          debugging('get_role_users() without specifying one single roleid needs to be called prefixing ' .
3933              'role assignments id (ra.id) as unique field, you can use $fields param for it.');
3934  
3935          if (!empty($roleid)) {
3936              // Solving partially the issue when specifying multiple roles.
3937              $users = array();
3938              foreach ($roleid as $id) {
3939                  // Ignoring duplicated keys keeping the first user appearance.
3940                  $users = $users + get_role_users($id, $context, $parent, $fields, $sort, $all, $group,
3941                      $limitfrom, $limitnum, $extrawheretest, $whereorsortparams);
3942              }
3943              return $users;
3944          }
3945      }
3946  
3947      $parentcontexts = '';
3948      if ($parent) {
3949          $parentcontexts = substr($context->path, 1); // kill leading slash
3950          $parentcontexts = str_replace('/', ',', $parentcontexts);
3951          if ($parentcontexts !== '') {
3952              $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
3953          }
3954      }
3955  
3956      if ($roleid) {
3957          list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_NAMED, 'r');
3958          $roleselect = "AND ra.roleid $rids";
3959      } else {
3960          $params = array();
3961          $roleselect = '';
3962      }
3963  
3964      if ($coursecontext = $context->get_course_context(false)) {
3965          $params['coursecontext'] = $coursecontext->id;
3966      } else {
3967          $params['coursecontext'] = 0;
3968      }
3969  
3970      if ($group) {
3971          $groupjoin   = "JOIN {groups_members} gm ON gm.userid = u.id";
3972          $groupselect = " AND gm.groupid = :groupid ";
3973          $params['groupid'] = $group;
3974      } else {
3975          $groupjoin   = '';
3976          $groupselect = '';
3977      }
3978  
3979      $params['contextid'] = $context->id;
3980  
3981      if ($extrawheretest) {
3982          $extrawheretest = ' AND ' . $extrawheretest;
3983      }
3984  
3985      if ($whereorsortparams) {
3986          $params = array_merge($params, $whereorsortparams);
3987      }
3988  
3989      if (!$sort) {
3990          list($sort, $sortparams) = users_order_by_sql('u');
3991          $params = array_merge($params, $sortparams);
3992      }
3993  
3994      // Adding the fields from $sort that are not present in $fields.
3995      $sortarray = preg_split('/,\s*/', $sort);
3996      $fieldsarray = preg_split('/,\s*/', $fields);
3997  
3998      // Discarding aliases from the fields.
3999      $fieldnames = array();
4000      foreach ($fieldsarray as $key => $field) {
4001          list($fieldnames[$key]) = explode(' ', $field);
4002      }
4003  
4004      $addedfields = array();
4005      foreach ($sortarray as $sortfield) {
4006          // Throw away any additional arguments to the sort (e.g. ASC/DESC).
4007          list($sortfield) = explode(' ', $sortfield);
4008          list($tableprefix) = explode('.', $sortfield);
4009          $fieldpresent = false;
4010          foreach ($fieldnames as $fieldname) {
4011              if ($fieldname === $sortfield || $fieldname === $tableprefix.'.*') {
4012                  $fieldpresent = true;
4013                  break;
4014              }
4015          }
4016  
4017          if (!$fieldpresent) {
4018              $fieldsarray[] = $sortfield;
4019              $addedfields[] = $sortfield;
4020          }
4021      }
4022  
4023      $fields = implode(', ', $fieldsarray);
4024      if (!empty($addedfields)) {
4025          $addedfields = implode(', ', $addedfields);
4026          debugging('get_role_users() adding '.$addedfields.' to the query result because they were required by $sort but missing in $fields');
4027      }
4028  
4029      if ($all === null) {
4030          // Previously null was used to indicate that parameter was not used.
4031          $all = true;
4032      }
4033      if (!$all and $coursecontext) {
4034          // Do not use get_enrolled_sql() here for performance reasons.
4035          $ejoin = "JOIN {user_enrolments} ue ON ue.userid = u.id
4036                    JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :ecourseid)";
4037          $params['ecourseid'] = $coursecontext->instanceid;
4038      } else {
4039          $ejoin = "";
4040      }
4041  
4042      $sql = "SELECT DISTINCT $fields, ra.roleid
4043                FROM {role_assignments} ra
4044                JOIN {user} u ON u.id = ra.userid
4045                JOIN {role} r ON ra.roleid = r.id
4046              $ejoin
4047           LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
4048          $groupjoin
4049               WHERE (ra.contextid = :contextid $parentcontexts)
4050                     $roleselect
4051                     $groupselect
4052                     $extrawheretest
4053            ORDER BY $sort";                  // join now so that we can just use fullname() later
4054  
4055      return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
4056  }
4057  
4058  /**
4059   * Counts all the users assigned this role in this context or higher
4060   *
4061   * @param int|array $roleid either int or an array of ints
4062   * @param context $context
4063   * @param bool $parent if true, get list of users assigned in higher context too
4064   * @return int Returns the result count
4065   */
4066  function count_role_users($roleid, context $context, $parent = false) {
4067      global $DB;
4068  
4069      if ($parent) {
4070          if ($contexts = $context->get_parent_context_ids()) {
4071              $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
4072          } else {
4073              $parentcontexts = '';
4074          }
4075      } else {
4076          $parentcontexts = '';
4077      }
4078  
4079      if ($roleid) {
4080          list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM);
4081          $roleselect = "AND r.roleid $rids";
4082      } else {
4083          $params = array();
4084          $roleselect = '';
4085      }
4086  
4087      array_unshift($params, $context->id);
4088  
4089      $sql = "SELECT COUNT(DISTINCT u.id)
4090                FROM {role_assignments} r
4091                JOIN {user} u ON u.id = r.userid
4092               WHERE (r.contextid = ? $parentcontexts)
4093                     $roleselect
4094                     AND u.deleted = 0";
4095  
4096      return $DB->count_records_sql($sql, $params);
4097  }
4098  
4099  /**
4100   * This function gets the list of courses that this user has a particular capability in.
4101   *
4102   * It is now reasonably efficient, but bear in mind that if there are users who have the capability
4103   * everywhere, it may return an array of all courses.
4104   *
4105   * @param string $capability Capability in question
4106   * @param int $userid User ID or null for current user
4107   * @param bool $doanything True if 'doanything' is permitted (default)
4108   * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
4109   *   otherwise use a comma-separated list of the fields you require, not including id.
4110   *   Add ctxid, ctxpath, ctxdepth etc to return course context information for preloading.
4111   * @param string $orderby If set, use a comma-separated list of fields from course
4112   *   table with sql modifiers (DESC) if needed
4113   * @param int $limit Limit the number of courses to return on success. Zero equals all entries.
4114   * @return array|bool Array of courses, if none found false is returned.
4115   */
4116  function get_user_capability_course($capability, $userid = null, $doanything = true, $fieldsexceptid = '', $orderby = '',
4117          $limit = 0) {
4118      global $DB, $USER;
4119  
4120      // Default to current user.
4121      if (!$userid) {
4122          $userid = $USER->id;
4123      }
4124  
4125      if ($doanything && is_siteadmin($userid)) {
4126          // If the user is a site admin and $doanything is enabled then there is no need to restrict
4127          // the list of courses.
4128          $contextlimitsql = '';
4129          $contextlimitparams = [];
4130      } else {
4131          // Gets SQL to limit contexts ('x' table) to those where the user has this capability.
4132          list ($contextlimitsql, $contextlimitparams) = \core\access\get_user_capability_course_helper::get_sql(
4133                  $userid, $capability);
4134          if (!$contextlimitsql) {
4135              // If the does not have this capability in any context, return false without querying.
4136              return false;
4137          }
4138  
4139          $contextlimitsql = 'WHERE' . $contextlimitsql;
4140      }
4141  
4142      // Convert fields list and ordering
4143      $fieldlist = '';
4144      if ($fieldsexceptid) {
4145          $fields = array_map('trim', explode(',', $fieldsexceptid));
4146          foreach ($fields as $field) {
4147              // Context fields have a different alias.
4148              if (strpos($field, 'ctx') === 0) {
4149                  switch($field) {
4150                      case 'ctxlevel' :
4151                          $realfield = 'contextlevel';
4152                          break;
4153                      case 'ctxinstance' :
4154                          $realfield = 'instanceid';
4155                          break;
4156                      default:
4157                          $realfield = substr($field, 3);
4158                          break;
4159                  }
4160                  $fieldlist .= ',x.' . $realfield . ' AS ' . $field;
4161              } else {
4162                  $fieldlist .= ',c.'.$field;
4163              }
4164          }
4165      }
4166      if ($orderby) {
4167          $fields = explode(',', $orderby);
4168          $orderby = '';
4169          foreach ($fields as $field) {
4170              if ($orderby) {
4171                  $orderby .= ',';
4172              }
4173              $orderby .= 'c.'.$field;
4174          }
4175          $orderby = 'ORDER BY '.$orderby;
4176      }
4177  
4178      $courses = array();
4179      $rs = $DB->get_recordset_sql("
4180              SELECT c.id $fieldlist
4181                FROM {course} c
4182                JOIN {context} x ON c.id = x.instanceid AND x.contextlevel = ?
4183              $contextlimitsql
4184              $orderby", array_merge([CONTEXT_COURSE], $contextlimitparams));
4185      foreach ($rs as $course) {
4186          $courses[] = $course;
4187          $limit--;
4188          if ($limit == 0) {
4189              break;
4190          }
4191      }
4192      $rs->close();
4193      return empty($courses) ? false : $courses;
4194  }
4195  
4196  /**
4197   * Switches the current user to another role for the current session and only
4198   * in the given context.
4199   *
4200   * The caller *must* check
4201   * - that this op is allowed
4202   * - that the requested role can be switched to in this context (use get_switchable_roles)
4203   * - that the requested role is NOT $CFG->defaultuserroleid
4204   *
4205   * To "unswitch" pass 0 as the roleid.
4206   *
4207   * This function *will* modify $USER->access - beware
4208   *
4209   * @param integer $roleid the role to switch to.
4210   * @param context $context the context in which to perform the switch.
4211   * @return bool success or failure.
4212   */
4213  function role_switch($roleid, context $context) {
4214      global $USER;
4215  
4216      // Add the ghost RA to $USER->access as $USER->access['rsw'][$path] = $roleid.
4217      // To un-switch just unset($USER->access['rsw'][$path]).
4218      //
4219      // Note: it is not possible to switch to roles that do not have course:view
4220  
4221      if (!isset($USER->access)) {
4222          load_all_capabilities();
4223      }
4224  
4225      // Add the switch RA
4226      if ($roleid == 0) {
4227          unset($USER->access['rsw'][$context->path]);
4228          return true;
4229      }
4230  
4231      $USER->access['rsw'][$context->path] = $roleid;
4232  
4233      return true;
4234  }
4235  
4236  /**
4237   * Checks if the user has switched roles within the given course.
4238   *
4239   * Note: You can only switch roles within the course, hence it takes a course id
4240   * rather than a context. On that note Petr volunteered to implement this across
4241   * all other contexts, all requests for this should be forwarded to him ;)
4242   *
4243   * @param int $courseid The id of the course to check
4244   * @return bool True if the user has switched roles within the course.
4245   */
4246  function is_role_switched($courseid) {
4247      global $USER;
4248      $context = context_course::instance($courseid, MUST_EXIST);
4249      return (!empty($USER->access['rsw'][$context->path]));
4250  }
4251  
4252  /**
4253   * Get any role that has an override on exact context
4254   *
4255   * @param context $context The context to check
4256   * @return array An array of roles
4257   */
4258  function get_roles_with_override_on_context(context $context) {
4259      global $DB;
4260  
4261      return $DB->get_records_sql("SELECT r.*
4262                                     FROM {role_capabilities} rc, {role} r
4263                                    WHERE rc.roleid = r.id AND rc.contextid = ?",
4264                                  array($context->id));
4265  }
4266  
4267  /**
4268   * Get all capabilities for this role on this context (overrides)
4269   *
4270   * @param stdClass $role
4271   * @param context $context
4272   * @return array
4273   */
4274  function get_capabilities_from_role_on_context($role, context $context) {
4275      global $DB;
4276  
4277      return $DB->get_records_sql("SELECT *
4278                                     FROM {role_capabilities}
4279                                    WHERE contextid = ? AND roleid = ?",
4280                                  array($context->id, $role->id));
4281  }
4282  
4283  /**
4284   * Find all user assignment of users for this role, on this context
4285   *
4286   * @param stdClass $role
4287   * @param context $context
4288   * @return array
4289   */
4290  function get_users_from_role_on_context($role, context $context) {
4291      global $DB;
4292  
4293      return $DB->get_records_sql("SELECT *
4294                                     FROM {role_assignments}
4295                                    WHERE contextid = ? AND roleid = ?",
4296                                  array($context->id, $role->id));
4297  }
4298  
4299  /**
4300   * Simple function returning a boolean true if user has roles
4301   * in context or parent contexts, otherwise false.
4302   *
4303   * @param int $userid
4304   * @param int $roleid
4305   * @param int $contextid empty means any context
4306   * @return bool
4307   */
4308  function user_has_role_assignment($userid, $roleid, $contextid = 0) {
4309      global $DB;
4310  
4311      if ($contextid) {
4312          if (!$context = context::instance_by_id($contextid, IGNORE_MISSING)) {
4313              return false;
4314          }
4315          $parents = $context->get_parent_context_ids(true);
4316          list($contexts, $params) = $DB->get_in_or_equal($parents, SQL_PARAMS_NAMED, 'r');
4317          $params['userid'] = $userid;
4318          $params['roleid'] = $roleid;
4319  
4320          $sql = "SELECT COUNT(ra.id)
4321                    FROM {role_assignments} ra
4322                   WHERE ra.userid = :userid AND ra.roleid = :roleid AND ra.contextid $contexts";
4323  
4324          $count = $DB->get_field_sql($sql, $params);
4325          return ($count > 0);
4326  
4327      } else {
4328          return $DB->record_exists('role_assignments', array('userid'=>$userid, 'roleid'=>$roleid));
4329      }
4330  }
4331  
4332  /**
4333   * Get localised role name or alias if exists and format the text.
4334   *
4335   * @param stdClass $role role object
4336   *      - optional 'coursealias' property should be included for performance reasons if course context used
4337   *      - description property is not required here
4338   * @param context|bool $context empty means system context
4339   * @param int $rolenamedisplay type of role name
4340   * @return string localised role name or course role name alias
4341   */
4342  function role_get_name(stdClass $role, $context = null, $rolenamedisplay = ROLENAME_ALIAS) {
4343      global $DB;
4344  
4345      if ($rolenamedisplay == ROLENAME_SHORT) {
4346          return $role->shortname;
4347      }
4348  
4349      if (!$context or !$coursecontext = $context->get_course_context(false)) {
4350          $coursecontext = null;
4351      }
4352  
4353      if ($coursecontext and !property_exists($role, 'coursealias') and ($rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH or $rolenamedisplay == ROLENAME_ALIAS_RAW)) {
4354          $role = clone($role); // Do not modify parameters.
4355          if ($r = $DB->get_record('role_names', array('roleid'=>$role->id, 'contextid'=>$coursecontext->id))) {
4356              $role->coursealias = $r->name;
4357          } else {
4358              $role->coursealias = null;
4359          }
4360      }
4361  
4362      if ($rolenamedisplay == ROLENAME_ALIAS_RAW) {
4363          if ($coursecontext) {
4364              return $role->coursealias;
4365          } else {
4366              return null;
4367          }
4368      }
4369  
4370      if (trim($role->name) !== '') {
4371          // For filtering always use context where was the thing defined - system for roles here.
4372          $original = format_string($role->name, true, array('context'=>context_system::instance()));
4373  
4374      } else {
4375          // Empty role->name means we want to see localised role name based on shortname,
4376          // only default roles are supposed to be localised.
4377          switch ($role->shortname) {
4378              case 'manager':         $original = get_string('manager', 'role'); break;
4379              case 'coursecreator':   $original = get_string('coursecreators'); break;
4380              case 'editingteacher':  $original = get_string('defaultcourseteacher'); break;
4381              case 'teacher':         $original = get_string('noneditingteacher'); break;
4382              case 'student':         $original = get_string('defaultcoursestudent'); break;
4383              case 'guest':           $original = get_string('guest'); break;
4384              case 'user':            $original = get_string('authenticateduser'); break;
4385              case 'frontpage':       $original = get_string('frontpageuser', 'role'); break;
4386              // We should not get here, the role UI should require the name for custom roles!
4387              default:                $original = $role->shortname; break;
4388          }
4389      }
4390  
4391      if ($rolenamedisplay == ROLENAME_ORIGINAL) {
4392          return $original;
4393      }
4394  
4395      if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
4396          return "$original ($role->shortname)";
4397      }
4398  
4399      if ($rolenamedisplay == ROLENAME_ALIAS) {
4400          if ($coursecontext and trim($role->coursealias) !== '') {
4401              return format_string($role->coursealias, true, array('context'=>$coursecontext));
4402          } else {
4403              return $original;
4404          }
4405      }
4406  
4407      if ($rolenamedisplay == ROLENAME_BOTH) {
4408          if ($coursecontext and trim($role->coursealias) !== '') {
4409              return format_string($role->coursealias, true, array('context'=>$coursecontext)) . " ($original)";
4410          } else {
4411              return $original;
4412          }
4413      }
4414  
4415      throw new coding_exception('Invalid $rolenamedisplay parameter specified in role_get_name()');
4416  }
4417  
4418  /**
4419   * Returns localised role description if available.
4420   * If the name is empty it tries to find the default role name using
4421   * hardcoded list of default role names or other methods in the future.
4422   *
4423   * @param stdClass $role
4424   * @return string localised role name
4425   */
4426  function role_get_description(stdClass $role) {
4427      if (!html_is_blank($role->description)) {
4428          return format_text($role->description, FORMAT_HTML, array('context'=>context_system::instance()));
4429      }
4430  
4431      switch ($role->shortname) {
4432          case 'manager':         return get_string('managerdescription', 'role');
4433          case 'coursecreator':   return get_string('coursecreatorsdescription');
4434          case 'editingteacher':  return get_string('defaultcourseteacherdescription');
4435          case 'teacher':         return get_string('noneditingteacherdescription');
4436          case 'student':         return get_string('defaultcoursestudentdescription');
4437          case 'guest':           return get_string('guestdescription');
4438          case 'user':            return get_string('authenticateduserdescription');
4439          case 'frontpage':       return get_string('frontpageuserdescription', 'role');
4440          default:                return '';
4441      }
4442  }
4443  
4444  /**
4445   * Get all the localised role names for a context.
4446   *
4447   * In new installs default roles have empty names, this function
4448   * add localised role names using current language pack.
4449   *
4450   * @param context $context the context, null means system context
4451   * @param array of role objects with a ->localname field containing the context-specific role name.
4452   * @param int $rolenamedisplay
4453   * @param bool $returnmenu true means id=>localname, false means id=>rolerecord
4454   * @return array Array of context-specific role names, or role objects with a ->localname field added.
4455   */
4456  function role_get_names(context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4457      return role_fix_names(get_all_roles($context), $context, $rolenamedisplay, $returnmenu);
4458  }
4459  
4460  /**
4461   * Prepare list of roles for display, apply aliases and localise default role names.
4462   *
4463   * @param array $roleoptions array roleid => roleobject (with optional coursealias), strings are accepted for backwards compatibility only
4464   * @param context $context the context, null means system context
4465   * @param int $rolenamedisplay
4466   * @param bool $returnmenu null means keep the same format as $roleoptions, true means id=>localname, false means id=>rolerecord
4467   * @return array Array of context-specific role names, or role objects with a ->localname field added.
4468   */
4469  function role_fix_names($roleoptions, context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4470      global $DB;
4471  
4472      if (empty($roleoptions)) {
4473          return array();
4474      }
4475  
4476      if (!$context or !$coursecontext = $context->get_course_context(false)) {
4477          $coursecontext = null;
4478      }
4479  
4480      // We usually need all role columns...
4481      $first = reset($roleoptions);
4482      if ($returnmenu === null) {
4483          $returnmenu = !is_object($first);
4484      }
4485  
4486      if (!is_object($first) or !property_exists($first, 'shortname')) {
4487          $allroles = get_all_roles($context);
4488          foreach ($roleoptions as $rid => $unused) {
4489              $roleoptions[$rid] = $allroles[$rid];
4490          }
4491      }
4492  
4493      // Inject coursealias if necessary.
4494      if ($coursecontext and ($rolenamedisplay == ROLENAME_ALIAS_RAW or $rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH)) {
4495          $first = reset($roleoptions);
4496          if (!property_exists($first, 'coursealias')) {
4497              $aliasnames = $DB->get_records('role_names', array('contextid'=>$coursecontext->id));
4498              foreach ($aliasnames as $alias) {
4499                  if (isset($roleoptions[$alias->roleid])) {
4500                      $roleoptions[$alias->roleid]->coursealias = $alias->name;
4501                  }
4502              }
4503          }
4504      }
4505  
4506      // Add localname property.
4507      foreach ($roleoptions as $rid => $role) {
4508          $roleoptions[$rid]->localname = role_get_name($role, $coursecontext, $rolenamedisplay);
4509      }
4510  
4511      if (!$returnmenu) {
4512          return $roleoptions;
4513      }
4514  
4515      $menu = array();
4516      foreach ($roleoptions as $rid => $role) {
4517          $menu[$rid] = $role->localname;
4518      }
4519  
4520      return $menu;
4521  }
4522  
4523  /**
4524   * Aids in detecting if a new line is required when reading a new capability
4525   *
4526   * This function helps admin/roles/manage.php etc to detect if a new line should be printed
4527   * when we read in a new capability.
4528   * Most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
4529   * but when we are in grade, all reports/import/export capabilities should be together
4530   *
4531   * @param string $cap component string a
4532   * @param string $comp component string b
4533   * @param int $contextlevel
4534   * @return bool whether 2 component are in different "sections"
4535   */
4536  function component_level_changed($cap, $comp, $contextlevel) {
4537  
4538      if (strstr($cap->component, '/') && strstr($comp, '/')) {
4539          $compsa = explode('/', $cap->component);
4540          $compsb = explode('/', $comp);
4541  
4542          // list of system reports
4543          if (($compsa[0] == 'report') && ($compsb[0] == 'report')) {
4544              return false;
4545          }
4546  
4547          // we are in gradebook, still
4548          if (($compsa[0] == 'gradeexport' || $compsa[0] == 'gradeimport' || $compsa[0] == 'gradereport') &&
4549              ($compsb[0] == 'gradeexport' || $compsb[0] == 'gradeimport' || $compsb[0] == 'gradereport')) {
4550              return false;
4551          }
4552  
4553          if (($compsa[0] == 'coursereport') && ($compsb[0] == 'coursereport')) {
4554              return false;
4555          }
4556      }
4557  
4558      return ($cap->component != $comp || $cap->contextlevel != $contextlevel);
4559  }
4560  
4561  /**
4562   * Fix the roles.sortorder field in the database, so it contains sequential integers,
4563   * and return an array of roleids in order.
4564   *
4565   * @param array $allroles array of roles, as returned by get_all_roles();
4566   * @return array $role->sortorder =-> $role->id with the keys in ascending order.
4567   */
4568  function fix_role_sortorder($allroles) {
4569      global $DB;
4570  
4571      $rolesort = array();
4572      $i = 0;
4573      foreach ($allroles as $role) {
4574          $rolesort[$i] = $role->id;
4575          if ($role->sortorder != $i) {
4576              $r = new stdClass();
4577              $r->id = $role->id;
4578              $r->sortorder = $i;
4579              $DB->update_record('role', $r);
4580              $allroles[$role->id]->sortorder = $i;
4581          }
4582          $i++;
4583      }
4584      return $rolesort;
4585  }
4586  
4587  /**
4588   * Switch the sort order of two roles (used in admin/roles/manage.php).
4589   *
4590   * @param stdClass $first The first role. Actually, only ->sortorder is used.
4591   * @param stdClass $second The second role. Actually, only ->sortorder is used.
4592   * @return boolean success or failure
4593   */
4594  function switch_roles($first, $second) {
4595      global $DB;
4596      $temp = $DB->get_field('role', 'MAX(sortorder) + 1', array());
4597      $result = $DB->set_field('role', 'sortorder', $temp, array('sortorder' => $first->sortorder));
4598      $result = $result && $DB->set_field('role', 'sortorder', $first->sortorder, array('sortorder' => $second->sortorder));
4599      $result = $result && $DB->set_field('role', 'sortorder', $second->sortorder, array('sortorder' => $temp));
4600      return $result;
4601  }
4602  
4603  /**
4604   * Duplicates all the base definitions of a role
4605   *
4606   * @param stdClass $sourcerole role to copy from
4607   * @param int $targetrole id of role to copy to
4608   */
4609  function role_cap_duplicate($sourcerole, $targetrole) {
4610      global $DB;
4611  
4612      $systemcontext = context_system::instance();
4613      $caps = $DB->get_records_sql("SELECT *
4614                                      FROM {role_capabilities}
4615                                     WHERE roleid = ? AND contextid = ?",
4616                                   array($sourcerole->id, $systemcontext->id));
4617      // adding capabilities
4618      foreach ($caps as $cap) {
4619          unset($cap->id);
4620          $cap->roleid = $targetrole;
4621          $DB->insert_record('role_capabilities', $cap);
4622      }
4623  
4624      // Reset any cache of this role, including MUC.
4625      accesslib_clear_role_cache($targetrole);
4626  }
4627  
4628  /**
4629   * Returns two lists, this can be used to find out if user has capability.
4630   * Having any needed role and no forbidden role in this context means
4631   * user has this capability in this context.
4632   * Use get_role_names_with_cap_in_context() if you need role names to display in the UI
4633   *
4634   * @param stdClass $context
4635   * @param string $capability
4636   * @return array($neededroles, $forbiddenroles)
4637   */
4638  function get_roles_with_cap_in_context($context, $capability) {
4639      global $DB;
4640  
4641      $ctxids = trim($context->path, '/'); // kill leading slash
4642      $ctxids = str_replace('/', ',', $ctxids);
4643  
4644      $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.depth
4645                FROM {role_capabilities} rc
4646                JOIN {context} ctx ON ctx.id = rc.contextid
4647                JOIN {capabilities} cap ON rc.capability = cap.name
4648               WHERE rc.capability = :cap AND ctx.id IN ($ctxids)
4649            ORDER BY rc.roleid ASC, ctx.depth DESC";
4650      $params = array('cap'=>$capability);
4651  
4652      if (!$capdefs = $DB->get_records_sql($sql, $params)) {
4653          // no cap definitions --> no capability
4654          return array(array(), array());
4655      }
4656  
4657      $forbidden = array();
4658      $needed    = array();
4659      foreach ($capdefs as $def) {
4660          if (isset($forbidden[$def->roleid])) {
4661              continue;
4662          }
4663          if ($def->permission == CAP_PROHIBIT) {
4664              $forbidden[$def->roleid] = $def->roleid;
4665              unset($needed[$def->roleid]);
4666              continue;
4667          }
4668          if (!isset($needed[$def->roleid])) {
4669              if ($def->permission == CAP_ALLOW) {
4670                  $needed[$def->roleid] = true;
4671              } else if ($def->permission == CAP_PREVENT) {
4672                  $needed[$def->roleid] = false;
4673              }
4674          }
4675      }
4676      unset($capdefs);
4677  
4678      // remove all those roles not allowing
4679      foreach ($needed as $key=>$value) {
4680          if (!$value) {
4681              unset($needed[$key]);
4682          } else {
4683              $needed[$key] = $key;
4684          }
4685      }
4686  
4687      return array($needed, $forbidden);
4688  }
4689  
4690  /**
4691   * Returns an array of role IDs that have ALL of the the supplied capabilities
4692   * Uses get_roles_with_cap_in_context(). Returns $allowed minus $forbidden
4693   *
4694   * @param stdClass $context
4695   * @param array $capabilities An array of capabilities
4696   * @return array of roles with all of the required capabilities
4697   */
4698  function get_roles_with_caps_in_context($context, $capabilities) {
4699      $neededarr = array();
4700      $forbiddenarr = array();
4701      foreach ($capabilities as $caprequired) {
4702          list($neededarr[], $forbiddenarr[]) = get_roles_with_cap_in_context($context, $caprequired);
4703      }
4704  
4705      $rolesthatcanrate = array();
4706      if (!empty($neededarr)) {
4707          foreach ($neededarr as $needed) {
4708              if (empty($rolesthatcanrate)) {
4709                  $rolesthatcanrate = $needed;
4710              } else {
4711                  //only want roles that have all caps
4712                  $rolesthatcanrate = array_intersect_key($rolesthatcanrate,$needed);
4713              }
4714          }
4715      }
4716      if (!empty($forbiddenarr) && !empty($rolesthatcanrate)) {
4717          foreach ($forbiddenarr as $forbidden) {
4718             //remove any roles that are forbidden any of the caps
4719             $rolesthatcanrate = array_diff($rolesthatcanrate, $forbidden);
4720          }
4721      }
4722      return $rolesthatcanrate;
4723  }
4724  
4725  /**
4726   * Returns an array of role names that have ALL of the the supplied capabilities
4727   * Uses get_roles_with_caps_in_context(). Returns $allowed minus $forbidden
4728   *
4729   * @param stdClass $context
4730   * @param array $capabilities An array of capabilities
4731   * @return array of roles with all of the required capabilities
4732   */
4733  function get_role_names_with_caps_in_context($context, $capabilities) {
4734      global $DB;
4735  
4736      $rolesthatcanrate = get_roles_with_caps_in_context($context, $capabilities);
4737      $allroles = $DB->get_records('role', null, 'sortorder DESC');
4738  
4739      $roles = array();
4740      foreach ($rolesthatcanrate as $r) {
4741          $roles[$r] = $allroles[$r];
4742      }
4743  
4744      return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
4745  }
4746  
4747  /**
4748   * This function verifies the prohibit comes from this context
4749   * and there are no more prohibits in parent contexts.
4750   *
4751   * @param int $roleid
4752   * @param context $context
4753   * @param string $capability name
4754   * @return bool
4755   */
4756  function prohibit_is_removable($roleid, context $context, $capability) {
4757      global $DB;
4758  
4759      $ctxids = trim($context->path, '/'); // kill leading slash
4760      $ctxids = str_replace('/', ',', $ctxids);
4761  
4762      $params = array('roleid'=>$roleid, 'cap'=>$capability, 'prohibit'=>CAP_PROHIBIT);
4763  
4764      $sql = "SELECT ctx.id
4765                FROM {role_capabilities} rc
4766                JOIN {context} ctx ON ctx.id = rc.contextid
4767                JOIN {capabilities} cap ON rc.capability = cap.name
4768               WHERE rc.roleid = :roleid AND rc.permission = :prohibit AND rc.capability = :cap AND ctx.id IN ($ctxids)
4769            ORDER BY ctx.depth DESC";
4770  
4771      if (!$prohibits = $DB->get_records_sql($sql, $params)) {
4772          // no prohibits == nothing to remove
4773          return true;
4774      }
4775  
4776      if (count($prohibits) > 1) {
4777          // more prohibits can not be removed
4778          return false;
4779      }
4780  
4781      return !empty($prohibits[$context->id]);
4782  }
4783  
4784  /**
4785   * More user friendly role permission changing,
4786   * it should produce as few overrides as possible.
4787   *
4788   * @param int $roleid
4789   * @param stdClass $context
4790   * @param string $capname capability name
4791   * @param int $permission
4792   * @return void
4793   */
4794  function role_change_permission($roleid, $context, $capname, $permission) {
4795      global $DB;
4796  
4797      if ($permission == CAP_INHERIT) {
4798          unassign_capability($capname, $roleid, $context->id);
4799          return;
4800      }
4801  
4802      $ctxids = trim($context->path, '/'); // kill leading slash
4803      $ctxids = str_replace('/', ',', $ctxids);
4804  
4805      $params = array('roleid'=>$roleid, 'cap'=>$capname);
4806  
4807      $sql = "SELECT ctx.id, rc.permission, ctx.depth
4808                FROM {role_capabilities} rc
4809                JOIN {context} ctx ON ctx.id = rc.contextid
4810                JOIN {capabilities} cap ON rc.capability = cap.name
4811               WHERE rc.roleid = :roleid AND rc.capability = :cap AND ctx.id IN ($ctxids)
4812            ORDER BY ctx.depth DESC";
4813  
4814      if ($existing = $DB->get_records_sql($sql, $params)) {
4815          foreach ($existing as $e) {
4816              if ($e->permission == CAP_PROHIBIT) {
4817                  // prohibit can not be overridden, no point in changing anything
4818                  return;
4819              }
4820          }
4821          $lowest = array_shift($existing);
4822          if ($lowest->permission == $permission) {
4823              // permission already set in this context or parent - nothing to do
4824              return;
4825          }
4826          if ($existing) {
4827              $parent = array_shift($existing);
4828              if ($parent->permission == $permission) {
4829                  // permission already set in parent context or parent - just unset in this context
4830                  // we do this because we want as few overrides as possible for performance reasons
4831                  unassign_capability($capname, $roleid, $context->id);
4832                  return;
4833              }
4834          }
4835  
4836      } else {
4837          if ($permission == CAP_PREVENT) {
4838              // nothing means role does not have permission
4839              return;
4840          }
4841      }
4842  
4843      // assign the needed capability
4844      assign_capability($capname, $permission, $roleid, $context->id, true);
4845  }
4846  
4847  
4848  /**
4849   * Basic moodle context abstraction class.
4850   *
4851   * Google confirms that no other important framework is using "context" class,
4852   * we could use something else like mcontext or moodle_context, but we need to type
4853   * this very often which would be annoying and it would take too much space...
4854   *
4855   * This class is derived from stdClass for backwards compatibility with
4856   * odl $context record that was returned from DML $DB->get_record()
4857   *
4858   * @package   core_access
4859   * @category  access
4860   * @copyright Petr Skoda {@link http://skodak.org}
4861   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4862   * @since     Moodle 2.2
4863   *
4864   * @property-read int $id context id
4865   * @property-read int $contextlevel CONTEXT_SYSTEM, CONTEXT_COURSE, etc.
4866   * @property-read int $instanceid id of related instance in each context
4867   * @property-read string $path path to context, starts with system context
4868   * @property-read int $depth
4869   */
4870  abstract class context extends stdClass implements IteratorAggregate {
4871  
4872      /**
4873       * The context id
4874       * Can be accessed publicly through $context->id
4875       * @var int
4876       */
4877      protected $_id;
4878  
4879      /**
4880       * The context level
4881       * Can be accessed publicly through $context->contextlevel
4882       * @var int One of CONTEXT_* e.g. CONTEXT_COURSE, CONTEXT_MODULE
4883       */
4884      protected $_contextlevel;
4885  
4886      /**
4887       * Id of the item this context is related to e.g. COURSE_CONTEXT => course.id
4888       * Can be accessed publicly through $context->instanceid
4889       * @var int
4890       */
4891      protected $_instanceid;
4892  
4893      /**
4894       * The path to the context always starting from the system context
4895       * Can be accessed publicly through $context->path
4896       * @var string
4897       */
4898      protected $_path;
4899  
4900      /**
4901       * The depth of the context in relation to parent contexts
4902       * Can be accessed publicly through $context->depth
4903       * @var int
4904       */
4905      protected $_depth;
4906  
4907      /**
4908       * Whether this context is locked or not.
4909       *
4910       * Can be accessed publicly through $context->locked.
4911       *
4912       * @var int
4913       */
4914      protected $_locked;
4915  
4916      /**
4917       * @var array Context caching info
4918       */
4919      private static $cache_contextsbyid = array();
4920  
4921      /**
4922       * @var array Context caching info
4923       */
4924      private static $cache_contexts     = array();
4925  
4926      /**
4927       * Context count
4928       * Why do we do count contexts? Because count($array) is horribly slow for large arrays
4929       * @var int
4930       */
4931      protected static $cache_count      = 0;
4932  
4933      /**
4934       * @var array Context caching info
4935       */
4936      protected static $cache_preloaded  = array();
4937  
4938      /**
4939       * @var context_system The system context once initialised
4940       */
4941      protected static $systemcontext    = null;
4942  
4943      /**
4944       * Resets the cache to remove all data.
4945       * @static
4946       */
4947      protected static function reset_caches() {
4948          self::$cache_contextsbyid = array();
4949          self::$cache_contexts     = array();
4950          self::$cache_count        = 0;
4951          self::$cache_preloaded    = array();
4952  
4953          self::$systemcontext = null;
4954      }
4955  
4956      /**
4957       * Adds a context to the cache. If the cache is full, discards a batch of
4958       * older entries.
4959       *
4960       * @static
4961       * @param context $context New context to add
4962       * @return void
4963       */
4964      protected static function cache_add(context $context) {
4965          if (isset(self::$cache_contextsbyid[$context->id])) {
4966              // already cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4967              return;
4968          }
4969  
4970          if (self::$cache_count >= CONTEXT_CACHE_MAX_SIZE) {
4971              $i = 0;
4972              foreach (self::$cache_contextsbyid as $ctx) {
4973                  $i++;
4974                  if ($i <= 100) {
4975                      // we want to keep the first contexts to be loaded on this page, hopefully they will be needed again later
4976                      continue;
4977                  }
4978                  if ($i > (CONTEXT_CACHE_MAX_SIZE / 3)) {
4979                      // we remove oldest third of the contexts to make room for more contexts
4980                      break;
4981                  }
4982                  unset(self::$cache_contextsbyid[$ctx->id]);
4983                  unset(self::$cache_contexts[$ctx->contextlevel][$ctx->instanceid]);
4984                  self::$cache_count--;
4985              }
4986          }
4987  
4988          self::$cache_contexts[$context->contextlevel][$context->instanceid] = $context;
4989          self::$cache_contextsbyid[$context->id] = $context;
4990          self::$cache_count++;
4991      }
4992  
4993      /**
4994       * Removes a context from the cache.
4995       *
4996       * @static
4997       * @param context $context Context object to remove
4998       * @return void
4999       */
5000      protected static function cache_remove(context $context) {
5001          if (!isset(self::$cache_contextsbyid[$context->id])) {
5002              // not cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
5003              return;
5004          }
5005          unset(self::$cache_contexts[$context->contextlevel][$context->instanceid]);
5006          unset(self::$cache_contextsbyid[$context->id]);
5007  
5008          self::$cache_count--;
5009  
5010          if (self::$cache_count < 0) {
5011              self::$cache_count = 0;
5012          }
5013      }
5014  
5015      /**
5016       * Gets a context from the cache.
5017       *
5018       * @static
5019       * @param int $contextlevel Context level
5020       * @param int $instance Instance ID
5021       * @return context|bool Context or false if not in cache
5022       */
5023      protected static function cache_get($contextlevel, $instance) {
5024          if (isset(self::$cache_contexts[$contextlevel][$instance])) {
5025              return self::$cache_contexts[$contextlevel][$instance];
5026          }
5027          return false;
5028      }
5029  
5030      /**
5031       * Gets a context from the cache based on its id.
5032       *
5033       * @static
5034       * @param int $id Context ID
5035       * @return context|bool Context or false if not in cache
5036       */
5037      protected static function cache_get_by_id($id) {
5038          if (isset(self::$cache_contextsbyid[$id])) {
5039              return self::$cache_contextsbyid[$id];
5040          }
5041          return false;
5042      }
5043  
5044      /**
5045       * Preloads context information from db record and strips the cached info.
5046       *
5047       * @static
5048       * @param stdClass $rec
5049       * @return void (modifies $rec)
5050       */
5051      protected static function preload_from_record(stdClass $rec) {
5052          $notenoughdata = false;
5053          $notenoughdata = $notenoughdata || empty($rec->ctxid);
5054          $notenoughdata = $notenoughdata || empty($rec->ctxlevel);
5055          $notenoughdata = $notenoughdata || !isset($rec->ctxinstance);
5056          $notenoughdata = $notenoughdata || empty($rec->ctxpath);
5057          $notenoughdata = $notenoughdata || empty($rec->ctxdepth);
5058          $notenoughdata = $notenoughdata || !isset($rec->ctxlocked);
5059          if ($notenoughdata) {
5060              // The record does not have enough data, passed here repeatedly or context does not exist yet.
5061              if (isset($rec->ctxid) && !isset($rec->ctxlocked)) {
5062                  debugging('Locked value missing. Code is possibly not usings the getter properly.', DEBUG_DEVELOPER);
5063              }
5064              return;
5065          }
5066  
5067          $record = (object) [
5068              'id'            => $rec->ctxid,
5069              'contextlevel'  => $rec->ctxlevel,
5070              'instanceid'    => $rec->ctxinstance,
5071              'path'          => $rec->ctxpath,
5072              'depth'         => $rec->ctxdepth,
5073              'locked'        => $rec->ctxlocked,
5074          ];
5075  
5076          unset($rec->ctxid);
5077          unset($rec->ctxlevel);
5078          unset($rec->ctxinstance);
5079          unset($rec->ctxpath);
5080          unset($rec->ctxdepth);
5081          unset($rec->ctxlocked);
5082  
5083          return context::create_instance_from_record($record);
5084      }
5085  
5086  
5087      // ====== magic methods =======
5088  
5089      /**
5090       * Magic setter method, we do not want anybody to modify properties from the outside
5091       * @param string $name
5092       * @param mixed $value
5093       */
5094      public function __set($name, $value) {
5095          debugging('Can not change context instance properties!');
5096      }
5097  
5098      /**
5099       * Magic method getter, redirects to read only values.
5100       * @param string $name
5101       * @return mixed
5102       */
5103      public function __get($name) {
5104          switch ($name) {
5105              case 'id':
5106                  return $this->_id;
5107              case 'contextlevel':
5108                  return $this->_contextlevel;
5109              case 'instanceid':
5110                  return $this->_instanceid;
5111              case 'path':
5112                  return $this->_path;
5113              case 'depth':
5114                  return $this->_depth;
5115              case 'locked':
5116                  return $this->is_locked();
5117  
5118              default:
5119                  debugging('Invalid context property accessed! '.$name);
5120                  return null;
5121          }
5122      }
5123  
5124      /**
5125       * Full support for isset on our magic read only properties.
5126       * @param string $name
5127       * @return bool
5128       */
5129      public function __isset($name) {
5130          switch ($name) {
5131              case 'id':
5132                  return isset($this->_id);
5133              case 'contextlevel':
5134                  return isset($this->_contextlevel);
5135              case 'instanceid':
5136                  return isset($this->_instanceid);
5137              case 'path':
5138                  return isset($this->_path);
5139              case 'depth':
5140                  return isset($this->_depth);
5141              case 'locked':
5142                  // Locked is always set.
5143                  return true;
5144              default:
5145                  return false;
5146          }
5147      }
5148  
5149      /**
5150       * All properties are read only, sorry.
5151       * @param string $name
5152       */
5153      public function __unset($name) {
5154          debugging('Can not unset context instance properties!');
5155      }
5156  
5157      // ====== implementing method from interface IteratorAggregate ======
5158  
5159      /**
5160       * Create an iterator because magic vars can't be seen by 'foreach'.
5161       *
5162       * Now we can convert context object to array using convert_to_array(),
5163       * and feed it properly to json_encode().
5164       */
5165      public function getIterator() {
5166          $ret = array(
5167              'id'           => $this->id,
5168              'contextlevel' => $this->contextlevel,
5169              'instanceid'   => $this->instanceid,
5170              'path'         => $this->path,
5171              'depth'        => $this->depth,
5172              'locked'       => $this->locked,
5173          );
5174          return new ArrayIterator($ret);
5175      }
5176  
5177      // ====== general context methods ======
5178  
5179      /**
5180       * Constructor is protected so that devs are forced to
5181       * use context_xxx::instance() or context::instance_by_id().
5182       *
5183       * @param stdClass $record
5184       */
5185      protected function __construct(stdClass $record) {
5186          $this->_id           = (int)$record->id;
5187          $this->_contextlevel = (int)$record->contextlevel;
5188          $this->_instanceid   = $record->instanceid;
5189          $this->_path         = $record->path;
5190          $this->_depth        = $record->depth;
5191  
5192          if (isset($record->locked)) {
5193              $this->_locked = $record->locked;
5194          } else if (!during_initial_install() && !moodle_needs_upgrading()) {
5195              debugging('Locked value missing. Code is possibly not usings the getter properly.', DEBUG_DEVELOPER);
5196          }
5197      }
5198  
5199      /**
5200       * This function is also used to work around 'protected' keyword problems in context_helper.
5201       * @static
5202       * @param stdClass $record
5203       * @return context instance
5204       */
5205      protected static function create_instance_from_record(stdClass $record) {
5206          $classname = context_helper::get_class_for_level($record->contextlevel);
5207  
5208          if ($context = context::cache_get_by_id($record->id)) {
5209              return $context;
5210          }
5211  
5212          $context = new $classname($record);
5213          context::cache_add($context);
5214  
5215          return $context;
5216      }
5217  
5218      /**
5219       * Copy prepared new contexts from temp table to context table,
5220       * we do this in db specific way for perf reasons only.
5221       * @static
5222       */
5223      protected static function merge_context_temp_table() {
5224          global $DB;
5225  
5226          /* MDL-11347:
5227           *  - mysql does not allow to use FROM in UPDATE statements
5228           *  - using two tables after UPDATE works in mysql, but might give unexpected
5229           *    results in pg 8 (depends on configuration)
5230           *  - using table alias in UPDATE does not work in pg < 8.2
5231           *
5232           * Different code for each database - mostly for performance reasons
5233           */
5234  
5235          $dbfamily = $DB->get_dbfamily();
5236          if ($dbfamily == 'mysql') {
5237              $updatesql = "UPDATE {context} ct, {context_temp} temp
5238                               SET ct.path     = temp.path,
5239                                   ct.depth    = temp.depth,
5240                                   ct.locked   = temp.locked
5241                             WHERE ct.id = temp.id";
5242          } else if ($dbfamily == 'oracle') {
5243              $updatesql = "UPDATE {context} ct
5244                               SET (ct.path, ct.depth, ct.locked) =
5245                                   (SELECT temp.path, temp.depth, temp.locked
5246                                      FROM {context_temp} temp
5247                                     WHERE temp.id=ct.id)
5248                             WHERE EXISTS (SELECT 'x'
5249                                             FROM {context_temp} temp
5250                                             WHERE temp.id = ct.id)";
5251          } else if ($dbfamily == 'postgres' or $dbfamily == 'mssql') {
5252              $updatesql = "UPDATE {context}
5253                               SET path     = temp.path,
5254                                   depth    = temp.depth,
5255                                   locked   = temp.locked
5256                              FROM {context_temp} temp
5257                             WHERE temp.id={context}.id";
5258          } else {
5259              // sqlite and others
5260              $updatesql = "UPDATE {context}
5261                               SET path     = (SELECT path FROM {context_temp} WHERE id = {context}.id),
5262                                   depth    = (SELECT depth FROM {context_temp} WHERE id = {context}.id),
5263                                   locked   = (SELECT locked FROM {context_temp} WHERE id = {context}.id)
5264                               WHERE id IN (SELECT id FROM {context_temp})";
5265          }
5266  
5267          $DB->execute($updatesql);
5268      }
5269  
5270     /**
5271      * Get a context instance as an object, from a given context id.
5272      *
5273      * @static
5274      * @param int $id context id
5275      * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
5276      *                        MUST_EXIST means throw exception if no record found
5277      * @return context|bool the context object or false if not found
5278      */
5279      public static function instance_by_id($id, $strictness = MUST_EXIST) {
5280          global $DB;
5281  
5282          if (get_called_class() !== 'context' and get_called_class() !== 'context_helper') {
5283              // some devs might confuse context->id and instanceid, better prevent these mistakes completely
5284              throw new coding_exception('use only context::instance_by_id() for real context levels use ::instance() methods');
5285          }
5286  
5287          if ($id == SYSCONTEXTID) {
5288              return context_system::instance(0, $strictness);
5289          }
5290  
5291          if (is_array($id) or is_object($id) or empty($id)) {
5292              throw new coding_exception('Invalid context id specified context::instance_by_id()');
5293          }
5294  
5295          if ($context = context::cache_get_by_id($id)) {
5296              return $context;
5297          }
5298  
5299          if ($record = $DB->get_record('context', array('id'=>$id), '*', $strictness)) {
5300              return context::create_instance_from_record($record);
5301          }
5302  
5303          return false;
5304      }
5305  
5306      /**
5307       * Update context info after moving context in the tree structure.
5308       *
5309       * @param context $newparent
5310       * @return void
5311       */
5312      public function update_moved(context $newparent) {
5313          global $DB;
5314  
5315          $frompath = $this->_path;
5316          $newpath  = $newparent->path . '/' . $this->_id;
5317  
5318          $trans = $DB->start_delegated_transaction();
5319  
5320          $setdepth = '';
5321          if (($newparent->depth +1) != $this->_depth) {
5322              $diff = $newparent->depth - $this->_depth + 1;
5323              $setdepth = ", depth = depth + $diff";
5324          }
5325          $sql = "UPDATE {context}
5326                     SET path = ?
5327                         $setdepth
5328                   WHERE id = ?";
5329          $params = array($newpath, $this->_id);
5330          $DB->execute($sql, $params);
5331  
5332          $this->_path  = $newpath;
5333          $this->_depth = $newparent->depth + 1;
5334  
5335          $sql = "UPDATE {context}
5336                     SET path = ".$DB->sql_concat("?", $DB->sql_substr("path", strlen($frompath)+1))."
5337                         $setdepth
5338                   WHERE path LIKE ?";
5339          $params = array($newpath, "{$frompath}/%");
5340          $DB->execute($sql, $params);
5341  
5342          $this->mark_dirty();
5343  
5344          context::reset_caches();
5345  
5346          $trans->allow_commit();
5347      }
5348  
5349      /**
5350       * Set whether this context has been locked or not.
5351       *
5352       * @param   bool    $locked
5353       * @return  $this
5354       */
5355      public function set_locked(bool $locked) {
5356          global $DB;
5357  
5358          if ($this->_locked == $locked) {
5359              return $this;
5360          }
5361  
5362          $this->_locked = $locked;
5363          $DB->set_field('context', 'locked', (int) $locked, ['id' => $this->id]);
5364          $this->mark_dirty();
5365  
5366          if ($locked) {
5367              $eventname = '\\core\\event\\context_locked';
5368          } else {
5369              $eventname = '\\core\\event\\context_unlocked';
5370          }
5371          $event = $eventname::create(['context' => $this, 'objectid' => $this->id]);
5372          $event->trigger();
5373  
5374          self::reset_caches();
5375  
5376          return $this;
5377      }
5378  
5379      /**
5380       * Remove all context path info and optionally rebuild it.
5381       *
5382       * @param bool $rebuild
5383       * @return void
5384       */
5385      public function reset_paths($rebuild = true) {
5386          global $DB;
5387  
5388          if ($this->_path) {
5389              $this->mark_dirty();
5390          }
5391          $DB->set_field_select('context', 'depth', 0, "path LIKE '%/$this->_id/%'");
5392          $DB->set_field_select('context', 'path', NULL, "path LIKE '%/$this->_id/%'");
5393          if ($this->_contextlevel != CONTEXT_SYSTEM) {
5394              $DB->set_field('context', 'depth', 0, array('id'=>$this->_id));
5395              $DB->set_field('context', 'path', NULL, array('id'=>$this->_id));
5396              $this->_depth = 0;
5397              $this->_path = null;
5398          }
5399  
5400          if ($rebuild) {
5401              context_helper::build_all_paths(false);
5402          }
5403  
5404          context::reset_caches();
5405      }
5406  
5407      /**
5408       * Delete all data linked to content, do not delete the context record itself
5409       */
5410      public function delete_content() {
5411          global $CFG, $DB;
5412  
5413          blocks_delete_all_for_context($this->_id);
5414          filter_delete_all_for_context($this->_id);
5415  
5416          require_once($CFG->dirroot . '/comment/lib.php');
5417          comment::delete_comments(array('contextid'=>$this->_id));
5418  
5419          require_once($CFG->dirroot.'/rating/lib.php');
5420          $delopt = new stdclass();
5421          $delopt->contextid = $this->_id;
5422          $rm = new rating_manager();
5423          $rm->delete_ratings($delopt);
5424  
5425          // delete all files attached to this context
5426          $fs = get_file_storage();
5427          $fs->delete_area_files($this->_id);
5428  
5429          // Delete all repository instances attached to this context.
5430          require_once($CFG->dirroot . '/repository/lib.php');
5431          repository::delete_all_for_context($this->_id);
5432  
5433          // delete all advanced grading data attached to this context
5434          require_once($CFG->dirroot.'/grade/grading/lib.php');
5435          grading_manager::delete_all_for_context($this->_id);
5436  
5437          // now delete stuff from role related tables, role_unassign_all
5438          // and unenrol should be called earlier to do proper cleanup
5439          $DB->delete_records('role_assignments', array('contextid'=>$this->_id));
5440          $DB->delete_records('role_names', array('contextid'=>$this->_id));
5441          $this->delete_capabilities();
5442      }
5443  
5444      /**
5445       * Unassign all capabilities from a context.
5446       */
5447      public function delete_capabilities() {
5448          global $DB;
5449  
5450          $ids = $DB->get_fieldset_select('role_capabilities', 'DISTINCT roleid', 'contextid = ?', array($this->_id));
5451          if ($ids) {
5452              $DB->delete_records('role_capabilities', array('contextid' => $this->_id));
5453  
5454              // Reset any cache of these roles, including MUC.
5455              accesslib_clear_role_cache($ids);
5456          }
5457      }
5458  
5459      /**
5460       * Delete the context content and the context record itself
5461       */
5462      public function delete() {
5463          global $DB;
5464  
5465          if ($this->_contextlevel <= CONTEXT_SYSTEM) {
5466              throw new coding_exception('Cannot delete system context');
5467          }
5468  
5469          // double check the context still exists
5470          if (!$DB->record_exists('context', array('id'=>$this->_id))) {
5471              context::cache_remove($this);
5472              return;
5473          }
5474  
5475          $this->delete_content();
5476          $DB->delete_records('context', array('id'=>$this->_id));
5477          // purge static context cache if entry present
5478          context::cache_remove($this);
5479  
5480          // Inform search engine to delete data related to this context.
5481          \core_search\manager::context_deleted($this);
5482      }
5483  
5484      // ====== context level related methods ======
5485  
5486      /**
5487       * Utility method for context creation
5488       *
5489       * @static
5490       * @param int $contextlevel
5491       * @param int $instanceid
5492       * @param string $parentpath
5493       * @return stdClass context record
5494       */
5495      protected static function insert_context_record($contextlevel, $instanceid, $parentpath) {
5496          global $DB;
5497  
5498          $record = new stdClass();
5499          $record->contextlevel = $contextlevel;
5500          $record->instanceid   = $instanceid;
5501          $record->depth        = 0;
5502          $record->path         = null; //not known before insert
5503          $record->locked       = 0;
5504  
5505          $record->id = $DB->insert_record('context', $record);
5506  
5507          // now add path if known - it can be added later
5508          if (!is_null($parentpath)) {
5509              $record->path = $parentpath.'/'.$record->id;
5510              $record->depth = substr_count($record->path, '/');
5511              $DB->update_record('context', $record);
5512          }
5513  
5514          return $record;
5515      }
5516  
5517      /**
5518       * Returns human readable context identifier.
5519       *
5520       * @param boolean $withprefix whether to prefix the name of the context with the
5521       *      type of context, e.g. User, Course, Forum, etc.
5522       * @param boolean $short whether to use the short name of the thing. Only applies
5523       *      to course contexts
5524       * @param boolean $escape Whether the returned name of the thing is to be
5525       *      HTML escaped or not.
5526       * @return string the human readable context name.
5527       */
5528      public function get_context_name($withprefix = true, $short = false, $escape = true) {
5529          // must be implemented in all context levels
5530          throw new coding_exception('can not get name of abstract context');
5531      }
5532  
5533      /**
5534       * Whether the current context is locked.
5535       *
5536       * @return  bool
5537       */
5538      public function is_locked() {
5539          if ($this->_locked) {
5540              return true;
5541          }
5542  
5543          if ($parent = $this->get_parent_context()) {
5544              return $parent->is_locked();
5545          }
5546  
5547          return false;
5548      }
5549  
5550      /**
5551       * Returns the most relevant URL for this context.
5552       *
5553       * @return moodle_url
5554       */
5555      public abstract function get_url();
5556  
5557      /**
5558       * Returns array of relevant context capability records.
5559       *
5560       * @return array
5561       */
5562      public abstract function get_capabilities();
5563  
5564      /**
5565       * Recursive function which, given a context, find all its children context ids.
5566       *
5567       * For course category contexts it will return immediate children and all subcategory contexts.
5568       * It will NOT recurse into courses or subcategories categories.
5569       * If you want to do that, call it on the returned courses/categories.
5570       *
5571       * When called for a course context, it will return the modules and blocks
5572       * displayed in the course page and blocks displayed on the module pages.
5573       *
5574       * If called on a user/course/module context it _will_ populate the cache with the appropriate
5575       * contexts ;-)
5576       *
5577       * @return array Array of child records
5578       */
5579      public function get_child_contexts() {
5580          global $DB;
5581  
5582          if (empty($this->_path) or empty($this->_depth)) {
5583              debugging('Can not find child contexts of context '.$this->_id.' try rebuilding of context paths');
5584              return array();
5585          }
5586  
5587          $sql = "SELECT ctx.*
5588                    FROM {context} ctx
5589                   WHERE ctx.path LIKE ?";
5590          $params = array($this->_path.'/%');
5591          $records = $DB->get_records_sql($sql, $params);
5592  
5593          $result = array();
5594          foreach ($records as $record) {
5595              $result[$record->id] = context::create_instance_from_record($record);
5596          }
5597  
5598          return $result;
5599      }
5600  
5601      /**
5602       * Determine if the current context is a parent of the possible child.
5603       *
5604       * @param   context $possiblechild
5605       * @param   bool $includeself Whether to check the current context
5606       * @return  bool
5607       */
5608      public function is_parent_of(context $possiblechild, bool $includeself): bool {
5609          // A simple substring check is used on the context path.
5610          // The possible child's path is used as a haystack, with the current context as the needle.
5611          // The path is prefixed with '+' to ensure that the parent always starts at the top.
5612          // It is suffixed with '+' to ensure that parents are not included.
5613          // The needle always suffixes with a '/' to ensure that the contextid uses a complete match (i.e. 142/ instead of 14).
5614          // The haystack is suffixed with '/+' if $includeself is true to allow the current context to match.
5615          // The haystack is suffixed with '+' if $includeself is false to prevent the current context from matching.
5616          $haystacksuffix = $includeself ? '/+' : '+';
5617  
5618          $strpos = strpos(
5619              "+{$possiblechild->path}{$haystacksuffix}",
5620              "+{$this->path}/"
5621          );
5622          return $strpos === 0;
5623      }
5624  
5625      /**
5626       * Returns parent contexts of this context in reversed order, i.e. parent first,
5627       * then grand parent, etc.
5628       *
5629       * @param bool $includeself true means include self too
5630       * @return array of context instances
5631       */
5632      public function get_parent_contexts($includeself = false) {
5633          if (!$contextids = $this->get_parent_context_ids($includeself)) {
5634              return array();
5635          }
5636  
5637          // Preload the contexts to reduce DB calls.
5638          context_helper::preload_contexts_by_id($contextids);
5639  
5640          $result = array();
5641          foreach ($contextids as $contextid) {
5642              $parent = context::instance_by_id($contextid, MUST_EXIST);
5643              $result[$parent->id] = $parent;
5644          }
5645  
5646          return $result;
5647      }
5648  
5649      /**
5650       * Determine if the current context is a child of the possible parent.
5651       *
5652       * @param   context $possibleparent
5653       * @param   bool $includeself Whether to check the current context
5654       * @return  bool
5655       */
5656      public function is_child_of(context $possibleparent, bool $includeself): bool {
5657          // A simple substring check is used on the context path.
5658          // The current context is used as a haystack, with the possible parent as the needle.
5659          // The path is prefixed with '+' to ensure that the parent always starts at the top.
5660          // It is suffixed with '+' to ensure that children are not included.
5661          // The needle always suffixes with a '/' to ensure that the contextid uses a complete match (i.e. 142/ instead of 14).
5662          // The haystack is suffixed with '/+' if $includeself is true to allow the current context to match.
5663          // The haystack is suffixed with '+' if $includeself is false to prevent the current context from matching.
5664          $haystacksuffix = $includeself ? '/+' : '+';
5665  
5666          $strpos = strpos(
5667              "+{$this->path}{$haystacksuffix}",
5668              "+{$possibleparent->path}/"
5669          );
5670          return $strpos === 0;
5671      }
5672  
5673      /**
5674       * Returns parent context ids of this context in reversed order, i.e. parent first,
5675       * then grand parent, etc.
5676       *
5677       * @param bool $includeself true means include self too
5678       * @return array of context ids
5679       */
5680      public function get_parent_context_ids($includeself = false) {
5681          if (empty($this->_path)) {
5682              return array();
5683          }
5684  
5685          $parentcontexts = trim($this->_path, '/'); // kill leading slash
5686          $parentcontexts = explode('/', $parentcontexts);
5687          if (!$includeself) {
5688              array_pop($parentcontexts); // and remove its own id
5689          }
5690  
5691          return array_reverse($parentcontexts);
5692      }
5693  
5694      /**
5695       * Returns parent context paths of this context.
5696       *
5697       * @param bool $includeself true means include self too
5698       * @return array of context paths
5699       */
5700      public function get_parent_context_paths($includeself = false) {
5701          if (empty($this->_path)) {
5702              return array();
5703          }
5704  
5705          $contextids = explode('/', $this->_path);
5706  
5707          $path = '';
5708          $paths = array();
5709          foreach ($contextids as $contextid) {
5710              if ($contextid) {
5711                  $path .= '/' . $contextid;
5712                  $paths[$contextid] = $path;
5713              }
5714          }
5715  
5716          if (!$includeself) {
5717              unset($paths[$this->_id]);
5718          }
5719  
5720          return $paths;
5721      }
5722  
5723      /**
5724       * Returns parent context
5725       *
5726       * @return context
5727       */
5728      public function get_parent_context() {
5729          if (empty($this->_path) or $this->_id == SYSCONTEXTID) {
5730              return false;
5731          }
5732  
5733          $parentcontexts = trim($this->_path, '/'); // kill leading slash
5734          $parentcontexts = explode('/', $parentcontexts);
5735          array_pop($parentcontexts); // self
5736          $contextid = array_pop($parentcontexts); // immediate parent
5737  
5738          return context::instance_by_id($contextid, MUST_EXIST);
5739      }
5740  
5741      /**
5742       * Is this context part of any course? If yes return course context.
5743       *
5744       * @param bool $strict true means throw exception if not found, false means return false if not found
5745       * @return context_course context of the enclosing course, null if not found or exception
5746       */
5747      public function get_course_context($strict = true) {
5748          if ($strict) {
5749              throw new coding_exception('Context does not belong to any course.');
5750          } else {
5751              return false;
5752          }
5753      }
5754  
5755      /**
5756       * Returns sql necessary for purging of stale context instances.
5757       *
5758       * @static
5759       * @return string cleanup SQL
5760       */
5761      protected static function get_cleanup_sql() {
5762          throw new coding_exception('get_cleanup_sql() method must be implemented in all context levels');
5763      }
5764  
5765      /**
5766       * Rebuild context paths and depths at context level.
5767       *
5768       * @static
5769       * @param bool $force
5770       * @return void
5771       */
5772      protected static function build_paths($force) {
5773          throw new coding_exception('build_paths() method must be implemented in all context levels');
5774      }
5775  
5776      /**
5777       * Create missing context instances at given level
5778       *
5779       * @static
5780       * @return void
5781       */
5782      protected static function create_level_instances() {
5783          throw new coding_exception('create_level_instances() method must be implemented in all context levels');
5784      }
5785  
5786      /**
5787       * Reset all cached permissions and definitions if the necessary.
5788       * @return void
5789       */
5790      public function reload_if_dirty() {
5791          global $ACCESSLIB_PRIVATE, $USER;
5792  
5793          // Load dirty contexts list if needed
5794          if (CLI_SCRIPT) {
5795              if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5796                  // we do not load dirty flags in CLI and cron
5797                  $ACCESSLIB_PRIVATE->dirtycontexts = array();
5798              }
5799          } else {
5800              if (!isset($USER->access['time'])) {
5801                  // Nothing has been loaded yet, so we do not need to check dirty flags now.
5802                  return;
5803              }
5804  
5805              // From skodak: No idea why -2 is there, server cluster time difference maybe...
5806              $changedsince = $USER->access['time'] - 2;
5807  
5808              if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5809                  $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $changedsince);
5810              }
5811  
5812              if (!isset($ACCESSLIB_PRIVATE->dirtyusers[$USER->id])) {
5813                  $ACCESSLIB_PRIVATE->dirtyusers[$USER->id] = get_cache_flag('accesslib/dirtyusers', $USER->id, $changedsince);
5814              }
5815          }
5816  
5817          $dirty = false;
5818  
5819          if (!empty($ACCESSLIB_PRIVATE->dirtyusers[$USER->id])) {
5820              $dirty = true;
5821          } else if (!empty($ACCESSLIB_PRIVATE->dirtycontexts)) {
5822              $paths = $this->get_parent_context_paths(true);
5823  
5824              foreach ($paths as $path) {
5825                  if (isset($ACCESSLIB_PRIVATE->dirtycontexts[$path])) {
5826                      $dirty = true;
5827                      break;
5828                  }
5829              }
5830          }
5831  
5832          if ($dirty) {
5833              // Reload all capabilities of USER and others - preserving loginas, roleswitches, etc.
5834              // Then cleanup any marks of dirtyness... at least from our short term memory!
5835              reload_all_capabilities();
5836          }
5837      }
5838  
5839      /**
5840       * Mark a context as dirty (with timestamp) so as to force reloading of the context.
5841       */
5842      public function mark_dirty() {
5843          global $CFG, $USER, $ACCESSLIB_PRIVATE;
5844  
5845          if (during_initial_install()) {
5846              return;
5847          }
5848  
5849          // only if it is a non-empty string
5850          if (is_string($this->_path) && $this->_path !== '') {
5851              set_cache_flag('accesslib/dirtycontexts', $this->_path, 1, time()+$CFG->sessiontimeout);
5852              if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5853                  $ACCESSLIB_PRIVATE->dirtycontexts[$this->_path] = 1;
5854              } else {
5855                  if (CLI_SCRIPT) {
5856                      $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5857                  } else {
5858                      if (isset($USER->access['time'])) {
5859                          $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5860                      } else {
5861                          $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5862                      }
5863                      // flags not loaded yet, it will be done later in $context->reload_if_dirty()
5864                  }
5865              }
5866          }
5867      }
5868  }
5869  
5870  
5871  /**
5872   * Context maintenance and helper methods.
5873   *
5874   * This is "extends context" is a bloody hack that tires to work around the deficiencies
5875   * in the "protected" keyword in PHP, this helps us to hide all the internals of context
5876   * level implementation from the rest of code, the code completion returns what developers need.
5877   *
5878   * Thank you Tim Hunt for helping me with this nasty trick.
5879   *
5880   * @package   core_access
5881   * @category  access
5882   * @copyright Petr Skoda {@link http://skodak.org}
5883   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5884   * @since     Moodle 2.2
5885   */
5886  class context_helper extends context {
5887  
5888      /**
5889       * @var array An array mapping context levels to classes
5890       */
5891      private static $alllevels;
5892  
5893      /**
5894       * Instance does not make sense here, only static use
5895       */
5896      protected function __construct() {
5897      }
5898  
5899      /**
5900       * Reset internal context levels array.
5901       */
5902      public static function reset_levels() {
5903          self::$alllevels = null;
5904      }
5905  
5906      /**
5907       * Initialise context levels, call before using self::$alllevels.
5908       */
5909      private static function init_levels() {
5910          global $CFG;
5911  
5912          if (isset(self::$alllevels)) {
5913              return;
5914          }
5915          self::$alllevels = array(
5916              CONTEXT_SYSTEM    => 'context_system',
5917              CONTEXT_USER      => 'context_user',
5918              CONTEXT_COURSECAT => 'context_coursecat',
5919              CONTEXT_COURSE    => 'context_course',
5920              CONTEXT_MODULE    => 'context_module',
5921              CONTEXT_BLOCK     => 'context_block',
5922          );
5923  
5924          if (empty($CFG->custom_context_classes)) {
5925              return;
5926          }
5927  
5928          $levels = $CFG->custom_context_classes;
5929          if (!is_array($levels)) {
5930              $levels = @unserialize($levels);
5931          }
5932          if (!is_array($levels)) {
5933              debugging('Invalid $CFG->custom_context_classes detected, value ignored.', DEBUG_DEVELOPER);
5934              return;
5935          }
5936  
5937          // Unsupported custom levels, use with care!!!
5938          foreach ($levels as $level => $classname) {
5939              self::$alllevels[$level] = $classname;
5940          }
5941          ksort(self::$alllevels);
5942      }
5943  
5944      /**
5945       * Returns a class name of the context level class
5946       *
5947       * @static
5948       * @param int $contextlevel (CONTEXT_SYSTEM, etc.)
5949       * @return string class name of the context class
5950       */
5951      public static function get_class_for_level($contextlevel) {
5952          self::init_levels();
5953          if (isset(self::$alllevels[$contextlevel])) {
5954              return self::$alllevels[$contextlevel];
5955          } else {
5956              throw new coding_exception('Invalid context level specified');
5957          }
5958      }
5959  
5960      /**
5961       * Returns a list of all context levels
5962       *
5963       * @static
5964       * @return array int=>string (level=>level class name)
5965       */
5966      public static function get_all_levels() {
5967          self::init_levels();
5968          return self::$alllevels;
5969      }
5970  
5971      /**
5972       * Remove stale contexts that belonged to deleted instances.
5973       * Ideally all code should cleanup contexts properly, unfortunately accidents happen...
5974       *
5975       * @static
5976       * @return void
5977       */
5978      public static function cleanup_instances() {
5979          global $DB;
5980          self::init_levels();
5981  
5982          $sqls = array();
5983          foreach (self::$alllevels as $level=>$classname) {
5984              $sqls[] = $classname::get_cleanup_sql();
5985          }
5986  
5987          $sql = implode(" UNION ", $sqls);
5988  
5989          // it is probably better to use transactions, it might be faster too
5990          $transaction = $DB->start_delegated_transaction();
5991  
5992          $rs = $DB->get_recordset_sql($sql);
5993          foreach ($rs as $record) {
5994              $context = context::create_instance_from_record($record);
5995              $context->delete();
5996          }
5997          $rs->close();
5998  
5999          $transaction->allow_commit();
6000      }
6001  
6002      /**
6003       * Create all context instances at the given level and above.
6004       *
6005       * @static
6006       * @param int $contextlevel null means all levels
6007       * @param bool $buildpaths
6008       * @return void
6009       */
6010      public static function create_instances($contextlevel = null, $buildpaths = true) {
6011          self::init_levels();
6012          foreach (self::$alllevels as $level=>$classname) {
6013              if ($contextlevel and $level > $contextlevel) {
6014                  // skip potential sub-contexts
6015                  continue;
6016              }
6017              $classname::create_level_instances();
6018              if ($buildpaths) {
6019                  $classname::build_paths(false);
6020              }
6021          }
6022      }
6023  
6024      /**
6025       * Rebuild paths and depths in all context levels.
6026       *
6027       * @static
6028       * @param bool $force false means add missing only
6029       * @return void
6030       */
6031      public static function build_all_paths($force = false) {
6032          self::init_levels();
6033          foreach (self::$alllevels as $classname) {
6034              $classname::build_paths($force);
6035          }
6036  
6037          // reset static course cache - it might have incorrect cached data
6038          accesslib_clear_all_caches(true);
6039      }
6040  
6041      /**
6042       * Resets the cache to remove all data.
6043       * @static
6044       */
6045      public static function reset_caches() {
6046          context::reset_caches();
6047      }
6048  
6049      /**
6050       * Returns all fields necessary for context preloading from user $rec.
6051       *
6052       * This helps with performance when dealing with hundreds of contexts.
6053       *
6054       * @static
6055       * @param string $tablealias context table alias in the query
6056       * @return array (table.column=>alias, ...)
6057       */
6058      public static function get_preload_record_columns($tablealias) {
6059          return [
6060              "$tablealias.id" => "ctxid",
6061              "$tablealias.path" => "ctxpath",
6062              "$tablealias.depth" => "ctxdepth",
6063              "$tablealias.contextlevel" => "ctxlevel",
6064              "$tablealias.instanceid" => "ctxinstance",
6065              "$tablealias.locked" => "ctxlocked",
6066          ];
6067      }
6068  
6069      /**
6070       * Returns all fields necessary for context preloading from user $rec.
6071       *
6072       * This helps with performance when dealing with hundreds of contexts.
6073       *
6074       * @static
6075       * @param string $tablealias context table alias in the query
6076       * @return string
6077       */
6078      public static function get_preload_record_columns_sql($tablealias) {
6079          return "$tablealias.id AS ctxid, " .
6080                 "$tablealias.path AS ctxpath, " .
6081                 "$tablealias.depth AS ctxdepth, " .
6082                 "$tablealias.contextlevel AS ctxlevel, " .
6083                 "$tablealias.instanceid AS ctxinstance, " .
6084                 "$tablealias.locked AS ctxlocked";
6085      }
6086  
6087      /**
6088       * Preloads context information from db record and strips the cached info.
6089       *
6090       * The db request has to contain all columns from context_helper::get_preload_record_columns().
6091       *
6092       * @static
6093       * @param stdClass $rec
6094       * @return void (modifies $rec)
6095       */
6096       public static function preload_from_record(stdClass $rec) {
6097           context::preload_from_record($rec);
6098       }
6099  
6100      /**
6101       * Preload a set of contexts using their contextid.
6102       *
6103       * @param   array $contextids
6104       */
6105      public static function preload_contexts_by_id(array $contextids) {
6106          global $DB;
6107  
6108          // Determine which contexts are not already cached.
6109          $tofetch = [];
6110          foreach ($contextids as $contextid) {
6111              if (!self::cache_get_by_id($contextid)) {
6112                  $tofetch[] = $contextid;
6113              }
6114          }
6115  
6116          if (count($tofetch) > 1) {
6117              // There are at least two to fetch.
6118              // There is no point only fetching a single context as this would be no more efficient than calling the existing code.
6119              list($insql, $inparams) = $DB->get_in_or_equal($tofetch, SQL_PARAMS_NAMED);
6120              $ctxs = $DB->get_records_select('context', "id {$insql}", $inparams, '',
6121                      \context_helper::get_preload_record_columns_sql('{context}'));
6122              foreach ($ctxs as $ctx) {
6123                  self::preload_from_record($ctx);
6124              }
6125          }
6126      }
6127  
6128      /**
6129       * Preload all contexts instances from course.
6130       *
6131       * To be used if you expect multiple queries for course activities...
6132       *
6133       * @static
6134       * @param int $courseid
6135       */
6136      public static function preload_course($courseid) {
6137          // Users can call this multiple times without doing any harm
6138          if (isset(context::$cache_preloaded[$courseid])) {
6139              return;
6140          }
6141          $coursecontext = context_course::instance($courseid);
6142          $coursecontext->get_child_contexts();
6143  
6144          context::$cache_preloaded[$courseid] = true;
6145      }
6146  
6147      /**
6148       * Delete context instance
6149       *
6150       * @static
6151       * @param int $contextlevel
6152       * @param int $instanceid
6153       * @return void
6154       */
6155      public static function delete_instance($contextlevel, $instanceid) {
6156          global $DB;
6157  
6158          // double check the context still exists
6159          if ($record = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
6160              $context = context::create_instance_from_record($record);
6161              $context->delete();
6162          } else {
6163              // we should try to purge the cache anyway
6164          }
6165      }
6166  
6167      /**
6168       * Returns the name of specified context level
6169       *
6170       * @static
6171       * @param int $contextlevel
6172       * @return string name of the context level
6173       */
6174      public static function get_level_name($contextlevel) {
6175          $classname = context_helper::get_class_for_level($contextlevel);
6176          return $classname::get_level_name();
6177      }
6178  
6179      /**
6180       * not used
6181       */
6182      public function get_url() {
6183      }
6184  
6185      /**
6186       * not used
6187       */
6188      public function get_capabilities() {
6189      }
6190  }
6191  
6192  
6193  /**
6194   * System context class
6195   *
6196   * @package   core_access
6197   * @category  access
6198   * @copyright Petr Skoda {@link http://skodak.org}
6199   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6200   * @since     Moodle 2.2
6201   */
6202  class context_system extends context {
6203      /**
6204       * Please use context_system::instance() if you need the instance of context.
6205       *
6206       * @param stdClass $record
6207       */
6208      protected function __construct(stdClass $record) {
6209          parent::__construct($record);
6210          if ($record->contextlevel != CONTEXT_SYSTEM) {
6211              throw new coding_exception('Invalid $record->contextlevel in context_system constructor.');
6212          }
6213      }
6214  
6215      /**
6216       * Returns human readable context level name.
6217       *
6218       * @static
6219       * @return string the human readable context level name.
6220       */
6221      public static function get_level_name() {
6222          return get_string('coresystem');
6223      }
6224  
6225      /**
6226       * Returns human readable context identifier.
6227       *
6228       * @param boolean $withprefix does not apply to system context
6229       * @param boolean $short does not apply to system context
6230       * @param boolean $escape does not apply to system context
6231       * @return string the human readable context name.
6232       */
6233      public function get_context_name($withprefix = true, $short = false, $escape = true) {
6234          return self::get_level_name();
6235      }
6236  
6237      /**
6238       * Returns the most relevant URL for this context.
6239       *
6240       * @return moodle_url
6241       */
6242      public function get_url() {
6243          return new moodle_url('/');
6244      }
6245  
6246      /**
6247       * Returns array of relevant context capability records.
6248       *
6249       * @return array
6250       */
6251      public function get_capabilities() {
6252          global $DB;
6253  
6254          $sort = 'ORDER BY contextlevel,component,name';   // To group them sensibly for display
6255  
6256          $params = array();
6257          $sql = "SELECT *
6258                    FROM {capabilities}";
6259  
6260          return $DB->get_records_sql($sql.' '.$sort, $params);
6261      }
6262  
6263      /**
6264       * Create missing context instances at system context
6265       * @static
6266       */
6267      protected static function create_level_instances() {
6268          // nothing to do here, the system context is created automatically in installer
6269          self::instance(0);
6270      }
6271  
6272      /**
6273       * Returns system context instance.
6274       *
6275       * @static
6276       * @param int $instanceid should be 0
6277       * @param int $strictness
6278       * @param bool $cache
6279       * @return context_system context instance
6280       */
6281      public static function instance($instanceid = 0, $strictness = MUST_EXIST, $cache = true) {
6282          global $DB;
6283  
6284          if ($instanceid != 0) {
6285              debugging('context_system::instance(): invalid $id parameter detected, should be 0');
6286          }
6287  
6288          if (defined('SYSCONTEXTID') and $cache) { // dangerous: define this in config.php to eliminate 1 query/page
6289              if (!isset(context::$systemcontext)) {
6290                  $record = new stdClass();
6291                  $record->id           = SYSCONTEXTID;
6292                  $record->contextlevel = CONTEXT_SYSTEM;
6293                  $record->instanceid   = 0;
6294                  $record->path         = '/'.SYSCONTEXTID;
6295                  $record->depth        = 1;
6296                  $record->locked       = 0;
6297                  context::$systemcontext = new context_system($record);
6298              }
6299              return context::$systemcontext;
6300          }
6301  
6302          try {
6303              // We ignore the strictness completely because system context must exist except during install.
6304              $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
6305          } catch (dml_exception $e) {
6306              //table or record does not exist
6307              if (!during_initial_install()) {
6308                  // do not mess with system context after install, it simply must exist
6309                  throw $e;
6310              }
6311              $record = null;
6312          }
6313  
6314          if (!$record) {
6315              $record = new stdClass();
6316              $record->contextlevel = CONTEXT_SYSTEM;
6317              $record->instanceid   = 0;
6318              $record->depth        = 1;
6319              $record->path         = null; // Not known before insert.
6320              $record->locked       = 0;
6321  
6322              try {
6323                  if ($DB->count_records('context')) {
6324                      // contexts already exist, this is very weird, system must be first!!!
6325                      return null;
6326                  }
6327                  if (defined('SYSCONTEXTID')) {
6328                      // this would happen only in unittest on sites that went through weird 1.7 upgrade
6329                      $record->id = SYSCONTEXTID;
6330                      $DB->import_record('context', $record);
6331                      $DB->get_manager()->reset_sequence('context');
6332                  } else {
6333                      $record->id = $DB->insert_record('context', $record);
6334                  }
6335              } catch (dml_exception $e) {
6336                  // can not create context - table does not exist yet, sorry
6337                  return null;
6338              }
6339          }
6340  
6341          if ($record->instanceid != 0) {
6342              // this is very weird, somebody must be messing with context table
6343              debugging('Invalid system context detected');
6344          }
6345  
6346          if ($record->depth != 1 or $record->path != '/'.$record->id) {
6347              // fix path if necessary, initial install or path reset
6348              $record->depth = 1;
6349              $record->path  = '/'.$record->id;
6350              $DB->update_record('context', $record);
6351          }
6352  
6353          if (empty($record->locked)) {
6354              $record->locked = 0;
6355          }
6356  
6357          if (!defined('SYSCONTEXTID')) {
6358              define('SYSCONTEXTID', $record->id);
6359          }
6360  
6361          context::$systemcontext = new context_system($record);
6362          return context::$systemcontext;
6363      }
6364  
6365      /**
6366       * Returns all site contexts except the system context, DO NOT call on production servers!!
6367       *
6368       * Contexts are not cached.
6369       *
6370       * @return array
6371       */
6372      public function get_child_contexts() {
6373          global $DB;
6374  
6375          debugging('Fetching of system context child courses is strongly discouraged on production servers (it may eat all available memory)!');
6376  
6377          // Just get all the contexts except for CONTEXT_SYSTEM level
6378          // and hope we don't OOM in the process - don't cache
6379          $sql = "SELECT c.*
6380                    FROM {context} c
6381                   WHERE contextlevel > ".CONTEXT_SYSTEM;
6382          $records = $DB->get_records_sql($sql);
6383  
6384          $result = array();
6385          foreach ($records as $record) {
6386              $result[$record->id] = context::create_instance_from_record($record);
6387          }
6388  
6389          return $result;
6390      }
6391  
6392      /**
6393       * Returns sql necessary for purging of stale context instances.
6394       *
6395       * @static
6396       * @return string cleanup SQL
6397       */
6398      protected static function get_cleanup_sql() {
6399          $sql = "
6400                    SELECT c.*
6401                      FROM {context} c
6402                     WHERE 1=2
6403                 ";
6404  
6405          return $sql;
6406      }
6407  
6408      /**
6409       * Rebuild context paths and depths at system context level.
6410       *
6411       * @static
6412       * @param bool $force
6413       */
6414      protected static function build_paths($force) {
6415          global $DB;
6416  
6417          /* note: ignore $force here, we always do full test of system context */
6418  
6419          // exactly one record must exist
6420          $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
6421  
6422          if ($record->instanceid != 0) {
6423              debugging('Invalid system context detected');
6424          }
6425  
6426          if (defined('SYSCONTEXTID') and $record->id != SYSCONTEXTID) {
6427              debugging('Invalid SYSCONTEXTID detected');
6428          }
6429  
6430          if ($record->depth != 1 or $record->path != '/'.$record->id) {
6431              // fix path if necessary, initial install or path reset
6432              $record->depth    = 1;
6433              $record->path     = '/'.$record->id;
6434              $DB->update_record('context', $record);
6435          }
6436      }
6437  
6438      /**
6439       * Set whether this context has been locked or not.
6440       *
6441       * @param   bool    $locked
6442       * @return  $this
6443       */
6444      public function set_locked(bool $locked) {
6445          throw new \coding_exception('It is not possible to lock the system context');
6446  
6447          return $this;
6448      }
6449  }
6450  
6451  
6452  /**
6453   * User context class
6454   *
6455   * @package   core_access
6456   * @category  access
6457   * @copyright Petr Skoda {@link http://skodak.org}
6458   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6459   * @since     Moodle 2.2
6460   */
6461  class context_user extends context {
6462      /**
6463       * Please use context_user::instance($userid) if you need the instance of context.
6464       * Alternatively if you know only the context id use context::instance_by_id($contextid)
6465       *
6466       * @param stdClass $record
6467       */
6468      protected function __construct(stdClass $record) {
6469          parent::__construct($record);
6470          if ($record->contextlevel != CONTEXT_USER) {
6471              throw new coding_exception('Invalid $record->contextlevel in context_user constructor.');
6472          }
6473      }
6474  
6475      /**
6476       * Returns human readable context level name.
6477       *
6478       * @static
6479       * @return string the human readable context level name.
6480       */
6481      public static function get_level_name() {
6482          return get_string('user');
6483      }
6484  
6485      /**
6486       * Returns human readable context identifier.
6487       *
6488       * @param boolean $withprefix whether to prefix the name of the context with User
6489       * @param boolean $short does not apply to user context
6490       * @param boolean $escape does not apply to user context
6491       * @return string the human readable context name.
6492       */
6493      public function get_context_name($withprefix = true, $short = false, $escape = true) {
6494          global $DB;
6495  
6496          $name = '';
6497          if ($user = $DB->get_record('user', array('id'=>$this->_instanceid, 'deleted'=>0))) {
6498              if ($withprefix){
6499                  $name = get_string('user').': ';
6500              }
6501              $name .= fullname($user);
6502          }
6503          return $name;
6504      }
6505  
6506      /**
6507       * Returns the most relevant URL for this context.
6508       *
6509       * @return moodle_url
6510       */
6511      public function get_url() {
6512          global $COURSE;
6513  
6514          if ($COURSE->id == SITEID) {
6515              $url = new moodle_url('/user/profile.php', array('id'=>$this->_instanceid));
6516          } else {
6517              $url = new moodle_url('/user/view.php', array('id'=>$this->_instanceid, 'courseid'=>$COURSE->id));
6518          }
6519          return $url;
6520      }
6521  
6522      /**
6523       * Returns array of relevant context capability records.
6524       *
6525       * @return array
6526       */
6527      public function get_capabilities() {
6528          global $DB;
6529  
6530          $sort = 'ORDER BY contextlevel,component,name';   // To group them sensibly for display
6531  
6532          $extracaps = array('moodle/grade:viewall');
6533          list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
6534          $sql = "SELECT *
6535                    FROM {capabilities}
6536                   WHERE contextlevel = ".CONTEXT_USER."
6537                         OR name $extra";
6538  
6539          return $records = $DB->get_records_sql($sql.' '.$sort, $params);
6540      }
6541  
6542      /**
6543       * Returns user context instance.
6544       *
6545       * @static
6546       * @param int $userid id from {user} table
6547       * @param int $strictness
6548       * @return context_user context instance
6549       */
6550      public static function instance($userid, $strictness = MUST_EXIST) {
6551          global $DB;
6552  
6553          if ($context = context::cache_get(CONTEXT_USER, $userid)) {
6554              return $context;
6555          }
6556  
6557          if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_USER, 'instanceid' => $userid))) {
6558              if ($user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0), 'id', $strictness)) {
6559                  $record = context::insert_context_record(CONTEXT_USER, $user->id, '/'.SYSCONTEXTID, 0);
6560              }
6561          }
6562  
6563          if ($record) {
6564              $context = new context_user($record);
6565              context::cache_add($context);
6566              return $context;
6567          }
6568  
6569          return false;
6570      }
6571  
6572      /**
6573       * Create missing context instances at user context level
6574       * @static
6575       */
6576      protected static function create_level_instances() {
6577          global $DB;
6578  
6579          $sql = "SELECT ".CONTEXT_USER.", u.id
6580                    FROM {user} u
6581                   WHERE u.deleted = 0
6582                         AND NOT EXISTS (SELECT 'x'
6583                                           FROM {context} cx
6584                                          WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER.")";
6585          $contextdata = $DB->get_recordset_sql($sql);
6586          foreach ($contextdata as $context) {
6587              context::insert_context_record(CONTEXT_USER, $context->id, null);
6588          }
6589          $contextdata->close();
6590      }
6591  
6592      /**
6593       * Returns sql necessary for purging of stale context instances.
6594       *
6595       * @static
6596       * @return string cleanup SQL
6597       */
6598      protected static function get_cleanup_sql() {
6599          $sql = "
6600                    SELECT c.*
6601                      FROM {context} c
6602           LEFT OUTER JOIN {user} u ON (c.instanceid = u.id AND u.deleted = 0)
6603                     WHERE u.id IS NULL AND c.contextlevel = ".CONTEXT_USER."
6604                 ";
6605  
6606          return $sql;
6607      }
6608  
6609      /**
6610       * Rebuild context paths and depths at user context level.
6611       *
6612       * @static
6613       * @param bool $force
6614       */
6615      protected static function build_paths($force) {
6616          global $DB;
6617  
6618          // First update normal users.
6619          $path = $DB->sql_concat('?', 'id');
6620          $pathstart = '/' . SYSCONTEXTID . '/';
6621          $params = array($pathstart);
6622  
6623          if ($force) {
6624              $where = "depth <> 2 OR path IS NULL OR path <> ({$path})";
6625              $params[] = $pathstart;
6626          } else {
6627              $where = "depth = 0 OR path IS NULL";
6628          }
6629  
6630          $sql = "UPDATE {context}
6631                     SET depth = 2,
6632                         path = {$path}
6633                   WHERE contextlevel = " . CONTEXT_USER . "
6634                     AND ($where)";
6635          $DB->execute($sql, $params);
6636      }
6637  }
6638  
6639  
6640  /**
6641   * Course category context class
6642   *
6643   * @package   core_access
6644   * @category  access
6645   * @copyright Petr Skoda {@link http://skodak.org}
6646   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6647   * @since     Moodle 2.2
6648   */
6649  class context_coursecat extends context {
6650      /**
6651       * Please use context_coursecat::instance($coursecatid) if you need the instance of context.
6652       * Alternatively if you know only the context id use context::instance_by_id($contextid)
6653       *
6654       * @param stdClass $record
6655       */
6656      protected function __construct(stdClass $record) {
6657          parent::__construct($record);
6658          if ($record->contextlevel != CONTEXT_COURSECAT) {
6659              throw new coding_exception('Invalid $record->contextlevel in context_coursecat constructor.');
6660          }
6661      }
6662  
6663      /**
6664       * Returns human readable context level name.
6665       *
6666       * @static
6667       * @return string the human readable context level name.
6668       */
6669      public static function get_level_name() {
6670          return get_string('category');
6671      }
6672  
6673      /**
6674       * Returns human readable context identifier.
6675       *
6676       * @param boolean $withprefix whether to prefix the name of the context with Category
6677       * @param boolean $short does not apply to course categories
6678       * @param boolean $escape Whether the returned name of the context is to be HTML escaped or not.
6679       * @return string the human readable context name.
6680       */
6681      public function get_context_name($withprefix = true, $short = false, $escape = true) {
6682          global $DB;
6683  
6684          $name = '';
6685          if ($category = $DB->get_record('course_categories', array('id'=>$this->_instanceid))) {
6686              if ($withprefix){
6687                  $name = get_string('category').': ';
6688              }
6689              if (!$escape) {
6690                  $name .= format_string($category->name, true, array('context' => $this, 'escape' => false));
6691              } else {
6692                  $name .= format_string($category->name, true, array('context' => $this));
6693              }
6694          }
6695          return $name;
6696      }
6697  
6698      /**
6699       * Returns the most relevant URL for this context.
6700       *
6701       * @return moodle_url
6702       */
6703      public function get_url() {
6704          return new moodle_url('/course/index.php', array('categoryid' => $this->_instanceid));
6705      }
6706  
6707      /**
6708       * Returns array of relevant context capability records.
6709       *
6710       * @return array
6711       */
6712      public function get_capabilities() {
6713          global $DB;
6714  
6715          $sort = 'ORDER BY contextlevel,component,name';   // To group them sensibly for display
6716  
6717          $params = array();
6718          $sql = "SELECT *
6719                    FROM {capabilities}
6720                   WHERE contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6721  
6722          return $DB->get_records_sql($sql.' '.$sort, $params);
6723      }
6724  
6725      /**
6726       * Returns course category context instance.
6727       *
6728       * @static
6729       * @param int $categoryid id from {course_categories} table
6730       * @param int $strictness
6731       * @return context_coursecat context instance
6732       */
6733      public static function instance($categoryid, $strictness = MUST_EXIST) {
6734          global $DB;
6735  
6736          if ($context = context::cache_get(CONTEXT_COURSECAT, $categoryid)) {
6737              return $context;
6738          }
6739  
6740          if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_COURSECAT, 'instanceid' => $categoryid))) {
6741              if ($category = $DB->get_record('course_categories', array('id' => $categoryid), 'id,parent', $strictness)) {
6742                  if ($category->parent) {
6743                      $parentcontext = context_coursecat::instance($category->parent);
6744                      $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, $parentcontext->path);
6745                  } else {
6746                      $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, '/'.SYSCONTEXTID, 0);
6747                  }
6748              }
6749          }
6750  
6751          if ($record) {
6752              $context = new context_coursecat($record);
6753              context::cache_add($context);
6754              return $context;
6755          }
6756  
6757          return false;
6758      }
6759  
6760      /**
6761       * Returns immediate child contexts of category and all subcategories,
6762       * children of subcategories and courses are not returned.
6763       *
6764       * @return array
6765       */
6766      public function get_child_contexts() {
6767          global $DB;
6768  
6769          if (empty($this->_path) or empty($this->_depth)) {
6770              debugging('Can not find child contexts of context '.$this->_id.' try rebuilding of context paths');
6771              return array();
6772          }
6773  
6774          $sql = "SELECT ctx.*
6775                    FROM {context} ctx
6776                   WHERE ctx.path LIKE ? AND (ctx.depth = ? OR ctx.contextlevel = ?)";
6777          $params = array($this->_path.'/%', $this->depth+1, CONTEXT_COURSECAT);
6778          $records = $DB->get_records_sql($sql, $params);
6779  
6780          $result = array();
6781          foreach ($records as $record) {
6782              $result[$record->id] = context::create_instance_from_record($record);
6783          }
6784  
6785          return $result;
6786      }
6787  
6788      /**
6789       * Create missing context instances at course category context level
6790       * @static
6791       */
6792      protected static function create_level_instances() {
6793          global $DB;
6794  
6795          $sql = "SELECT ".CONTEXT_COURSECAT.", cc.id
6796                    FROM {course_categories} cc
6797                   WHERE NOT EXISTS (SELECT 'x'
6798                                       FROM {context} cx
6799                                      WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
6800          $contextdata = $DB->get_recordset_sql($sql);
6801          foreach ($contextdata as $context) {
6802              context::insert_context_record(CONTEXT_COURSECAT, $context->id, null);
6803          }
6804          $contextdata->close();
6805      }
6806  
6807      /**
6808       * Returns sql necessary for purging of stale context instances.
6809       *
6810       * @static
6811       * @return string cleanup SQL
6812       */
6813      protected static function get_cleanup_sql() {
6814          $sql = "
6815                    SELECT c.*
6816                      FROM {context} c
6817           LEFT OUTER JOIN {course_categories} cc ON c.instanceid = cc.id
6818                     WHERE cc.id IS NULL AND c.contextlevel = ".CONTEXT_COURSECAT."
6819                 ";
6820  
6821          return $sql;
6822      }
6823  
6824      /**
6825       * Rebuild context paths and depths at course category context level.
6826       *
6827       * @static
6828       * @param bool $force
6829       */
6830      protected static function build_paths($force) {
6831          global $DB;
6832  
6833          if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSECAT." AND (depth = 0 OR path IS NULL)")) {
6834              if ($force) {
6835                  $ctxemptyclause = $emptyclause = '';
6836              } else {
6837                  $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6838                  $emptyclause    = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6839              }
6840  
6841              $base = '/'.SYSCONTEXTID;
6842  
6843              // Normal top level categories
6844              $sql = "UPDATE {context}
6845                         SET depth=2,
6846                             path=".$DB->sql_concat("'$base/'", 'id')."
6847                       WHERE contextlevel=".CONTEXT_COURSECAT."
6848                             AND EXISTS (SELECT 'x'
6849                                           FROM {course_categories} cc
6850                                          WHERE cc.id = {context}.instanceid AND cc.depth=1)
6851                             $emptyclause";
6852              $DB->execute($sql);
6853  
6854              // Deeper categories - one query per depthlevel
6855              $maxdepth = $DB->get_field_sql("SELECT MAX(depth) FROM {course_categories}");
6856              for ($n=2; $n<=$maxdepth; $n++) {
6857                  $sql = "INSERT INTO {context_temp} (id, path, depth, locked)
6858                          SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1, ctx.locked
6859                            FROM {context} ctx
6860                            JOIN {course_categories} cc ON (cc.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSECAT." AND cc.depth = $n)
6861                            JOIN {context} pctx ON (pctx.instanceid = cc.parent AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6862                           WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6863                                 $ctxemptyclause";
6864                  $trans = $DB->start_delegated_transaction();
6865                  $DB->delete_records('context_temp');
6866                  $DB->execute($sql);
6867                  context::merge_context_temp_table();
6868                  $DB->delete_records('context_temp');
6869                  $trans->allow_commit();
6870  
6871              }
6872          }
6873      }
6874  }
6875  
6876  
6877  /**
6878   * Course context class
6879   *
6880   * @package   core_access
6881   * @category  access
6882   * @copyright Petr Skoda {@link http://skodak.org}
6883   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6884   * @since     Moodle 2.2
6885   */
6886  class context_course extends context {
6887      /**
6888       * Please use context_course::instance($courseid) if you need the instance of context.
6889       * Alternatively if you know only the context id use context::instance_by_id($contextid)
6890       *
6891       * @param stdClass $record
6892       */
6893      protected function __construct(stdClass $record) {
6894          parent::__construct($record);
6895          if ($record->contextlevel != CONTEXT_COURSE) {
6896              throw new coding_exception('Invalid $record->contextlevel in context_course constructor.');
6897          }
6898      }
6899  
6900      /**
6901       * Returns human readable context level name.
6902       *
6903       * @static
6904       * @return string the human readable context level name.
6905       */
6906      public static function get_level_name() {
6907          return get_string('course');
6908      }
6909  
6910      /**
6911       * Returns human readable context identifier.
6912       *
6913       * @param boolean $withprefix whether to prefix the name of the context with Course
6914       * @param boolean $short whether to use the short name of the thing.
6915       * @param bool $escape Whether the returned category name is to be HTML escaped or not.
6916       * @return string the human readable context name.
6917       */
6918      public function get_context_name($withprefix = true, $short = false, $escape = true) {
6919          global $DB;
6920  
6921          $name = '';
6922          if ($this->_instanceid == SITEID) {
6923              $name = get_string('frontpage', 'admin');
6924          } else {
6925              if ($course = $DB->get_record('course', array('id'=>$this->_instanceid))) {
6926                  if ($withprefix){
6927                      $name = get_string('course').': ';
6928                  }
6929                  if ($short){
6930                      if (!$escape) {
6931                          $name .= format_string($course->shortname, true, array('context' => $this, 'escape' => false));
6932                      } else {
6933                          $name .= format_string($course->shortname, true, array('context' => $this));
6934                      }
6935                  } else {
6936                      if (!$escape) {
6937                          $name .= format_string(get_course_display_name_for_list($course), true, array('context' => $this,
6938                              'escape' => false));
6939                      } else {
6940                          $name .= format_string(get_course_display_name_for_list($course), true, array('context' => $this));
6941                      }
6942                 }
6943              }
6944          }
6945          return $name;
6946      }
6947  
6948      /**
6949       * Returns the most relevant URL for this context.
6950       *
6951       * @return moodle_url
6952       */
6953      public function get_url() {
6954          if ($this->_instanceid != SITEID) {
6955              return new moodle_url('/course/view.php', array('id'=>$this->_instanceid));
6956          }
6957  
6958          return new moodle_url('/');
6959      }
6960  
6961      /**
6962       * Returns array of relevant context capability records.
6963       *
6964       * @return array
6965       */
6966      public function get_capabilities() {
6967          global $DB;
6968  
6969          $sort = 'ORDER BY contextlevel,component,name';   // To group them sensibly for display
6970  
6971          $params = array();
6972          $sql = "SELECT *
6973                    FROM {capabilities}
6974                   WHERE contextlevel IN (".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6975  
6976          return $DB->get_records_sql($sql.' '.$sort, $params);
6977      }
6978  
6979      /**
6980       * Is this context part of any course? If yes return course context.
6981       *
6982       * @param bool $strict true means throw exception if not found, false means return false if not found
6983       * @return context_course context of the enclosing course, null if not found or exception
6984       */
6985      public function get_course_context($strict = true) {
6986          return $this;
6987      }
6988  
6989      /**
6990       * Returns course context instance.
6991       *
6992       * @static
6993       * @param int $courseid id from {course} table
6994       * @param int $strictness
6995       * @return context_course context instance
6996       */
6997      public static function instance($courseid, $strictness = MUST_EXIST) {
6998          global $DB;
6999  
7000          if ($context = context::cache_get(CONTEXT_COURSE, $courseid)) {
7001              return $context;
7002          }
7003  
7004          if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_COURSE, 'instanceid' => $courseid))) {
7005              if ($course = $DB->get_record('course', array('id' => $courseid), 'id,category', $strictness)) {
7006                  if ($course->category) {
7007                      $parentcontext = context_coursecat::instance($course->category);
7008                      $record = context::insert_context_record(CONTEXT_COURSE, $course->id, $parentcontext->path);
7009                  } else {
7010                      $record = context::insert_context_record(CONTEXT_COURSE, $course->id, '/'.SYSCONTEXTID, 0);
7011                  }
7012              }
7013          }
7014  
7015          if ($record) {
7016              $context = new context_course($record);
7017              context::cache_add($context);
7018              return $context;
7019          }
7020  
7021          return false;
7022      }
7023  
7024      /**
7025       * Create missing context instances at course context level
7026       * @static
7027       */
7028      protected static function create_level_instances() {
7029          global $DB;
7030  
7031          $sql = "SELECT ".CONTEXT_COURSE.", c.id
7032                    FROM {course} c
7033                   WHERE NOT EXISTS (SELECT 'x'
7034                                       FROM {context} cx
7035                                      WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE.")";
7036          $contextdata = $DB->get_recordset_sql($sql);
7037          foreach ($contextdata as $context) {
7038              context::insert_context_record(CONTEXT_COURSE, $context->id, null);
7039          }
7040          $contextdata->close();
7041      }
7042  
7043      /**
7044       * Returns sql necessary for purging of stale context instances.
7045       *
7046       * @static
7047       * @return string cleanup SQL
7048       */
7049      protected static function get_cleanup_sql() {
7050          $sql = "
7051                    SELECT c.*
7052                      FROM {context} c
7053           LEFT OUTER JOIN {course} co ON c.instanceid = co.id
7054                     WHERE co.id IS NULL AND c.contextlevel = ".CONTEXT_COURSE."
7055                 ";
7056  
7057          return $sql;
7058      }
7059  
7060      /**
7061       * Rebuild context paths and depths at course context level.
7062       *
7063       * @static
7064       * @param bool $force
7065       */
7066      protected static function build_paths($force) {
7067          global $DB;
7068  
7069          if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSE." AND (depth = 0 OR path IS NULL)")) {
7070              if ($force) {
7071                  $ctxemptyclause = $emptyclause = '';
7072              } else {
7073                  $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7074                  $emptyclause    = "AND ({context}.path IS NULL OR {context}.depth = 0)";
7075              }
7076  
7077              $base = '/'.SYSCONTEXTID;
7078  
7079              // Standard frontpage
7080              $sql = "UPDATE {context}
7081                         SET depth = 2,
7082                             path = ".$DB->sql_concat("'$base/'", 'id')."
7083                       WHERE contextlevel = ".CONTEXT_COURSE."
7084                             AND EXISTS (SELECT 'x'
7085                                           FROM {course} c
7086                                          WHERE c.id = {context}.instanceid AND c.category = 0)
7087                             $emptyclause";
7088              $DB->execute($sql);
7089  
7090              // standard courses
7091              $sql = "INSERT INTO {context_temp} (id, path, depth, locked)
7092                      SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1, ctx.locked
7093                        FROM {context} ctx
7094                        JOIN {course} c ON (c.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSE." AND c.category <> 0)
7095                        JOIN {context} pctx ON (pctx.instanceid = c.category AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
7096                       WHERE pctx.path IS NOT NULL AND pctx.depth > 0
7097                             $ctxemptyclause";
7098              $trans = $DB->start_delegated_transaction();
7099              $DB->delete_records('context_temp');
7100              $DB->execute($sql);
7101              context::merge_context_temp_table();
7102              $DB->delete_records('context_temp');
7103              $trans->allow_commit();
7104          }
7105      }
7106  }
7107  
7108  
7109  /**
7110   * Course module context class
7111   *
7112   * @package   core_access
7113   * @category  access
7114   * @copyright Petr Skoda {@link http://skodak.org}
7115   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7116   * @since     Moodle 2.2
7117   */
7118  class context_module extends context {
7119      /**
7120       * Please use context_module::instance($cmid) if you need the instance of context.
7121       * Alternatively if you know only the context id use context::instance_by_id($contextid)
7122       *
7123       * @param stdClass $record
7124       */
7125      protected function __construct(stdClass $record) {
7126          parent::__construct($record);
7127          if ($record->contextlevel != CONTEXT_MODULE) {
7128              throw new coding_exception('Invalid $record->contextlevel in context_module constructor.');
7129          }
7130      }
7131  
7132      /**
7133       * Returns human readable context level name.
7134       *
7135       * @static
7136       * @return string the human readable context level name.
7137       */
7138      public static function get_level_name() {
7139          return get_string('activitymodule');
7140      }
7141  
7142      /**
7143       * Returns human readable context identifier.
7144       *
7145       * @param boolean $withprefix whether to prefix the name of the context with the
7146       *      module name, e.g. Forum, Glossary, etc.
7147       * @param boolean $short does not apply to module context
7148       * @param boolean $escape Whether the returned name of the context is to be HTML escaped or not.
7149       * @return string the human readable context name.
7150       */
7151      public function get_context_name($withprefix = true, $short = false, $escape = true) {
7152          global $DB;
7153  
7154          $name = '';
7155          if ($cm = $DB->get_record_sql("SELECT cm.*, md.name AS modname
7156                                           FROM {course_modules} cm
7157                                           JOIN {modules} md ON md.id = cm.module
7158                                          WHERE cm.id = ?", array($this->_instanceid))) {
7159              if ($mod = $DB->get_record($cm->modname, array('id' => $cm->instance))) {
7160                      if ($withprefix){
7161                          $name = get_string('modulename', $cm->modname).': ';
7162                      }
7163                      if (!$escape) {
7164                          $name .= format_string($mod->name, true, array('context' => $this, 'escape' => false));
7165                      } else {
7166                          $name .= format_string($mod->name, true, array('context' => $this));
7167                      }
7168                  }
7169              }
7170          return $name;
7171      }
7172  
7173      /**
7174       * Returns the most relevant URL for this context.
7175       *
7176       * @return moodle_url
7177       */
7178      public function get_url() {
7179          global $DB;
7180  
7181          if ($modname = $DB->get_field_sql("SELECT md.name AS modname
7182                                               FROM {course_modules} cm
7183                                               JOIN {modules} md ON md.id = cm.module
7184                                              WHERE cm.id = ?", array($this->_instanceid))) {
7185              return new moodle_url('/mod/' . $modname . '/view.php', array('id'=>$this->_instanceid));
7186          }
7187  
7188          return new moodle_url('/');
7189      }
7190  
7191      /**
7192       * Returns array of relevant context capability records.
7193       *
7194       * @return array
7195       */
7196      public function get_capabilities() {
7197          global $DB, $CFG;
7198  
7199          $sort = 'ORDER BY contextlevel,component,name';   // To group them sensibly for display
7200  
7201          $cm = $DB->get_record('course_modules', array('id'=>$this->_instanceid));
7202          $module = $DB->get_record('modules', array('id'=>$cm->module));
7203  
7204          $subcaps = array();
7205  
7206          $modulepath = "{$CFG->dirroot}/mod/{$module->name}";
7207          if (file_exists("{$modulepath}/db/subplugins.json")) {
7208              $subplugins = (array) json_decode(file_get_contents("{$modulepath}/db/subplugins.json"))->plugintypes;
7209          } else if (file_exists("{$modulepath}/db/subplugins.php")) {
7210              debugging('Use of subplugins.php has been deprecated. ' .
7211                      'Please update your plugin to provide a subplugins.json file instead.',
7212                      DEBUG_DEVELOPER);
7213              $subplugins = array();  // should be redefined in the file
7214              include("{$modulepath}/db/subplugins.php");
7215          }
7216  
7217          if (!empty($subplugins)) {
7218              foreach (array_keys($subplugins) as $subplugintype) {
7219                  foreach (array_keys(core_component::get_plugin_list($subplugintype)) as $subpluginname) {
7220                      $subcaps = array_merge($subcaps, array_keys(load_capability_def($subplugintype.'_'.$subpluginname)));
7221                  }
7222              }
7223          }
7224  
7225          $modfile = "{$modulepath}/lib.php";
7226          $extracaps = array();
7227          if (file_exists($modfile)) {
7228              include_once($modfile);
7229              $modfunction = $module->name.'_get_extra_capabilities';
7230              if (function_exists($modfunction)) {
7231                  $extracaps = $modfunction();
7232              }
7233          }
7234  
7235          $extracaps = array_merge($subcaps, $extracaps);
7236          $extra = '';
7237          list($extra, $params) = $DB->get_in_or_equal(
7238              $extracaps, SQL_PARAMS_NAMED, 'cap0', true, '');
7239          if (!empty($extra)) {
7240              $extra = "OR name $extra";
7241          }
7242  
7243          // Fetch the list of modules, and remove this one.
7244          $components = \core_component::get_component_list();
7245          $componentnames = $components['mod'];
7246          unset($componentnames["mod_{$module->name}"]);
7247          $componentnames = array_keys($componentnames);
7248  
7249          // Exclude all other modules.
7250          list($notcompsql, $notcompparams) = $DB->get_in_or_equal($componentnames, SQL_PARAMS_NAMED, 'notcomp', false);
7251          $params = array_merge($params, $notcompparams);
7252  
7253  
7254          // Exclude other component submodules.
7255          $i = 0;
7256          $ignorecomponents = [];
7257          foreach ($componentnames as $mod) {
7258              if ($subplugins = \core_component::get_subplugins($mod)) {
7259                  foreach (array_keys($subplugins) as $subplugintype) {
7260                      $paramname = "notlike{$i}";
7261                      $ignorecomponents[] = $DB->sql_like('component', ":{$paramname}", true, true, true);
7262                      $params[$paramname] = "{$subplugintype}_%";
7263                      $i++;
7264                  }
7265              }
7266          }
7267          $notlikesql = "(" . implode(' AND ', $ignorecomponents) . ")";
7268  
7269          $sql = "SELECT *
7270                    FROM {capabilities}
7271                   WHERE (contextlevel = ".CONTEXT_MODULE."
7272                     AND component {$notcompsql}
7273                     AND {$notlikesql})
7274                         $extra";
7275  
7276          return $DB->get_records_sql($sql.' '.$sort, $params);
7277      }
7278  
7279      /**
7280       * Is this context part of any course? If yes return course context.
7281       *
7282       * @param bool $strict true means throw exception if not found, false means return false if not found
7283       * @return context_course context of the enclosing course, null if not found or exception
7284       */
7285      public function get_course_context($strict = true) {
7286          return $this->get_parent_context();
7287      }
7288  
7289      /**
7290       * Returns module context instance.
7291       *
7292       * @static
7293       * @param int $cmid id of the record from {course_modules} table; pass cmid there, NOT id in the instance column
7294       * @param int $strictness
7295       * @return context_module context instance
7296       */
7297      public static function instance($cmid, $strictness = MUST_EXIST) {
7298          global $DB;
7299  
7300          if ($context = context::cache_get(CONTEXT_MODULE, $cmid)) {
7301              return $context;
7302          }
7303  
7304          if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_MODULE, 'instanceid' => $cmid))) {
7305              if ($cm = $DB->get_record('course_modules', array('id' => $cmid), 'id,course', $strictness)) {
7306                  $parentcontext = context_course::instance($cm->course);
7307                  $record = context::insert_context_record(CONTEXT_MODULE, $cm->id, $parentcontext->path);
7308              }
7309          }
7310  
7311          if ($record) {
7312              $context = new context_module($record);
7313              context::cache_add($context);
7314              return $context;
7315          }
7316  
7317          return false;
7318      }
7319  
7320      /**
7321       * Create missing context instances at module context level
7322       * @static
7323       */
7324      protected static function create_level_instances() {
7325          global $DB;
7326  
7327          $sql = "SELECT ".CONTEXT_MODULE.", cm.id
7328                    FROM {course_modules} cm
7329                   WHERE NOT EXISTS (SELECT 'x'
7330                                       FROM {context} cx
7331                                      WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE.")";
7332          $contextdata = $DB->get_recordset_sql($sql);
7333          foreach ($contextdata as $context) {
7334              context::insert_context_record(CONTEXT_MODULE, $context->id, null);
7335          }
7336          $contextdata->close();
7337      }
7338  
7339      /**
7340       * Returns sql necessary for purging of stale context instances.
7341       *
7342       * @static
7343       * @return string cleanup SQL
7344       */
7345      protected static function get_cleanup_sql() {
7346          $sql = "
7347                    SELECT c.*
7348                      FROM {context} c
7349           LEFT OUTER JOIN {course_modules} cm ON c.instanceid = cm.id
7350                     WHERE cm.id IS NULL AND c.contextlevel = ".CONTEXT_MODULE."
7351                 ";
7352  
7353          return $sql;
7354      }
7355  
7356      /**
7357       * Rebuild context paths and depths at module context level.
7358       *
7359       * @static
7360       * @param bool $force
7361       */
7362      protected static function build_paths($force) {
7363          global $DB;
7364  
7365          if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_MODULE." AND (depth = 0 OR path IS NULL)")) {
7366              if ($force) {
7367                  $ctxemptyclause = '';
7368              } else {
7369                  $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7370              }
7371  
7372              $sql = "INSERT INTO {context_temp} (id, path, depth, locked)
7373                      SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1, ctx.locked
7374                        FROM {context} ctx
7375                        JOIN {course_modules} cm ON (cm.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_MODULE.")
7376                        JOIN {context} pctx ON (pctx.instanceid = cm.course AND pctx.contextlevel = ".CONTEXT_COURSE.")
7377                       WHERE pctx.path IS NOT NULL AND pctx.depth > 0
7378                             $ctxemptyclause";
7379              $trans = $DB->start_delegated_transaction();
7380              $DB->delete_records('context_temp');
7381              $DB->execute($sql);
7382              context::merge_context_temp_table();
7383              $DB->delete_records('context_temp');
7384              $trans->allow_commit();
7385          }
7386      }
7387  }
7388  
7389  
7390  /**
7391   * Block context class
7392   *
7393   * @package   core_access
7394   * @category  access
7395   * @copyright Petr Skoda {@link http://skodak.org}
7396   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7397   * @since     Moodle 2.2
7398   */
7399  class context_block extends context {
7400      /**
7401       * Please use context_block::instance($blockinstanceid) if you need the instance of context.
7402       * Alternatively if you know only the context id use context::instance_by_id($contextid)
7403       *
7404       * @param stdClass $record
7405       */
7406      protected function __construct(stdClass $record) {
7407          parent::__construct($record);
7408          if ($record->contextlevel != CONTEXT_BLOCK) {
7409              throw new coding_exception('Invalid $record->contextlevel in context_block constructor');
7410          }
7411      }
7412  
7413      /**
7414       * Returns human readable context level name.
7415       *
7416       * @static
7417       * @return string the human readable context level name.
7418       */
7419      public static function get_level_name() {
7420          return get_string('block');
7421      }
7422  
7423      /**
7424       * Returns human readable context identifier.
7425       *
7426       * @param boolean $withprefix whether to prefix the name of the context with Block
7427       * @param boolean $short does not apply to block context
7428       * @param boolean $escape does not apply to block context
7429       * @return string the human readable context name.
7430       */
7431      public function get_context_name($withprefix = true, $short = false, $escape = true) {
7432          global $DB, $CFG;
7433  
7434          $name = '';
7435          if ($blockinstance = $DB->get_record('block_instances', array('id'=>$this->_instanceid))) {
7436              global $CFG;
7437              require_once("$CFG->dirroot/blocks/moodleblock.class.php");
7438              require_once("$CFG->dirroot/blocks/$blockinstance->blockname/block_$blockinstance->blockname.php");
7439              $blockname = "block_$blockinstance->blockname";
7440              if ($blockobject = new $blockname()) {
7441                  if ($withprefix){
7442                      $name = get_string('block').': ';
7443                  }
7444                  $name .= $blockobject->title;
7445              }
7446          }
7447  
7448          return $name;
7449      }
7450  
7451      /**
7452       * Returns the most relevant URL for this context.
7453       *
7454       * @return moodle_url
7455       */
7456      public function get_url() {
7457          $parentcontexts = $this->get_parent_context();
7458          return $parentcontexts->get_url();
7459      }
7460  
7461      /**
7462       * Returns array of relevant context capability records.
7463       *
7464       * @return array
7465       */
7466      public function get_capabilities() {
7467          global $DB;
7468  
7469          $sort = 'ORDER BY contextlevel,component,name';   // To group them sensibly for display
7470  
7471          $params = array();
7472          $bi = $DB->get_record('block_instances', array('id' => $this->_instanceid));
7473  
7474          $extra = '';
7475          $extracaps = block_method_result($bi->blockname, 'get_extra_capabilities');
7476          if ($extracaps) {
7477              list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
7478              $extra = "OR name $extra";
7479          }
7480  
7481          $sql = "SELECT *
7482                    FROM {capabilities}
7483                   WHERE (contextlevel = ".CONTEXT_BLOCK."
7484                         AND component = :component)
7485                         $extra";
7486          $params['component'] = 'block_' . $bi->blockname;
7487  
7488          return $DB->get_records_sql($sql.' '.$sort, $params);
7489      }
7490  
7491      /**
7492       * Is this context part of any course? If yes return course context.
7493       *
7494       * @param bool $strict true means throw exception if not found, false means return false if not found
7495       * @return context_course context of the enclosing course, null if not found or exception
7496       */
7497      public function get_course_context($strict = true) {
7498          $parentcontext = $this->get_parent_context();
7499          return $parentcontext->get_course_context($strict);
7500      }
7501  
7502      /**
7503       * Returns block context instance.
7504       *
7505       * @static
7506       * @param int $blockinstanceid id from {block_instances} table.
7507       * @param int $strictness
7508       * @return context_block context instance
7509       */
7510      public static function instance($blockinstanceid, $strictness = MUST_EXIST) {
7511          global $DB;
7512  
7513          if ($context = context::cache_get(CONTEXT_BLOCK, $blockinstanceid)) {
7514              return $context;
7515          }
7516  
7517          if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_BLOCK, 'instanceid' => $blockinstanceid))) {
7518              if ($bi = $DB->get_record('block_instances', array('id' => $blockinstanceid), 'id,parentcontextid', $strictness)) {
7519                  $parentcontext = context::instance_by_id($bi->parentcontextid);
7520                  $record = context::insert_context_record(CONTEXT_BLOCK, $bi->id, $parentcontext->path);
7521              }
7522          }
7523  
7524          if ($record) {
7525              $context = new context_block($record);
7526              context::cache_add($context);
7527              return $context;
7528          }
7529  
7530          return false;
7531      }
7532  
7533      /**
7534       * Block do not have child contexts...
7535       * @return array
7536       */
7537      public function get_child_contexts() {
7538          return array();
7539      }
7540  
7541      /**
7542       * Create missing context instances at block context level
7543       * @static
7544       */
7545      protected static function create_level_instances() {
7546          global $DB;
7547  
7548          $sql = "SELECT ".CONTEXT_BLOCK.", bi.id
7549                    FROM {block_instances} bi
7550                   WHERE NOT EXISTS (SELECT 'x'
7551                                       FROM {context} cx
7552                                      WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")";
7553          $contextdata = $DB->get_recordset_sql($sql);
7554          foreach ($contextdata as $context) {
7555              context::insert_context_record(CONTEXT_BLOCK, $context->id, null);
7556          }
7557          $contextdata->close();
7558      }
7559  
7560      /**
7561       * Returns sql necessary for purging of stale context instances.
7562       *
7563       * @static
7564       * @return string cleanup SQL
7565       */
7566      protected static function get_cleanup_sql() {
7567          $sql = "
7568                    SELECT c.*
7569                      FROM {context} c
7570           LEFT OUTER JOIN {block_instances} bi ON c.instanceid = bi.id
7571                     WHERE bi.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK."
7572                 ";
7573  
7574          return $sql;
7575      }
7576  
7577      /**
7578       * Rebuild context paths and depths at block context level.
7579       *
7580       * @static
7581       * @param bool $force
7582       */
7583      protected static function build_paths($force) {
7584          global $DB;
7585  
7586          if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_BLOCK." AND (depth = 0 OR path IS NULL)")) {
7587              if ($force) {
7588                  $ctxemptyclause = '';
7589              } else {
7590                  $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7591              }
7592  
7593              // pctx.path IS NOT NULL prevents fatal problems with broken block instances that point to invalid context parent
7594              $sql = "INSERT INTO {context_temp} (id, path, depth, locked)
7595                      SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1, ctx.locked
7596                        FROM {context} ctx
7597                        JOIN {block_instances} bi ON (bi.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_BLOCK.")
7598                        JOIN {context} pctx ON (pctx.id = bi.parentcontextid)
7599                       WHERE (pctx.path IS NOT NULL AND pctx.depth > 0)
7600                             $ctxemptyclause";
7601              $trans = $DB->start_delegated_transaction();
7602              $DB->delete_records('context_temp');
7603              $DB->execute($sql);
7604              context::merge_context_temp_table();
7605              $DB->delete_records('context_temp');
7606              $trans->allow_commit();
7607          }
7608      }
7609  }
7610  
7611  
7612  // ============== DEPRECATED FUNCTIONS ==========================================
7613  // Old context related functions were deprecated in 2.0, it is recommended
7614  // to use context classes in new code. Old function can be used when
7615  // creating patches that are supposed to be backported to older stable branches.
7616  // These deprecated functions will not be removed in near future,
7617  // before removing devs will be warned with a debugging message first,
7618  // then we will add error message and only after that we can remove the functions
7619  // completely.
7620  
7621  /**
7622   * Runs get_records select on context table and returns the result
7623   * Does get_records_select on the context table, and returns the results ordered
7624   * by contextlevel, and then the natural sort order within each level.
7625   * for the purpose of $select, you need to know that the context table has been
7626   * aliased to ctx, so for example, you can call get_sorted_contexts('ctx.depth = 3');
7627   *
7628   * @param string $select the contents of the WHERE clause. Remember to do ctx.fieldname.
7629   * @param array $params any parameters required by $select.
7630   * @return array the requested context records.
7631   */
7632  function get_sorted_contexts($select, $params = array()) {
7633  
7634      //TODO: we should probably rewrite all the code that is using this thing, the trouble is we MUST NOT modify the context instances...
7635  
7636      global $DB;
7637      if ($select) {
7638          $select = 'WHERE ' . $select;
7639      }
7640      return $DB->get_records_sql("
7641              SELECT ctx.*
7642                FROM {context} ctx
7643                LEFT JOIN {user} u ON ctx.contextlevel = " . CONTEXT_USER . " AND u.id = ctx.instanceid
7644                LEFT JOIN {course_categories} cat ON ctx.contextlevel = " . CONTEXT_COURSECAT . " AND cat.id = ctx.instanceid
7645                LEFT JOIN {course} c ON ctx.contextlevel = " . CONTEXT_COURSE . " AND c.id = ctx.instanceid
7646                LEFT JOIN {course_modules} cm ON ctx.contextlevel = " . CONTEXT_MODULE . " AND cm.id = ctx.instanceid
7647                LEFT JOIN {block_instances} bi ON ctx.contextlevel = " . CONTEXT_BLOCK . " AND bi.id = ctx.instanceid
7648             $select
7649            ORDER BY ctx.contextlevel, bi.defaultregion, COALESCE(cat.sortorder, c.sortorder, cm.section, bi.defaultweight), u.lastname, u.firstname, cm.id
7650              ", $params);
7651  }
7652  
7653  /**
7654   * Given context and array of users, returns array of users whose enrolment status is suspended,
7655   * or enrolment has expired or has not started. Also removes those users from the given array
7656   *
7657   * @param context $context context in which suspended users should be extracted.
7658   * @param array $users list of users.
7659   * @param array $ignoreusers array of user ids to ignore, e.g. guest
7660   * @return array list of suspended users.
7661   */
7662  function extract_suspended_users($context, &$users, $ignoreusers=array()) {
7663      global $DB;
7664  
7665      // Get active enrolled users.
7666      list($sql, $params) = get_enrolled_sql($context, null, null, true);
7667      $activeusers = $DB->get_records_sql($sql, $params);
7668  
7669      // Move suspended users to a separate array & remove from the initial one.
7670      $susers = array();
7671      if (sizeof($activeusers)) {
7672          foreach ($users as $userid => $user) {
7673              if (!array_key_exists($userid, $activeusers) && !in_array($userid, $ignoreusers)) {
7674                  $susers[$userid] = $user;
7675                  unset($users[$userid]);
7676              }
7677          }
7678      }
7679      return $susers;
7680  }
7681  
7682  /**
7683   * Given context and array of users, returns array of user ids whose enrolment status is suspended,
7684   * or enrolment has expired or not started.
7685   *
7686   * @param context $context context in which user enrolment is checked.
7687   * @param bool $usecache Enable or disable (default) the request cache
7688   * @return array list of suspended user id's.
7689   */
7690  function get_suspended_userids(context $context, $usecache = false) {
7691      global $DB;
7692  
7693      if ($usecache) {
7694          $cache = cache::make('core', 'suspended_userids');
7695          $susers = $cache->get($context->id);
7696          if ($susers !== false) {
7697              return $susers;
7698          }
7699      }
7700  
7701      $coursecontext = $context->get_course_context();
7702      $susers = array();
7703  
7704      // Front page users are always enrolled, so suspended list is empty.
7705      if ($coursecontext->instanceid != SITEID) {
7706          list($sql, $params) = get_enrolled_sql($context, null, null, false, true);
7707          $susers = $DB->get_fieldset_sql($sql, $params);
7708          $susers = array_combine($susers, $susers);
7709      }
7710  
7711      // Cache results for the remainder of this request.
7712      if ($usecache) {
7713          $cache->set($context->id, $susers);
7714      }
7715  
7716      return $susers;
7717  }
7718  
7719  /**
7720   * Gets sql for finding users with capability in the given context
7721   *
7722   * @param context $context
7723   * @param string|array $capability Capability name or array of names.
7724   *      If an array is provided then this is the equivalent of a logical 'OR',
7725   *      i.e. the user needs to have one of these capabilities.
7726   * @return array($sql, $params)
7727   */
7728  function get_with_capability_sql(context $context, $capability) {
7729      static $i = 0;
7730      $i++;
7731      $prefix = 'cu' . $i . '_';
7732  
7733      $capjoin = get_with_capability_join($context, $capability, $prefix . 'u.id');
7734  
7735      $sql = "SELECT DISTINCT {$prefix}u.id
7736                FROM {user} {$prefix}u
7737              $capjoin->joins
7738               WHERE {$prefix}u.deleted = 0 AND $capjoin->wheres";
7739  
7740      return array($sql, $capjoin->params);
7741  }