PageRenderTime 52ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/accesslib.php

https://github.com/mylescarrick/moodle
PHP | 6291 lines | 3637 code | 755 blank | 1899 comment | 749 complexity | 8ce3d4a97f29057435ac570bd95d5440 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1, BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  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. * This file contains functions for managing user access
  18. *
  19. * <b>Public API vs internals</b>
  20. *
  21. * General users probably only care about
  22. *
  23. * Context handling
  24. * - get_context_instance()
  25. * - get_context_instance_by_id()
  26. * - get_parent_contexts()
  27. * - get_child_contexts()
  28. *
  29. * Whether the user can do something...
  30. * - has_capability()
  31. * - has_any_capability()
  32. * - has_all_capabilities()
  33. * - require_capability()
  34. * - require_login() (from moodlelib)
  35. *
  36. * What courses has this user access to?
  37. * - get_user_courses_bycap()
  38. *
  39. * What users can do X in this context?
  40. * - get_users_by_capability()
  41. *
  42. * Enrol/unenrol
  43. * - enrol_into_course()
  44. * - role_assign()/role_unassign()
  45. *
  46. *
  47. * Advanced use
  48. * - load_all_capabilities()
  49. * - reload_all_capabilities()
  50. * - has_capability_in_accessdata()
  51. * - is_siteadmin()
  52. * - get_user_access_sitewide()
  53. * - load_subcontext()
  54. * - get_role_access_bycontext()
  55. *
  56. * <b>Name conventions</b>
  57. *
  58. * "ctx" means context
  59. *
  60. * <b>accessdata</b>
  61. *
  62. * Access control data is held in the "accessdata" array
  63. * which - for the logged-in user, will be in $USER->access
  64. *
  65. * For other users can be generated and passed around (but may also be cached
  66. * against userid in $ACCESSLIB_PRIVATE->accessdatabyuser.
  67. *
  68. * $accessdata is a multidimensional array, holding
  69. * role assignments (RAs), role-capabilities-perm sets
  70. * (role defs) and a list of courses we have loaded
  71. * data for.
  72. *
  73. * Things are keyed on "contextpaths" (the path field of
  74. * the context table) for fast walking up/down the tree.
  75. * <code>
  76. * $accessdata[ra][$contextpath]= array($roleid)
  77. * [$contextpath]= array($roleid)
  78. * [$contextpath]= array($roleid)
  79. * </code>
  80. *
  81. * Role definitions are stored like this
  82. * (no cap merge is done - so it's compact)
  83. *
  84. * <code>
  85. * $accessdata[rdef][$contextpath:$roleid][mod/forum:viewpost] = 1
  86. * [mod/forum:editallpost] = -1
  87. * [mod/forum:startdiscussion] = -1000
  88. * </code>
  89. *
  90. * See how has_capability_in_accessdata() walks up/down the tree.
  91. *
  92. * Normally - specially for the logged-in user, we only load
  93. * rdef and ra down to the course level, but not below. This
  94. * keeps accessdata small and compact. Below-the-course ra/rdef
  95. * are loaded as needed. We keep track of which courses we
  96. * have loaded ra/rdef in
  97. * <code>
  98. * $accessdata[loaded] = array($contextpath, $contextpath)
  99. * </code>
  100. *
  101. * <b>Stale accessdata</b>
  102. *
  103. * For the logged-in user, accessdata is long-lived.
  104. *
  105. * On each pageload we load $ACCESSLIB_PRIVATE->dirtycontexts which lists
  106. * context paths affected by changes. Any check at-or-below
  107. * a dirty context will trigger a transparent reload of accessdata.
  108. *
  109. * Changes at the system level will force the reload for everyone.
  110. *
  111. * <b>Default role caps</b>
  112. * The default role assignment is not in the DB, so we
  113. * add it manually to accessdata.
  114. *
  115. * This means that functions that work directly off the
  116. * DB need to ensure that the default role caps
  117. * are dealt with appropriately.
  118. *
  119. * @package core
  120. * @subpackage role
  121. * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
  122. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  123. */
  124. defined('MOODLE_INTERNAL') || die();
  125. /** permission definitions */
  126. define('CAP_INHERIT', 0);
  127. /** permission definitions */
  128. define('CAP_ALLOW', 1);
  129. /** permission definitions */
  130. define('CAP_PREVENT', -1);
  131. /** permission definitions */
  132. define('CAP_PROHIBIT', -1000);
  133. /** context definitions */
  134. define('CONTEXT_SYSTEM', 10);
  135. /** context definitions */
  136. define('CONTEXT_USER', 30);
  137. /** context definitions */
  138. define('CONTEXT_COURSECAT', 40);
  139. /** context definitions */
  140. define('CONTEXT_COURSE', 50);
  141. /** context definitions */
  142. define('CONTEXT_MODULE', 70);
  143. /** context definitions */
  144. define('CONTEXT_BLOCK', 80);
  145. /** capability risks - see {@link http://docs.moodle.org/en/Development:Hardening_new_Roles_system} */
  146. define('RISK_MANAGETRUST', 0x0001);
  147. /** capability risks - see {@link http://docs.moodle.org/en/Development:Hardening_new_Roles_system} */
  148. define('RISK_CONFIG', 0x0002);
  149. /** capability risks - see {@link http://docs.moodle.org/en/Development:Hardening_new_Roles_system} */
  150. define('RISK_XSS', 0x0004);
  151. /** capability risks - see {@link http://docs.moodle.org/en/Development:Hardening_new_Roles_system} */
  152. define('RISK_PERSONAL', 0x0008);
  153. /** capability risks - see {@link http://docs.moodle.org/en/Development:Hardening_new_Roles_system} */
  154. define('RISK_SPAM', 0x0010);
  155. /** capability risks - see {@link http://docs.moodle.org/en/Development:Hardening_new_Roles_system} */
  156. define('RISK_DATALOSS', 0x0020);
  157. /** rolename displays - the name as defined in the role definition */
  158. define('ROLENAME_ORIGINAL', 0);
  159. /** rolename displays - the name as defined by a role alias */
  160. define('ROLENAME_ALIAS', 1);
  161. /** rolename displays - Both, like this: Role alias (Original)*/
  162. define('ROLENAME_BOTH', 2);
  163. /** rolename displays - the name as defined in the role definition and the shortname in brackets*/
  164. define('ROLENAME_ORIGINALANDSHORT', 3);
  165. /** rolename displays - the name as defined by a role alias, in raw form suitable for editing*/
  166. define('ROLENAME_ALIAS_RAW', 4);
  167. /** rolename displays - the name is simply short role name*/
  168. define('ROLENAME_SHORT', 5);
  169. /**
  170. * Internal class provides a cache of context information. The cache is
  171. * restricted in size.
  172. *
  173. * This cache should NOT be used outside accesslib.php!
  174. *
  175. * @private
  176. * @author Sam Marshall
  177. */
  178. class context_cache {
  179. private $contextsbyid;
  180. private $contexts;
  181. private $count;
  182. /**
  183. * @var int Maximum number of contexts that will be cached.
  184. */
  185. const MAX_SIZE = 2500;
  186. /**
  187. * @var int Once contexts reach maximum number, this many will be removed from cache.
  188. */
  189. const REDUCE_SIZE = 1000;
  190. /**
  191. * Initialises (empty)
  192. */
  193. public function __construct() {
  194. $this->reset();
  195. }
  196. /**
  197. * Resets the cache to remove all data.
  198. */
  199. public function reset() {
  200. $this->contexts = array();
  201. $this->contextsbyid = array();
  202. $this->count = 0;
  203. }
  204. /**
  205. * Adds a context to the cache. If the cache is full, discards a batch of
  206. * older entries.
  207. * @param stdClass $context New context to add
  208. */
  209. public function add(stdClass $context) {
  210. if ($this->count >= self::MAX_SIZE) {
  211. for ($i=0; $i<self::REDUCE_SIZE; $i++) {
  212. if ($first = reset($this->contextsbyid)) {
  213. unset($this->contextsbyid[$first->id]);
  214. unset($this->contexts[$first->contextlevel][$first->instanceid]);
  215. }
  216. }
  217. $this->count -= self::REDUCE_SIZE;
  218. if ($this->count < 0) {
  219. // most probably caused by the drift, the reset() above
  220. // might have returned false because there might not be any more elements
  221. $this->count = 0;
  222. }
  223. }
  224. $this->contexts[$context->contextlevel][$context->instanceid] = $context;
  225. $this->contextsbyid[$context->id] = $context;
  226. // Note the count may get out of synch slightly if you cache a context
  227. // that is already cached, but it doesn't really matter much and I
  228. // didn't think it was worth the performance hit.
  229. $this->count++;
  230. }
  231. /**
  232. * Removes a context from the cache.
  233. * @param stdClass $context Context object to remove (must include fields
  234. * ->id, ->contextlevel, ->instanceid at least)
  235. */
  236. public function remove(stdClass $context) {
  237. unset($this->contexts[$context->contextlevel][$context->instanceid]);
  238. unset($this->contextsbyid[$context->id]);
  239. // Again the count may get a bit out of synch if you remove things
  240. // that don't exist
  241. $this->count--;
  242. if ($this->count < 0) {
  243. $this->count = 0;
  244. }
  245. }
  246. /**
  247. * Gets a context from the cache.
  248. * @param int $contextlevel Context level
  249. * @param int $instance Instance ID
  250. * @return stdClass|bool Context or false if not in cache
  251. */
  252. public function get($contextlevel, $instance) {
  253. if (isset($this->contexts[$contextlevel][$instance])) {
  254. return $this->contexts[$contextlevel][$instance];
  255. }
  256. return false;
  257. }
  258. /**
  259. * Gets a context from the cache based on its id.
  260. * @param int $id Context ID
  261. * @return stdClass|bool Context or false if not in cache
  262. */
  263. public function get_by_id($id) {
  264. if (isset($this->contextsbyid[$id])) {
  265. return $this->contextsbyid[$id];
  266. }
  267. return false;
  268. }
  269. /**
  270. * @return int Count of contexts in cache (approximately)
  271. */
  272. public function get_approx_count() {
  273. return $this->count;
  274. }
  275. }
  276. /**
  277. * Although this looks like a global variable, it isn't really.
  278. *
  279. * It is just a private implementation detail to accesslib that MUST NOT be used elsewhere.
  280. * It is used to cache various bits of data between function calls for performance reasons.
  281. * Sadly, a PHP global variable is the only way to implement this, without rewriting everything
  282. * as methods of a class, instead of functions.
  283. *
  284. * @global stdClass $ACCESSLIB_PRIVATE
  285. * @name $ACCESSLIB_PRIVATE
  286. */
  287. global $ACCESSLIB_PRIVATE;
  288. $ACCESSLIB_PRIVATE = new stdClass();
  289. $ACCESSLIB_PRIVATE->contexcache = new context_cache();
  290. $ACCESSLIB_PRIVATE->systemcontext = null; // Used in get_system_context
  291. $ACCESSLIB_PRIVATE->dirtycontexts = null; // Dirty contexts cache
  292. $ACCESSLIB_PRIVATE->accessdatabyuser = array(); // Holds the $accessdata structure for users other than $USER
  293. $ACCESSLIB_PRIVATE->roledefinitions = array(); // role definitions cache - helps a lot with mem usage in cron
  294. $ACCESSLIB_PRIVATE->croncache = array(); // Used in get_role_access
  295. $ACCESSLIB_PRIVATE->preloadedcourses = array(); // Used in preload_course_contexts.
  296. $ACCESSLIB_PRIVATE->capabilities = null; // detailed information about the capabilities
  297. /**
  298. * Clears accesslib's private caches. ONLY BE USED BY UNIT TESTS
  299. *
  300. * This method should ONLY BE USED BY UNIT TESTS. It clears all of
  301. * accesslib's private caches. You need to do this before setting up test data,
  302. * and also at the end of the tests.
  303. */
  304. function accesslib_clear_all_caches_for_unit_testing() {
  305. global $UNITTEST, $USER, $ACCESSLIB_PRIVATE;
  306. if (empty($UNITTEST->running)) {
  307. throw new coding_exception('You must not call clear_all_caches outside of unit tests.');
  308. }
  309. $ACCESSLIB_PRIVATE->contexcache = new context_cache();
  310. $ACCESSLIB_PRIVATE->systemcontext = null;
  311. $ACCESSLIB_PRIVATE->dirtycontexts = null;
  312. $ACCESSLIB_PRIVATE->accessdatabyuser = array();
  313. $ACCESSLIB_PRIVATE->roledefinitions = array();
  314. $ACCESSLIB_PRIVATE->croncache = array();
  315. $ACCESSLIB_PRIVATE->preloadedcourses = array();
  316. $ACCESSLIB_PRIVATE->capabilities = null;
  317. unset($USER->access);
  318. }
  319. /**
  320. * This is really slow!!! do not use above course context level
  321. *
  322. * @param int $roleid
  323. * @param object $context
  324. * @return array
  325. */
  326. function get_role_context_caps($roleid, $context) {
  327. global $DB;
  328. //this is really slow!!!! - do not use above course context level!
  329. $result = array();
  330. $result[$context->id] = array();
  331. // first emulate the parent context capabilities merging into context
  332. $searchcontexts = array_reverse(get_parent_contexts($context));
  333. array_push($searchcontexts, $context->id);
  334. foreach ($searchcontexts as $cid) {
  335. if ($capabilities = $DB->get_records('role_capabilities', array('roleid'=>$roleid, 'contextid'=>$cid))) {
  336. foreach ($capabilities as $cap) {
  337. if (!array_key_exists($cap->capability, $result[$context->id])) {
  338. $result[$context->id][$cap->capability] = 0;
  339. }
  340. $result[$context->id][$cap->capability] += $cap->permission;
  341. }
  342. }
  343. }
  344. // now go through the contexts bellow given context
  345. $searchcontexts = array_keys(get_child_contexts($context));
  346. foreach ($searchcontexts as $cid) {
  347. if ($capabilities = $DB->get_records('role_capabilities', array('roleid'=>$roleid, 'contextid'=>$cid))) {
  348. foreach ($capabilities as $cap) {
  349. if (!array_key_exists($cap->contextid, $result)) {
  350. $result[$cap->contextid] = array();
  351. }
  352. $result[$cap->contextid][$cap->capability] = $cap->permission;
  353. }
  354. }
  355. }
  356. return $result;
  357. }
  358. /**
  359. * Gets the accessdata for role "sitewide" (system down to course)
  360. *
  361. * @param int $roleid
  362. * @param array $accessdata defaults to null
  363. * @return array
  364. */
  365. function get_role_access($roleid, $accessdata = null) {
  366. global $CFG, $DB;
  367. /* Get it in 1 cheap DB query...
  368. * - relevant role caps at the root and down
  369. * to the course level - but not below
  370. */
  371. if (is_null($accessdata)) {
  372. $accessdata = array(); // named list
  373. $accessdata['ra'] = array();
  374. $accessdata['rdef'] = array();
  375. $accessdata['loaded'] = array();
  376. }
  377. //
  378. // Overrides for the role IN ANY CONTEXTS
  379. // down to COURSE - not below -
  380. //
  381. $sql = "SELECT ctx.path,
  382. rc.capability, rc.permission
  383. FROM {context} ctx
  384. JOIN {role_capabilities} rc
  385. ON rc.contextid=ctx.id
  386. WHERE rc.roleid = ?
  387. AND ctx.contextlevel <= ".CONTEXT_COURSE."
  388. ORDER BY ctx.depth, ctx.path";
  389. $params = array($roleid);
  390. // we need extra caching in CLI scripts and cron
  391. if (CLI_SCRIPT) {
  392. global $ACCESSLIB_PRIVATE;
  393. if (!isset($ACCESSLIB_PRIVATE->croncache[$roleid])) {
  394. $ACCESSLIB_PRIVATE->croncache[$roleid] = array();
  395. $rs = $DB->get_recordset_sql($sql, $params);
  396. foreach ($rs as $rd) {
  397. $ACCESSLIB_PRIVATE->croncache[$roleid][] = $rd;
  398. }
  399. $rs->close();
  400. }
  401. foreach ($ACCESSLIB_PRIVATE->croncache[$roleid] as $rd) {
  402. $k = "{$rd->path}:{$roleid}";
  403. $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
  404. }
  405. } else {
  406. $rs = $DB->get_recordset_sql($sql, $params);
  407. if ($rs->valid()) {
  408. foreach ($rs as $rd) {
  409. $k = "{$rd->path}:{$roleid}";
  410. $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
  411. }
  412. unset($rd);
  413. }
  414. $rs->close();
  415. }
  416. return $accessdata;
  417. }
  418. /**
  419. * Gets the accessdata for role "sitewide" (system down to course)
  420. *
  421. * @param int $roleid
  422. * @param array $accessdata defaults to null
  423. * @return array
  424. */
  425. function get_default_frontpage_role_access($roleid, $accessdata = null) {
  426. global $CFG, $DB;
  427. $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
  428. $base = '/'. SYSCONTEXTID .'/'. $frontpagecontext->id;
  429. //
  430. // Overrides for the role in any contexts related to the course
  431. //
  432. $sql = "SELECT ctx.path,
  433. rc.capability, rc.permission
  434. FROM {context} ctx
  435. JOIN {role_capabilities} rc
  436. ON rc.contextid=ctx.id
  437. WHERE rc.roleid = ?
  438. AND (ctx.id = ".SYSCONTEXTID." OR ctx.path LIKE ?)
  439. AND ctx.contextlevel <= ".CONTEXT_COURSE."
  440. ORDER BY ctx.depth, ctx.path";
  441. $params = array($roleid, "$base/%");
  442. $rs = $DB->get_recordset_sql($sql, $params);
  443. if ($rs->valid()) {
  444. foreach ($rs as $rd) {
  445. $k = "{$rd->path}:{$roleid}";
  446. $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
  447. }
  448. unset($rd);
  449. }
  450. $rs->close();
  451. return $accessdata;
  452. }
  453. /**
  454. * Get the default guest role
  455. *
  456. * @return stdClass role
  457. */
  458. function get_guest_role() {
  459. global $CFG, $DB;
  460. if (empty($CFG->guestroleid)) {
  461. if ($roles = $DB->get_records('role', array('archetype'=>'guest'))) {
  462. $guestrole = array_shift($roles); // Pick the first one
  463. set_config('guestroleid', $guestrole->id);
  464. return $guestrole;
  465. } else {
  466. debugging('Can not find any guest role!');
  467. return false;
  468. }
  469. } else {
  470. if ($guestrole = $DB->get_record('role', array('id'=>$CFG->guestroleid))) {
  471. return $guestrole;
  472. } else {
  473. //somebody is messing with guest roles, remove incorrect setting and try to find a new one
  474. set_config('guestroleid', '');
  475. return get_guest_role();
  476. }
  477. }
  478. }
  479. /**
  480. * Check whether a user has a particular capability in a given context.
  481. *
  482. * For example::
  483. * $context = get_context_instance(CONTEXT_MODULE, $cm->id);
  484. * has_capability('mod/forum:replypost',$context)
  485. *
  486. * By default checks the capabilities of the current user, but you can pass a
  487. * different userid. By default will return true for admin users, but you can override that with the fourth argument.
  488. *
  489. * Guest and not-logged-in users can never get any dangerous capability - that is any write capability
  490. * or capabilities with XSS, config or data loss risks.
  491. *
  492. * @param string $capability the name of the capability to check. For example mod/forum:view
  493. * @param object $context the context to check the capability in. You normally get this with {@link get_context_instance}.
  494. * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
  495. * @param boolean $doanything If false, ignores effect of admin role assignment
  496. * @return boolean true if the user has this capability. Otherwise false.
  497. */
  498. function has_capability($capability, $context, $user = null, $doanything = true) {
  499. global $USER, $CFG, $DB, $SCRIPT, $ACCESSLIB_PRIVATE;
  500. if (during_initial_install()) {
  501. if ($SCRIPT === "/$CFG->admin/index.php" or $SCRIPT === "/$CFG->admin/cliupgrade.php") {
  502. // we are in an installer - roles can not work yet
  503. return true;
  504. } else {
  505. return false;
  506. }
  507. }
  508. if (strpos($capability, 'moodle/legacy:') === 0) {
  509. throw new coding_exception('Legacy capabilities can not be used any more!');
  510. }
  511. // the original $CONTEXT here was hiding serious errors
  512. // for security reasons do not reuse previous context
  513. if (empty($context)) {
  514. debugging('Incorrect context specified');
  515. return false;
  516. }
  517. if (!is_bool($doanything)) {
  518. throw new coding_exception('Capability parameter "doanything" is wierd ("'.$doanything.'"). This has to be fixed in code.');
  519. }
  520. // make sure there is a real user specified
  521. if ($user === null) {
  522. $userid = !empty($USER->id) ? $USER->id : 0;
  523. } else {
  524. $userid = !empty($user->id) ? $user->id : $user;
  525. }
  526. // capability must exist
  527. if (!$capinfo = get_capability_info($capability)) {
  528. debugging('Capability "'.$capability.'" was not found! This should be fixed in code.');
  529. return false;
  530. }
  531. // make sure the guest account and not-logged-in users never get any risky caps no matter what the actual settings are.
  532. if (($capinfo->captype === 'write') or ((int)$capinfo->riskbitmask & (RISK_XSS | RISK_CONFIG | RISK_DATALOSS))) {
  533. if (isguestuser($userid) or $userid == 0) {
  534. return false;
  535. }
  536. }
  537. if (is_null($context->path) or $context->depth == 0) {
  538. //this should not happen
  539. $contexts = array(SYSCONTEXTID, $context->id);
  540. $context->path = '/'.SYSCONTEXTID.'/'.$context->id;
  541. debugging('Context id '.$context->id.' does not have valid path, please use build_context_path()', DEBUG_DEVELOPER);
  542. } else {
  543. $contexts = explode('/', $context->path);
  544. array_shift($contexts);
  545. }
  546. if (CLI_SCRIPT && !isset($USER->access)) {
  547. // In cron, some modules setup a 'fake' $USER,
  548. // ensure we load the appropriate accessdata.
  549. if (isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
  550. $ACCESSLIB_PRIVATE->dirtycontexts = null; //load fresh dirty contexts
  551. } else {
  552. load_user_accessdata($userid);
  553. $ACCESSLIB_PRIVATE->dirtycontexts = array();
  554. }
  555. $USER->access = $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
  556. } else if (isset($USER->id) && ($USER->id == $userid) && !isset($USER->access)) {
  557. // caps not loaded yet - better to load them to keep BC with 1.8
  558. // not-logged-in user or $USER object set up manually first time here
  559. load_all_capabilities();
  560. $ACCESSLIB_PRIVATE->accessdatabyuser = array(); // reset the cache for other users too, the dirty contexts are empty now
  561. $ACCESSLIB_PRIVATE->roledefinitions = array();
  562. }
  563. // Load dirty contexts list if needed
  564. if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
  565. if (isset($USER->access['time'])) {
  566. $ACCESSLIB_PRIVATE->dirtycontexts = get_dirty_contexts($USER->access['time']);
  567. }
  568. else {
  569. $ACCESSLIB_PRIVATE->dirtycontexts = array();
  570. }
  571. }
  572. // Careful check for staleness...
  573. if (count($ACCESSLIB_PRIVATE->dirtycontexts) !== 0 and is_contextpath_dirty($contexts, $ACCESSLIB_PRIVATE->dirtycontexts)) {
  574. // reload all capabilities - preserving loginas, roleswitches, etc
  575. // and then cleanup any marks of dirtyness... at least from our short
  576. // term memory! :-)
  577. $ACCESSLIB_PRIVATE->accessdatabyuser = array();
  578. $ACCESSLIB_PRIVATE->roledefinitions = array();
  579. if (CLI_SCRIPT) {
  580. load_user_accessdata($userid);
  581. $USER->access = $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
  582. $ACCESSLIB_PRIVATE->dirtycontexts = array();
  583. } else {
  584. reload_all_capabilities();
  585. }
  586. }
  587. // Find out if user is admin - it is not possible to override the doanything in any way
  588. // and it is not possible to switch to admin role either.
  589. if ($doanything) {
  590. if (is_siteadmin($userid)) {
  591. if ($userid != $USER->id) {
  592. return true;
  593. }
  594. // make sure switchrole is not used in this context
  595. if (empty($USER->access['rsw'])) {
  596. return true;
  597. }
  598. $parts = explode('/', trim($context->path, '/'));
  599. $path = '';
  600. $switched = false;
  601. foreach ($parts as $part) {
  602. $path .= '/' . $part;
  603. if (!empty($USER->access['rsw'][$path])) {
  604. $switched = true;
  605. break;
  606. }
  607. }
  608. if (!$switched) {
  609. return true;
  610. }
  611. //ok, admin switched role in this context, let's use normal access control rules
  612. }
  613. }
  614. // divulge how many times we are called
  615. //// error_log("has_capability: id:{$context->id} path:{$context->path} userid:$userid cap:$capability");
  616. if (isset($USER->id) && ($USER->id == $userid)) { // we must accept strings and integers in $userid
  617. //
  618. // For the logged in user, we have $USER->access
  619. // which will have all RAs and caps preloaded for
  620. // course and above contexts.
  621. //
  622. // Contexts below courses && contexts that do not
  623. // hang from courses are loaded into $USER->access
  624. // on demand, and listed in $USER->access[loaded]
  625. //
  626. if ($context->contextlevel <= CONTEXT_COURSE) {
  627. // Course and above are always preloaded
  628. return has_capability_in_accessdata($capability, $context, $USER->access);
  629. }
  630. // Load accessdata for below-the-course contexts
  631. if (!path_inaccessdata($context->path,$USER->access)) {
  632. // error_log("loading access for context {$context->path} for $capability at {$context->contextlevel} {$context->id}");
  633. // $bt = debug_backtrace();
  634. // error_log("bt {$bt[0]['file']} {$bt[0]['line']}");
  635. load_subcontext($USER->id, $context, $USER->access);
  636. }
  637. return has_capability_in_accessdata($capability, $context, $USER->access);
  638. }
  639. if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
  640. load_user_accessdata($userid);
  641. }
  642. if ($context->contextlevel <= CONTEXT_COURSE) {
  643. // Course and above are always preloaded
  644. return has_capability_in_accessdata($capability, $context, $ACCESSLIB_PRIVATE->accessdatabyuser[$userid]);
  645. }
  646. // Load accessdata for below-the-course contexts as needed
  647. if (!path_inaccessdata($context->path, $ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
  648. // error_log("loading access for context {$context->path} for $capability at {$context->contextlevel} {$context->id}");
  649. // $bt = debug_backtrace();
  650. // error_log("bt {$bt[0]['file']} {$bt[0]['line']}");
  651. load_subcontext($userid, $context, $ACCESSLIB_PRIVATE->accessdatabyuser[$userid]);
  652. }
  653. return has_capability_in_accessdata($capability, $context, $ACCESSLIB_PRIVATE->accessdatabyuser[$userid]);
  654. }
  655. /**
  656. * Check if the user has any one of several capabilities from a list.
  657. *
  658. * This is just a utility method that calls has_capability in a loop. Try to put
  659. * the capabilities that most users are likely to have first in the list for best
  660. * performance.
  661. *
  662. * There are probably tricks that could be done to improve the performance here, for example,
  663. * check the capabilities that are already cached first.
  664. *
  665. * @see has_capability()
  666. * @param array $capabilities an array of capability names.
  667. * @param object $context the context to check the capability in. You normally get this with {@link get_context_instance}.
  668. * @param integer $userid A user id. By default (null) checks the permissions of the current user.
  669. * @param boolean $doanything If false, ignore effect of admin role assignment
  670. * @return boolean true if the user has any of these capabilities. Otherwise false.
  671. */
  672. function has_any_capability($capabilities, $context, $userid = null, $doanything = true) {
  673. if (!is_array($capabilities)) {
  674. debugging('Incorrect $capabilities parameter in has_any_capabilities() call - must be an array');
  675. return false;
  676. }
  677. foreach ($capabilities as $capability) {
  678. if (has_capability($capability, $context, $userid, $doanything)) {
  679. return true;
  680. }
  681. }
  682. return false;
  683. }
  684. /**
  685. * Check if the user has all the capabilities in a list.
  686. *
  687. * This is just a utility method that calls has_capability in a loop. Try to put
  688. * the capabilities that fewest users are likely to have first in the list for best
  689. * performance.
  690. *
  691. * There are probably tricks that could be done to improve the performance here, for example,
  692. * check the capabilities that are already cached first.
  693. *
  694. * @see has_capability()
  695. * @param array $capabilities an array of capability names.
  696. * @param object $context the context to check the capability in. You normally get this with {@link get_context_instance}.
  697. * @param integer $userid A user id. By default (null) checks the permissions of the current user.
  698. * @param boolean $doanything If false, ignore effect of admin role assignment
  699. * @return boolean true if the user has all of these capabilities. Otherwise false.
  700. */
  701. function has_all_capabilities($capabilities, $context, $userid = null, $doanything = true) {
  702. if (!is_array($capabilities)) {
  703. debugging('Incorrect $capabilities parameter in has_all_capabilities() call - must be an array');
  704. return false;
  705. }
  706. foreach ($capabilities as $capability) {
  707. if (!has_capability($capability, $context, $userid, $doanything)) {
  708. return false;
  709. }
  710. }
  711. return true;
  712. }
  713. /**
  714. * Check if the user is an admin at the site level.
  715. *
  716. * Please note that use of proper capabilities is always encouraged,
  717. * this function is supposed to be used from core or for temporary hacks.
  718. *
  719. * @param int|object $user_or_id user id or user object
  720. * @returns bool true if user is one of the administrators, false otherwise
  721. */
  722. function is_siteadmin($user_or_id = null) {
  723. global $CFG, $USER;
  724. if ($user_or_id === null) {
  725. $user_or_id = $USER;
  726. }
  727. if (empty($user_or_id)) {
  728. return false;
  729. }
  730. if (!empty($user_or_id->id)) {
  731. // we support
  732. $userid = $user_or_id->id;
  733. } else {
  734. $userid = $user_or_id;
  735. }
  736. $siteadmins = explode(',', $CFG->siteadmins);
  737. return in_array($userid, $siteadmins);
  738. }
  739. /**
  740. * Returns true if user has at least one role assign
  741. * of 'coursecontact' role (is potentially listed in some course descriptions).
  742. *
  743. * @param $userid
  744. * @return stdClass
  745. */
  746. function has_coursecontact_role($userid) {
  747. global $DB, $CFG;
  748. if (empty($CFG->coursecontact)) {
  749. return false;
  750. }
  751. $sql = "SELECT 1
  752. FROM {role_assignments}
  753. WHERE userid = :userid AND roleid IN ($CFG->coursecontact)";
  754. return $DB->record_exists_sql($sql, array('userid'=>$userid));
  755. }
  756. /**
  757. * @param string $path
  758. * @return string
  759. */
  760. function get_course_from_path($path) {
  761. // assume that nothing is more than 1 course deep
  762. if (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
  763. return $matches[1];
  764. }
  765. return false;
  766. }
  767. /**
  768. * @param string $path
  769. * @param array $accessdata
  770. * @return bool
  771. */
  772. function path_inaccessdata($path, $accessdata) {
  773. if (empty($accessdata['loaded'])) {
  774. return false;
  775. }
  776. // assume that contexts hang from sys or from a course
  777. // this will only work well with stuff that hangs from a course
  778. if (in_array($path, $accessdata['loaded'], true)) {
  779. // error_log("found it!");
  780. return true;
  781. }
  782. $base = '/' . SYSCONTEXTID;
  783. while (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
  784. $path = $matches[1];
  785. if ($path === $base) {
  786. return false;
  787. }
  788. if (in_array($path, $accessdata['loaded'], true)) {
  789. return true;
  790. }
  791. }
  792. return false;
  793. }
  794. /**
  795. * Does the user have a capability to do something?
  796. *
  797. * Walk the accessdata array and return true/false.
  798. * Deals with prohibits, roleswitching, aggregating
  799. * capabilities, etc.
  800. *
  801. * The main feature of here is being FAST and with no
  802. * side effects.
  803. *
  804. * Notes:
  805. *
  806. * Switch Roles exits early
  807. * ------------------------
  808. * cap checks within a switchrole need to exit early
  809. * in our bottom up processing so they don't "see" that
  810. * there are real RAs that can do all sorts of things.
  811. *
  812. * Switch Role merges with default role
  813. * ------------------------------------
  814. * If you are a teacher in course X, you have at least
  815. * teacher-in-X + defaultloggedinuser-sitewide. So in the
  816. * course you'll have techer+defaultloggedinuser.
  817. * We try to mimic that in switchrole.
  818. *
  819. * Permission evaluation
  820. * ---------------------
  821. * Originally there was an extremely complicated way
  822. * to determine the user access that dealt with
  823. * "locality" or role assignments and role overrides.
  824. * Now we simply evaluate access for each role separately
  825. * and then verify if user has at least one role with allow
  826. * and at the same time no role with prohibit.
  827. *
  828. * @param string $capability
  829. * @param object $context
  830. * @param array $accessdata
  831. * @return bool
  832. */
  833. function has_capability_in_accessdata($capability, $context, array $accessdata) {
  834. global $CFG;
  835. if (empty($context->id)) {
  836. throw new coding_exception('Invalid context specified');
  837. }
  838. // Build $paths as a list of current + all parent "paths" with order bottom-to-top
  839. $contextids = explode('/', trim($context->path, '/'));
  840. $paths = array($context->path);
  841. while ($contextids) {
  842. array_pop($contextids);
  843. $paths[] = '/' . implode('/', $contextids);
  844. }
  845. unset($contextids);
  846. $roles = array();
  847. $switchedrole = false;
  848. // Find out if role switched
  849. if (!empty($accessdata['rsw'])) {
  850. // From the bottom up...
  851. foreach ($paths as $path) {
  852. if (isset($accessdata['rsw'][$path])) {
  853. // Found a switchrole assignment - check for that role _plus_ the default user role
  854. $roles = array($accessdata['rsw'][$path]=>null, $CFG->defaultuserroleid=>null);
  855. $switchedrole = true;
  856. break;
  857. }
  858. }
  859. }
  860. if (!$switchedrole) {
  861. // get all users roles in this context and above
  862. foreach ($paths as $path) {
  863. if (isset($accessdata['ra'][$path])) {
  864. foreach ($accessdata['ra'][$path] as $roleid) {
  865. $roles[$roleid] = null;
  866. }
  867. }
  868. }
  869. }
  870. // Now find out what access is given to each role, going bottom-->up direction
  871. foreach ($roles as $roleid => $ignored) {
  872. foreach ($paths as $path) {
  873. if (isset($accessdata['rdef']["{$path}:$roleid"][$capability])) {
  874. $perm = (int)$accessdata['rdef']["{$path}:$roleid"][$capability];
  875. if ($perm === CAP_PROHIBIT or is_null($roles[$roleid])) {
  876. $roles[$roleid] = $perm;
  877. }
  878. }
  879. }
  880. }
  881. // any CAP_PROHIBIT found means no permission for the user
  882. if (array_search(CAP_PROHIBIT, $roles) !== false) {
  883. return false;
  884. }
  885. // at least one CAP_ALLOW means the user has a permission
  886. return (array_search(CAP_ALLOW, $roles) !== false);
  887. }
  888. /**
  889. * @param object $context
  890. * @param array $accessdata
  891. * @return array
  892. */
  893. function aggregate_roles_from_accessdata($context, $accessdata) {
  894. $path = $context->path;
  895. // build $contexts as a list of "paths" of the current
  896. // contexts and parents with the order top-to-bottom
  897. $contexts = array($path);
  898. while (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
  899. $path = $matches[1];
  900. array_unshift($contexts, $path);
  901. }
  902. $cc = count($contexts);
  903. $roles = array();
  904. // From the bottom up...
  905. for ($n=$cc-1; $n>=0; $n--) {
  906. $ctxp = $contexts[$n];
  907. if (isset($accessdata['ra'][$ctxp]) && count($accessdata['ra'][$ctxp])) {
  908. // Found assignments on this leaf
  909. $addroles = $accessdata['ra'][$ctxp];
  910. $roles = array_merge($roles, $addroles);
  911. }
  912. }
  913. return array_unique($roles);
  914. }
  915. /**
  916. * A convenience function that tests has_capability, and displays an error if
  917. * the user does not have that capability.
  918. *
  919. * NOTE before Moodle 2.0, this function attempted to make an appropriate
  920. * require_login call before checking the capability. This is no longer the case.
  921. * You must call require_login (or one of its variants) if you want to check the
  922. * user is logged in, before you call this function.
  923. *
  924. * @see has_capability()
  925. *
  926. * @param string $capability the name of the capability to check. For example mod/forum:view
  927. * @param object $context the context to check the capability in. You normally get this with {@link get_context_instance}.
  928. * @param integer $userid A user id. By default (null) checks the permissions of the current user.
  929. * @param bool $doanything If false, ignore effect of admin role assignment
  930. * @param string $errorstring The error string to to user. Defaults to 'nopermissions'.
  931. * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
  932. * @return void terminates with an error if the user does not have the given capability.
  933. */
  934. function require_capability($capability, $context, $userid = null, $doanything = true,
  935. $errormessage = 'nopermissions', $stringfile = '') {
  936. if (!has_capability($capability, $context, $userid, $doanything)) {
  937. throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
  938. }
  939. }
  940. /**
  941. * Get an array of courses where cap requested is available
  942. * and user is enrolled, this can be relatively slow.
  943. *
  944. * @param string $capability - name of the capability
  945. * @param array $accessdata_ignored
  946. * @param bool $doanything_ignored
  947. * @param string $sort - sorting fields - prefix each fieldname with "c."
  948. * @param array $fields - additional fields you are interested in...
  949. * @param int $limit_ignored
  950. * @return array $courses - ordered array of course objects - see notes above
  951. */
  952. function get_user_courses_bycap($userid, $cap, $accessdata_ignored, $doanything_ignored, $sort = 'c.sortorder ASC', $fields = null, $limit_ignored = 0) {
  953. //TODO: this should be most probably deprecated
  954. $courses = enrol_get_users_courses($userid, true, $fields, $sort);
  955. foreach ($courses as $id=>$course) {
  956. $context = get_context_instance(CONTEXT_COURSE, $id);
  957. if (!has_capability($cap, $context, $userid)) {
  958. unset($courses[$id]);
  959. }
  960. }
  961. return $courses;
  962. }
  963. /**
  964. * Return a nested array showing role assignments
  965. * all relevant role capabilities for the user at
  966. * site/course_category/course levels
  967. *
  968. * We do _not_ delve deeper than courses because the number of
  969. * overrides at the module/block levels is HUGE.
  970. *
  971. * [ra] => [/path/][]=roleid
  972. * [rdef] => [/path/:roleid][capability]=permission
  973. * [loaded] => array('/path', '/path')
  974. *
  975. * @param int $userid - the id of the user
  976. * @return array
  977. */
  978. function get_user_access_sitewide($userid) {
  979. global $CFG, $DB;
  980. /* Get in 3 cheap DB queries...
  981. * - role assignments
  982. * - relevant role caps
  983. * - above and within this user's RAs
  984. * - below this user's RAs - limited to course level
  985. */
  986. $accessdata = array(); // named list
  987. $accessdata['ra'] = array();
  988. $accessdata['rdef'] = array();
  989. $accessdata['loaded'] = array();
  990. //
  991. // Role assignments
  992. //
  993. $sql = "SELECT ctx.path, ra.roleid
  994. FROM {role_assignments} ra
  995. JOIN {context} ctx ON ctx.id=ra.contextid
  996. WHERE ra.userid = ? AND ctx.contextlevel <= ".CONTEXT_COURSE;
  997. $params = array($userid);
  998. $rs = $DB->get_recordset_sql($sql, $params);
  999. //
  1000. // raparents collects paths & roles we need to walk up
  1001. // the parenthood to build the rdef
  1002. //
  1003. $raparents = array();
  1004. if ($rs) {
  1005. foreach ($rs as $ra) {
  1006. // RAs leafs are arrays to support multi
  1007. // role assignments...
  1008. if (!isset($accessdata['ra'][$ra->path])) {
  1009. $accessdata['ra'][$ra->path] = array();
  1010. }
  1011. $accessdata['ra'][$ra->path][$ra->roleid] = $ra->roleid;
  1012. // Concatenate as string the whole path (all related context)
  1013. // for this role. This is damn faster than using array_merge()
  1014. // Will unique them later
  1015. if (isset($raparents[$ra->roleid])) {
  1016. $raparents[$ra->roleid] .= $ra->path;
  1017. } else {
  1018. $raparents[$ra->roleid] = $ra->path;
  1019. }
  1020. }
  1021. unset($ra);
  1022. $rs->close();
  1023. }
  1024. // Walk up the tree to grab all the roledefs
  1025. // of interest to our user...
  1026. //
  1027. // NOTE: we use a series of IN clauses here - which
  1028. // might explode on huge sites with very convoluted nesting of
  1029. // categories... - extremely unlikely that the number of categories
  1030. // and roletypes is so large that we hit the limits of IN()
  1031. $clauses = '';
  1032. $cparams = array();
  1033. foreach ($raparents as $roleid=>$strcontexts) {
  1034. $contexts = implode(',', array_unique(explode('/', trim($strcontexts, '/'))));
  1035. if ($contexts ==! '') {
  1036. if ($clauses) {
  1037. $clauses .= ' OR ';
  1038. }
  1039. $clauses .= "(roleid=? AND contextid IN ($contexts))";
  1040. $cparams[] = $roleid;
  1041. }
  1042. }
  1043. if ($clauses !== '') {
  1044. $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
  1045. FROM {role_capabilities} rc
  1046. JOIN {context} ctx ON rc.contextid=ctx.id
  1047. WHERE $clauses";
  1048. unset($clauses);
  1049. $rs = $DB->get_recordset_sql($sql, $cparams);
  1050. if ($rs) {
  1051. foreach ($rs as $rd) {
  1052. $k = "{$rd->path}:{$rd->roleid}";
  1053. $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
  1054. }
  1055. unset($rd);
  1056. $rs->close();
  1057. }
  1058. }
  1059. //
  1060. // Overrides for the role assignments IN SUBCONTEXTS
  1061. // (though we still do _not_ go below the course level.
  1062. //
  1063. // NOTE that the JOIN w sctx is with 3-way triangulation to
  1064. // catch overrides to the applicable role in any subcontext, based
  1065. // on the path field of the parent.
  1066. //
  1067. $sql = "SELECT sctx.path, ra.roleid,
  1068. ctx.path AS parentpath,
  1069. rco.capability, rco.permission
  1070. FROM {role_assignments} ra
  1071. JOIN {context} ctx
  1072. ON ra.contextid=ctx.id
  1073. JOIN {context} sctx
  1074. ON (sctx.path LIKE " . $DB->sql_concat('ctx.path',"'/%'"). " )
  1075. JOIN {role_capabilities} rco
  1076. ON (rco.roleid=ra.roleid AND rco.contextid=sctx.id)
  1077. WHERE ra.userid = ?
  1078. AND ctx.contextlevel <= ".CONTEXT_COURSECAT."
  1079. AND sctx.contextlevel <= ".CONTEXT_COURSE."
  1080. ORDER BY sctx.depth, sctx.path, ra.roleid";
  1081. $params = array($userid);
  1082. $rs = $DB->get_recordset_sql($sql, $params);
  1083. if ($rs) {
  1084. foreach ($rs as $rd) {
  1085. $k = "{$rd->path}:{$rd->roleid}";
  1086. $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
  1087. }
  1088. unset($rd);
  1089. $rs->close();
  1090. }
  1091. return $accessdata;
  1092. }
  1093. /**
  1094. * Add to the access ctrl array the data needed by a user for a given context
  1095. *
  1096. * @param integer $userid the id of the user
  1097. * @param object $context needs path!
  1098. * @param array $accessdata accessdata array
  1099. * @return void
  1100. */
  1101. function load_subcontext($userid, $context, &$accessdata) {
  1102. global $CFG, $DB;
  1103. /* Get the additional RAs and relevant rolecaps
  1104. * - role assignments - with role_caps
  1105. * - relevant role caps
  1106. * - above this user's RAs
  1107. * - below this user's RAs - limited to course level
  1108. */
  1109. $base = "/" . SYSCONTEXTID;
  1110. //
  1111. // Replace $context with the target context we will
  1112. // load. Normally, this will be a course context, but
  1113. // may be a different top-level context.
  1114. //
  1115. // We have 3 cases
  1116. //
  1117. // - Course
  1118. // - BLOCK/PERSON/USER/COURSE(sitecourse) hanging from SYSTEM
  1119. // - BLOCK/MODULE/GROUP hanging from a course
  1120. //
  1121. // For course contexts, we _already_ have the RAs
  1122. // but the cost of re-fetching is minimal so we don't care.
  1123. //
  1124. if ($context->contextlevel !== CONTEXT_COURSE
  1125. && $context->path !== "$base/{$context->id}") {
  1126. // Case BLOCK/MODULE/GROUP hanging from a course
  1127. // Assumption: the course _must_ be our parent
  1128. // If we ever see stuff nested further this needs to
  1129. // change to do 1 query over the exploded path to
  1130. // find out which one is the course
  1131. $courses = explode('/',get_course_from_path($context->path));
  1132. $targetid = array_pop($courses);
  1133. $context = get_context_instance_by_id($targetid);
  1134. }
  1135. //
  1136. // Role assignments in the context and below
  1137. //
  1138. $sql = "SELECT ctx.path, ra.roleid
  1139. FROM {role_assignments} ra
  1140. JOIN {context} ctx
  1141. ON ra.contextid=ctx.id
  1142. WHERE ra.userid = ?
  1143. AND (ctx.path = ? OR ctx.path LIKE ?)
  1144. ORDER BY ctx.depth, ctx.path, ra.roleid";
  1145. $params = array($userid, $context->path, $context->path."/%");
  1146. $rs = $DB->get_recordset_sql($sql, $params);
  1147. //
  1148. // Read in the RAs, preventing duplicates
  1149. //
  1150. if ($rs) {
  1151. $localroles = array();
  1152. $lastseen = '';
  1153. foreach ($rs as $ra) {
  1154. if (!isset($accessdata['ra'][$ra->path])) {
  1155. $accessdata['ra'][$ra->path] = array();
  1156. }
  1157. // only add if is not a repeat caused
  1158. // by capability join...
  1159. // (this check is cheaper than in_array())
  1160. if ($lastseen !== $ra->path.':'.$ra->roleid) {
  1161. $lastseen = $ra->path.':'.$ra->roleid;
  1162. $accessdata['ra'][$ra->path][$ra->roleid] = $ra->roleid;
  1163. array_push($localroles, $ra->roleid);
  1164. }
  1165. }
  1166. $rs->close();
  1167. }
  1168. //
  1169. // Walk up and down the tree to grab all the roledefs
  1170. // of interest to our user...
  1171. //
  1172. // NOTES
  1173. // - we use IN() but the number of roles is very limited.
  1174. //
  1175. $courseroles = aggregate_roles_from_accessdata($context, $accessdata);
  1176. // Do we have any interesting "local" roles?
  1177. $localroles = array_diff($localroles,$courseroles); // only "new" local roles
  1178. $wherelocalroles='';
  1179. if (count($localroles)) {
  1180. // Role defs for local roles in 'higher' contexts...
  1181. $contexts = substr($context->path, 1); // kill leading slash
  1182. $contexts = str_replace('/', ',', $contexts);
  1183. $localroleids = implode(',',$localroles);
  1184. $wherelocalroles="OR (rc.roleid IN ({$localroleids})
  1185. AND ctx.id IN ($contexts))" ;
  1186. }
  1187. // We will want overrides for all of them
  1188. $whereroles = '';
  1189. if ($roleids = implode(',',array_merge($courseroles,$localroles))) {
  1190. $whereroles = "rc.roleid IN ($roleids) AND";
  1191. }
  1192. $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
  1193. FROM {role_capabilities} rc
  1194. JOIN {context} ctx
  1195. ON rc.contextid=ctx.id
  1196. WHERE ($whereroles
  1197. (ctx.id=? OR ctx.path LIKE ?))
  1198. $wherelocalroles
  1199. ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
  1200. $params = array($context->id, $context->path."/%");
  1201. $newrdefs = array();
  1202. $rs = $DB->get_recordset_sql($sql, $params);
  1203. foreach ($rs as $rd) {
  1204. $k = "{$rd->path}:{$rd->roleid}";
  1205. if (!array_key_exists($k, $newrdefs)) {
  1206. $newrdefs[$k] = array();
  1207. }
  1208. $newrdefs[$k][$rd->capability] = $rd->permission;
  1209. }
  1210. $rs->close();
  1211. compact_rdefs($newrdefs);
  1212. foreach ($newrdefs as $key=>$value) {
  1213. $accessdata['rdef'][$key] =& $newrdefs[$key];
  1214. }
  1215. // error_log("loaded {$context->path}");
  1216. $accessdata['loaded'][] = $context->path;
  1217. }
  1218. /**
  1219. * Add to the access ctrl array the data needed by a role for a given context.
  1220. *
  1221. * The data is added in the rdef key.
  1222. *
  1223. * This role-centric function is useful for role_switching
  1224. * and to get an overview of what a role gets under a
  1225. * given context and below...
  1226. *
  1227. * @param integer $roleid the id of the user
  1228. * @param object $context needs path!
  1229. * @param array $accessdata accessdata array null by default
  1230. * @return array
  1231. */
  1232. function get_role_access_bycontext($roleid, $context, $accessdata = null) {
  1233. global $CFG, $DB;
  1234. /* Get the relevant rolecaps into rdef
  1235. * - relevant role caps
  1236. * - at ctx and above
  1237. * - below this ctx
  1238. */
  1239. if (is_null($accessdata)) {
  1240. $accessdata = array(); // named list
  1241. $accessdata['ra'] = array();
  1242. $accessdata['rdef'] = array();
  1243. $accessdata['loaded'] = array();
  1244. }
  1245. $contexts = substr($context->path, 1); // kill leading slash
  1246. $contexts = str_replace('/', ',', $contexts);
  1247. //
  1248. // Walk up and down the tree to grab all the roledefs
  1249. // of interest to our role...
  1250. //
  1251. // NOTE: we use an IN clauses here - which
  1252. // might explode on huge sites with very convoluted nesting of
  1253. // categories... - extremely unlikely that the number of nested
  1254. // categories is so large that we hit the limits of IN()
  1255. //
  1256. $sql = "SELECT ctx.path, rc.capability, rc.permission
  1257. FROM {role_capabilities} rc
  1258. JOIN {context} ctx
  1259. ON rc.contextid=ctx.id
  1260. WHERE rc.roleid=? AND
  1261. ( ctx.id IN ($contexts) OR
  1262. ctx.path LIKE ? )
  1263. ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
  1264. $params = array($roleid, $context->path."/%");
  1265. $rs = $DB->get_recordset_sql($sql, $params);
  1266. foreach ($rs as $rd) {
  1267. $k = "{$rd->path}:{$roleid}";
  1268. $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
  1269. }
  1270. $rs->close();
  1271. return $accessdata;
  1272. }
  1273. /**
  1274. * Load accessdata for a user into the $ACCESSLIB_PRIVATE->accessdatabyuser global
  1275. *
  1276. * Used by has_capability() - but feel free
  1277. * to call it if you are about to run a BIG
  1278. * cron run across a bazillion users.
  1279. *
  1280. * @param int $userid
  1281. * @return array returns ACCESSLIB_PRIVATE->accessdatabyuser[userid]
  1282. */
  1283. function load_user_accessdata($userid) {
  1284. global $CFG, $ACCESSLIB_PRIVATE;
  1285. $base = '/'.SYSCONTEXTID;
  1286. $accessdata = get_user_access_sitewide($userid);
  1287. $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
  1288. //
  1289. // provide "default role" & set 'dr'
  1290. //
  1291. if (!empty($CFG->defaultuserroleid)) {
  1292. $accessdata = ge

Large files files are truncated, but you can click here to view the full file