PageRenderTime 83ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/accesslib.php

https://bitbucket.org/ceu/moodle_demo
PHP | 5809 lines | 3392 code | 733 blank | 1684 comment | 752 complexity | 80a2cdbb08e7015d6d1d38c21de86bd4 MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-2.0, LGPL-2.1
  1. <?php // $Id: accesslib.php,v 1.421.2.111 2011/08/03 16:28:19 moodlerobot Exp $
  2. ///////////////////////////////////////////////////////////////////////////
  3. // //
  4. // NOTICE OF COPYRIGHT //
  5. // //
  6. // Moodle - Modular Object-Oriented Dynamic Learning Environment //
  7. // http://moodle.org //
  8. // //
  9. // Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com //
  10. // //
  11. // This program is free software; you can redistribute it and/or modify //
  12. // it under the terms of the GNU General Public License as published by //
  13. // the Free Software Foundation; either version 2 of the License, or //
  14. // (at your option) any later version. //
  15. // //
  16. // This program is distributed in the hope that it will be useful, //
  17. // but WITHOUT ANY WARRANTY; without even the implied warranty of //
  18. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
  19. // GNU General Public License for more details: //
  20. // //
  21. // http://www.gnu.org/copyleft/gpl.html //
  22. // //
  23. ///////////////////////////////////////////////////////////////////////////
  24. /**
  25. * Public API vs internals
  26. * -----------------------
  27. *
  28. * General users probably only care about
  29. *
  30. * Context handling
  31. * - get_context_instance()
  32. * - get_context_instance_by_id()
  33. * - get_parent_contexts()
  34. * - get_child_contexts()
  35. *
  36. * Whether the user can do something...
  37. * - has_capability()
  38. * - has_any_capability()
  39. * - has_all_capabilities()
  40. * - require_capability()
  41. * - require_login() (from moodlelib)
  42. *
  43. * What courses has this user access to?
  44. * - get_user_courses_bycap()
  45. *
  46. * What users can do X in this context?
  47. * - get_users_by_capability()
  48. *
  49. * Enrol/unenrol
  50. * - enrol_into_course()
  51. * - role_assign()/role_unassign()
  52. *
  53. *
  54. * Advanced use
  55. * - load_all_capabilities()
  56. * - reload_all_capabilities()
  57. * - $ACCESS global
  58. * - has_capability_in_accessdata()
  59. * - is_siteadmin()
  60. * - get_user_access_sitewide()
  61. * - load_subcontext()
  62. * - get_role_access_bycontext()
  63. *
  64. * Name conventions
  65. * ----------------
  66. *
  67. * - "ctx" means context
  68. *
  69. * accessdata
  70. * ----------
  71. *
  72. * Access control data is held in the "accessdata" array
  73. * which - for the logged-in user, will be in $USER->access
  74. *
  75. * For other users can be generated and passed around (but see
  76. * the $ACCESS global).
  77. *
  78. * $accessdata is a multidimensional array, holding
  79. * role assignments (RAs), role-capabilities-perm sets
  80. * (role defs) and a list of courses we have loaded
  81. * data for.
  82. *
  83. * Things are keyed on "contextpaths" (the path field of
  84. * the context table) for fast walking up/down the tree.
  85. *
  86. * $accessdata[ra][$contextpath]= array($roleid)
  87. * [$contextpath]= array($roleid)
  88. * [$contextpath]= array($roleid)
  89. *
  90. * Role definitions are stored like this
  91. * (no cap merge is done - so it's compact)
  92. *
  93. * $accessdata[rdef][$contextpath:$roleid][mod/forum:viewpost] = 1
  94. * [mod/forum:editallpost] = -1
  95. * [mod/forum:startdiscussion] = -1000
  96. *
  97. * See how has_capability_in_accessdata() walks up/down the tree.
  98. *
  99. * Normally - specially for the logged-in user, we only load
  100. * rdef and ra down to the course level, but not below. This
  101. * keeps accessdata small and compact. Below-the-course ra/rdef
  102. * are loaded as needed. We keep track of which courses we
  103. * have loaded ra/rdef in
  104. *
  105. * $accessdata[loaded] = array($contextpath, $contextpath)
  106. *
  107. * Stale accessdata
  108. * ----------------
  109. *
  110. * For the logged-in user, accessdata is long-lived.
  111. *
  112. * On each pageload we load $DIRTYPATHS which lists
  113. * context paths affected by changes. Any check at-or-below
  114. * a dirty context will trigger a transparent reload of accessdata.
  115. *
  116. * Changes at the sytem level will force the reload for everyone.
  117. *
  118. * Default role caps
  119. * -----------------
  120. * The default role assignment is not in the DB, so we
  121. * add it manually to accessdata.
  122. *
  123. * This means that functions that work directly off the
  124. * DB need to ensure that the default role caps
  125. * are dealt with appropriately.
  126. *
  127. */
  128. require_once $CFG->dirroot.'/lib/blocklib.php';
  129. // permission definitions
  130. define('CAP_INHERIT', 0);
  131. define('CAP_ALLOW', 1);
  132. define('CAP_PREVENT', -1);
  133. define('CAP_PROHIBIT', -1000);
  134. // context definitions
  135. define('CONTEXT_SYSTEM', 10);
  136. define('CONTEXT_USER', 30);
  137. define('CONTEXT_COURSECAT', 40);
  138. define('CONTEXT_COURSE', 50);
  139. define('CONTEXT_MODULE', 70);
  140. define('CONTEXT_BLOCK', 80);
  141. // capability risks - see http://docs.moodle.org/dev/Hardening_new_Roles_system
  142. define('RISK_MANAGETRUST', 0x0001);
  143. define('RISK_CONFIG', 0x0002);
  144. define('RISK_XSS', 0x0004);
  145. define('RISK_PERSONAL', 0x0008);
  146. define('RISK_SPAM', 0x0010);
  147. define('RISK_DATALOSS', 0x0020);
  148. // rolename displays
  149. define('ROLENAME_ORIGINAL', 0);// the name as defined in the role definition
  150. define('ROLENAME_ALIAS', 1); // the name as defined by a role alias
  151. define('ROLENAME_BOTH', 2); // Both, like this: Role alias (Original)
  152. require_once($CFG->dirroot.'/group/lib.php');
  153. if (!defined('MAX_CONTEXT_CACHE_SIZE')) {
  154. define('MAX_CONTEXT_CACHE_SIZE', 5000);
  155. }
  156. $context_cache = array(); // Cache of all used context objects for performance (by level and instance)
  157. $context_cache_id = array(); // Index to above cache by id
  158. $DIRTYCONTEXTS = null; // dirty contexts cache
  159. $ACCESS = array(); // cache of caps for cron user switching and has_capability for other users (==not $USER)
  160. $RDEFS = array(); // role definitions cache - helps a lot with mem usage in cron
  161. /**
  162. * Adds a context to the cache.
  163. * @param object $context Context object to be cached
  164. */
  165. function cache_context($context) {
  166. global $context_cache, $context_cache_id;
  167. // If there are too many items in the cache already, remove items until
  168. // there is space
  169. while (count($context_cache_id) >= MAX_CONTEXT_CACHE_SIZE) {
  170. $first = reset($context_cache_id);
  171. unset($context_cache_id[$first->id]);
  172. unset($context_cache[$first->contextlevel][$first->instanceid]);
  173. }
  174. // Add this context to the cache
  175. $context_cache_id[$context->id] = $context;
  176. $context_cache[$context->contextlevel][$context->instanceid] = $context;
  177. }
  178. function get_role_context_caps($roleid, $context) {
  179. //this is really slow!!!! - do not use above course context level!
  180. $result = array();
  181. $result[$context->id] = array();
  182. // first emulate the parent context capabilities merging into context
  183. $searchcontexts = array_reverse(get_parent_contexts($context));
  184. array_push($searchcontexts, $context->id);
  185. foreach ($searchcontexts as $cid) {
  186. if ($capabilities = get_records_select('role_capabilities', "roleid = $roleid AND contextid = $cid")) {
  187. foreach ($capabilities as $cap) {
  188. if (!array_key_exists($cap->capability, $result[$context->id])) {
  189. $result[$context->id][$cap->capability] = 0;
  190. }
  191. $result[$context->id][$cap->capability] += $cap->permission;
  192. }
  193. }
  194. }
  195. // now go through the contexts bellow given context
  196. $searchcontexts = array_keys(get_child_contexts($context));
  197. foreach ($searchcontexts as $cid) {
  198. if ($capabilities = get_records_select('role_capabilities', "roleid = $roleid AND contextid = $cid")) {
  199. foreach ($capabilities as $cap) {
  200. if (!array_key_exists($cap->contextid, $result)) {
  201. $result[$cap->contextid] = array();
  202. }
  203. $result[$cap->contextid][$cap->capability] = $cap->permission;
  204. }
  205. }
  206. }
  207. return $result;
  208. }
  209. /**
  210. * Gets the accessdata for role "sitewide"
  211. * (system down to course)
  212. *
  213. * @return array
  214. */
  215. function get_role_access($roleid, $accessdata=NULL) {
  216. global $CFG;
  217. /* Get it in 1 cheap DB query...
  218. * - relevant role caps at the root and down
  219. * to the course level - but not below
  220. */
  221. if (is_null($accessdata)) {
  222. $accessdata = array(); // named list
  223. $accessdata['ra'] = array();
  224. $accessdata['rdef'] = array();
  225. $accessdata['loaded'] = array();
  226. }
  227. //
  228. // Overrides for the role IN ANY CONTEXTS
  229. // down to COURSE - not below -
  230. //
  231. $sql = "SELECT ctx.path,
  232. rc.capability, rc.permission
  233. FROM {$CFG->prefix}context ctx
  234. JOIN {$CFG->prefix}role_capabilities rc
  235. ON rc.contextid=ctx.id
  236. WHERE rc.roleid = {$roleid}
  237. AND ctx.contextlevel <= ".CONTEXT_COURSE."
  238. ORDER BY ctx.depth, ctx.path";
  239. // we need extra caching in cron only
  240. if (defined('FULLME') and FULLME === 'cron') {
  241. static $cron_cache = array();
  242. if (!isset($cron_cache[$roleid])) {
  243. $cron_cache[$roleid] = array();
  244. if ($rs = get_recordset_sql($sql)) {
  245. while ($rd = rs_fetch_next_record($rs)) {
  246. $cron_cache[$roleid][] = $rd;
  247. }
  248. rs_close($rs);
  249. }
  250. }
  251. foreach ($cron_cache[$roleid] as $rd) {
  252. $k = "{$rd->path}:{$roleid}";
  253. $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
  254. }
  255. } else {
  256. if ($rs = get_recordset_sql($sql)) {
  257. while ($rd = rs_fetch_next_record($rs)) {
  258. $k = "{$rd->path}:{$roleid}";
  259. $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
  260. }
  261. unset($rd);
  262. rs_close($rs);
  263. }
  264. }
  265. return $accessdata;
  266. }
  267. /**
  268. * Gets the accessdata for role "sitewide"
  269. * (system down to course)
  270. *
  271. * @return array
  272. */
  273. function get_default_frontpage_role_access($roleid, $accessdata=NULL) {
  274. global $CFG;
  275. $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
  276. $base = '/'. SYSCONTEXTID .'/'. $frontpagecontext->id;
  277. //
  278. // Overrides for the role in any contexts related to the course
  279. //
  280. $sql = "SELECT ctx.path,
  281. rc.capability, rc.permission
  282. FROM {$CFG->prefix}context ctx
  283. JOIN {$CFG->prefix}role_capabilities rc
  284. ON rc.contextid=ctx.id
  285. WHERE rc.roleid = {$roleid}
  286. AND (ctx.id = ".SYSCONTEXTID." OR ctx.path LIKE '$base/%')
  287. AND ctx.contextlevel <= ".CONTEXT_COURSE."
  288. ORDER BY ctx.depth, ctx.path";
  289. if ($rs = get_recordset_sql($sql)) {
  290. while ($rd = rs_fetch_next_record($rs)) {
  291. $k = "{$rd->path}:{$roleid}";
  292. $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
  293. }
  294. unset($rd);
  295. rs_close($rs);
  296. }
  297. return $accessdata;
  298. }
  299. /**
  300. * Get the default guest role
  301. * @return object role
  302. */
  303. function get_guest_role() {
  304. global $CFG;
  305. if (empty($CFG->guestroleid)) {
  306. if ($roles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW)) {
  307. $guestrole = array_shift($roles); // Pick the first one
  308. set_config('guestroleid', $guestrole->id);
  309. return $guestrole;
  310. } else {
  311. debugging('Can not find any guest role!');
  312. return false;
  313. }
  314. } else {
  315. if ($guestrole = get_record('role','id', $CFG->guestroleid)) {
  316. return $guestrole;
  317. } else {
  318. //somebody is messing with guest roles, remove incorrect setting and try to find a new one
  319. set_config('guestroleid', '');
  320. return get_guest_role();
  321. }
  322. }
  323. }
  324. /**
  325. * This function returns whether the current user has the capability of performing a function
  326. * For example, we can do has_capability('mod/forum:replypost',$context) in forum
  327. * @param string $capability - name of the capability (or debugcache or clearcache)
  328. * @param object $context - a context object (record from context table)
  329. * @param integer $userid - a userid number, empty if current $USER
  330. * @param bool $doanything - if false, ignore do anything
  331. * @return bool
  332. */
  333. function has_capability($capability, $context, $userid=NULL, $doanything=true) {
  334. global $USER, $ACCESS, $CFG, $DIRTYCONTEXTS;
  335. // the original $CONTEXT here was hiding serious errors
  336. // for security reasons do not reuse previous context
  337. if (empty($context)) {
  338. debugging('Incorrect context specified');
  339. return false;
  340. }
  341. /// Some sanity checks
  342. if (debugging('',DEBUG_DEVELOPER)) {
  343. if (!is_valid_capability($capability)) {
  344. debugging('Capability "'.$capability.'" was not found! This should be fixed in code.');
  345. }
  346. if (!is_bool($doanything)) {
  347. debugging('Capability parameter "doanything" is wierd ("'.$doanything.'"). This should be fixed in code.');
  348. }
  349. }
  350. if (empty($userid)) { // we must accept null, 0, '0', '' etc. in $userid
  351. $userid = $USER->id;
  352. }
  353. if (is_null($context->path) or $context->depth == 0) {
  354. //this should not happen
  355. $contexts = array(SYSCONTEXTID, $context->id);
  356. $context->path = '/'.SYSCONTEXTID.'/'.$context->id;
  357. debugging('Context id '.$context->id.' does not have valid path, please use build_context_path()', DEBUG_DEVELOPER);
  358. } else {
  359. $contexts = explode('/', $context->path);
  360. array_shift($contexts);
  361. }
  362. if (defined('FULLME') && FULLME === 'cron' && !isset($USER->access)) {
  363. // In cron, some modules setup a 'fake' $USER,
  364. // ensure we load the appropriate accessdata.
  365. if (isset($ACCESS[$userid])) {
  366. $DIRTYCONTEXTS = NULL; //load fresh dirty contexts
  367. } else {
  368. load_user_accessdata($userid);
  369. $DIRTYCONTEXTS = array();
  370. }
  371. $USER->access = $ACCESS[$userid];
  372. } else if ($USER->id == $userid && !isset($USER->access)) {
  373. // caps not loaded yet - better to load them to keep BC with 1.8
  374. // not-logged-in user or $USER object set up manually first time here
  375. load_all_capabilities();
  376. $ACCESS = array(); // reset the cache for other users too, the dirty contexts are empty now
  377. $RDEFS = array();
  378. }
  379. // Load dirty contexts list if needed
  380. if (!isset($DIRTYCONTEXTS)) {
  381. if (isset($USER->access['time'])) {
  382. $DIRTYCONTEXTS = get_dirty_contexts($USER->access['time']);
  383. }
  384. else {
  385. $DIRTYCONTEXTS = array();
  386. }
  387. }
  388. // Careful check for staleness...
  389. if (count($DIRTYCONTEXTS) !== 0 and is_contextpath_dirty($contexts, $DIRTYCONTEXTS)) {
  390. // reload all capabilities - preserving loginas, roleswitches, etc
  391. // and then cleanup any marks of dirtyness... at least from our short
  392. // term memory! :-)
  393. $ACCESS = array();
  394. $RDEFS = array();
  395. if (defined('FULLME') && FULLME === 'cron') {
  396. load_user_accessdata($userid);
  397. $USER->access = $ACCESS[$userid];
  398. $DIRTYCONTEXTS = array();
  399. } else {
  400. reload_all_capabilities();
  401. }
  402. }
  403. // divulge how many times we are called
  404. //// error_log("has_capability: id:{$context->id} path:{$context->path} userid:$userid cap:$capability");
  405. if ($USER->id == $userid) { // we must accept strings and integers in $userid
  406. //
  407. // For the logged in user, we have $USER->access
  408. // which will have all RAs and caps preloaded for
  409. // course and above contexts.
  410. //
  411. // Contexts below courses && contexts that do not
  412. // hang from courses are loaded into $USER->access
  413. // on demand, and listed in $USER->access[loaded]
  414. //
  415. if ($context->contextlevel <= CONTEXT_COURSE) {
  416. // Course and above are always preloaded
  417. return has_capability_in_accessdata($capability, $context, $USER->access, $doanything);
  418. }
  419. // Load accessdata for below-the-course contexts
  420. if (!path_inaccessdata($context->path,$USER->access)) {
  421. // error_log("loading access for context {$context->path} for $capability at {$context->contextlevel} {$context->id}");
  422. // $bt = debug_backtrace();
  423. // error_log("bt {$bt[0]['file']} {$bt[0]['line']}");
  424. load_subcontext($USER->id, $context, $USER->access);
  425. }
  426. return has_capability_in_accessdata($capability, $context, $USER->access, $doanything);
  427. }
  428. if (!isset($ACCESS[$userid])) {
  429. load_user_accessdata($userid);
  430. }
  431. if ($context->contextlevel <= CONTEXT_COURSE) {
  432. // Course and above are always preloaded
  433. return has_capability_in_accessdata($capability, $context, $ACCESS[$userid], $doanything);
  434. }
  435. // Load accessdata for below-the-course contexts as needed
  436. if (!path_inaccessdata($context->path, $ACCESS[$userid])) {
  437. // error_log("loading access for context {$context->path} for $capability at {$context->contextlevel} {$context->id}");
  438. // $bt = debug_backtrace();
  439. // error_log("bt {$bt[0]['file']} {$bt[0]['line']}");
  440. load_subcontext($userid, $context, $ACCESS[$userid]);
  441. }
  442. return has_capability_in_accessdata($capability, $context, $ACCESS[$userid], $doanything);
  443. }
  444. /**
  445. * This function returns whether the current user has any of the capabilities in the
  446. * $capabilities array. This is a simple wrapper around has_capability for convinience.
  447. *
  448. * There are probably tricks that could be done to improve the performance here, for example,
  449. * check the capabilities that are already cached first.
  450. *
  451. * @param array $capabilities - an array of capability names.
  452. * @param object $context - a context object (record from context table)
  453. * @param integer $userid - a userid number, empty if current $USER
  454. * @param bool $doanything - if false, ignore do anything
  455. * @return bool
  456. */
  457. function has_any_capability($capabilities, $context, $userid=NULL, $doanything=true) {
  458. foreach ($capabilities as $capability) {
  459. if (has_capability($capability, $context, $userid, $doanything)) {
  460. return true;
  461. }
  462. }
  463. return false;
  464. }
  465. /**
  466. * This function returns whether the current user has all of the capabilities in the
  467. * $capabilities array. This is a simple wrapper around has_capability for convinience.
  468. *
  469. * There are probably tricks that could be done to improve the performance here, for example,
  470. * check the capabilities that are already cached first.
  471. *
  472. * @param array $capabilities - an array of capability names.
  473. * @param object $context - a context object (record from context table)
  474. * @param integer $userid - a userid number, empty if current $USER
  475. * @param bool $doanything - if false, ignore do anything
  476. * @return bool
  477. */
  478. function has_all_capabilities($capabilities, $context, $userid=NULL, $doanything=true) {
  479. if (!is_array($capabilities)) {
  480. debugging('Incorrect $capabilities parameter in has_all_capabilities() call - must be an array');
  481. return false;
  482. }
  483. foreach ($capabilities as $capability) {
  484. if (!has_capability($capability, $context, $userid, $doanything)) {
  485. return false;
  486. }
  487. }
  488. return true;
  489. }
  490. /**
  491. * Uses 1 DB query to answer whether a user is an admin at the sitelevel.
  492. * It depends on DB schema >=1.7 but does not depend on the new datastructures
  493. * in v1.9 (context.path, or $USER->access)
  494. *
  495. * Will return true if the userid has any of
  496. * - moodle/site:config
  497. * - moodle/legacy:admin
  498. * - moodle/site:doanything
  499. *
  500. * @param int $userid
  501. * @returns bool $isadmin
  502. */
  503. function is_siteadmin($userid) {
  504. global $CFG;
  505. $sql = "SELECT SUM(rc.permission)
  506. FROM " . $CFG->prefix . "role_capabilities rc
  507. JOIN " . $CFG->prefix . "context ctx
  508. ON ctx.id=rc.contextid
  509. JOIN " . $CFG->prefix . "role_assignments ra
  510. ON ra.roleid=rc.roleid AND ra.contextid=ctx.id
  511. WHERE ctx.contextlevel=10
  512. AND ra.userid={$userid}
  513. AND rc.capability IN ('moodle/site:config', 'moodle/legacy:admin', 'moodle/site:doanything')
  514. GROUP BY rc.capability
  515. HAVING SUM(rc.permission) > 0";
  516. $isadmin = record_exists_sql($sql);
  517. return $isadmin;
  518. }
  519. function get_course_from_path ($path) {
  520. // assume that nothing is more than 1 course deep
  521. if (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
  522. return $matches[1];
  523. }
  524. return false;
  525. }
  526. function path_inaccessdata($path, $accessdata) {
  527. // assume that contexts hang from sys or from a course
  528. // this will only work well with stuff that hangs from a course
  529. if (in_array($path, $accessdata['loaded'], true)) {
  530. // error_log("found it!");
  531. return true;
  532. }
  533. $base = '/' . SYSCONTEXTID;
  534. while (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
  535. $path = $matches[1];
  536. if ($path === $base) {
  537. return false;
  538. }
  539. if (in_array($path, $accessdata['loaded'], true)) {
  540. return true;
  541. }
  542. }
  543. return false;
  544. }
  545. /**
  546. * Walk the accessdata array and return true/false.
  547. * Deals with prohibits, roleswitching, aggregating
  548. * capabilities, etc.
  549. *
  550. * The main feature of here is being FAST and with no
  551. * side effects.
  552. *
  553. * Notes:
  554. *
  555. * Switch Roles exits early
  556. * -----------------------
  557. * cap checks within a switchrole need to exit early
  558. * in our bottom up processing so they don't "see" that
  559. * there are real RAs that can do all sorts of things.
  560. *
  561. * Switch Role merges with default role
  562. * ------------------------------------
  563. * If you are a teacher in course X, you have at least
  564. * teacher-in-X + defaultloggedinuser-sitewide. So in the
  565. * course you'll have techer+defaultloggedinuser.
  566. * We try to mimic that in switchrole.
  567. *
  568. * Local-most role definition and role-assignment wins
  569. * ---------------------------------------------------
  570. * So if the local context has said 'allow', it wins
  571. * over a high-level context that says 'deny'.
  572. * This is applied when walking rdefs, and RAs.
  573. * Only at the same context the values are SUM()med.
  574. *
  575. * The exception is CAP_PROHIBIT.
  576. *
  577. * "Guest default role" exception
  578. * ------------------------------
  579. *
  580. * See MDL-7513 and $ignoreguest below for details.
  581. *
  582. * The rule is that
  583. *
  584. * IF we are being asked about moodle/legacy:guest
  585. * OR moodle/course:view
  586. * FOR a real, logged-in user
  587. * AND we reached the top of the path in ra and rdef
  588. * AND that role has moodle/legacy:guest === 1...
  589. * THEN we act as if we hadn't seen it.
  590. *
  591. * Note that this function must be kept in synch with has_capability_in_accessdata.
  592. *
  593. * To Do:
  594. *
  595. * - Document how it works
  596. * - Rewrite in ASM :-)
  597. *
  598. */
  599. function has_capability_in_accessdata($capability, $context, $accessdata, $doanything) {
  600. global $CFG;
  601. $path = $context->path;
  602. // build $contexts as a list of "paths" of the current
  603. // contexts and parents with the order top-to-bottom
  604. $contexts = array($path);
  605. while (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
  606. $path = $matches[1];
  607. array_unshift($contexts, $path);
  608. }
  609. $ignoreguest = false;
  610. if (isset($accessdata['dr'])
  611. && ($capability == 'moodle/course:view'
  612. || $capability == 'moodle/legacy:guest')) {
  613. // At the base, ignore rdefs where moodle/legacy:guest
  614. // is set
  615. $ignoreguest = $accessdata['dr'];
  616. }
  617. // Coerce it to an int
  618. $CAP_PROHIBIT = (int)CAP_PROHIBIT;
  619. $cc = count($contexts);
  620. $can = 0;
  621. $capdepth = 0;
  622. //
  623. // role-switches loop
  624. //
  625. if (isset($accessdata['rsw'])) {
  626. // check for isset() is fast
  627. // empty() is slow...
  628. if (empty($accessdata['rsw'])) {
  629. unset($accessdata['rsw']); // keep things fast and unambiguous
  630. break;
  631. }
  632. // From the bottom up...
  633. for ($n=$cc-1;$n>=0;$n--) {
  634. $ctxp = $contexts[$n];
  635. if (isset($accessdata['rsw'][$ctxp])) {
  636. // Found a switchrole assignment
  637. // check for that role _plus_ the default user role
  638. $ras = array($accessdata['rsw'][$ctxp],$CFG->defaultuserroleid);
  639. for ($rn=0;$rn<2;$rn++) {
  640. $roleid = (int)$ras[$rn];
  641. // Walk the path for capabilities
  642. // from the bottom up...
  643. for ($m=$cc-1;$m>=0;$m--) {
  644. $capctxp = $contexts[$m];
  645. if (isset($accessdata['rdef']["{$capctxp}:$roleid"][$capability])) {
  646. $perm = (int)$accessdata['rdef']["{$capctxp}:$roleid"][$capability];
  647. // The most local permission (first to set) wins
  648. // the only exception is CAP_PROHIBIT
  649. if ($can === 0) {
  650. $can = $perm;
  651. } elseif ($perm === $CAP_PROHIBIT) {
  652. $can = $perm;
  653. break;
  654. }
  655. }
  656. }
  657. }
  658. // As we are dealing with a switchrole,
  659. // we return _here_, do _not_ walk up
  660. // the hierarchy any further
  661. if ($can < 1) {
  662. if ($doanything) {
  663. // didn't find it as an explicit cap,
  664. // but maybe the user can doanything in this context...
  665. return has_capability_in_accessdata('moodle/site:doanything', $context, $accessdata, false);
  666. } else {
  667. return false;
  668. }
  669. } else {
  670. return true;
  671. }
  672. }
  673. }
  674. }
  675. //
  676. // Main loop for normal RAs
  677. // From the bottom up...
  678. //
  679. for ($n=$cc-1;$n>=0;$n--) {
  680. $ctxp = $contexts[$n];
  681. if (isset($accessdata['ra'][$ctxp])) {
  682. // Found role assignments on this leaf
  683. $ras = $accessdata['ra'][$ctxp];
  684. $rc = count($ras);
  685. $ctxcan = 0;
  686. $ctxcapdepth = 0;
  687. for ($rn=0;$rn<$rc;$rn++) {
  688. $roleid = (int)$ras[$rn];
  689. $rolecan = 0;
  690. $rolecapdepth = 0;
  691. // Walk the path for capabilities
  692. // from the bottom up...
  693. for ($m=$cc-1;$m>=0;$m--) {
  694. $capctxp = $contexts[$m];
  695. // ignore some guest caps
  696. // at base ra and rdef
  697. if ($ignoreguest == $roleid
  698. && $n === 0
  699. && $m === 0
  700. && isset($accessdata['rdef']["{$capctxp}:$roleid"]['moodle/legacy:guest'])
  701. && $accessdata['rdef']["{$capctxp}:$roleid"]['moodle/legacy:guest'] > 0) {
  702. continue;
  703. }
  704. if (isset($accessdata['rdef']["{$capctxp}:$roleid"][$capability])) {
  705. $perm = (int)$accessdata['rdef']["{$capctxp}:$roleid"][$capability];
  706. // The most local permission (first to set) wins
  707. // the only exception is CAP_PROHIBIT
  708. if ($rolecan === 0) {
  709. $rolecan = $perm;
  710. $rolecapdepth = $m;
  711. } elseif ($perm === $CAP_PROHIBIT) {
  712. $rolecan = $perm;
  713. $rolecapdepth = $m;
  714. break;
  715. }
  716. }
  717. }
  718. // Rules for RAs at the same context...
  719. // - prohibits always wins
  720. // - permissions at the same ctxlevel & capdepth are added together
  721. // - deeper capdepth wins
  722. if ($ctxcan === $CAP_PROHIBIT || $rolecan === $CAP_PROHIBIT) {
  723. $ctxcan = $CAP_PROHIBIT;
  724. $ctxcapdepth = 0;
  725. } elseif ($ctxcapdepth === $rolecapdepth) {
  726. $ctxcan += $rolecan;
  727. } elseif ($ctxcapdepth < $rolecapdepth) {
  728. $ctxcan = $rolecan;
  729. $ctxcapdepth = $rolecapdepth;
  730. } else { // ctxcaptdepth is deeper
  731. // rolecap ignored
  732. }
  733. }
  734. // The most local RAs with a defined
  735. // permission ($ctxcan) win, except
  736. // for CAP_PROHIBIT
  737. // NOTE: If we want the deepest RDEF to
  738. // win regardless of the depth of the RA,
  739. // change the elseif below to read
  740. // ($can === 0 || $capdepth < $ctxcapdepth) {
  741. if ($ctxcan === $CAP_PROHIBIT) {
  742. $can = $ctxcan;
  743. break;
  744. } elseif ($can === 0) { // see note above
  745. $can = $ctxcan;
  746. $capdepth = $ctxcapdepth;
  747. }
  748. }
  749. }
  750. if ($can < 1) {
  751. if ($doanything) {
  752. // didn't find it as an explicit cap,
  753. // but maybe the user can doanything in this context...
  754. return has_capability_in_accessdata('moodle/site:doanything', $context, $accessdata, false);
  755. } else {
  756. return false;
  757. }
  758. } else {
  759. return true;
  760. }
  761. }
  762. function aggregate_roles_from_accessdata($context, $accessdata) {
  763. $path = $context->path;
  764. // build $contexts as a list of "paths" of the current
  765. // contexts and parents with the order top-to-bottom
  766. $contexts = array($path);
  767. while (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
  768. $path = $matches[1];
  769. array_unshift($contexts, $path);
  770. }
  771. $cc = count($contexts);
  772. $roles = array();
  773. // From the bottom up...
  774. for ($n=$cc-1;$n>=0;$n--) {
  775. $ctxp = $contexts[$n];
  776. if (isset($accessdata['ra'][$ctxp]) && count($accessdata['ra'][$ctxp])) {
  777. // Found assignments on this leaf
  778. $addroles = $accessdata['ra'][$ctxp];
  779. $roles = array_merge($roles, $addroles);
  780. }
  781. }
  782. return array_unique($roles);
  783. }
  784. /**
  785. * This is an easy to use function, combining has_capability() with require_course_login().
  786. * And will call those where needed.
  787. *
  788. * It checks for a capability assertion being true. If it isn't
  789. * then the page is terminated neatly with a standard error message.
  790. *
  791. * If the user is not logged in, or is using 'guest' access or other special "users,
  792. * it provides a logon prompt.
  793. *
  794. * @param string $capability - name of the capability
  795. * @param object $context - a context object (record from context table)
  796. * @param integer $userid - a userid number
  797. * @param bool $doanything - if false, ignore do anything
  798. * @param string $errorstring - an errorstring
  799. * @param string $stringfile - which stringfile to get it from
  800. */
  801. function require_capability($capability, $context, $userid=NULL, $doanything=true,
  802. $errormessage='nopermissions', $stringfile='') {
  803. global $USER, $CFG;
  804. /* Empty $userid means current user, if the current user is not logged in,
  805. * then make sure they are (if needed).
  806. * Originally there was a check for loaded permissions - it is not needed here.
  807. * Context is now required parameter, the cached $CONTEXT was only hiding errors.
  808. */
  809. $errorlink = '';
  810. if (empty($userid)) {
  811. if ($context->contextlevel == CONTEXT_COURSE) {
  812. require_login($context->instanceid);
  813. } else if ($context->contextlevel == CONTEXT_MODULE) {
  814. if (!$cm = get_record('course_modules', 'id', $context->instanceid)) {
  815. error('Incorrect module');
  816. }
  817. if (!$course = get_record('course', 'id', $cm->course)) {
  818. error('Incorrect course.');
  819. }
  820. require_course_login($course, true, $cm);
  821. $errorlink = $CFG->wwwroot.'/course/view.php?id='.$cm->course;
  822. } else if ($context->contextlevel == CONTEXT_SYSTEM) {
  823. if (!empty($CFG->forcelogin)) {
  824. require_login();
  825. }
  826. } else {
  827. require_login();
  828. }
  829. }
  830. /// OK, if they still don't have the capability then print a nice error message
  831. if (!has_capability($capability, $context, $userid, $doanything)) {
  832. $capabilityname = get_capability_string($capability);
  833. print_error($errormessage, $stringfile, $errorlink, $capabilityname);
  834. }
  835. }
  836. /**
  837. * Get an array of courses (with magic extra bits)
  838. * where the accessdata and in DB enrolments show
  839. * that the cap requested is available.
  840. *
  841. * The main use is for get_my_courses().
  842. *
  843. * Notes
  844. *
  845. * - $fields is an array of fieldnames to ADD
  846. * so name the fields you really need, which will
  847. * be added and uniq'd
  848. *
  849. * - the course records have $c->context which is a fully
  850. * valid context object. Saves you a query per course!
  851. *
  852. * - the course records have $c->categorypath to make
  853. * category lookups cheap
  854. *
  855. * - current implementation is split in -
  856. *
  857. * - if the user has the cap systemwide, stupidly
  858. * grab *every* course for a capcheck. This eats
  859. * a TON of bandwidth, specially on large sites
  860. * with separate DBs...
  861. *
  862. * - otherwise, fetch "likely" courses with a wide net
  863. * that should get us _cheaply_ at least the courses we need, and some
  864. * we won't - we get courses that...
  865. * - are in a category where user has the cap
  866. * - or where use has a role-assignment (any kind)
  867. * - or where the course has an override on for this cap
  868. *
  869. * - walk the courses recordset checking the caps oneach one
  870. * the checks are all in memory and quite fast
  871. * (though we could implement a specialised variant of the
  872. * has_capability_in_accessdata() code to speed it up)
  873. *
  874. * @param string $capability - name of the capability
  875. * @param array $accessdata - accessdata session array
  876. * @param bool $doanything - if false, ignore do anything
  877. * @param string $sort - sorting fields - prefix each fieldname with "c."
  878. * @param array $fields - additional fields you are interested in...
  879. * @param int $limit - set if you want to limit the number of courses
  880. * @return array $courses - ordered array of course objects - see notes above
  881. *
  882. */
  883. function get_user_courses_bycap($userid, $cap, $accessdata, $doanything, $sort='c.sortorder ASC', $fields=NULL, $limit=0) {
  884. global $CFG;
  885. // Slim base fields, let callers ask for what they need...
  886. $basefields = array('id', 'sortorder', 'shortname', 'idnumber');
  887. if (!is_null($fields)) {
  888. $fields = array_merge($basefields, $fields);
  889. $fields = array_unique($fields);
  890. } else {
  891. $fields = $basefields;
  892. }
  893. // If any of the fields is '*', leave it alone, discarding the rest
  894. // to avoid ambiguous columns under some silly DBs. See MDL-18746 :-D
  895. if (in_array('*', $fields)) {
  896. $fields = array('*');
  897. }
  898. $coursefields = 'c.' .implode(',c.', $fields);
  899. $sort = trim($sort);
  900. if ($sort !== '') {
  901. $sort = "ORDER BY $sort";
  902. }
  903. $sysctx = get_context_instance(CONTEXT_SYSTEM);
  904. if (has_capability_in_accessdata($cap, $sysctx, $accessdata, $doanything)) {
  905. //
  906. // Apparently the user has the cap sitewide, so walk *every* course
  907. // (the cap checks are moderately fast, but this moves massive bandwidth w the db)
  908. // Yuck.
  909. //
  910. $sql = "SELECT $coursefields,
  911. ctx.id AS ctxid, ctx.path AS ctxpath,
  912. ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel,
  913. cc.path AS categorypath
  914. FROM {$CFG->prefix}course c
  915. JOIN {$CFG->prefix}course_categories cc
  916. ON c.category=cc.id
  917. JOIN {$CFG->prefix}context ctx
  918. ON (c.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
  919. $sort ";
  920. $rs = get_recordset_sql($sql);
  921. } else {
  922. //
  923. // narrow down where we have the caps to a few contexts
  924. // this will be a combination of
  925. // - courses where user has an explicit enrolment
  926. // - courses that have an override (any status) on that capability
  927. // - categories where user has the rights (granted status) on that capability
  928. //
  929. $sql = "SELECT ctx.*
  930. FROM {$CFG->prefix}context ctx
  931. WHERE ctx.contextlevel=".CONTEXT_COURSECAT."
  932. ORDER BY ctx.depth";
  933. $rs = get_recordset_sql($sql);
  934. $catpaths = array();
  935. while ($catctx = rs_fetch_next_record($rs)) {
  936. if ($catctx->path != ''
  937. && has_capability_in_accessdata($cap, $catctx, $accessdata, $doanything)) {
  938. $catpaths[] = $catctx->path;
  939. }
  940. }
  941. rs_close($rs);
  942. $catclause = '';
  943. if (count($catpaths)) {
  944. $cc = count($catpaths);
  945. for ($n=0;$n<$cc;$n++) {
  946. $catpaths[$n] = "ctx.path LIKE '{$catpaths[$n]}/%'";
  947. }
  948. $catclause = 'WHERE (' . implode(' OR ', $catpaths) .')';
  949. }
  950. unset($catpaths);
  951. $capany = '';
  952. if ($doanything) {
  953. $capany = " OR rc.capability='moodle/site:doanything'";
  954. }
  955. /// UNION 3 queries:
  956. /// - user role assignments in courses
  957. /// - user capability (override - any status) in courses
  958. /// - user right (granted status) in categories (optionally executed)
  959. /// Enclosing the 3-UNION into an inline_view to avoid column names conflict and making the ORDER BY cross-db
  960. /// and to allow selection of TEXT columns in the query (MSSQL and Oracle limitation). MDL-16209
  961. $sql = "
  962. SELECT $coursefields, ctxid, ctxpath, ctxdepth, ctxlevel, categorypath
  963. FROM (
  964. SELECT c.id,
  965. ctx.id AS ctxid, ctx.path AS ctxpath,
  966. ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel,
  967. cc.path AS categorypath
  968. FROM {$CFG->prefix}course c
  969. JOIN {$CFG->prefix}course_categories cc
  970. ON c.category=cc.id
  971. JOIN {$CFG->prefix}context ctx
  972. ON (c.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
  973. JOIN {$CFG->prefix}role_assignments ra
  974. ON (ra.contextid=ctx.id AND ra.userid=$userid)
  975. UNION
  976. SELECT c.id,
  977. ctx.id AS ctxid, ctx.path AS ctxpath,
  978. ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel,
  979. cc.path AS categorypath
  980. FROM {$CFG->prefix}course c
  981. JOIN {$CFG->prefix}course_categories cc
  982. ON c.category=cc.id
  983. JOIN {$CFG->prefix}context ctx
  984. ON (c.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
  985. JOIN {$CFG->prefix}role_capabilities rc
  986. ON (rc.contextid=ctx.id AND (rc.capability='$cap' $capany)) ";
  987. if (!empty($catclause)) { /// If we have found the right in categories, add child courses here too
  988. $sql .= "
  989. UNION
  990. SELECT c.id,
  991. ctx.id AS ctxid, ctx.path AS ctxpath,
  992. ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel,
  993. cc.path AS categorypath
  994. FROM {$CFG->prefix}course c
  995. JOIN {$CFG->prefix}course_categories cc
  996. ON c.category=cc.id
  997. JOIN {$CFG->prefix}context ctx
  998. ON (c.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
  999. $catclause";
  1000. }
  1001. /// Close the inline_view and join with courses table to get requested $coursefields
  1002. $sql .= "
  1003. ) inline_view
  1004. INNER JOIN {$CFG->prefix}course c
  1005. ON inline_view.id = c.id";
  1006. /// To keep cross-db we need to strip any prefix in the ORDER BY clause for queries using UNION
  1007. $sql .= "
  1008. " . preg_replace('/[a-z]+\./i', '', $sort); /// Add ORDER BY clause
  1009. $rs = get_recordset_sql($sql);
  1010. }
  1011. /// Confirm rights (granted capability) for each course returned
  1012. $courses = array();
  1013. $cc = 0; // keep count
  1014. while ($c = rs_fetch_next_record($rs)) {
  1015. // build the context obj
  1016. $c = make_context_subobj($c);
  1017. if (has_capability_in_accessdata($cap, $c->context, $accessdata, $doanything)) {
  1018. if ($limit > 0 && $cc >= $limit) {
  1019. break;
  1020. }
  1021. $courses[] = $c;
  1022. $cc++;
  1023. }
  1024. }
  1025. rs_close($rs);
  1026. return $courses;
  1027. }
  1028. /**
  1029. * It will return a nested array showing role assignments
  1030. * all relevant role capabilities for the user at
  1031. * site/metacourse/course_category/course levels
  1032. *
  1033. * We do _not_ delve deeper than courses because the number of
  1034. * overrides at the module/block levels is HUGE.
  1035. *
  1036. * [ra] => [/path/] = array(roleid, roleid)
  1037. * [rdef] => [/path/:roleid][capability]=permission
  1038. * [loaded] => array('/path', '/path')
  1039. *
  1040. * @param $userid integer - the id of the user
  1041. *
  1042. */
  1043. function get_user_access_sitewide($userid) {
  1044. global $CFG;
  1045. // this flag has not been set!
  1046. // (not clean install, or upgraded successfully to 1.7 and up)
  1047. if (empty($CFG->rolesactive)) {
  1048. return false;
  1049. }
  1050. /* Get in 3 cheap DB queries...
  1051. * - role assignments - with role_caps
  1052. * - relevant role caps
  1053. * - above this user's RAs
  1054. * - below this user's RAs - limited to course level
  1055. */
  1056. $accessdata = array(); // named list
  1057. $accessdata['ra'] = array();
  1058. $accessdata['rdef'] = array();
  1059. $accessdata['loaded'] = array();
  1060. $sitectx = get_system_context();
  1061. $base = '/'.$sitectx->id;
  1062. //
  1063. // Role assignments - and any rolecaps directly linked
  1064. // because it's cheap to read rolecaps here over many
  1065. // RAs
  1066. //
  1067. $sql = "SELECT ctx.path, ra.roleid, rc.capability, rc.permission
  1068. FROM {$CFG->prefix}role_assignments ra
  1069. JOIN {$CFG->prefix}context ctx
  1070. ON ra.contextid=ctx.id
  1071. LEFT OUTER JOIN {$CFG->prefix}role_capabilities rc
  1072. ON (rc.roleid=ra.roleid AND rc.contextid=ra.contextid)
  1073. WHERE ra.userid = $userid AND ctx.contextlevel <= ".CONTEXT_COURSE."
  1074. ORDER BY ctx.depth, ctx.path, ra.roleid";
  1075. $rs = get_recordset_sql($sql);
  1076. //
  1077. // raparents collects paths & roles we need to walk up
  1078. // the parenthood to build the rdef
  1079. //
  1080. // the array will bulk up a bit with dups
  1081. // which we'll later clear up
  1082. //
  1083. $raparents = array();
  1084. $lastseen = '';
  1085. if ($rs) {
  1086. while ($ra = rs_fetch_next_record($rs)) {
  1087. // RAs leafs are arrays to support multi
  1088. // role assignments...
  1089. if (!isset($accessdata['ra'][$ra->path])) {
  1090. $accessdata['ra'][$ra->path] = array();
  1091. }
  1092. // only add if is not a repeat caused
  1093. // by capability join...
  1094. // (this check is cheaper than in_array())
  1095. if ($lastseen !== $ra->path.':'.$ra->roleid) {
  1096. $lastseen = $ra->path.':'.$ra->roleid;
  1097. array_push($accessdata['ra'][$ra->path], $ra->roleid);
  1098. $parentids = explode('/', $ra->path);
  1099. array_shift($parentids); // drop empty leading "context"
  1100. array_pop($parentids); // drop _this_ context
  1101. if (isset($raparents[$ra->roleid])) {
  1102. $raparents[$ra->roleid] = array_merge($raparents[$ra->roleid],
  1103. $parentids);
  1104. } else {
  1105. $raparents[$ra->roleid] = $parentids;
  1106. }
  1107. }
  1108. // Always add the roleded
  1109. if (!empty($ra->capability)) {
  1110. $k = "{$ra->path}:{$ra->roleid}";
  1111. $accessdata['rdef'][$k][$ra->capability] = $ra->permission;
  1112. }
  1113. }
  1114. unset($ra);
  1115. rs_close($rs);
  1116. }
  1117. // Walk up the tree to grab all the roledefs
  1118. // of interest to our user...
  1119. // NOTE: we use a series of IN clauses here - which
  1120. // might explode on huge sites with very convoluted nesting of
  1121. // categories... - extremely unlikely that the number of categories
  1122. // and roletypes is so large that we hit the limits of IN()
  1123. $clauses = array();
  1124. foreach ($raparents as $roleid=>$contexts) {
  1125. $contexts = implode(',', array_unique($contexts));
  1126. if ($contexts ==! '') {
  1127. $clauses[] = "(roleid=$roleid AND contextid IN ($contexts))";
  1128. }
  1129. }
  1130. $clauses = implode(" OR ", $clauses);
  1131. if ($clauses !== '') {
  1132. $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
  1133. FROM {$CFG->prefix}role_capabilities rc
  1134. JOIN {$CFG->prefix}context ctx
  1135. ON rc.contextid=ctx.id
  1136. WHERE $clauses
  1137. ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
  1138. $rs = get_recordset_sql($sql);
  1139. unset($clauses);
  1140. if ($rs) {
  1141. while ($rd = rs_fetch_next_record($rs)) {
  1142. $k = "{$rd->path}:{$rd->roleid}";
  1143. $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
  1144. }
  1145. unset($rd);
  1146. rs_close($rs);
  1147. }
  1148. }
  1149. //
  1150. // Overrides for the role assignments IN SUBCONTEXTS
  1151. // (though we still do _not_ go below the course level.
  1152. //
  1153. // NOTE that the JOIN w sctx is with 3-way triangulation to
  1154. // catch overrides to the applicable role in any subcontext, based
  1155. // on the path field of the parent.
  1156. //
  1157. $sql = "SELECT sctx.path, ra.roleid,
  1158. ctx.path AS parentpath,
  1159. rco.capability, rco.permission
  1160. FROM {$CFG->prefix}role_assignments ra
  1161. JOIN {$CFG->prefix}context ctx
  1162. ON ra.contextid=ctx.id
  1163. JOIN {$CFG->prefix}context sctx
  1164. ON (sctx.path LIKE " . sql_concat('ctx.path',"'/%'"). " )
  1165. JOIN {$CFG->prefix}role_capabilities rco
  1166. ON (rco.roleid=ra.roleid AND rco.contextid=sctx.id)
  1167. WHERE ra.userid = $userid
  1168. AND ctx.contextlevel <= ".CONTEXT_COURSECAT."
  1169. AND sctx.contextlevel <= ".CONTEXT_COURSE."
  1170. ORDER BY sctx.depth, sctx.path, ra.roleid";
  1171. $rs = get_recordset_sql($sql);
  1172. if ($rs) {
  1173. while ($rd = rs_fetch_next_record($rs)) {
  1174. $k = "{$rd->path}:{$rd->roleid}";
  1175. $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
  1176. }
  1177. unset($rd);
  1178. rs_close($rs);
  1179. }
  1180. return $accessdata;
  1181. }
  1182. /**
  1183. * It add to the access ctrl array the data
  1184. * needed by a user for a given context
  1185. *
  1186. * @param $userid integer - the id of the user
  1187. * @param $context context obj - needs path!
  1188. * @param $accessdata array accessdata array
  1189. */
  1190. function load_subcontext($userid, $context, &$accessdata) {
  1191. global $CFG;
  1192. /* Get the additional RAs and relevant rolecaps
  1193. * - role assignments - with role_caps
  1194. * - relevant role caps
  1195. * - above this user's RAs
  1196. * - below this user's RAs - limited to course level
  1197. */
  1198. $base = "/" . SYSCONTEXTID;
  1199. //
  1200. // Replace $context with the target context we will
  1201. // load. Normally, this will be a course context, but
  1202. // may be a different top-level context.
  1203. //
  1204. // We have 3 cases
  1205. //
  1206. // - Course
  1207. // - BLOCK/PERSON/USER/COURSE(sitecourse) hanging from SYSTEM
  1208. // - BLOCK/MODULE/GROUP hanging from a course
  1209. //
  1210. // For course contexts, we _already_ have the RAs
  1211. // but the cost of re-fetching is minimal so we don't care.
  1212. //
  1213. if ($context->contextlevel !== CONTEXT_COURSE
  1214. && $context->path !== "$base/{$context->id}") {
  1215. // Case BLOCK/MODULE/GROUP hanging from a course
  1216. // Assumption: the course _must_ be our parent
  1217. // If we ever see stuff nested further this needs to
  1218. // change to do 1 query over the exploded path to
  1219. // find out which one is the course
  1220. $courses = explode('/',get_course_from_path($context->path));
  1221. $targetid = array_pop($courses);
  1222. $context = get_context_instance_by_id($targetid);
  1223. }
  1224. //
  1225. // Role assignments in the context and below
  1226. //
  1227. $sql = "SELECT ctx.path, ra.roleid
  1228. FROM {$CFG->prefix}role_assignments ra
  1229. JOIN {$CFG->prefix}context ctx
  1230. ON ra.contextid=ctx.id
  1231. WHERE ra.userid = $userid
  1232. AND (ctx.path = '{$context->path}' OR ctx.path LIKE '{$context->path}/%')
  1233. ORDER BY ctx.depth, ctx.path, ra.roleid";
  1234. $rs = get_recordset_sql($sql);
  1235. //
  1236. // Read in the RAs, preventing duplicates
  1237. //
  1238. $localroles = array();
  1239. $lastseen = '';
  1240. while ($ra = rs_fetch_next_record($rs)) {
  1241. if (!isset($accessdata['ra'][$ra->path])) {
  1242. $accessdata['ra'][$ra->path] = array();
  1243. }
  1244. // only add if is not a repeat caused
  1245. // by capability join...
  1246. // (this check is cheaper than in_array())
  1247. if ($lastseen !== $ra->path.':'.$ra->roleid) {
  1248. $lastseen = $ra->path.':'.$ra->roleid;
  1249. array_push($accessdata['ra'][$ra->path], $ra->roleid);
  1250. array_push($localroles, $ra->roleid);
  1251. }
  1252. }
  1253. rs_close($rs);
  1254. //
  1255. // Walk up and down the tree to grab all the roledefs
  1256. // of interest to our user...
  1257. //
  1258. // NOTES
  1259. // - we use IN() but the number of roles is very limited.
  1260. //
  1261. $courseroles = aggregate_roles_from_accessdata($context, $accessdata);
  1262. // Do we have any interesting "local" roles?
  1263. $localroles = array_diff($localroles,$courseroles); // only "new" local roles
  1264. $wherelocalroles='';
  1265. if (count($localroles)) {
  1266. // Role defs for local roles in 'higher' contexts...
  1267. $contexts = substr($context->path, 1); // kill leading slash
  1268. $contexts = str_replace('/', ',', $contexts);
  1269. $localroleids = implode(',',$localroles);
  1270. $wherelocalroles="OR (rc.roleid IN ({$localroleids})
  1271. AND ctx.id IN ($contexts))" ;
  1272. }
  1273. // We will want overrides for all of them
  1274. $whereroles = '';
  1275. if ($roleids = implode(',',array_merge($courseroles,$localroles))) {
  1276. $whereroles = "rc.roleid IN ($roleids) AND";
  1277. }
  1278. $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
  1279. FROM {$CFG->prefix}role_capabilities rc
  1280. JOIN {$CFG->prefix}context ctx
  1281. ON rc.contextid=ctx.id
  1282. WHERE ($whereroles
  1283. (ctx.id={$context->id} OR ctx.path LIKE '{$context->path}/%'))
  1284. $wherelocalroles
  1285. ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
  1286. $newrdefs = array();
  1287. if ($rs = get_recordset_sql($sql)) {
  1288. while ($rd = rs_fetch_next_record($rs)) {
  1289. $k = "{$rd->path}:{$rd->roleid}";
  1290. if (!array_key_exists($k, $newrdefs)) {
  1291. $newrdefs[$k] = array();
  1292. }
  1293. $newrdefs[$k][$rd->capability] = $rd->permission;
  1294. }
  1295. rs_close($rs);
  1296. } else {
  1297. debugging('Bad SQL encountered!');
  1298. }
  1299. compact_rdefs($newrdefs);
  1300. foreach ($newrdefs as $key=>$value) {
  1301. $accessdata['rdef'][$key] =& $newrdefs[$key];
  1302. }
  1303. // error_log("loaded {$context->path}");
  1304. $accessdata['loaded'][] = $context->path;
  1305. }
  1306. /**
  1307. * It add to the access ctrl array the data
  1308. * needed by a role for a given context.
  1309. *
  1310. * The data is added in the rdef key.
  1311. *
  1312. * This role-centric function is useful for role_switching
  1313. * and to get an overview of what a role gets under a
  1314. * given context and below...
  1315. *
  1316. * @param $roleid integer - the id of the user
  1317. * @param $context context obj - needs path!
  1318. * @param $accessdata accessdata array
  1319. *
  1320. */
  1321. function get_role_access_bycontext($roleid, $context, $accessdata=NULL) {
  1322. global $CFG;
  1323. /* Get the relevant rolecaps into rdef
  1324. * - relevant role caps
  1325. * - at ctx and above
  1326. * - below this ctx
  1327. */
  1328. if (is_null($accessdata)) {
  1329. $accessdata = array(); // named list
  1330. $accessdata['ra'] = array();
  1331. $accessdata['rdef'] = array();
  1332. $accessdata['loaded'] = array();
  1333. }
  1334. $contexts = substr($context->path, 1); // kill leading slash
  1335. $contexts = str_replace('/', ',', $contexts);
  1336. //
  1337. // Walk up and down the tree to grab all the roledefs
  1338. // of interest to our role...
  1339. //
  1340. // NOTE: we use an IN clauses here - which
  1341. // might explode on huge sites with very convoluted nesting of
  1342. // categories... - extremely unlikely that the number of nested
  1343. // categories is so large that we hit the limits of IN()
  1344. //
  1345. $sql = "SELECT ctx.path, rc.capability, rc.permission
  1346. FROM {$CFG->prefix}role_capabilities rc
  1347. JOIN {$CFG->prefix}context ctx
  1348. ON rc.contextid=ctx.id
  1349. WHERE rc.roleid=$roleid AND
  1350. ( ctx.id IN ($contexts) OR
  1351. ctx.path LIKE '{$context->path}/%' )
  1352. ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
  1353. $rs = get_recordset_sql($sql);
  1354. while ($rd = rs_fetch_next_record($rs)) {
  1355. $k = "{$rd->path}:{$roleid}";
  1356. $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
  1357. }
  1358. rs_close($rs);
  1359. return $accessdata;
  1360. }
  1361. /**
  1362. * Load accessdata for a user
  1363. * into the $ACCESS global
  1364. *
  1365. * Used by has_capability() - but feel free
  1366. * to call it if you are about to run a BIG
  1367. * cron run across a bazillion users.
  1368. *
  1369. */
  1370. function load_user_accessdata($userid) {
  1371. global $ACCESS,$CFG;
  1372. $base = '/'.SYSCONTEXTID;
  1373. $accessdata = get_user_access_sitewide($userid);
  1374. $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
  1375. //
  1376. // provide "default role" & set 'dr'
  1377. //
  1378. if (!empty($CFG->defaultuserroleid)) {
  1379. $accessdata = get_role_access($CFG->defaultuserroleid, $accessdata);
  1380. if (!isset($accessdata['ra'][$base])) {
  1381. $accessdata['ra'][$base] = array($CFG->defaultuserroleid);
  1382. } else {
  1383. array_push($accessdata['ra'][$base], $CFG->defaultuserroleid);
  1384. }
  1385. $accessdata['dr'] = $CFG->defaultuserroleid;
  1386. }
  1387. //
  1388. // provide "default frontpage role"
  1389. //
  1390. if (!empty($CFG->defaultfrontpageroleid)) {
  1391. $base = '/'. SYSCONTEXTID .'/'. $frontpagecontext->id;
  1392. $accessdata = get_default_frontpage_role_access($CFG->defaultfrontpageroleid, $accessdata);
  1393. if (!isset($accessdata['ra'][$base])) {
  1394. $accessdata['ra'][$base] = array($CFG->defaultfrontpageroleid);
  1395. } else {
  1396. array_push($accessdata['ra'][$base], $CFG->defaultfrontpageroleid);
  1397. }
  1398. }
  1399. // for dirty timestamps in cron
  1400. $accessdata['time'] = time();
  1401. $ACCESS[$userid] = $accessdata;
  1402. compact_rdefs($ACCESS[$userid]['rdef']);
  1403. return true;
  1404. }
  1405. /**
  1406. * Use shared copy of role definistions stored in $RDEFS;
  1407. * @param array $rdefs array of role definitions in contexts
  1408. */
  1409. function compact_rdefs(&$rdefs) {
  1410. global $RDEFS;
  1411. /*
  1412. * This is a basic sharing only, we could also
  1413. * use md5 sums of values. The main purpose is to
  1414. * reduce mem in cron jobs - many users in $ACCESS array.
  1415. */
  1416. foreach ($rdefs as $key => $value) {
  1417. if (!array_key_exists($key, $RDEFS)) {
  1418. $RDEFS[$key] = $rdefs[$key];
  1419. }
  1420. $rdefs[$key] =& $RDEFS[$key];
  1421. }
  1422. }
  1423. /**
  1424. * A convenience function to completely load all the capabilities
  1425. * for the current user. This is what gets called from complete_user_login()
  1426. * for example. Call it only _after_ you've setup $USER and called
  1427. * check_enrolment_plugins();
  1428. *
  1429. */
  1430. function load_all_capabilities() {
  1431. global $USER, $CFG, $DIRTYCONTEXTS;
  1432. $base = '/'.SYSCONTEXTID;
  1433. if (isguestuser()) {
  1434. $guest = get_guest_role();
  1435. // Load the rdefs
  1436. $USER->access = get_role_access($guest->id);
  1437. // Put the ghost enrolment in place...
  1438. $USER->access['ra'][$base] = array($guest->id);
  1439. } else if (isloggedin()) {
  1440. $accessdata = get_user_access_sitewide($USER->id);
  1441. //
  1442. // provide "default role" & set 'dr'
  1443. //
  1444. if (!empty($CFG->defaultuserroleid)) {
  1445. $accessdata = get_role_access($CFG->defaultuserroleid, $accessdata);
  1446. if (!isset($accessdata['ra'][$base])) {
  1447. $accessdata['ra'][$base] = array($CFG->defaultuserroleid);
  1448. } else {
  1449. array_push($accessdata['ra'][$base], $CFG->defaultuserroleid);
  1450. }
  1451. $accessdata['dr'] = $CFG->defaultuserroleid;
  1452. }
  1453. $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
  1454. //
  1455. // provide "default frontpage role"
  1456. //
  1457. if (!empty($CFG->defaultfrontpageroleid)) {
  1458. $base = '/'. SYSCONTEXTID .'/'. $frontpagecontext->id;
  1459. $accessdata = get_default_frontpage_role_access($CFG->defaultfrontpageroleid, $accessdata);
  1460. if (!isset($accessdata['ra'][$base])) {
  1461. $accessdata['ra'][$base] = array($CFG->defaultfrontpageroleid);
  1462. } else {
  1463. array_push($accessdata['ra'][$base], $CFG->defaultfrontpageroleid);
  1464. }
  1465. }
  1466. $USER->access = $accessdata;
  1467. } else if (!empty($CFG->notloggedinroleid)) {
  1468. $USER->access = get_role_access($CFG->notloggedinroleid);
  1469. $USER->access['ra'][$base] = array($CFG->notloggedinroleid);
  1470. }
  1471. // Timestamp to read dirty context timestamps later
  1472. $USER->access['time'] = time();
  1473. $DIRTYCONTEXTS = array();
  1474. // Clear to force a refresh
  1475. unset($USER->mycourses);
  1476. }
  1477. /**
  1478. * A convenience function to completely reload all the capabilities
  1479. * for the current user when roles have been updated in a relevant
  1480. * context -- but PRESERVING switchroles and loginas.
  1481. *
  1482. * That is - completely transparent to the user.
  1483. *
  1484. * Note: rewrites $USER->access completely.
  1485. *
  1486. */
  1487. function reload_all_capabilities() {
  1488. global $USER,$CFG;
  1489. // error_log("reloading");
  1490. // copy switchroles
  1491. $sw = array();
  1492. if (isset($USER->access['rsw'])) {
  1493. $sw = $USER->access['rsw'];
  1494. // error_log(print_r($sw,1));
  1495. }
  1496. unset($USER->access);
  1497. unset($USER->mycourses);
  1498. load_all_capabilities();
  1499. foreach ($sw as $path => $roleid) {
  1500. $context = get_record('context', 'path', $path);
  1501. role_switch($roleid, $context);
  1502. }
  1503. }
  1504. /*
  1505. * Adds a temp role to an accessdata array.
  1506. *
  1507. * Useful for the "temporary guest" access
  1508. * we grant to logged-in users.
  1509. *
  1510. * Note - assumes a course context!
  1511. *
  1512. */
  1513. function load_temp_role($context, $roleid, $accessdata) {
  1514. global $CFG;
  1515. //
  1516. // Load rdefs for the role in -
  1517. // - this context
  1518. // - all the parents
  1519. // - and below - IOWs overrides...
  1520. //
  1521. // turn the path into a list of context ids
  1522. $contexts = substr($context->path, 1); // kill leading slash
  1523. $contexts = str_replace('/', ',', $contexts);
  1524. $sql = "SELECT ctx.path,
  1525. rc.capability, rc.permission
  1526. FROM {$CFG->prefix}context ctx
  1527. JOIN {$CFG->prefix}role_capabilities rc
  1528. ON rc.contextid=ctx.id
  1529. WHERE (ctx.id IN ($contexts)
  1530. OR ctx.path LIKE '{$context->path}/%')
  1531. AND rc.roleid = {$roleid}
  1532. ORDER BY ctx.depth, ctx.path";
  1533. $rs = get_recordset_sql($sql);
  1534. while ($rd = rs_fetch_next_record($rs)) {
  1535. $k = "{$rd->path}:{$roleid}";
  1536. $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
  1537. }
  1538. rs_close($rs);
  1539. //
  1540. // Say we loaded everything for the course context
  1541. // - which we just did - if the user gets a proper
  1542. // RA in this session, this data will need to be reloaded,
  1543. // but that is handled by the complete accessdata reload
  1544. //
  1545. array_push($accessdata['loaded'], $context->path);
  1546. //
  1547. // Add the ghost RA
  1548. //
  1549. if (isset($accessdata['ra'][$context->path])) {
  1550. array_push($accessdata['ra'][$context->path], $roleid);
  1551. } else {
  1552. $accessdata['ra'][$context->path] = array($roleid);
  1553. }
  1554. return $accessdata;
  1555. }
  1556. /**
  1557. * Check all the login enrolment information for the given user object
  1558. * by querying the enrolment plugins
  1559. */
  1560. function check_enrolment_plugins(&$user) {
  1561. global $CFG;
  1562. static $inprogress; // To prevent this function being called more than once in an invocation
  1563. if (!empty($inprogress[$user->id])) {
  1564. return;
  1565. }
  1566. $inprogress[$user->id] = true; // Set the flag
  1567. require_once($CFG->dirroot .'/enrol/enrol.class.php');
  1568. if (!($plugins = explode(',', $CFG->enrol_plugins_enabled))) {
  1569. $plugins = array($CFG->enrol);
  1570. }
  1571. foreach ($plugins as $plugin) {
  1572. $enrol = enrolment_factory::factory($plugin);
  1573. if (method_exists($enrol, 'setup_enrolments')) { /// Plugin supports Roles (Moodle 1.7 and later)
  1574. $enrol->setup_enrolments($user);
  1575. } else { /// Run legacy enrolment methods
  1576. if (method_exists($enrol, 'get_student_courses')) {
  1577. $enrol->get_student_courses($user);
  1578. }
  1579. if (method_exists($enrol, 'get_teacher_courses')) {
  1580. $enrol->get_teacher_courses($user);
  1581. }
  1582. /// deal with $user->students and $user->teachers stuff
  1583. unset($user->student);
  1584. unset($user->teacher);
  1585. }
  1586. unset($enrol);
  1587. }
  1588. unset($inprogress[$user->id]); // Unset the flag
  1589. }
  1590. /**
  1591. * Installs the roles system.
  1592. * This function runs on a fresh install as well as on an upgrade from the old
  1593. * hard-coded student/teacher/admin etc. roles to the new roles system.
  1594. */
  1595. function moodle_install_roles() {
  1596. global $CFG, $db;
  1597. /// Create a system wide context for assignemnt.
  1598. $systemcontext = $context = get_context_instance(CONTEXT_SYSTEM);
  1599. /// Create default/legacy roles and capabilities.
  1600. /// (1 legacy capability per legacy role at system level).
  1601. $adminrole = create_role(addslashes(get_string('administrator')), 'admin',
  1602. addslashes(get_string('administratordescription')), 'moodle/legacy:admin');
  1603. $coursecreatorrole = create_role(addslashes(get_string('coursecreators')), 'coursecreator',
  1604. addslashes(get_string('coursecreatorsdescription')), 'moodle/legacy:coursecreator');
  1605. $editteacherrole = create_role(addslashes(get_string('defaultcourseteacher')), 'editingteacher',
  1606. addslashes(get_string('defaultcourseteacherdescription')), 'moodle/legacy:editingteacher');
  1607. $noneditteacherrole = create_role(addslashes(get_string('noneditingteacher')), 'teacher',
  1608. addslashes(get_string('noneditingteacherdescription')), 'moodle/legacy:teacher');
  1609. $studentrole = create_role(addslashes(get_string('defaultcoursestudent')), 'student',
  1610. addslashes(get_string('defaultcoursestudentdescription')), 'moodle/legacy:student');
  1611. $guestrole = create_role(addslashes(get_string('guest')), 'guest',
  1612. addslashes(get_string('guestdescription')), 'moodle/legacy:guest');
  1613. $userrole = create_role(addslashes(get_string('authenticateduser')), 'user',
  1614. addslashes(get_string('authenticateduserdescription')), 'moodle/legacy:user');
  1615. /// Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles
  1616. if (!assign_capability('moodle/site:doanything', CAP_ALLOW, $adminrole, $systemcontext->id)) {
  1617. error('Could not assign moodle/site:doanything to the admin role');
  1618. }
  1619. if (!update_capabilities()) {
  1620. error('Had trouble upgrading the core capabilities for the Roles System');
  1621. }
  1622. /// Look inside user_admin, user_creator, user_teachers, user_students and
  1623. /// assign above new roles. If a user has both teacher and student role,
  1624. /// only teacher role is assigned. The assignment should be system level.
  1625. $dbtables = $db->MetaTables('TABLES');
  1626. /// Set up the progress bar
  1627. $usertables = array('user_admins', 'user_coursecreators', 'user_teachers', 'user_students');
  1628. $totalcount = $progresscount = 0;
  1629. foreach ($usertables as $usertable) {
  1630. if (in_array($CFG->prefix.$usertable, $dbtables)) {
  1631. $totalcount += count_records($usertable);
  1632. }
  1633. }
  1634. print_progress(0, $totalcount, 5, 1, 'Processing role assignments');
  1635. /// Upgrade the admins.
  1636. /// Sort using id ASC, first one is primary admin.
  1637. if (in_array($CFG->prefix.'user_admins', $dbtables)) {
  1638. if ($rs = get_recordset_sql('SELECT * from '.$CFG->prefix.'user_admins ORDER BY ID ASC')) {
  1639. while ($admin = rs_fetch_next_record($rs)) {
  1640. role_assign($adminrole, $admin->userid, 0, $systemcontext->id);
  1641. $progresscount++;
  1642. print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
  1643. }
  1644. rs_close($rs);
  1645. }
  1646. } else {
  1647. // This is a fresh install.
  1648. }
  1649. /// Upgrade course creators.
  1650. if (in_array($CFG->prefix.'user_coursecreators', $dbtables)) {
  1651. if ($rs = get_recordset('user_coursecreators')) {
  1652. while ($coursecreator = rs_fetch_next_record($rs)) {
  1653. role_assign($coursecreatorrole, $coursecreator->userid, 0, $systemcontext->id);
  1654. $progresscount++;
  1655. print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
  1656. }
  1657. rs_close($rs);
  1658. }
  1659. }
  1660. /// Upgrade editting teachers and non-editting teachers.
  1661. if (in_array($CFG->prefix.'user_teachers', $dbtables)) {
  1662. if ($rs = get_recordset('user_teachers')) {
  1663. while ($teacher = rs_fetch_next_record($rs)) {
  1664. // removed code here to ignore site level assignments
  1665. // since the contexts are separated now
  1666. // populate the user_lastaccess table
  1667. $access = new object();
  1668. $access->timeaccess = $teacher->timeaccess;
  1669. $access->userid = $teacher->userid;
  1670. $access->courseid = $teacher->course;
  1671. insert_record('user_lastaccess', $access);
  1672. // assign the default student role
  1673. $coursecontext = get_context_instance(CONTEXT_COURSE, $teacher->course); // needs cache
  1674. // hidden teacher
  1675. if ($teacher->authority == 0) {
  1676. $hiddenteacher = 1;
  1677. } else {
  1678. $hiddenteacher = 0;
  1679. }
  1680. if ($teacher->editall) { // editting teacher
  1681. role_assign($editteacherrole, $teacher->userid, 0, $coursecontext->id, $teacher->timestart, $teacher->timeend, $hiddenteacher, $teacher->enrol, $teacher->timemodified);
  1682. } else {
  1683. role_assign($noneditteacherrole, $teacher->userid, 0, $coursecontext->id, $teacher->timestart, $teacher->timeend, $hiddenteacher, $teacher->enrol, $teacher->timemodified);
  1684. }
  1685. $progresscount++;
  1686. print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
  1687. }
  1688. rs_close($rs);
  1689. }
  1690. }
  1691. /// Upgrade students.
  1692. if (in_array($CFG->prefix.'user_students', $dbtables)) {
  1693. if ($rs = get_recordset('user_students')) {
  1694. while ($student = rs_fetch_next_record($rs)) {
  1695. // populate the user_lastaccess table
  1696. $access = new object;
  1697. $access->timeaccess = $student->timeaccess;
  1698. $access->userid = $student->userid;
  1699. $access->courseid = $student->course;
  1700. insert_record('user_lastaccess', $access);
  1701. // assign the default student role
  1702. $coursecontext = get_context_instance(CONTEXT_COURSE, $student->course);
  1703. role_assign($studentrole, $student->userid, 0, $coursecontext->id, $student->timestart, $student->timeend, 0, $student->enrol, $student->time);
  1704. $progresscount++;
  1705. print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
  1706. }
  1707. rs_close($rs);
  1708. }
  1709. }
  1710. /// Upgrade guest (only 1 entry).
  1711. if ($guestuser = get_record('user', 'username', 'guest')) {
  1712. role_assign($guestrole, $guestuser->id, 0, $systemcontext->id);
  1713. }
  1714. print_progress($totalcount, $totalcount, 5, 1, 'Processing role assignments');
  1715. /// Insert the correct records for legacy roles
  1716. allow_assign($adminrole, $adminrole);
  1717. allow_assign($adminrole, $coursecreatorrole);
  1718. allow_assign($adminrole, $noneditteacherrole);
  1719. allow_assign($adminrole, $editteacherrole);
  1720. allow_assign($adminrole, $studentrole);
  1721. allow_assign($adminrole, $guestrole);
  1722. allow_assign($coursecreatorrole, $noneditteacherrole);
  1723. allow_assign($coursecreatorrole, $editteacherrole);
  1724. allow_assign($coursecreatorrole, $studentrole);
  1725. allow_assign($coursecreatorrole, $guestrole);
  1726. allow_assign($editteacherrole, $noneditteacherrole);
  1727. allow_assign($editteacherrole, $studentrole);
  1728. allow_assign($editteacherrole, $guestrole);
  1729. /// Set up default allow override matrix
  1730. allow_override($adminrole, $adminrole);
  1731. allow_override($adminrole, $coursecreatorrole);
  1732. allow_override($adminrole, $noneditteacherrole);
  1733. allow_override($adminrole, $editteacherrole);
  1734. allow_override($adminrole, $studentrole);
  1735. allow_override($adminrole, $guestrole);
  1736. allow_override($adminrole, $userrole);
  1737. //See MDL-15841
  1738. //allow_override($editteacherrole, $noneditteacherrole);
  1739. //allow_override($editteacherrole, $studentrole);
  1740. //allow_override($editteacherrole, $guestrole);
  1741. /// Delete the old user tables when we are done
  1742. $tables = array('user_students', 'user_teachers', 'user_coursecreators', 'user_admins');
  1743. foreach ($tables as $tablename) {
  1744. $table = new XMLDBTable($tablename);
  1745. if (table_exists($table)) {
  1746. drop_table($table);
  1747. }
  1748. }
  1749. }
  1750. /**
  1751. * Returns array of all legacy roles.
  1752. */
  1753. function get_legacy_roles() {
  1754. return array(
  1755. 'admin' => 'moodle/legacy:admin',
  1756. 'coursecreator' => 'moodle/legacy:coursecreator',
  1757. 'editingteacher' => 'moodle/legacy:editingteacher',
  1758. 'teacher' => 'moodle/legacy:teacher',
  1759. 'student' => 'moodle/legacy:student',
  1760. 'guest' => 'moodle/legacy:guest',
  1761. 'user' => 'moodle/legacy:user'
  1762. );
  1763. }
  1764. function get_legacy_type($roleid) {
  1765. $sitecontext = get_context_instance(CONTEXT_SYSTEM);
  1766. $legacyroles = get_legacy_roles();
  1767. $result = '';
  1768. foreach($legacyroles as $ltype=>$lcap) {
  1769. $localoverride = get_local_override($roleid, $sitecontext->id, $lcap);
  1770. if (!empty($localoverride->permission) and $localoverride->permission == CAP_ALLOW) {
  1771. //choose first selected legacy capability - reset the rest
  1772. if (empty($result)) {
  1773. $result = $ltype;
  1774. } else {
  1775. unassign_capability($lcap, $roleid);
  1776. }
  1777. }
  1778. }
  1779. return $result;
  1780. }
  1781. /**
  1782. * Assign the defaults found in this capabality definition to roles that have
  1783. * the corresponding legacy capabilities assigned to them.
  1784. * @param $legacyperms - an array in the format (example):
  1785. * 'guest' => CAP_PREVENT,
  1786. * 'student' => CAP_ALLOW,
  1787. * 'teacher' => CAP_ALLOW,
  1788. * 'editingteacher' => CAP_ALLOW,
  1789. * 'coursecreator' => CAP_ALLOW,
  1790. * 'admin' => CAP_ALLOW
  1791. * @return boolean - success or failure.
  1792. */
  1793. function assign_legacy_capabilities($capability, $legacyperms) {
  1794. $legacyroles = get_legacy_roles();
  1795. foreach ($legacyperms as $type => $perm) {
  1796. $systemcontext = get_context_instance(CONTEXT_SYSTEM);
  1797. if (!array_key_exists($type, $legacyroles)) {
  1798. error('Incorrect legacy role definition for type: '.$type);
  1799. }
  1800. if ($roles = get_roles_with_capability($legacyroles[$type], CAP_ALLOW)) {
  1801. foreach ($roles as $role) {
  1802. // Assign a site level capability.
  1803. if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
  1804. return false;
  1805. }
  1806. }
  1807. }
  1808. }
  1809. return true;
  1810. }
  1811. /**
  1812. * Checks to see if a capability is a legacy capability.
  1813. * @param $capabilityname
  1814. * @return boolean
  1815. */
  1816. function islegacy($capabilityname) {
  1817. if (strpos($capabilityname, 'moodle/legacy') === 0) {
  1818. return true;
  1819. } else {
  1820. return false;
  1821. }
  1822. }
  1823. /**********************************
  1824. * Context Manipulation functions *
  1825. **********************************/
  1826. /**
  1827. * Create a new context record for use by all roles-related stuff
  1828. * assumes that the caller has done the homework.
  1829. *
  1830. * @param $level
  1831. * @param $instanceid
  1832. *
  1833. * @return object newly created context
  1834. */
  1835. function create_context($contextlevel, $instanceid) {
  1836. global $CFG;
  1837. if ($contextlevel == CONTEXT_SYSTEM) {
  1838. return create_system_context();
  1839. }
  1840. $context = new object();
  1841. $context->contextlevel = $contextlevel;
  1842. $context->instanceid = $instanceid;
  1843. // Define $context->path based on the parent
  1844. // context. In other words... Who is your daddy?
  1845. $basepath = '/' . SYSCONTEXTID;
  1846. $basedepth = 1;
  1847. $result = true;
  1848. switch ($contextlevel) {
  1849. case CONTEXT_COURSECAT:
  1850. $sql = "SELECT ctx.path, ctx.depth
  1851. FROM {$CFG->prefix}context ctx
  1852. JOIN {$CFG->prefix}course_categories cc
  1853. ON (cc.parent=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT.")
  1854. WHERE cc.id={$instanceid}";
  1855. if ($p = get_record_sql($sql)) {
  1856. $basepath = $p->path;
  1857. $basedepth = $p->depth;
  1858. } else if ($category = get_record('course_categories', 'id', $instanceid)) {
  1859. if (empty($category->parent)) {
  1860. // ok - this is a top category
  1861. } else if ($parent = get_context_instance(CONTEXT_COURSECAT, $category->parent)) {
  1862. $basepath = $parent->path;
  1863. $basedepth = $parent->depth;
  1864. } else {
  1865. // wrong parent category - no big deal, this can be fixed later
  1866. $basepath = null;
  1867. $basedepth = 0;
  1868. }
  1869. } else {
  1870. // incorrect category id
  1871. $result = false;
  1872. }
  1873. break;
  1874. case CONTEXT_COURSE:
  1875. $sql = "SELECT ctx.path, ctx.depth
  1876. FROM {$CFG->prefix}context ctx
  1877. JOIN {$CFG->prefix}course c
  1878. ON (c.category=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT.")
  1879. WHERE c.id={$instanceid} AND c.id !=" . SITEID;
  1880. if ($p = get_record_sql($sql)) {
  1881. $basepath = $p->path;
  1882. $basedepth = $p->depth;
  1883. } else if ($course = get_record('course', 'id', $instanceid)) {
  1884. if ($course->id == SITEID) {
  1885. //ok - no parent category
  1886. } else if ($parent = get_context_instance(CONTEXT_COURSECAT, $course->category)) {
  1887. $basepath = $parent->path;
  1888. $basedepth = $parent->depth;
  1889. } else {
  1890. // wrong parent category of course - no big deal, this can be fixed later
  1891. $basepath = null;
  1892. $basedepth = 0;
  1893. }
  1894. } else if ($instanceid == SITEID) {
  1895. // no errors for missing site course during installation
  1896. return false;
  1897. } else {
  1898. // incorrect course id
  1899. $result = false;
  1900. }
  1901. break;
  1902. case CONTEXT_MODULE:
  1903. $sql = "SELECT ctx.path, ctx.depth
  1904. FROM {$CFG->prefix}context ctx
  1905. JOIN {$CFG->prefix}course_modules cm
  1906. ON (cm.course=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
  1907. WHERE cm.id={$instanceid}";
  1908. if ($p = get_record_sql($sql)) {
  1909. $basepath = $p->path;
  1910. $basedepth = $p->depth;
  1911. } else if ($cm = get_record('course_modules', 'id', $instanceid)) {
  1912. if ($parent = get_context_instance(CONTEXT_COURSE, $cm->course)) {
  1913. $basepath = $parent->path;
  1914. $basedepth = $parent->depth;
  1915. } else {
  1916. // course does not exist - modules can not exist without a course
  1917. $result = false;
  1918. }
  1919. } else {
  1920. // cm does not exist
  1921. $result = false;
  1922. }
  1923. break;
  1924. case CONTEXT_BLOCK:
  1925. // Only non-pinned & course-page based
  1926. $sql = "SELECT ctx.path, ctx.depth
  1927. FROM {$CFG->prefix}context ctx
  1928. JOIN {$CFG->prefix}block_instance bi
  1929. ON (bi.pageid=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
  1930. WHERE bi.id={$instanceid} AND bi.pagetype='course-view'";
  1931. if ($p = get_record_sql($sql)) {
  1932. $basepath = $p->path;
  1933. $basedepth = $p->depth;
  1934. } else if ($bi = get_record('block_instance', 'id', $instanceid)) {
  1935. if ($bi->pagetype != 'course-view') {
  1936. // ok - not a course block
  1937. } else if ($parent = get_context_instance(CONTEXT_COURSE, $bi->pageid)) {
  1938. $basepath = $parent->path;
  1939. $basedepth = $parent->depth;
  1940. } else {
  1941. // parent course does not exist - course blocks can not exist without a course
  1942. $result = false;
  1943. }
  1944. } else {
  1945. // block does not exist
  1946. $result = false;
  1947. }
  1948. break;
  1949. case CONTEXT_USER:
  1950. // default to basepath
  1951. break;
  1952. }
  1953. // if grandparents unknown, maybe rebuild_context_path() will solve it later
  1954. if ($basedepth != 0) {
  1955. $context->depth = $basedepth+1;
  1956. }
  1957. if ($result and $id = insert_record('context', $context)) {
  1958. // can't set the full path till we know the id!
  1959. if ($basedepth != 0 and !empty($basepath)) {
  1960. set_field('context', 'path', $basepath.'/'. $id, 'id', $id);
  1961. }
  1962. return get_context_instance_by_id($id);
  1963. } else {
  1964. debugging('Error: could not insert new context level "'.
  1965. s($contextlevel).'", instance "'.
  1966. s($instanceid).'".');
  1967. return false;
  1968. }
  1969. }
  1970. /**
  1971. * This hacky function is needed because we can not change system context instanceid using normal upgrade routine.
  1972. */
  1973. function get_system_context($cache=true) {
  1974. static $cached = null;
  1975. if ($cache and defined('SYSCONTEXTID')) {
  1976. if (is_null($cached)) {
  1977. $cached = new object();
  1978. $cached->id = SYSCONTEXTID;
  1979. $cached->contextlevel = CONTEXT_SYSTEM;
  1980. $cached->instanceid = 0;
  1981. $cached->path = '/'.SYSCONTEXTID;
  1982. $cached->depth = 1;
  1983. }
  1984. return $cached;
  1985. }
  1986. if (!$context = get_record('context', 'contextlevel', CONTEXT_SYSTEM)) {
  1987. $context = new object();
  1988. $context->contextlevel = CONTEXT_SYSTEM;
  1989. $context->instanceid = 0;
  1990. $context->depth = 1;
  1991. $context->path = NULL; //not known before insert
  1992. if (!$context->id = insert_record('context', $context)) {
  1993. // better something than nothing - let's hope it will work somehow
  1994. if (!defined('SYSCONTEXTID')) {
  1995. define('SYSCONTEXTID', 1);
  1996. }
  1997. debugging('Can not create system context');
  1998. $context->id = SYSCONTEXTID;
  1999. $context->path = '/'.SYSCONTEXTID;
  2000. return $context;
  2001. }
  2002. }
  2003. if (!isset($context->depth) or $context->depth != 1 or $context->instanceid != 0 or $context->path != '/'.$context->id) {
  2004. $context->instanceid = 0;
  2005. $context->path = '/'.$context->id;
  2006. $context->depth = 1;
  2007. update_record('context', $context);
  2008. }
  2009. if (!defined('SYSCONTEXTID')) {
  2010. define('SYSCONTEXTID', $context->id);
  2011. }
  2012. $cached = $context;
  2013. return $cached;
  2014. }
  2015. /**
  2016. * Remove a context record and any dependent entries,
  2017. * removes context from static context cache too
  2018. * @param $level
  2019. * @param $instanceid
  2020. *
  2021. * @return bool properly deleted
  2022. */
  2023. function delete_context($contextlevel, $instanceid) {
  2024. global $context_cache, $context_cache_id;
  2025. // do not use get_context_instance(), because the related object might not exist,
  2026. // or the context does not exist yet and it would be created now
  2027. if ($context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instanceid)) {
  2028. $result = delete_records('role_assignments', 'contextid', $context->id) &&
  2029. delete_records('role_capabilities', 'contextid', $context->id) &&
  2030. delete_records('role_names', 'contextid', $context->id) &&
  2031. delete_records('context', 'id', $context->id);
  2032. // do not mark dirty contexts if parents unknown
  2033. if (!is_null($context->path) and $context->depth > 0) {
  2034. mark_context_dirty($context->path);
  2035. }
  2036. // purge static context cache if entry present
  2037. unset($context_cache[$contextlevel][$instanceid]);
  2038. unset($context_cache_id[$context->id]);
  2039. return $result;
  2040. } else {
  2041. return true;
  2042. }
  2043. }
  2044. /**
  2045. * Precreates all contexts including all parents
  2046. * @param int $contextlevel, empty means all
  2047. * @param bool $buildpaths update paths and depths
  2048. * @param bool $feedback show sql feedback
  2049. * @return void
  2050. */
  2051. function create_contexts($contextlevel=null, $buildpaths=true, $feedback=false) {
  2052. global $CFG;
  2053. //make sure system context exists
  2054. $syscontext = get_system_context(false);
  2055. if (empty($contextlevel) or $contextlevel == CONTEXT_COURSECAT
  2056. or $contextlevel == CONTEXT_COURSE
  2057. or $contextlevel == CONTEXT_MODULE
  2058. or $contextlevel == CONTEXT_BLOCK) {
  2059. $sql = "INSERT INTO {$CFG->prefix}context (contextlevel, instanceid)
  2060. SELECT ".CONTEXT_COURSECAT.", cc.id
  2061. FROM {$CFG->prefix}course_categories cc
  2062. WHERE NOT EXISTS (SELECT 'x'
  2063. FROM {$CFG->prefix}context cx
  2064. WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
  2065. execute_sql($sql, $feedback);
  2066. }
  2067. if (empty($contextlevel) or $contextlevel == CONTEXT_COURSE
  2068. or $contextlevel == CONTEXT_MODULE
  2069. or $contextlevel == CONTEXT_BLOCK) {
  2070. $sql = "INSERT INTO {$CFG->prefix}context (contextlevel, instanceid)
  2071. SELECT ".CONTEXT_COURSE.", c.id
  2072. FROM {$CFG->prefix}course c
  2073. WHERE NOT EXISTS (SELECT 'x'
  2074. FROM {$CFG->prefix}context cx
  2075. WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE.")";
  2076. execute_sql($sql, $feedback);
  2077. }
  2078. if (empty($contextlevel) or $contextlevel == CONTEXT_MODULE) {
  2079. $sql = "INSERT INTO {$CFG->prefix}context (contextlevel, instanceid)
  2080. SELECT ".CONTEXT_MODULE.", cm.id
  2081. FROM {$CFG->prefix}course_modules cm
  2082. WHERE NOT EXISTS (SELECT 'x'
  2083. FROM {$CFG->prefix}context cx
  2084. WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE.")";
  2085. execute_sql($sql, $feedback);
  2086. }
  2087. if (empty($contextlevel) or $contextlevel == CONTEXT_BLOCK) {
  2088. $sql = "INSERT INTO {$CFG->prefix}context (contextlevel, instanceid)
  2089. SELECT ".CONTEXT_BLOCK.", bi.id
  2090. FROM {$CFG->prefix}block_instance bi
  2091. WHERE NOT EXISTS (SELECT 'x'
  2092. FROM {$CFG->prefix}context cx
  2093. WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")";
  2094. execute_sql($sql, $feedback);
  2095. }
  2096. if (empty($contextlevel) or $contextlevel == CONTEXT_USER) {
  2097. $sql = "INSERT INTO {$CFG->prefix}context (contextlevel, instanceid)
  2098. SELECT ".CONTEXT_USER.", u.id
  2099. FROM {$CFG->prefix}user u
  2100. WHERE u.deleted=0
  2101. AND NOT EXISTS (SELECT 'x'
  2102. FROM {$CFG->prefix}context cx
  2103. WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER.")";
  2104. execute_sql($sql, $feedback);
  2105. }
  2106. if ($buildpaths) {
  2107. build_context_path(false, $feedback);
  2108. }
  2109. }
  2110. /**
  2111. * Remove stale context records
  2112. *
  2113. * @return bool
  2114. */
  2115. function cleanup_contexts() {
  2116. global $CFG;
  2117. $sql = " SELECT c.contextlevel,
  2118. c.instanceid AS instanceid
  2119. FROM {$CFG->prefix}context c
  2120. LEFT OUTER JOIN {$CFG->prefix}course_categories t
  2121. ON c.instanceid = t.id
  2122. WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_COURSECAT . "
  2123. UNION
  2124. SELECT c.contextlevel,
  2125. c.instanceid
  2126. FROM {$CFG->prefix}context c
  2127. LEFT OUTER JOIN {$CFG->prefix}course t
  2128. ON c.instanceid = t.id
  2129. WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_COURSE . "
  2130. UNION
  2131. SELECT c.contextlevel,
  2132. c.instanceid
  2133. FROM {$CFG->prefix}context c
  2134. LEFT OUTER JOIN {$CFG->prefix}course_modules t
  2135. ON c.instanceid = t.id
  2136. WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_MODULE . "
  2137. UNION
  2138. SELECT c.contextlevel,
  2139. c.instanceid
  2140. FROM {$CFG->prefix}context c
  2141. LEFT OUTER JOIN {$CFG->prefix}user t
  2142. ON c.instanceid = t.id
  2143. WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_USER . "
  2144. UNION
  2145. SELECT c.contextlevel,
  2146. c.instanceid
  2147. FROM {$CFG->prefix}context c
  2148. LEFT OUTER JOIN {$CFG->prefix}block_instance t
  2149. ON c.instanceid = t.id
  2150. WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_BLOCK . "
  2151. ";
  2152. if ($rs = get_recordset_sql($sql)) {
  2153. begin_sql();
  2154. $tx = true;
  2155. while ($tx && $ctx = rs_fetch_next_record($rs)) {
  2156. $tx = $tx && delete_context($ctx->contextlevel, $ctx->instanceid);
  2157. }
  2158. rs_close($rs);
  2159. if ($tx) {
  2160. commit_sql();
  2161. return true;
  2162. }
  2163. rollback_sql();
  2164. return false;
  2165. rs_close($rs);
  2166. }
  2167. return true;
  2168. }
  2169. /**
  2170. * Preloads all contexts relating to a course: course, modules, and blocks.
  2171. *
  2172. * @param int $courseid Course ID
  2173. * @return void
  2174. */
  2175. function preload_course_contexts($courseid) {
  2176. global $context_cache, $context_cache_id, $CFG;
  2177. // Users can call this multiple times without doing any harm
  2178. static $preloadedcourses = array();
  2179. if (array_key_exists($courseid, $preloadedcourses)) {
  2180. return;
  2181. }
  2182. $sql = "SELECT x.instanceid, x.id, x.contextlevel, x.path, x.depth
  2183. FROM {$CFG->prefix}course_modules cm
  2184. JOIN {$CFG->prefix}context x ON x.instanceid=cm.id
  2185. WHERE cm.course={$courseid}
  2186. AND x.contextlevel=".CONTEXT_MODULE."
  2187. UNION ALL
  2188. SELECT x.instanceid, x.id, x.contextlevel, x.path, x.depth
  2189. FROM {$CFG->prefix}block_instance bi
  2190. JOIN {$CFG->prefix}context x ON x.instanceid=bi.id
  2191. WHERE bi.pageid={$courseid}
  2192. AND bi.pagetype='course-view'
  2193. AND x.contextlevel=".CONTEXT_BLOCK."
  2194. UNION ALL
  2195. SELECT x.instanceid, x.id, x.contextlevel, x.path, x.depth
  2196. FROM {$CFG->prefix}context x
  2197. WHERE x.instanceid={$courseid}
  2198. AND x.contextlevel=".CONTEXT_COURSE."";
  2199. $rs = get_recordset_sql($sql);
  2200. while($context = rs_fetch_next_record($rs)) {
  2201. cache_context($context);
  2202. }
  2203. rs_close($rs);
  2204. $preloadedcourses[$courseid] = true;
  2205. }
  2206. /**
  2207. * Get the context instance as an object. This function will create the
  2208. * context instance if it does not exist yet.
  2209. * @param integer $level The context level, for example CONTEXT_COURSE, or CONTEXT_MODULE.
  2210. * @param integer $instance The instance id. For $level = CONTEXT_COURSE, this would be $course->id,
  2211. * for $level = CONTEXT_MODULE, this would be $cm->id. And so on.
  2212. * @return object The context object.
  2213. */
  2214. function get_context_instance($contextlevel, $instance=0) {
  2215. global $context_cache, $context_cache_id, $CFG;
  2216. static $allowed_contexts = array(CONTEXT_SYSTEM, CONTEXT_USER, CONTEXT_COURSECAT, CONTEXT_COURSE, CONTEXT_MODULE, CONTEXT_BLOCK);
  2217. if ($contextlevel === 'clearcache') {
  2218. // TODO: Remove for v2.0
  2219. // No longer needed, but we'll catch it to avoid erroring out on custom code.
  2220. // This used to be a fix for MDL-9016
  2221. // "Restoring into existing course, deleting first
  2222. // deletes context and doesn't recreate it"
  2223. return false;
  2224. }
  2225. /// System context has special cache
  2226. if ($contextlevel == CONTEXT_SYSTEM) {
  2227. return get_system_context();
  2228. }
  2229. /// check allowed context levels
  2230. if (!in_array($contextlevel, $allowed_contexts)) {
  2231. // fatal error, code must be fixed - probably typo or switched parameters
  2232. error('Error: get_context_instance() called with incorrect context level "'.s($contextlevel).'"');
  2233. }
  2234. if (!is_array($instance)) {
  2235. /// Check the cache
  2236. if (isset($context_cache[$contextlevel][$instance])) { // Already cached
  2237. return $context_cache[$contextlevel][$instance];
  2238. }
  2239. /// Get it from the database, or create it
  2240. if (!$context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance)) {
  2241. $context = create_context($contextlevel, $instance);
  2242. }
  2243. /// Only add to cache if context isn't empty.
  2244. if (!empty($context)) {
  2245. cache_context($context);
  2246. }
  2247. return $context;
  2248. }
  2249. /// ok, somebody wants to load several contexts to save some db queries ;-)
  2250. $instances = $instance;
  2251. $result = array();
  2252. foreach ($instances as $key=>$instance) {
  2253. /// Check the cache first
  2254. if (isset($context_cache[$contextlevel][$instance])) { // Already cached
  2255. $result[$instance] = $context_cache[$contextlevel][$instance];
  2256. unset($instances[$key]);
  2257. continue;
  2258. }
  2259. }
  2260. if ($instances) {
  2261. if (count($instances) > 1) {
  2262. $instanceids = implode(',', $instances);
  2263. $instanceids = "instanceid IN ($instanceids)";
  2264. } else {
  2265. $instance = reset($instances);
  2266. $instanceids = "instanceid = $instance";
  2267. }
  2268. if (!$contexts = get_records_sql("SELECT instanceid, id, contextlevel, path, depth
  2269. FROM {$CFG->prefix}context
  2270. WHERE contextlevel=$contextlevel AND $instanceids")) {
  2271. $contexts = array();
  2272. }
  2273. foreach ($instances as $instance) {
  2274. if (isset($contexts[$instance])) {
  2275. $context = $contexts[$instance];
  2276. } else {
  2277. $context = create_context($contextlevel, $instance);
  2278. }
  2279. if (!empty($context)) {
  2280. cache_context($context);
  2281. }
  2282. $result[$instance] = $context;
  2283. }
  2284. }
  2285. return $result;
  2286. }
  2287. /**
  2288. * Get a context instance as an object, from a given context id.
  2289. * @param mixed $id a context id or array of ids.
  2290. * @return mixed object or array of the context object.
  2291. */
  2292. function get_context_instance_by_id($id) {
  2293. global $context_cache, $context_cache_id;
  2294. if ($id == SYSCONTEXTID) {
  2295. return get_system_context();
  2296. }
  2297. if (isset($context_cache_id[$id])) { // Already cached
  2298. return $context_cache_id[$id];
  2299. }
  2300. if ($context = get_record('context', 'id', $id)) { // Update the cache and return
  2301. cache_context($context);
  2302. return $context;
  2303. }
  2304. return false;
  2305. }
  2306. /**
  2307. * Get the local override (if any) for a given capability in a role in a context
  2308. * @param $roleid
  2309. * @param $contextid
  2310. * @param $capability
  2311. */
  2312. function get_local_override($roleid, $contextid, $capability) {
  2313. return get_record('role_capabilities', 'roleid', $roleid, 'capability', $capability, 'contextid', $contextid);
  2314. }
  2315. /************************************
  2316. * DB TABLE RELATED FUNCTIONS *
  2317. ************************************/
  2318. /**
  2319. * function that creates a role
  2320. * @param name - role name
  2321. * @param shortname - role short name
  2322. * @param description - role description
  2323. * @param legacy - optional legacy capability
  2324. * @return id or false
  2325. */
  2326. function create_role($name, $shortname, $description, $legacy='') {
  2327. // check for duplicate role name
  2328. if ($role = get_record('role','name', $name)) {
  2329. error('there is already a role with this name!');
  2330. }
  2331. if ($role = get_record('role','shortname', $shortname)) {
  2332. error('there is already a role with this shortname!');
  2333. }
  2334. $role = new object();
  2335. $role->name = $name;
  2336. $role->shortname = $shortname;
  2337. $role->description = $description;
  2338. //find free sortorder number
  2339. $role->sortorder = count_records('role');
  2340. while (get_record('role','sortorder', $role->sortorder)) {
  2341. $role->sortorder += 1;
  2342. }
  2343. if (!$context = get_context_instance(CONTEXT_SYSTEM)) {
  2344. return false;
  2345. }
  2346. if ($id = insert_record('role', $role)) {
  2347. if ($legacy) {
  2348. assign_capability($legacy, CAP_ALLOW, $id, $context->id);
  2349. }
  2350. /// By default, users with role:manage at site level
  2351. /// should be able to assign users to this new role, and override this new role's capabilities
  2352. // find all admin roles
  2353. if ($adminroles = get_roles_with_capability('moodle/role:manage', CAP_ALLOW, $context)) {
  2354. // foreach admin role
  2355. foreach ($adminroles as $arole) {
  2356. // write allow_assign and allow_overrid
  2357. allow_assign($arole->id, $id);
  2358. allow_override($arole->id, $id);
  2359. }
  2360. }
  2361. return $id;
  2362. } else {
  2363. return false;
  2364. }
  2365. }
  2366. /**
  2367. * function that deletes a role and cleanups up after it
  2368. * @param roleid - id of role to delete
  2369. * @return success
  2370. */
  2371. function delete_role($roleid) {
  2372. global $CFG, $USER;
  2373. $success = true;
  2374. // mdl 10149, check if this is the last active admin role
  2375. // if we make the admin role not deletable then this part can go
  2376. $systemcontext = get_context_instance(CONTEXT_SYSTEM);
  2377. if ($role = get_record('role', 'id', $roleid)) {
  2378. if (record_exists('role_capabilities', 'contextid', $systemcontext->id, 'roleid', $roleid, 'capability', 'moodle/site:doanything')) {
  2379. // deleting an admin role
  2380. $status = false;
  2381. if ($adminroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, $systemcontext)) {
  2382. foreach ($adminroles as $adminrole) {
  2383. if ($adminrole->id != $roleid) {
  2384. // some other admin role
  2385. if (record_exists('role_assignments', 'roleid', $adminrole->id, 'contextid', $systemcontext->id)) {
  2386. // found another admin role with at least 1 user assigned
  2387. $status = true;
  2388. break;
  2389. }
  2390. }
  2391. }
  2392. }
  2393. if ($status !== true) {
  2394. error ('You can not delete this role because there is no other admin roles with users assigned');
  2395. }
  2396. }
  2397. }
  2398. // first unssign all users
  2399. if (!role_unassign($roleid)) {
  2400. debugging("Error while unassigning all users from role with ID $roleid!");
  2401. $success = false;
  2402. }
  2403. // cleanup all references to this role, ignore errors
  2404. if ($success) {
  2405. // MDL-10679 find all contexts where this role has an override
  2406. $contexts = get_records_sql("SELECT contextid, contextid
  2407. FROM {$CFG->prefix}role_capabilities
  2408. WHERE roleid = $roleid");
  2409. delete_records('role_capabilities', 'roleid', $roleid);
  2410. delete_records('role_allow_assign', 'roleid', $roleid);
  2411. delete_records('role_allow_assign', 'allowassign', $roleid);
  2412. delete_records('role_allow_override', 'roleid', $roleid);
  2413. delete_records('role_allow_override', 'allowoverride', $roleid);
  2414. delete_records('role_names', 'roleid', $roleid);
  2415. }
  2416. // finally delete the role itself
  2417. // get this before the name is gone for logging
  2418. $rolename = get_field('role', 'name', 'id', $roleid);
  2419. if ($success and !delete_records('role', 'id', $roleid)) {
  2420. debugging("Could not delete role record with ID $roleid!");
  2421. $success = false;
  2422. }
  2423. if ($success) {
  2424. add_to_log(SITEID, 'role', 'delete', 'admin/roles/action=delete&roleid='.$roleid, $rolename, '', $USER->id);
  2425. }
  2426. return $success;
  2427. }
  2428. /**
  2429. * Function to write context specific overrides, or default capabilities.
  2430. * @param module - string name
  2431. * @param capability - string name
  2432. * @param contextid - context id
  2433. * @param roleid - role id
  2434. * @param permission - int 1,-1 or -1000
  2435. * should not be writing if permission is 0
  2436. */
  2437. function assign_capability($capability, $permission, $roleid, $contextid, $overwrite=false) {
  2438. global $USER;
  2439. if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
  2440. unassign_capability($capability, $roleid, $contextid);
  2441. return true;
  2442. }
  2443. $existing = get_record('role_capabilities', 'contextid', $contextid, 'roleid', $roleid, 'capability', $capability);
  2444. if ($existing and !$overwrite) { // We want to keep whatever is there already
  2445. return true;
  2446. }
  2447. $cap = new object;
  2448. $cap->contextid = $contextid;
  2449. $cap->roleid = $roleid;
  2450. $cap->capability = $capability;
  2451. $cap->permission = $permission;
  2452. $cap->timemodified = time();
  2453. $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
  2454. if ($existing) {
  2455. $cap->id = $existing->id;
  2456. return update_record('role_capabilities', $cap);
  2457. } else {
  2458. $c = get_record('context', 'id', $contextid);
  2459. return insert_record('role_capabilities', $cap);
  2460. }
  2461. }
  2462. /**
  2463. * Unassign a capability from a role.
  2464. * @param $roleid - the role id
  2465. * @param $capability - the name of the capability
  2466. * @return boolean - success or failure
  2467. */
  2468. function unassign_capability($capability, $roleid, $contextid=NULL) {
  2469. if (isset($contextid)) {
  2470. // delete from context rel, if this is the last override in this context
  2471. $status = delete_records('role_capabilities', 'capability', $capability,
  2472. 'roleid', $roleid, 'contextid', $contextid);
  2473. } else {
  2474. $status = delete_records('role_capabilities', 'capability', $capability,
  2475. 'roleid', $roleid);
  2476. }
  2477. return $status;
  2478. }
  2479. /**
  2480. * Get the roles that have a given capability assigned to it. This function
  2481. * does not resolve the actual permission of the capability. It just checks
  2482. * for assignment only.
  2483. * @param $capability - capability name (string)
  2484. * @param $permission - optional, the permission defined for this capability
  2485. * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT
  2486. * @return array or role objects
  2487. */
  2488. function get_roles_with_capability($capability, $permission=NULL, $context='') {
  2489. global $CFG;
  2490. if ($context) {
  2491. if ($contexts = get_parent_contexts($context)) {
  2492. $listofcontexts = '('.implode(',', $contexts).')';
  2493. } else {
  2494. $sitecontext = get_context_instance(CONTEXT_SYSTEM);
  2495. $listofcontexts = '('.$sitecontext->id.')'; // must be site
  2496. }
  2497. $contextstr = "AND (rc.contextid = '$context->id' OR rc.contextid IN $listofcontexts)";
  2498. } else {
  2499. $contextstr = '';
  2500. }
  2501. $selectroles = "SELECT r.*
  2502. FROM {$CFG->prefix}role r,
  2503. {$CFG->prefix}role_capabilities rc
  2504. WHERE rc.capability = '$capability'
  2505. AND rc.roleid = r.id $contextstr";
  2506. if (isset($permission)) {
  2507. $selectroles .= " AND rc.permission = '$permission'";
  2508. }
  2509. return get_records_sql($selectroles);
  2510. }
  2511. /**
  2512. * This function makes a role-assignment (a role for a user or group in a particular context)
  2513. * @param $roleid - the role of the id
  2514. * @param $userid - userid
  2515. * @param $groupid - group id
  2516. * @param $contextid - id of the context
  2517. * @param $timestart - time this assignment becomes effective
  2518. * @param $timeend - time this assignemnt ceases to be effective
  2519. * @uses $USER
  2520. * @return id - new id of the assigment
  2521. */
  2522. function role_assign($roleid, $userid, $groupid, $contextid, $timestart=0, $timeend=0, $hidden=0, $enrol='manual',$timemodified='') {
  2523. global $USER, $CFG;
  2524. /// Do some data validation
  2525. if (empty($roleid)) {
  2526. debugging('Role ID not provided');
  2527. return false;
  2528. }
  2529. if (empty($userid) && empty($groupid)) {
  2530. debugging('Either userid or groupid must be provided');
  2531. return false;
  2532. }
  2533. if ($userid && !record_exists('user', 'id', $userid)) {
  2534. debugging('User ID '.intval($userid).' does not exist!');
  2535. return false;
  2536. }
  2537. if ($groupid && !groups_group_exists($groupid)) {
  2538. debugging('Group ID '.intval($groupid).' does not exist!');
  2539. return false;
  2540. }
  2541. if (!$context = get_context_instance_by_id($contextid)) {
  2542. debugging('Context ID '.intval($contextid).' does not exist!');
  2543. return false;
  2544. }
  2545. if (($timestart and $timeend) and ($timestart > $timeend)) {
  2546. debugging('The end time can not be earlier than the start time');
  2547. return false;
  2548. }
  2549. if (!$timemodified) {
  2550. $timemodified = time();
  2551. }
  2552. /// Check for existing entry
  2553. if ($userid) {
  2554. $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id, 'userid', $userid);
  2555. } else {
  2556. $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id, 'groupid', $groupid);
  2557. }
  2558. if (empty($ra)) { // Create a new entry
  2559. $ra = new object();
  2560. $ra->roleid = $roleid;
  2561. $ra->contextid = $context->id;
  2562. $ra->userid = $userid;
  2563. $ra->hidden = $hidden;
  2564. $ra->enrol = $enrol;
  2565. /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
  2566. /// by repeating queries with the same exact parameters in a 100 secs time window
  2567. $ra->timestart = round($timestart, -2);
  2568. $ra->timeend = $timeend;
  2569. $ra->timemodified = $timemodified;
  2570. $ra->modifierid = empty($USER->id) ? 0 : $USER->id;
  2571. if (!$ra->id = insert_record('role_assignments', $ra)) {
  2572. return false;
  2573. }
  2574. } else { // We already have one, just update it
  2575. $ra->id = $ra->id;
  2576. $ra->hidden = $hidden;
  2577. $ra->enrol = $enrol;
  2578. /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
  2579. /// by repeating queries with the same exact parameters in a 100 secs time window
  2580. $ra->timestart = round($timestart, -2);
  2581. $ra->timeend = $timeend;
  2582. $ra->timemodified = $timemodified;
  2583. $ra->modifierid = empty($USER->id) ? 0 : $USER->id;
  2584. if (!update_record('role_assignments', $ra)) {
  2585. return false;
  2586. }
  2587. }
  2588. /// mark context as dirty - modules might use has_capability() in xxx_role_assing()
  2589. /// again expensive, but needed
  2590. mark_context_dirty($context->path);
  2591. if (!empty($USER->id) && $USER->id == $userid) {
  2592. /// If the user is the current user, then do full reload of capabilities too.
  2593. load_all_capabilities();
  2594. }
  2595. /// Ask all the modules if anything needs to be done for this user
  2596. if ($mods = get_list_of_plugins('mod')) {
  2597. foreach ($mods as $mod) {
  2598. include_once($CFG->dirroot.'/mod/'.$mod.'/lib.php');
  2599. $functionname = $mod.'_role_assign';
  2600. if (function_exists($functionname)) {
  2601. $functionname($userid, $context, $roleid);
  2602. }
  2603. }
  2604. }
  2605. /// now handle metacourse role assignments if in course context
  2606. if ($context->contextlevel == CONTEXT_COURSE) {
  2607. if ($parents = get_records('course_meta', 'child_course', $context->instanceid)) {
  2608. foreach ($parents as $parent) {
  2609. sync_metacourse($parent->parent_course);
  2610. }
  2611. }
  2612. }
  2613. events_trigger('role_assigned', $ra);
  2614. return true;
  2615. }
  2616. /**
  2617. * Deletes one or more role assignments. You must specify at least one parameter.
  2618. * @param $roleid
  2619. * @param $userid
  2620. * @param $groupid
  2621. * @param $contextid
  2622. * @param $enrol unassign only if enrolment type matches, NULL means anything
  2623. * @return boolean - success or failure
  2624. */
  2625. function role_unassign($roleid=0, $userid=0, $groupid=0, $contextid=0, $enrol=NULL) {
  2626. global $USER, $CFG;
  2627. require_once($CFG->dirroot.'/group/lib.php');
  2628. $success = true;
  2629. $args = array('roleid', 'userid', 'groupid', 'contextid');
  2630. $select = array();
  2631. foreach ($args as $arg) {
  2632. if ($$arg) {
  2633. $select[] = $arg.' = '.$$arg;
  2634. }
  2635. }
  2636. if (!empty($enrol)) {
  2637. $select[] = "enrol='$enrol'";
  2638. }
  2639. if ($select) {
  2640. if ($ras = get_records_select('role_assignments', implode(' AND ', $select))) {
  2641. $mods = get_list_of_plugins('mod');
  2642. foreach($ras as $ra) {
  2643. $fireevent = false;
  2644. /// infinite loop protection when deleting recursively
  2645. if (!$ra = get_record('role_assignments', 'id', $ra->id)) {
  2646. continue;
  2647. }
  2648. if (delete_records('role_assignments', 'id', $ra->id)) {
  2649. $fireevent = true;
  2650. } else {
  2651. $success = false;
  2652. }
  2653. if (!$context = get_context_instance_by_id($ra->contextid)) {
  2654. // strange error, not much to do
  2655. continue;
  2656. }
  2657. /* mark contexts as dirty here, because we need the refreshed
  2658. * caps bellow to delete group membership and user_lastaccess!
  2659. * and yes, this is very expensive for bulk operations :-(
  2660. */
  2661. mark_context_dirty($context->path);
  2662. /// If the user is the current user, then do full reload of capabilities too.
  2663. if (!empty($USER->id) && $USER->id == $ra->userid) {
  2664. load_all_capabilities();
  2665. }
  2666. /// Ask all the modules if anything needs to be done for this user
  2667. foreach ($mods as $mod) {
  2668. include_once($CFG->dirroot.'/mod/'.$mod.'/lib.php');
  2669. $functionname = $mod.'_role_unassign';
  2670. if (function_exists($functionname)) {
  2671. $functionname($ra->userid, $context); // watch out, $context might be NULL if something goes wrong
  2672. }
  2673. }
  2674. /// now handle metacourse role unassigment and removing from goups if in course context
  2675. if ($context->contextlevel == CONTEXT_COURSE) {
  2676. // cleanup leftover course groups/subscriptions etc when user has
  2677. // no capability to view course
  2678. // this may be slow, but this is the proper way of doing it
  2679. if (!has_capability('moodle/course:view', $context, $ra->userid)) {
  2680. // remove from groups
  2681. groups_delete_group_members($context->instanceid, $ra->userid);
  2682. // delete lastaccess records
  2683. delete_records('user_lastaccess', 'userid', $ra->userid, 'courseid', $context->instanceid);
  2684. }
  2685. //unassign roles in metacourses if needed
  2686. if ($parents = get_records('course_meta', 'child_course', $context->instanceid)) {
  2687. foreach ($parents as $parent) {
  2688. sync_metacourse($parent->parent_course);
  2689. }
  2690. }
  2691. }
  2692. if ($fireevent) {
  2693. events_trigger('role_unassigned', $ra);
  2694. }
  2695. }
  2696. }
  2697. }
  2698. return $success;
  2699. }
  2700. /**
  2701. * A convenience function to take care of the common case where you
  2702. * just want to enrol someone using the default role into a course
  2703. *
  2704. * @param object $course
  2705. * @param object $user
  2706. * @param string $enrol - the plugin used to do this enrolment
  2707. */
  2708. function enrol_into_course($course, $user, $enrol) {
  2709. $timestart = time();
  2710. // remove time part from the timestamp and keep only the date part
  2711. $timestart = make_timestamp(date('Y', $timestart), date('m', $timestart), date('d', $timestart), 0, 0, 0);
  2712. if ($course->enrolperiod) {
  2713. $timeend = $timestart + $course->enrolperiod;
  2714. } else {
  2715. $timeend = 0;
  2716. }
  2717. if ($role = get_default_course_role($course)) {
  2718. $context = get_context_instance(CONTEXT_COURSE, $course->id);
  2719. if (!role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, $enrol)) {
  2720. return false;
  2721. }
  2722. // force accessdata refresh for users visiting this context...
  2723. mark_context_dirty($context->path);
  2724. email_welcome_message_to_user($course, $user);
  2725. add_to_log($course->id, 'course', 'enrol',
  2726. 'view.php?id='.$course->id, $course->id);
  2727. return true;
  2728. }
  2729. return false;
  2730. }
  2731. /**
  2732. * Loads the capability definitions for the component (from file). If no
  2733. * capabilities are defined for the component, we simply return an empty array.
  2734. * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
  2735. * @return array of capabilities
  2736. */
  2737. function load_capability_def($component) {
  2738. global $CFG;
  2739. if ($component == 'moodle') {
  2740. $defpath = $CFG->libdir.'/db/access.php';
  2741. $varprefix = 'moodle';
  2742. } else {
  2743. $compparts = explode('/', $component);
  2744. if ($compparts[0] == 'report') {
  2745. $defpath = $CFG->dirroot.'/'.$CFG->admin.'/report/'.$compparts[1].'/db/access.php';
  2746. $varprefix = $compparts[0].'_'.$compparts[1];
  2747. } else if ($compparts[0] == 'block') {
  2748. // Blocks are an exception. Blocks directory is 'blocks', and not
  2749. // 'block'. So we need to jump through hoops.
  2750. $defpath = $CFG->dirroot.'/'.$compparts[0].
  2751. 's/'.$compparts[1].'/db/access.php';
  2752. $varprefix = $compparts[0].'_'.$compparts[1];
  2753. } else if ($compparts[0] == 'format') {
  2754. // Similar to the above, course formats are 'format' while they
  2755. // are stored in 'course/format'.
  2756. $defpath = $CFG->dirroot.'/course/'.$component.'/db/access.php';
  2757. $varprefix = $compparts[0].'_'.$compparts[1];
  2758. } else if ($compparts[0] == 'gradeimport') {
  2759. $defpath = $CFG->dirroot.'/grade/import/'.$compparts[1].'/db/access.php';
  2760. $varprefix = $compparts[0].'_'.$compparts[1];
  2761. } else if ($compparts[0] == 'gradeexport') {
  2762. $defpath = $CFG->dirroot.'/grade/export/'.$compparts[1].'/db/access.php';
  2763. $varprefix = $compparts[0].'_'.$compparts[1];
  2764. } else if ($compparts[0] == 'gradereport') {
  2765. $defpath = $CFG->dirroot.'/grade/report/'.$compparts[1].'/db/access.php';
  2766. $varprefix = $compparts[0].'_'.$compparts[1];
  2767. } else if ($compparts[0] == 'coursereport') {
  2768. $defpath = $CFG->dirroot.'/course/report/'.$compparts[1].'/db/access.php';
  2769. $varprefix = $compparts[0].'_'.$compparts[1];
  2770. } else {
  2771. $defpath = $CFG->dirroot.'/'.$component.'/db/access.php';
  2772. $varprefix = str_replace('/', '_', $component);
  2773. }
  2774. }
  2775. $capabilities = array();
  2776. if (file_exists($defpath)) {
  2777. require($defpath);
  2778. $capabilities = ${$varprefix.'_capabilities'};
  2779. }
  2780. return $capabilities;
  2781. }
  2782. /**
  2783. * Gets the capabilities that have been cached in the database for this
  2784. * component.
  2785. * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
  2786. * @return array of capabilities
  2787. */
  2788. function get_cached_capabilities($component='moodle') {
  2789. if ($component == 'moodle') {
  2790. $storedcaps = get_records_select('capabilities',
  2791. "name LIKE 'moodle/%:%'");
  2792. } else if ($component == 'local') {
  2793. $storedcaps = get_records_select('capabilities',
  2794. "name LIKE 'moodle/local:%'");
  2795. } else {
  2796. $storedcaps = get_records_select('capabilities',
  2797. "name LIKE '$component:%'");
  2798. }
  2799. return $storedcaps;
  2800. }
  2801. /**
  2802. * Returns default capabilities for given legacy role type.
  2803. *
  2804. * @param string legacy role name
  2805. * @return array
  2806. */
  2807. function get_default_capabilities($legacyrole) {
  2808. if (!$allcaps = get_records('capabilities')) {
  2809. error('Error: no capabilitites defined!');
  2810. }
  2811. $alldefs = array();
  2812. $defaults = array();
  2813. $components = array();
  2814. foreach ($allcaps as $cap) {
  2815. if (!in_array($cap->component, $components)) {
  2816. $components[] = $cap->component;
  2817. $alldefs = array_merge($alldefs, load_capability_def($cap->component));
  2818. }
  2819. }
  2820. foreach($alldefs as $name=>$def) {
  2821. if (isset($def['legacy'][$legacyrole])) {
  2822. $defaults[$name] = $def['legacy'][$legacyrole];
  2823. }
  2824. }
  2825. //some exceptions
  2826. $defaults['moodle/legacy:'.$legacyrole] = CAP_ALLOW;
  2827. if ($legacyrole == 'admin') {
  2828. $defaults['moodle/site:doanything'] = CAP_ALLOW;
  2829. }
  2830. return $defaults;
  2831. }
  2832. /**
  2833. * Reset role capabilitites to default according to selected legacy capability.
  2834. * If several legacy caps selected, use the first from get_default_capabilities.
  2835. * If no legacy selected, removes all capabilities.
  2836. *
  2837. * @param int @roleid
  2838. */
  2839. function reset_role_capabilities($roleid) {
  2840. $sitecontext = get_context_instance(CONTEXT_SYSTEM);
  2841. $legacyroles = get_legacy_roles();
  2842. $defaultcaps = array();
  2843. foreach($legacyroles as $ltype=>$lcap) {
  2844. $localoverride = get_local_override($roleid, $sitecontext->id, $lcap);
  2845. if (!empty($localoverride->permission) and $localoverride->permission == CAP_ALLOW) {
  2846. //choose first selected legacy capability
  2847. $defaultcaps = get_default_capabilities($ltype);
  2848. break;
  2849. }
  2850. }
  2851. delete_records('role_capabilities', 'roleid', $roleid);
  2852. if (!empty($defaultcaps)) {
  2853. foreach($defaultcaps as $cap=>$permission) {
  2854. assign_capability($cap, $permission, $roleid, $sitecontext->id);
  2855. }
  2856. }
  2857. }
  2858. /**
  2859. * Updates the capabilities table with the component capability definitions.
  2860. * If no parameters are given, the function updates the core moodle
  2861. * capabilities.
  2862. *
  2863. * Note that the absence of the db/access.php capabilities definition file
  2864. * will cause any stored capabilities for the component to be removed from
  2865. * the database.
  2866. *
  2867. * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
  2868. * @return boolean
  2869. */
  2870. function update_capabilities($component='moodle') {
  2871. $storedcaps = array();
  2872. $filecaps = load_capability_def($component);
  2873. $cachedcaps = get_cached_capabilities($component);
  2874. if ($cachedcaps) {
  2875. foreach ($cachedcaps as $cachedcap) {
  2876. array_push($storedcaps, $cachedcap->name);
  2877. // update risk bitmasks and context levels in existing capabilities if needed
  2878. if (array_key_exists($cachedcap->name, $filecaps)) {
  2879. if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
  2880. $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
  2881. }
  2882. if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
  2883. $updatecap = new object();
  2884. $updatecap->id = $cachedcap->id;
  2885. $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
  2886. if (!update_record('capabilities', $updatecap)) {
  2887. return false;
  2888. }
  2889. }
  2890. if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
  2891. $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
  2892. }
  2893. if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
  2894. $updatecap = new object();
  2895. $updatecap->id = $cachedcap->id;
  2896. $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
  2897. if (!update_record('capabilities', $updatecap)) {
  2898. return false;
  2899. }
  2900. }
  2901. }
  2902. }
  2903. }
  2904. // Are there new capabilities in the file definition?
  2905. $newcaps = array();
  2906. foreach ($filecaps as $filecap => $def) {
  2907. if (!$storedcaps ||
  2908. ($storedcaps && in_array($filecap, $storedcaps) === false)) {
  2909. if (!array_key_exists('riskbitmask', $def)) {
  2910. $def['riskbitmask'] = 0; // no risk if not specified
  2911. }
  2912. $newcaps[$filecap] = $def;
  2913. }
  2914. }
  2915. // Add new capabilities to the stored definition.
  2916. foreach ($newcaps as $capname => $capdef) {
  2917. $capability = new object;
  2918. $capability->name = $capname;
  2919. $capability->captype = $capdef['captype'];
  2920. $capability->contextlevel = $capdef['contextlevel'];
  2921. $capability->component = $component;
  2922. $capability->riskbitmask = $capdef['riskbitmask'];
  2923. if (!insert_record('capabilities', $capability, false, 'id')) {
  2924. return false;
  2925. }
  2926. if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $storedcaps)){
  2927. if ($rolecapabilities = get_records('role_capabilities', 'capability', $capdef['clonepermissionsfrom'])){
  2928. foreach ($rolecapabilities as $rolecapability){
  2929. //assign_capability will update rather than insert if capability exists
  2930. if (!assign_capability($capname, $rolecapability->permission,
  2931. $rolecapability->roleid, $rolecapability->contextid, true)){
  2932. notify('Could not clone capabilities for '.$capname);
  2933. }
  2934. }
  2935. }
  2936. // Do we need to assign the new capabilities to roles that have the
  2937. // legacy capabilities moodle/legacy:* as well?
  2938. // we ignore legacy key if we have cloned permissions
  2939. } else if (isset($capdef['legacy']) && is_array($capdef['legacy']) &&
  2940. !assign_legacy_capabilities($capname, $capdef['legacy'])) {
  2941. notify('Could not assign legacy capabilities for '.$capname);
  2942. }
  2943. }
  2944. // Are there any capabilities that have been removed from the file
  2945. // definition that we need to delete from the stored capabilities and
  2946. // role assignments?
  2947. capabilities_cleanup($component, $filecaps);
  2948. // reset static caches
  2949. is_valid_capability('reset', false);
  2950. return true;
  2951. }
  2952. /**
  2953. * Deletes cached capabilities that are no longer needed by the component.
  2954. * Also unassigns these capabilities from any roles that have them.
  2955. * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
  2956. * @param $newcapdef - array of the new capability definitions that will be
  2957. * compared with the cached capabilities
  2958. * @return int - number of deprecated capabilities that have been removed
  2959. */
  2960. function capabilities_cleanup($component, $newcapdef=NULL) {
  2961. $removedcount = 0;
  2962. if ($cachedcaps = get_cached_capabilities($component)) {
  2963. foreach ($cachedcaps as $cachedcap) {
  2964. if (empty($newcapdef) ||
  2965. array_key_exists($cachedcap->name, $newcapdef) === false) {
  2966. // Remove from capabilities cache.
  2967. if (!delete_records('capabilities', 'name', $cachedcap->name)) {
  2968. error('Could not delete deprecated capability '.$cachedcap->name);
  2969. } else {
  2970. $removedcount++;
  2971. }
  2972. // Delete from roles.
  2973. if($roles = get_roles_with_capability($cachedcap->name)) {
  2974. foreach($roles as $role) {
  2975. if (!unassign_capability($cachedcap->name, $role->id)) {
  2976. error('Could not unassign deprecated capability '.
  2977. $cachedcap->name.' from role '.$role->name);
  2978. }
  2979. }
  2980. }
  2981. } // End if.
  2982. }
  2983. }
  2984. return $removedcount;
  2985. }
  2986. /****************
  2987. * UI FUNCTIONS *
  2988. ****************/
  2989. /**
  2990. * prints human readable context identifier.
  2991. */
  2992. function print_context_name($context, $withprefix = true, $short = false) {
  2993. $name = '';
  2994. switch ($context->contextlevel) {
  2995. case CONTEXT_SYSTEM: // by now it's a definite an inherit
  2996. $name = get_string('coresystem');
  2997. break;
  2998. case CONTEXT_USER:
  2999. if ($user = get_record('user', 'id', $context->instanceid)) {
  3000. if ($withprefix){
  3001. $name = get_string('user').': ';
  3002. }
  3003. $name .= fullname($user);
  3004. }
  3005. break;
  3006. case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
  3007. if ($category = get_record('course_categories', 'id', $context->instanceid)) {
  3008. if ($withprefix){
  3009. $name = get_string('category').': ';
  3010. }
  3011. $name .=format_string($category->name);
  3012. }
  3013. break;
  3014. case CONTEXT_COURSE: // 1 to 1 to course cat
  3015. if ($context->instanceid == SITEID) {
  3016. $name = get_string('frontpage', 'admin');
  3017. } else {
  3018. if ($course = get_record('course', 'id', $context->instanceid)) {
  3019. if ($withprefix){
  3020. $name = get_string('course').': ';
  3021. }
  3022. if (!$short){
  3023. $name .= format_string($course->shortname);
  3024. } else {
  3025. $name .= format_string($course->fullname);
  3026. }
  3027. }
  3028. }
  3029. break;
  3030. case CONTEXT_MODULE: // 1 to 1 to course
  3031. if ($cm = get_record('course_modules','id',$context->instanceid)) {
  3032. if ($module = get_record('modules','id',$cm->module)) {
  3033. if ($mod = get_record($module->name, 'id', $cm->instance)) {
  3034. if ($withprefix){
  3035. $name = get_string('activitymodule').': ';
  3036. }
  3037. $name .= $mod->name;
  3038. }
  3039. }
  3040. }
  3041. break;
  3042. case CONTEXT_BLOCK: // not necessarily 1 to 1 to course
  3043. if ($blockinstance = get_record('block_instance','id',$context->instanceid)) {
  3044. if ($block = get_record('block','id',$blockinstance->blockid)) {
  3045. global $CFG;
  3046. require_once("$CFG->dirroot/blocks/moodleblock.class.php");
  3047. require_once("$CFG->dirroot/blocks/$block->name/block_$block->name.php");
  3048. $blockname = "block_$block->name";
  3049. if ($blockobject = new $blockname()) {
  3050. if ($withprefix){
  3051. $name = get_string('block').': ';
  3052. }
  3053. $name .= $blockobject->title;
  3054. }
  3055. }
  3056. }
  3057. break;
  3058. default:
  3059. error ('This is an unknown context (' . $context->contextlevel . ') in print_context_name!');
  3060. return false;
  3061. }
  3062. return $name;
  3063. }
  3064. /**
  3065. * Extracts the relevant capabilities given a contextid.
  3066. * All case based, example an instance of forum context.
  3067. * Will fetch all forum related capabilities, while course contexts
  3068. * Will fetch all capabilities
  3069. * @param object context
  3070. * @return array();
  3071. *
  3072. * capabilities
  3073. * `name` varchar(150) NOT NULL,
  3074. * `captype` varchar(50) NOT NULL,
  3075. * `contextlevel` int(10) NOT NULL,
  3076. * `component` varchar(100) NOT NULL,
  3077. */
  3078. function fetch_context_capabilities($context) {
  3079. global $CFG;
  3080. $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
  3081. switch ($context->contextlevel) {
  3082. case CONTEXT_SYSTEM: // all
  3083. $SQL = "SELECT *
  3084. FROM {$CFG->prefix}capabilities";
  3085. break;
  3086. case CONTEXT_USER:
  3087. $extracaps = array('moodle/grade:viewall');
  3088. foreach ($extracaps as $key=>$value) {
  3089. $extracaps[$key]= "'$value'";
  3090. }
  3091. $extra = implode(',', $extracaps);
  3092. $SQL = "SELECT *
  3093. FROM {$CFG->prefix}capabilities
  3094. WHERE contextlevel = ".CONTEXT_USER."
  3095. OR name IN ($extra)";
  3096. break;
  3097. case CONTEXT_COURSECAT: // course category context and bellow
  3098. $SQL = "SELECT *
  3099. FROM {$CFG->prefix}capabilities
  3100. WHERE contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
  3101. break;
  3102. case CONTEXT_COURSE: // course context and bellow
  3103. $SQL = "SELECT *
  3104. FROM {$CFG->prefix}capabilities
  3105. WHERE contextlevel IN (".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
  3106. break;
  3107. case CONTEXT_MODULE: // mod caps
  3108. $cm = get_record('course_modules', 'id', $context->instanceid);
  3109. $module = get_record('modules', 'id', $cm->module);
  3110. $modfile = "$CFG->dirroot/mod/$module->name/lib.php";
  3111. if (file_exists($modfile)) {
  3112. include_once($modfile);
  3113. $modfunction = $module->name.'_get_extra_capabilities';
  3114. if (function_exists($modfunction)) {
  3115. $extracaps = $modfunction();
  3116. }
  3117. }
  3118. if(empty($extracaps)) {
  3119. $extracaps = array();
  3120. }
  3121. // All modules allow viewhiddenactivities. This is so you can hide
  3122. // the module then override to allow specific roles to see it.
  3123. // The actual check is in course page so not module-specific
  3124. $extracaps[]="moodle/course:viewhiddenactivities";
  3125. if (count($extracaps) == 1) {
  3126. $extra = "OR name = '".reset($extracaps)."'";
  3127. } else {
  3128. foreach ($extracaps as $key=>$value) {
  3129. $extracaps[$key]= "'$value'";
  3130. }
  3131. $extra = implode(',', $extracaps);
  3132. $extra = "OR name IN ($extra)";
  3133. }
  3134. $SQL = "SELECT *
  3135. FROM {$CFG->prefix}capabilities
  3136. WHERE (contextlevel = ".CONTEXT_MODULE."
  3137. AND component = 'mod/$module->name')
  3138. $extra";
  3139. break;
  3140. case CONTEXT_BLOCK: // block caps
  3141. $cb = get_record('block_instance', 'id', $context->instanceid);
  3142. $block = get_record('block', 'id', $cb->blockid);
  3143. $extra = "";
  3144. if ($blockinstance = block_instance($block->name)) {
  3145. if ($extracaps = $blockinstance->get_extra_capabilities()) {
  3146. foreach ($extracaps as $key=>$value) {
  3147. $extracaps[$key]= "'$value'";
  3148. }
  3149. $extra = implode(',', $extracaps);
  3150. $extra = "OR name IN ($extra)";
  3151. }
  3152. }
  3153. $SQL = "SELECT *
  3154. FROM {$CFG->prefix}capabilities
  3155. WHERE (contextlevel = ".CONTEXT_BLOCK."
  3156. AND component = 'block/$block->name')
  3157. $extra";
  3158. break;
  3159. default:
  3160. return false;
  3161. }
  3162. if (!$records = get_records_sql($SQL.' '.$sort)) {
  3163. $records = array();
  3164. }
  3165. return $records;
  3166. }
  3167. /**
  3168. * This function pulls out all the resolved capabilities (overrides and
  3169. * defaults) of a role used in capability overrides in contexts at a given
  3170. * context.
  3171. * @param obj $context
  3172. * @param int $roleid
  3173. * @param bool self - if set to true, resolve till this level, else stop at immediate parent level
  3174. * @return array
  3175. */
  3176. function role_context_capabilities($roleid, $context, $cap='') {
  3177. global $CFG;
  3178. $contexts = get_parent_contexts($context);
  3179. $contexts[] = $context->id;
  3180. $contexts = '('.implode(',', $contexts).')';
  3181. if ($cap) {
  3182. $search = " AND rc.capability = '$cap' ";
  3183. } else {
  3184. $search = '';
  3185. }
  3186. $SQL = "SELECT rc.*
  3187. FROM {$CFG->prefix}role_capabilities rc,
  3188. {$CFG->prefix}context c
  3189. WHERE rc.contextid in $contexts
  3190. AND rc.roleid = $roleid
  3191. AND rc.contextid = c.id $search
  3192. ORDER BY c.contextlevel DESC,
  3193. rc.capability DESC";
  3194. $capabilities = array();
  3195. if ($records = get_records_sql($SQL)) {
  3196. // We are traversing via reverse order.
  3197. foreach ($records as $record) {
  3198. // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
  3199. if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
  3200. $capabilities[$record->capability] = $record->permission;
  3201. }
  3202. }
  3203. }
  3204. return $capabilities;
  3205. }
  3206. /**
  3207. * Recursive function which, given a context, find all parent context ids,
  3208. * and return the array in reverse order, i.e. parent first, then grand
  3209. * parent, etc.
  3210. *
  3211. * @param object $context
  3212. * @return array()
  3213. */
  3214. function get_parent_contexts($context) {
  3215. if ($context->path == '') {
  3216. return array();
  3217. }
  3218. $parentcontexts = substr($context->path, 1); // kill leading slash
  3219. $parentcontexts = explode('/', $parentcontexts);
  3220. array_pop($parentcontexts); // and remove its own id
  3221. return array_reverse($parentcontexts);
  3222. }
  3223. /**
  3224. * Return the id of the parent of this context, or false if there is no parent (only happens if this
  3225. * is the site context.)
  3226. *
  3227. * @param object $context
  3228. * @return integer the id of the parent context.
  3229. */
  3230. function get_parent_contextid($context) {
  3231. $parentcontexts = get_parent_contexts($context);
  3232. if (count($parentcontexts) == 0) {
  3233. return false;
  3234. }
  3235. return array_shift($parentcontexts);
  3236. }
  3237. /**
  3238. * @param object $context a context object.
  3239. * @return true if this context is the front page context, or a context inside it,
  3240. * otherwise false.
  3241. */
  3242. function is_inside_frontpage($context) {
  3243. $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
  3244. return strpos($context->path . '/', $frontpagecontext->path . '/') === 0;
  3245. }
  3246. /**
  3247. * Recursive function which, given a context, find all its children context ids.
  3248. *
  3249. * When called for a course context, it will return the modules and blocks
  3250. * displayed in the course page.
  3251. *
  3252. * For course category contexts it will return categories and courses. It will
  3253. * NOT recurse into courses - if you want to do that, call it on the returned
  3254. * courses.
  3255. *
  3256. * If called on a course context it _will_ populate the cache with the appropriate
  3257. * contexts ;-)
  3258. *
  3259. * @param object $context.
  3260. * @return array of child records
  3261. */
  3262. function get_child_contexts($context) {
  3263. global $CFG, $context_cache;
  3264. // We *MUST* populate the context_cache as the callers
  3265. // will probably ask for the full record anyway soon after
  3266. // soon after calling us ;-)
  3267. switch ($context->contextlevel) {
  3268. case CONTEXT_BLOCK:
  3269. // No children.
  3270. return array();
  3271. break;
  3272. case CONTEXT_MODULE:
  3273. // No children.
  3274. return array();
  3275. break;
  3276. case CONTEXT_COURSE:
  3277. // Find
  3278. // - module instances - easy
  3279. // - blocks assigned to the course-view page explicitly - easy
  3280. $sql = " SELECT ctx.*
  3281. FROM {$CFG->prefix}context ctx
  3282. WHERE ctx.path LIKE '{$context->path}/%'
  3283. AND ctx.contextlevel IN (".CONTEXT_MODULE.",".CONTEXT_BLOCK.")
  3284. ";
  3285. $rs = get_recordset_sql($sql);
  3286. $records = array();
  3287. while ($rec = rs_fetch_next_record($rs)) {
  3288. $records[$rec->id] = $rec;
  3289. $context_cache[$rec->contextlevel][$rec->instanceid] = $rec;
  3290. }
  3291. rs_close($rs);
  3292. return $records;
  3293. break;
  3294. case CONTEXT_COURSECAT:
  3295. // Find
  3296. // - categories
  3297. // - courses
  3298. $sql = " SELECT ctx.*
  3299. FROM {$CFG->prefix}context ctx
  3300. WHERE ctx.path LIKE '{$context->path}/%'
  3301. AND ctx.contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.")
  3302. ";
  3303. $rs = get_recordset_sql($sql);
  3304. $records = array();
  3305. while ($rec = rs_fetch_next_record($rs)) {
  3306. $records[$rec->id] = $rec;
  3307. $context_cache[$rec->contextlevel][$rec->instanceid] = $rec;
  3308. }
  3309. rs_close($rs);
  3310. return $records;
  3311. break;
  3312. case CONTEXT_USER:
  3313. // No children.
  3314. return array();
  3315. break;
  3316. case CONTEXT_SYSTEM:
  3317. // Just get all the contexts except for CONTEXT_SYSTEM level
  3318. // and hope we don't OOM in the process - don't cache
  3319. $sql = 'SELECT c.*'.
  3320. 'FROM '.$CFG->prefix.'context c '.
  3321. 'WHERE contextlevel != '.CONTEXT_SYSTEM;
  3322. return get_records_sql($sql);
  3323. break;
  3324. default:
  3325. error('This is an unknown context (' . $context->contextlevel . ') in get_child_contexts!');
  3326. return false;
  3327. }
  3328. }
  3329. /**
  3330. * Gets a string for sql calls, searching for stuff in this context or above
  3331. * @param object $context
  3332. * @return string
  3333. */
  3334. function get_related_contexts_string($context) {
  3335. if ($parents = get_parent_contexts($context)) {
  3336. return (' IN ('.$context->id.','.implode(',', $parents).')');
  3337. } else {
  3338. return (' ='.$context->id);
  3339. }
  3340. }
  3341. /**
  3342. * Verifies if given capability installed.
  3343. *
  3344. * @param string $capabilityname
  3345. * @param bool $cached
  3346. * @return book true if capability exists
  3347. */
  3348. function is_valid_capability($capabilityname, $cached=true) {
  3349. static $capsnames = null; // one request per page only
  3350. if (is_null($capsnames) or !$cached) {
  3351. $capsnames = get_records_menu('capabilities', '', '', '', 'name, 1');
  3352. }
  3353. return array_key_exists($capabilityname, $capsnames);
  3354. }
  3355. /**
  3356. * Returns the human-readable, translated version of the capability.
  3357. * Basically a big switch statement.
  3358. * @param $capabilityname - e.g. mod/choice:readresponses
  3359. */
  3360. function get_capability_string($capabilityname) {
  3361. // Typical capabilityname is mod/choice:readresponses
  3362. $names = split('/', $capabilityname);
  3363. $stringname = $names[1]; // choice:readresponses
  3364. $components = split(':', $stringname);
  3365. $componentname = $components[0]; // choice
  3366. switch ($names[0]) {
  3367. case 'report':
  3368. $string = get_string($stringname, 'report_'.$componentname);
  3369. break;
  3370. case 'mod':
  3371. $string = get_string($stringname, $componentname);
  3372. break;
  3373. case 'block':
  3374. $string = get_string($stringname, 'block_'.$componentname);
  3375. break;
  3376. case 'moodle':
  3377. if ($componentname == 'local') {
  3378. $string = get_string($stringname, 'local');
  3379. } else {
  3380. $string = get_string($stringname, 'role');
  3381. }
  3382. break;
  3383. case 'enrol':
  3384. $string = get_string($stringname, 'enrol_'.$componentname);
  3385. break;
  3386. case 'format':
  3387. $string = get_string($stringname, 'format_'.$componentname);
  3388. break;
  3389. case 'gradeexport':
  3390. $string = get_string($stringname, 'gradeexport_'.$componentname);
  3391. break;
  3392. case 'gradeimport':
  3393. $string = get_string($stringname, 'gradeimport_'.$componentname);
  3394. break;
  3395. case 'gradereport':
  3396. $string = get_string($stringname, 'gradereport_'.$componentname);
  3397. break;
  3398. case 'coursereport':
  3399. $string = get_string($stringname, 'coursereport_'.$componentname);
  3400. break;
  3401. default:
  3402. $string = get_string($stringname);
  3403. break;
  3404. }
  3405. return $string;
  3406. }
  3407. /**
  3408. * This gets the mod/block/course/core etc strings.
  3409. * @param $component
  3410. * @param $contextlevel
  3411. */
  3412. function get_component_string($component, $contextlevel) {
  3413. switch ($contextlevel) {
  3414. case CONTEXT_SYSTEM:
  3415. if (preg_match('|^enrol/|', $component)) {
  3416. $langname = str_replace('/', '_', $component);
  3417. $string = get_string('enrolname', $langname);
  3418. } else if (preg_match('|^block/|', $component)) {
  3419. $langname = str_replace('/', '_', $component);
  3420. $string = get_string('blockname', $langname);
  3421. } else if (preg_match('|^local|', $component)) {
  3422. $langname = str_replace('/', '_', $component);
  3423. $string = get_string('local');
  3424. } else if (preg_match('|^report/|', $component)) {
  3425. $string = get_string('reports');
  3426. } else {
  3427. $string = get_string('coresystem');
  3428. }
  3429. break;
  3430. case CONTEXT_USER:
  3431. $string = get_string('users');
  3432. break;
  3433. case CONTEXT_COURSECAT:
  3434. $string = get_string('categories');
  3435. break;
  3436. case CONTEXT_COURSE:
  3437. if (preg_match('|^gradeimport/|', $component)
  3438. || preg_match('|^gradeexport/|', $component)
  3439. || preg_match('|^gradereport/|', $component)) {
  3440. $string = get_string('gradebook', 'admin');
  3441. } else if (preg_match('|^coursereport/|', $component)) {
  3442. $string = get_string('coursereports');
  3443. } else {
  3444. $string = get_string('course');
  3445. }
  3446. break;
  3447. case CONTEXT_MODULE:
  3448. $string = get_string('modulename', basename($component));
  3449. break;
  3450. case CONTEXT_BLOCK:
  3451. if( $component == 'moodle' ){
  3452. $string = get_string('block');
  3453. }else{
  3454. $string = get_string('blockname', 'block_'.basename($component));
  3455. }
  3456. break;
  3457. default:
  3458. error ('This is an unknown context $contextlevel (' . $contextlevel . ') in get_component_string!');
  3459. return false;
  3460. }
  3461. return $string;
  3462. }
  3463. /**
  3464. * Gets the list of roles assigned to this context and up (parents)
  3465. * @param object $context
  3466. * @param view - set to true when roles are pulled for display only
  3467. * this is so that we can filter roles with no visible
  3468. * assignment, for example, you might want to "hide" all
  3469. * course creators when browsing the course participants
  3470. * list.
  3471. * @return array
  3472. */
  3473. function get_roles_used_in_context($context, $view = false) {
  3474. global $CFG;
  3475. // filter for roles with all hidden assignments
  3476. // no need to return when only pulling roles for reviewing
  3477. // e.g. participants page.
  3478. $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))? ' AND ra.hidden = 0 ':'';
  3479. $contextlist = get_related_contexts_string($context);
  3480. $sql = "SELECT DISTINCT r.id,
  3481. r.name,
  3482. r.shortname,
  3483. r.sortorder
  3484. FROM {$CFG->prefix}role_assignments ra,
  3485. {$CFG->prefix}role r
  3486. WHERE r.id = ra.roleid
  3487. AND ra.contextid $contextlist
  3488. $hiddensql
  3489. ORDER BY r.sortorder ASC";
  3490. return get_records_sql($sql);
  3491. }
  3492. /**
  3493. * This function is used to print roles column in user profile page.
  3494. * @param int userid
  3495. * @param object context
  3496. * @return string
  3497. */
  3498. function get_user_roles_in_context($userid, $context, $view=true){
  3499. global $CFG, $USER;
  3500. $rolestring = '';
  3501. $SQL = 'select * from '.$CFG->prefix.'role_assignments ra, '.$CFG->prefix.'role r where ra.userid='.$userid.' and ra.contextid='.$context->id.' and ra.roleid = r.id';
  3502. $rolenames = array();
  3503. if ($roles = get_records_sql($SQL)) {
  3504. foreach ($roles as $userrole) {
  3505. // MDL-12544, if we are in view mode and current user has no capability to view hidden assignment, skip it
  3506. if ($userrole->hidden && $view && !has_capability('moodle/role:viewhiddenassigns', $context)) {
  3507. continue;
  3508. }
  3509. $rolenames[$userrole->roleid] = $userrole->name;
  3510. }
  3511. $rolenames = role_fix_names($rolenames, $context); // Substitute aliases
  3512. foreach ($rolenames as $roleid => $rolename) {
  3513. $rolenames[$roleid] = '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$context->id.'&amp;roleid='.$roleid.'">'.$rolename.'</a>';
  3514. }
  3515. $rolestring = implode(',', $rolenames);
  3516. }
  3517. return $rolestring;
  3518. }
  3519. /**
  3520. * Checks if a user can override capabilities of a particular role in this context
  3521. * @param object $context
  3522. * @param int targetroleid - the id of the role you want to override
  3523. * @return boolean
  3524. */
  3525. function user_can_override($context, $targetroleid) {
  3526. // TODO: not needed anymore, remove in 2.0
  3527. // first check if user has override capability
  3528. // if not return false;
  3529. if (!has_capability('moodle/role:override', $context)) {
  3530. return false;
  3531. }
  3532. // pull out all active roles of this user from this context(or above)
  3533. if ($userroles = get_user_roles($context)) {
  3534. foreach ($userroles as $userrole) {
  3535. // if any in the role_allow_override table, then it's ok
  3536. if (get_record('role_allow_override', 'roleid', $userrole->roleid, 'allowoverride', $targetroleid)) {
  3537. return true;
  3538. }
  3539. }
  3540. }
  3541. return false;
  3542. }
  3543. /**
  3544. * Checks if a user can assign users to a particular role in this context
  3545. * @param object $context
  3546. * @param int targetroleid - the id of the role you want to assign users to
  3547. * @return boolean
  3548. */
  3549. function user_can_assign($context, $targetroleid) {
  3550. // first check if user has override capability
  3551. // if not return false;
  3552. if (!has_capability('moodle/role:assign', $context)) {
  3553. return false;
  3554. }
  3555. // pull out all active roles of this user from this context(or above)
  3556. if ($userroles = get_user_roles($context)) {
  3557. foreach ($userroles as $userrole) {
  3558. // if any in the role_allow_override table, then it's ok
  3559. if (get_record('role_allow_assign', 'roleid', $userrole->roleid, 'allowassign', $targetroleid)) {
  3560. return true;
  3561. }
  3562. }
  3563. }
  3564. return false;
  3565. }
  3566. /** Returns all site roles in correct sort order.
  3567. *
  3568. */
  3569. function get_all_roles() {
  3570. return get_records('role', '', '', 'sortorder ASC');
  3571. }
  3572. /**
  3573. * gets all the user roles assigned in this context, or higher contexts
  3574. * this is mainly used when checking if a user can assign a role, or overriding a role
  3575. * i.e. we need to know what this user holds, in order to verify against allow_assign and
  3576. * allow_override tables
  3577. * @param object $context
  3578. * @param int $userid
  3579. * @param view - set to true when roles are pulled for display only
  3580. * this is so that we can filter roles with no visible
  3581. * assignment, for example, you might want to "hide" all
  3582. * course creators when browsing the course participants
  3583. * list.
  3584. * @return array
  3585. */
  3586. function get_user_roles($context, $userid=0, $checkparentcontexts=true, $order='c.contextlevel DESC, r.sortorder ASC', $view=false) {
  3587. global $USER, $CFG, $db;
  3588. if (empty($userid)) {
  3589. if (empty($USER->id)) {
  3590. return array();
  3591. }
  3592. $userid = $USER->id;
  3593. }
  3594. // set up hidden sql
  3595. $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))? ' AND ra.hidden = 0 ':'';
  3596. if ($checkparentcontexts && ($parents = get_parent_contexts($context))) {
  3597. $contexts = ' ra.contextid IN ('.implode(',' , $parents).','.$context->id.')';
  3598. } else {
  3599. $contexts = ' ra.contextid = \''.$context->id.'\'';
  3600. }
  3601. if (!$return = get_records_sql('SELECT ra.*, r.name, r.shortname
  3602. FROM '.$CFG->prefix.'role_assignments ra,
  3603. '.$CFG->prefix.'role r,
  3604. '.$CFG->prefix.'context c
  3605. WHERE ra.userid = '.$userid.'
  3606. AND ra.roleid = r.id
  3607. AND ra.contextid = c.id
  3608. AND '.$contexts . $hiddensql .'
  3609. ORDER BY '.$order)) {
  3610. $return = array();
  3611. }
  3612. return $return;
  3613. }
  3614. /**
  3615. * Creates a record in the allow_override table
  3616. * @param int sroleid - source roleid
  3617. * @param int troleid - target roleid
  3618. * @return int - id or false
  3619. */
  3620. function allow_override($sroleid, $troleid) {
  3621. $record = new object();
  3622. $record->roleid = $sroleid;
  3623. $record->allowoverride = $troleid;
  3624. return insert_record('role_allow_override', $record);
  3625. }
  3626. /**
  3627. * Creates a record in the allow_assign table
  3628. * @param int sroleid - source roleid
  3629. * @param int troleid - target roleid
  3630. * @return int - id or false
  3631. */
  3632. function allow_assign($sroleid, $troleid) {
  3633. $record = new object;
  3634. $record->roleid = $sroleid;
  3635. $record->allowassign = $troleid;
  3636. return insert_record('role_allow_assign', $record);
  3637. }
  3638. /**
  3639. * Gets a list of roles that this user can assign in this context
  3640. * @param object $context
  3641. * @param string $field
  3642. * @param int $rolenamedisplay
  3643. * @return array
  3644. */
  3645. function get_assignable_roles($context, $field='name', $rolenamedisplay=ROLENAME_ALIAS) {
  3646. global $USER, $CFG;
  3647. if (!has_capability('moodle/role:assign', $context)) {
  3648. return array();
  3649. }
  3650. $parents = get_parent_contexts($context);
  3651. $parents[] = $context->id;
  3652. $contexts = implode(',' , $parents);
  3653. if (!$roles = get_records_sql("SELECT ro.*
  3654. FROM {$CFG->prefix}role ro,
  3655. (
  3656. SELECT DISTINCT r.id
  3657. FROM {$CFG->prefix}role r,
  3658. {$CFG->prefix}role_assignments ra,
  3659. {$CFG->prefix}role_allow_assign raa
  3660. WHERE ra.userid = $USER->id AND ra.contextid IN ($contexts)
  3661. AND raa.roleid = ra.roleid AND r.id = raa.allowassign
  3662. ) inline_view
  3663. WHERE ro.id = inline_view.id
  3664. ORDER BY ro.sortorder ASC")) {
  3665. return array();
  3666. }
  3667. foreach ($roles as $role) {
  3668. $roles[$role->id] = $role->$field;
  3669. }
  3670. return role_fix_names($roles, $context, $rolenamedisplay);
  3671. }
  3672. /**
  3673. * Gets a list of roles that this user can assign in this context, for the switchrole menu
  3674. *
  3675. * @param object $context
  3676. * @param string $field
  3677. * @param int $rolenamedisplay
  3678. * @return array
  3679. */
  3680. function get_assignable_roles_for_switchrole($context, $field='name', $rolenamedisplay=ROLENAME_ALIAS) {
  3681. global $USER, $CFG;
  3682. if (!$CFG->allowuserswitchrolestheycantassign) { //config implemented for MDL-11313
  3683. if (!has_capability('moodle/role:assign', $context)) {
  3684. return array();
  3685. }
  3686. }
  3687. $parents = get_parent_contexts($context);
  3688. $parents[] = $context->id;
  3689. $contexts = implode(',' , $parents);
  3690. if (!$roles = get_records_sql("SELECT ro.*
  3691. FROM {$CFG->prefix}role ro,
  3692. (
  3693. SELECT DISTINCT r.id
  3694. FROM {$CFG->prefix}role r,
  3695. {$CFG->prefix}role_assignments ra,
  3696. {$CFG->prefix}role_allow_assign raa,
  3697. {$CFG->prefix}role_capabilities rc
  3698. WHERE ra.userid = $USER->id AND ra.contextid IN ($contexts)
  3699. AND raa.roleid = ra.roleid AND r.id = raa.allowassign
  3700. AND r.id = rc.roleid AND rc.capability = 'moodle/course:view' AND rc.permission = " . CAP_ALLOW . "
  3701. AND NOT EXISTS (SELECT 1 FROM {$CFG->prefix}role_capabilities irc
  3702. WHERE irc.roleid = r.id AND irc.capability = 'moodle/site:doanything' AND irc.permission = " . CAP_ALLOW . ")
  3703. ) inline_view
  3704. WHERE ro.id = inline_view.id
  3705. ORDER BY ro.sortorder ASC")) {
  3706. return array();
  3707. }
  3708. foreach ($roles as $role) {
  3709. $roles[$role->id] = $role->$field;
  3710. }
  3711. return role_fix_names($roles, $context, $rolenamedisplay);
  3712. }
  3713. /**
  3714. * Gets a list of roles that this user can override or safeoverride in this context
  3715. * @param object $context
  3716. * @param string $field
  3717. * @param int $rolenamedisplay
  3718. * @return array
  3719. */
  3720. function get_overridable_roles($context, $field='name', $rolenamedisplay=ROLENAME_ALIAS) {
  3721. global $USER, $CFG;
  3722. if (!has_capability('moodle/role:override', $context) and !has_capability('moodle/role:safeoverride', $context)) {
  3723. return array();
  3724. }
  3725. $parents = get_parent_contexts($context);
  3726. $parents[] = $context->id;
  3727. $contexts = implode(',' , $parents);
  3728. if (!$roles = get_records_sql("SELECT ro.*
  3729. FROM {$CFG->prefix}role ro,
  3730. (
  3731. SELECT DISTINCT r.id
  3732. FROM {$CFG->prefix}role r,
  3733. {$CFG->prefix}role_assignments ra,
  3734. {$CFG->prefix}role_allow_override rao
  3735. WHERE ra.userid = $USER->id AND ra.contextid IN ($contexts)
  3736. AND rao.roleid = ra.roleid AND r.id = rao.allowoverride
  3737. ) inline_view
  3738. WHERE ro.id = inline_view.id
  3739. ORDER BY ro.sortorder ASC")) {
  3740. return array();
  3741. }
  3742. foreach ($roles as $role) {
  3743. $roles[$role->id] = $role->$field;
  3744. }
  3745. return role_fix_names($roles, $context, $rolenamedisplay);
  3746. }
  3747. /**
  3748. * Returns a role object that is the default role for new enrolments
  3749. * in a given course
  3750. *
  3751. * @param object $course
  3752. * @return object $role
  3753. */
  3754. function get_default_course_role($course) {
  3755. global $CFG;
  3756. /// First let's take the default role the course may have
  3757. if (!empty($course->defaultrole)) {
  3758. if ($role = get_record('role', 'id', $course->defaultrole)) {
  3759. return $role;
  3760. }
  3761. }
  3762. /// Otherwise the site setting should tell us
  3763. if ($CFG->defaultcourseroleid) {
  3764. if ($role = get_record('role', 'id', $CFG->defaultcourseroleid)) {
  3765. return $role;
  3766. }
  3767. }
  3768. /// It's unlikely we'll get here, but just in case, try and find a student role
  3769. if ($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW)) {
  3770. return array_shift($studentroles); /// Take the first one
  3771. }
  3772. return NULL;
  3773. }
  3774. /**
  3775. * Who has this capability in this context?
  3776. *
  3777. * This can be a very expensive call - use sparingly and keep
  3778. * the results if you are going to need them again soon.
  3779. *
  3780. * Note if $fields is empty this function attempts to get u.*
  3781. * which can get rather large - and has a serious perf impact
  3782. * on some DBs.
  3783. *
  3784. * @param $context - object
  3785. * @param $capability - string capability, or an array of capabilities, in which
  3786. * case users having any of those capabilities will be returned.
  3787. * For performance reasons, you are advised to put the capability
  3788. * that the user is most likely to have first.
  3789. * @param $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
  3790. * @param $sort - the sort order. Default is lastaccess time.
  3791. * @param $limitfrom - number of records to skip (offset)
  3792. * @param $limitnum - number of records to fetch
  3793. * @param $groups - single group or array of groups - only return
  3794. * users who are in one of these group(s).
  3795. * @param $exceptions - list of users to exclude
  3796. * @param view - set to true when roles are pulled for display only
  3797. * this is so that we can filter roles with no visible
  3798. * assignment, for example, you might want to "hide" all
  3799. * course creators when browsing the course participants
  3800. * list.
  3801. * @param boolean $useviewallgroups if $groups is set the return users who
  3802. * have capability both $capability and moodle/site:accessallgroups
  3803. * in this context, as well as users who have $capability and who are
  3804. * in $groups.
  3805. */
  3806. function get_users_by_capability($context, $capability, $fields='', $sort='',
  3807. $limitfrom='', $limitnum='', $groups='', $exceptions='', $doanything=true,
  3808. $view=false, $useviewallgroups=false) {
  3809. global $CFG;
  3810. $ctxids = substr($context->path, 1); // kill leading slash
  3811. $ctxids = str_replace('/', ',', $ctxids);
  3812. // Context is the frontpage
  3813. $isfrontpage = false;
  3814. $iscoursepage = false; // coursepage other than fp
  3815. if ($context->contextlevel == CONTEXT_COURSE) {
  3816. if ($context->instanceid == SITEID) {
  3817. $isfrontpage = true;
  3818. } else {
  3819. $iscoursepage = true;
  3820. }
  3821. }
  3822. // What roles/rolecaps are interesting?
  3823. if (is_array($capability)) {
  3824. $caps = "'" . implode("','", $capability) . "'";
  3825. $capabilities = $capability;
  3826. } else {
  3827. $caps = "'" . $capability . "'";
  3828. $capabilities = array($capability);
  3829. }
  3830. if ($doanything===true) {
  3831. $caps .= ",'moodle/site:doanything'";
  3832. $capabilities[] = 'moodle/site:doanything';
  3833. $doanything_join='';
  3834. $doanything_cond='';
  3835. } else {
  3836. // This is an outer join against
  3837. // admin-ish roleids. Any row that succeeds
  3838. // in JOINing here ends up removed from
  3839. // the resultset. This means we remove
  3840. // rolecaps from roles that also have
  3841. // 'doanything' capabilities.
  3842. $doanything_join="LEFT OUTER JOIN (
  3843. SELECT DISTINCT rc.roleid
  3844. FROM {$CFG->prefix}role_capabilities rc
  3845. WHERE rc.capability='moodle/site:doanything'
  3846. AND rc.permission=".CAP_ALLOW."
  3847. AND rc.contextid IN ($ctxids)
  3848. ) dar
  3849. ON rc.roleid=dar.roleid";
  3850. $doanything_cond="AND dar.roleid IS NULL";
  3851. }
  3852. // fetch all capability records - we'll walk several
  3853. // times over them, and should be a small set
  3854. $negperm = false; // has any negative (<0) permission?
  3855. $roleids = array();
  3856. $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability,
  3857. ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
  3858. FROM {$CFG->prefix}role_capabilities rc
  3859. JOIN {$CFG->prefix}context ctx on rc.contextid = ctx.id
  3860. $doanything_join
  3861. WHERE rc.capability IN ($caps) AND ctx.id IN ($ctxids)
  3862. $doanything_cond
  3863. ORDER BY rc.roleid ASC, ctx.depth ASC";
  3864. if ($capdefs = get_records_sql($sql)) {
  3865. foreach ($capdefs AS $rcid=>$rc) {
  3866. $roleids[] = (int)$rc->roleid;
  3867. if ($rc->permission < 0) {
  3868. $negperm = true;
  3869. }
  3870. }
  3871. }
  3872. $roleids = array_unique($roleids);
  3873. if (count($roleids)===0) { // noone here!
  3874. return false;
  3875. }
  3876. // is the default role interesting? does it have
  3877. // a relevant rolecap? (we use this a lot later)
  3878. if (in_array((int)$CFG->defaultuserroleid, $roleids, true)) {
  3879. $defaultroleinteresting = true;
  3880. } else {
  3881. $defaultroleinteresting = false;
  3882. }
  3883. // is the default role interesting? does it have
  3884. // a relevant rolecap? (we use this a lot later)
  3885. if (($isfrontpage or is_inside_frontpage($context)) and !empty($CFG->defaultfrontpageroleid) and in_array((int)$CFG->defaultfrontpageroleid, $roleids, true)) {
  3886. if (!empty($CFG->fullusersbycapabilityonfrontpage)) {
  3887. // new in 1.9.6 - full support for defaultfrontpagerole MDL-19039
  3888. $frontpageroleinteresting = true;
  3889. } else {
  3890. // old style 1.9.0-1.9.5 - much faster + fewer negative override problems on frontpage
  3891. $frontpageroleinteresting = ($context->contextlevel == CONTEXT_COURSE);
  3892. }
  3893. } else {
  3894. $frontpageroleinteresting = false;
  3895. }
  3896. //
  3897. // Prepare query clauses
  3898. //
  3899. $wherecond = array();
  3900. // Non-deleted users. We never return deleted users.
  3901. $wherecond['nondeleted'] = 'u.deleted = 0';
  3902. /// Groups
  3903. if ($groups) {
  3904. if (is_array($groups)) {
  3905. $grouptest = 'gm.groupid IN (' . implode(',', $groups) . ')';
  3906. } else {
  3907. $grouptest = 'gm.groupid = ' . $groups;
  3908. }
  3909. $grouptest = 'u.id IN (SELECT userid FROM ' .
  3910. $CFG->prefix . 'groups_members gm WHERE ' . $grouptest . ')';
  3911. if ($useviewallgroups) {
  3912. $viewallgroupsusers = get_users_by_capability($context,
  3913. 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
  3914. $wherecond['groups'] = '('. $grouptest . ' OR u.id IN (' .
  3915. implode(',', array_keys($viewallgroupsusers)) . '))';
  3916. } else {
  3917. $wherecond['groups'] = '(' . $grouptest .')';
  3918. }
  3919. }
  3920. /// User exceptions
  3921. if (!empty($exceptions)) {
  3922. $wherecond['userexceptions'] = ' u.id NOT IN ('.$exceptions.')';
  3923. }
  3924. /// Set up hidden role-assignments sql
  3925. if ($view && !has_capability('moodle/role:viewhiddenassigns', $context)) {
  3926. $condhiddenra = 'AND ra.hidden = 0 ';
  3927. $sscondhiddenra = 'AND ssra.hidden = 0 ';
  3928. } else {
  3929. $condhiddenra = '';
  3930. $sscondhiddenra = '';
  3931. }
  3932. // Collect WHERE conditions
  3933. $where = implode(' AND ', array_values($wherecond));
  3934. if ($where != '') {
  3935. $where = 'WHERE ' . $where;
  3936. }
  3937. /// Set up default fields
  3938. if (empty($fields)) {
  3939. if ($iscoursepage) {
  3940. $fields = 'u.*, ul.timeaccess as lastaccess';
  3941. } else {
  3942. $fields = 'u.*';
  3943. }
  3944. } else {
  3945. if (debugging('', DEBUG_DEVELOPER) && strpos($fields, 'u.*') === false &&
  3946. strpos($fields, 'u.id') === false) {
  3947. debugging('u.id must be included in the list of fields passed to get_users_by_capability.', DEBUG_DEVELOPER);
  3948. }
  3949. }
  3950. /// Set up default sort
  3951. if (empty($sort)) { // default to course lastaccess or just lastaccess
  3952. if ($iscoursepage) {
  3953. $sort = 'ul.timeaccess';
  3954. } else {
  3955. $sort = 'u.lastaccess';
  3956. }
  3957. }
  3958. $sortby = $sort ? " ORDER BY $sort " : '';
  3959. // User lastaccess JOIN
  3960. if ((strpos($sort, 'ul.timeaccess') === FALSE) and (strpos($fields, 'ul.timeaccess') === FALSE)) { // user_lastaccess is not required MDL-13810
  3961. $uljoin = '';
  3962. } else {
  3963. $uljoin = "LEFT OUTER JOIN {$CFG->prefix}user_lastaccess ul
  3964. ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
  3965. }
  3966. //
  3967. // Simple cases - No negative permissions means we can take shortcuts
  3968. //
  3969. if (!$negperm) {
  3970. // at the frontpage, and all site users have it - easy!
  3971. if ($frontpageroleinteresting) {
  3972. return get_records_sql("SELECT $fields
  3973. FROM {$CFG->prefix}user u
  3974. WHERE u.deleted = 0
  3975. ORDER BY $sort",
  3976. $limitfrom, $limitnum);
  3977. }
  3978. // all site users have it, anyway
  3979. // TODO: NOT ALWAYS! Check this case because this gets run for cases like this:
  3980. // 1) Default role has the permission for a module thing like mod/choice:choose
  3981. // 2) We are checking for an activity module context in a course
  3982. // 3) Thus all users are returned even though course:view is also required
  3983. if ($defaultroleinteresting) {
  3984. $sql = "SELECT $fields
  3985. FROM {$CFG->prefix}user u
  3986. $uljoin
  3987. $where
  3988. ORDER BY $sort";
  3989. return get_records_sql($sql, $limitfrom, $limitnum);
  3990. }
  3991. /// Simple SQL assuming no negative rolecaps.
  3992. /// We use a subselect to grab the role assignments
  3993. /// ensuring only one row per user -- even if they
  3994. /// have many "relevant" role assignments.
  3995. $select = " SELECT $fields";
  3996. $from = " FROM {$CFG->prefix}user u
  3997. JOIN (SELECT DISTINCT ssra.userid
  3998. FROM {$CFG->prefix}role_assignments ssra
  3999. WHERE ssra.contextid IN ($ctxids)
  4000. AND ssra.roleid IN (".implode(',',$roleids) .")
  4001. $sscondhiddenra
  4002. ) ra ON ra.userid = u.id
  4003. $uljoin ";
  4004. return get_records_sql($select.$from.$where.$sortby, $limitfrom, $limitnum);
  4005. }
  4006. //
  4007. // If there are any negative rolecaps, we need to
  4008. // work through a subselect that will bring several rows
  4009. // per user (one per RA).
  4010. // Since we cannot do the job in pure SQL (not without SQL stored
  4011. // procedures anyway), we end up tied to processing the data in PHP
  4012. // all the way down to pagination.
  4013. //
  4014. // In some cases, this will mean bringing across a ton of data --
  4015. // when paginating, we have to walk the permisisons of all the rows
  4016. // in the _previous_ pages to get the pagination correct in the case
  4017. // of users that end up not having the permission - this removed.
  4018. //
  4019. // Prepare the role permissions datastructure for fast lookups
  4020. $roleperms = array(); // each role cap and depth
  4021. foreach ($capdefs AS $rcid=>$rc) {
  4022. $rid = (int)$rc->roleid;
  4023. $perm = (int)$rc->permission;
  4024. $rcdepth = (int)$rc->ctxdepth;
  4025. if (!isset($roleperms[$rc->capability][$rid])) {
  4026. $roleperms[$rc->capability][$rid] = (object)array('perm' => $perm,
  4027. 'rcdepth' => $rcdepth);
  4028. } else {
  4029. if ($roleperms[$rc->capability][$rid]->perm == CAP_PROHIBIT) {
  4030. continue;
  4031. }
  4032. // override - as we are going
  4033. // from general to local perms
  4034. // (as per the ORDER BY...depth ASC above)
  4035. // and local perms win...
  4036. $roleperms[$rc->capability][$rid] = (object)array('perm' => $perm,
  4037. 'rcdepth' => $rcdepth);
  4038. }
  4039. }
  4040. if ($context->contextlevel == CONTEXT_SYSTEM
  4041. || $frontpageroleinteresting
  4042. || $defaultroleinteresting) {
  4043. // Handle system / sitecourse / defaultrole-with-perhaps-neg-overrides
  4044. // with a SELECT FROM user LEFT OUTER JOIN against ra -
  4045. // This is expensive on the SQL and PHP sides -
  4046. // moves a ton of data across the wire.
  4047. $ss = "SELECT u.id as userid, ra.roleid,
  4048. ctx.depth
  4049. FROM {$CFG->prefix}user u
  4050. LEFT OUTER JOIN {$CFG->prefix}role_assignments ra
  4051. ON (ra.userid = u.id
  4052. AND ra.contextid IN ($ctxids)
  4053. AND ra.roleid IN (".implode(',',$roleids) .")
  4054. $condhiddenra)
  4055. LEFT OUTER JOIN {$CFG->prefix}context ctx
  4056. ON ra.contextid=ctx.id
  4057. WHERE u.deleted=0";
  4058. } else {
  4059. // "Normal complex case" - the rolecaps we are after will
  4060. // be defined in a role assignment somewhere.
  4061. $ss = "SELECT ra.userid as userid, ra.roleid,
  4062. ctx.depth
  4063. FROM {$CFG->prefix}role_assignments ra
  4064. JOIN {$CFG->prefix}context ctx
  4065. ON ra.contextid=ctx.id
  4066. WHERE ra.contextid IN ($ctxids)
  4067. $condhiddenra
  4068. AND ra.roleid IN (".implode(',',$roleids) .")";
  4069. }
  4070. $select = "SELECT $fields ,ra.roleid, ra.depth ";
  4071. $from = "FROM ($ss) ra
  4072. JOIN {$CFG->prefix}user u
  4073. ON ra.userid=u.id
  4074. $uljoin ";
  4075. // Each user's entries MUST come clustered together
  4076. // and RAs ordered in depth DESC - the role/cap resolution
  4077. // code depends on this.
  4078. $sort .= ' , ra.userid ASC, ra.depth DESC';
  4079. $sortby .= ' , ra.userid ASC, ra.depth DESC ';
  4080. $rs = get_recordset_sql($select.$from.$where.$sortby);
  4081. //
  4082. // Process the user accounts+RAs, folding repeats together...
  4083. //
  4084. // The processing for this recordset is tricky - to fold
  4085. // the role/perms of users with multiple role-assignments
  4086. // correctly while still processing one-row-at-a-time
  4087. // we need to add a few additional 'private' fields to
  4088. // the results array - so we can treat the rows as a
  4089. // state machine to track the cap/perms and at what RA-depth
  4090. // and RC-depth they were defined.
  4091. //
  4092. // So what we do here is:
  4093. // - loop over rows, checking pagination limits
  4094. // - when we find a new user, if we are in the page add it to the
  4095. // $results, and start building $ras array with its role-assignments
  4096. // - when we are dealing with the next user, or are at the end of the userlist
  4097. // (last rec or last in page), trigger the check-permission idiom
  4098. // - the check permission idiom will
  4099. // - add the default enrolment if needed
  4100. // - call has_any_capability_from_rarc(), which based on RAs and RCs will return a bool
  4101. // (should be fairly tight code ;-) )
  4102. // - if the user has permission, all is good, just $c++ (counter)
  4103. // - ...else, decrease the counter - so pagination is kept straight,
  4104. // and (if we are in the page) remove from the results
  4105. //
  4106. $results = array();
  4107. // pagination controls
  4108. $c = 0;
  4109. $limitfrom = (int)$limitfrom;
  4110. $limitnum = (int)$limitnum;
  4111. //
  4112. // Track our last user id so we know when we are dealing
  4113. // with a new user...
  4114. //
  4115. $lastuserid = 0;
  4116. //
  4117. // In this loop, we
  4118. // $ras: role assignments, multidimensional array
  4119. // treat as a stack - going from local to general
  4120. // $ras = (( roleid=> x, $depth=>y) , ( roleid=> x, $depth=>y))
  4121. //
  4122. while ($user = rs_fetch_next_record($rs)) {
  4123. //error_log(" Record: " . print_r($user,1));
  4124. //
  4125. // Pagination controls
  4126. // Note that we might end up removing a user
  4127. // that ends up _not_ having the rights,
  4128. // therefore rolling back $c
  4129. //
  4130. if ($lastuserid != $user->id) {
  4131. // Did the last user end up with a positive permission?
  4132. if ($lastuserid !=0) {
  4133. if ($frontpageroleinteresting) {
  4134. // add frontpage role if interesting
  4135. $ras[] = array('roleid' => $CFG->defaultfrontpageroleid,
  4136. 'depth' => $context->depth);
  4137. }
  4138. if ($defaultroleinteresting) {
  4139. // add the role at the end of $ras
  4140. $ras[] = array( 'roleid' => $CFG->defaultuserroleid,
  4141. 'depth' => 1 );
  4142. }
  4143. if (has_any_capability_from_rarc($ras, $roleperms, $capabilities)) {
  4144. $c++;
  4145. } else {
  4146. // remove the user from the result set,
  4147. // only if we are 'in the page'
  4148. if ($limitfrom === 0 || $c >= $limitfrom) {
  4149. unset($results[$lastuserid]);
  4150. }
  4151. }
  4152. }
  4153. // Did we hit pagination limit?
  4154. if ($limitnum !==0 && $c >= ($limitfrom+$limitnum)) { // we are done!
  4155. break;
  4156. }
  4157. // New user setup, and $ras reset
  4158. $lastuserid = $user->id;
  4159. $ras = array();
  4160. if (!empty($user->roleid)) {
  4161. $ras[] = array( 'roleid' => (int)$user->roleid,
  4162. 'depth' => (int)$user->depth );
  4163. }
  4164. // if we are 'in the page', also add the rec
  4165. // to the results...
  4166. if ($limitfrom === 0 || $c >= $limitfrom) {
  4167. $results[$user->id] = $user; // trivial
  4168. }
  4169. } else {
  4170. // Additional RA for $lastuserid
  4171. $ras[] = array( 'roleid'=>(int)$user->roleid,
  4172. 'depth'=>(int)$user->depth );
  4173. }
  4174. } // end while(fetch)
  4175. // Prune last entry if necessary
  4176. if ($lastuserid !=0) {
  4177. if ($frontpageroleinteresting) {
  4178. // add frontpage role if interesting
  4179. $ras[] = array('roleid' => $CFG->defaultfrontpageroleid,
  4180. 'depth' => $context->depth);
  4181. }
  4182. if ($defaultroleinteresting) {
  4183. // add the role at the end of $ras
  4184. $ras[] = array( 'roleid' => $CFG->defaultuserroleid,
  4185. 'depth' => 1 );
  4186. }
  4187. if (!has_any_capability_from_rarc($ras, $roleperms, $capabilities)) {
  4188. // remove the user from the result set,
  4189. // only if we are 'in the page'
  4190. if ($limitfrom === 0 || $c >= $limitfrom) {
  4191. if (isset($results[$lastuserid])) {
  4192. unset($results[$lastuserid]);
  4193. }
  4194. }
  4195. }
  4196. }
  4197. return $results;
  4198. }
  4199. /*
  4200. * Fast (fast!) utility function to resolve if any of a list of capabilities is
  4201. * granted, based on Role Assignments and Role Capabilities.
  4202. *
  4203. * Used (at least) by get_users_by_capability().
  4204. *
  4205. * If PHP had fast built-in memoize functions, we could
  4206. * add a $contextid parameter and memoize the return values.
  4207. *
  4208. * Note that this function must be kept in synch with has_capability_in_accessdata.
  4209. *
  4210. * @param array $ras - role assignments
  4211. * @param array $roleperms - role permissions
  4212. * @param string $capabilities - array of capability names
  4213. * @return boolean
  4214. */
  4215. function has_any_capability_from_rarc($ras, $roleperms, $caps) {
  4216. // Mini-state machine, using $hascap
  4217. // $hascap[ 'moodle/foo:bar' ]->perm = CAP_SOMETHING (numeric constant)
  4218. // $hascap[ 'moodle/foo:bar' ]->radepth = depth of the role assignment that set it
  4219. // $hascap[ 'moodle/foo:bar' ]->rcdepth = depth of the rolecap that set it
  4220. // -- when resolving conflicts, we need to look into radepth first, if unresolved
  4221. $hascap = array();
  4222. //
  4223. // Compute which permission/roleassignment/rolecap
  4224. // wins for each capability we are walking
  4225. //
  4226. foreach ($ras as $ra) {
  4227. foreach ($caps as $cap) {
  4228. if (!isset($roleperms[$cap][$ra['roleid']])) {
  4229. // nothing set for this cap - skip
  4230. continue;
  4231. }
  4232. // We explicitly clone here as we
  4233. // add more properties to it
  4234. // that must stay separate from the
  4235. // original roleperm data structure
  4236. $rp = clone($roleperms[$cap][$ra['roleid']]);
  4237. $rp->radepth = $ra['depth'];
  4238. // Trivial case, we are the first to set
  4239. if (!isset($hascap[$cap])) {
  4240. $hascap[$cap] = $rp;
  4241. }
  4242. //
  4243. // Resolve who prevails, in order of precendence
  4244. // - Prohibits always wins
  4245. // - Locality of RA
  4246. // - Locality of RC
  4247. //
  4248. //// Prohibits...
  4249. if ($rp->perm === CAP_PROHIBIT) {
  4250. $hascap[$cap] = $rp;
  4251. continue;
  4252. }
  4253. if ($hascap[$cap]->perm === CAP_PROHIBIT) {
  4254. continue;
  4255. }
  4256. // Locality of RA - the look is ordered by depth DESC
  4257. // so from local to general -
  4258. // Higher RA loses to local RA... unless perm===0
  4259. /// Thanks to the order of the records, $rp->radepth <= $hascap[$cap]->radepth
  4260. if ($rp->radepth > $hascap[$cap]->radepth) {
  4261. error_log('Should not happen @ ' . __FUNCTION__.':'.__LINE__);
  4262. }
  4263. if ($rp->radepth < $hascap[$cap]->radepth) {
  4264. if ($hascap[$cap]->perm!==0) {
  4265. // Wider RA loses to local RAs...
  4266. continue;
  4267. } else {
  4268. // "Higher RA resolves conflict" case,
  4269. // local RAs had cancelled eachother
  4270. $hascap[$cap] = $rp;
  4271. continue;
  4272. }
  4273. }
  4274. // Same ralevel - locality of RC wins
  4275. if ($rp->rcdepth > $hascap[$cap]->rcdepth) {
  4276. $hascap[$cap] = $rp;
  4277. continue;
  4278. }
  4279. if ($rp->rcdepth > $hascap[$cap]->rcdepth) {
  4280. continue;
  4281. }
  4282. // We match depth - add them
  4283. $hascap[$cap]->perm += $rp->perm;
  4284. }
  4285. }
  4286. foreach ($caps as $capability) {
  4287. if (isset($hascap[$capability]) && $hascap[$capability]->perm > 0) {
  4288. return true;
  4289. }
  4290. }
  4291. return false;
  4292. }
  4293. /**
  4294. * Will re-sort a $users results array (from get_users_by_capability(), usually)
  4295. * based on a sorting policy. This is to support the odd practice of
  4296. * sorting teachers by 'authority', where authority was "lowest id of the role
  4297. * assignment".
  4298. *
  4299. * Will execute 1 database query. Only suitable for small numbers of users, as it
  4300. * uses an u.id IN() clause.
  4301. *
  4302. * Notes about the sorting criteria.
  4303. *
  4304. * As a default, we cannot rely on role.sortorder because then
  4305. * admins/coursecreators will always win. That is why the sane
  4306. * rule "is locality matters most", with sortorder as 2nd
  4307. * consideration.
  4308. *
  4309. * If you want role.sortorder, use the 'sortorder' policy, and
  4310. * name explicitly what roles you want to cover. It's probably
  4311. * a good idea to see what roles have the capabilities you want
  4312. * (array_diff() them against roiles that have 'can-do-anything'
  4313. * to weed out admin-ish roles. Or fetch a list of roles from
  4314. * variables like $CFG->coursemanagers .
  4315. *
  4316. * @param array users Users' array, keyed on userid
  4317. * @param object context
  4318. * @param array roles - ids of the roles to include, optional
  4319. * @param string policy - defaults to locality, more about
  4320. * @return array - sorted copy of the array
  4321. */
  4322. function sort_by_roleassignment_authority($users, $context, $roles=array(), $sortpolicy='locality') {
  4323. global $CFG;
  4324. $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
  4325. $contextwhere = ' ra.contextid IN ('.str_replace('/', ',',substr($context->path, 1)).')';
  4326. if (empty($roles)) {
  4327. $roleswhere = '';
  4328. } else {
  4329. $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
  4330. }
  4331. $sql = "SELECT ra.userid
  4332. FROM {$CFG->prefix}role_assignments ra
  4333. JOIN {$CFG->prefix}role r
  4334. ON ra.roleid=r.id
  4335. JOIN {$CFG->prefix}context ctx
  4336. ON ra.contextid=ctx.id
  4337. WHERE
  4338. $userswhere
  4339. AND $contextwhere
  4340. $roleswhere
  4341. ";
  4342. // Default 'locality' policy -- read PHPDoc notes
  4343. // about sort policies...
  4344. $orderby = 'ORDER BY
  4345. ctx.depth DESC, /* locality wins */
  4346. r.sortorder ASC, /* rolesorting 2nd criteria */
  4347. ra.id /* role assignment order tie-breaker */';
  4348. if ($sortpolicy === 'sortorder') {
  4349. $orderby = 'ORDER BY
  4350. r.sortorder ASC, /* rolesorting 2nd criteria */
  4351. ra.id /* role assignment order tie-breaker */';
  4352. }
  4353. $sortedids = get_fieldset_sql($sql . $orderby);
  4354. $sortedusers = array();
  4355. $seen = array();
  4356. foreach ($sortedids as $id) {
  4357. // Avoid duplicates
  4358. if (isset($seen[$id])) {
  4359. continue;
  4360. }
  4361. $seen[$id] = true;
  4362. // assign
  4363. $sortedusers[$id] = $users[$id];
  4364. }
  4365. return $sortedusers;
  4366. }
  4367. /**
  4368. * gets all the users assigned this role in this context or higher
  4369. * @param int roleid (can also be an array of ints!)
  4370. * @param int contextid
  4371. * @param bool parent if true, get list of users assigned in higher context too
  4372. * @param string fields - fields from user (u.) , role assignment (ra) or role (r.)
  4373. * @param string sort - sort from user (u.) , role assignment (ra) or role (r.)
  4374. * @param bool gethidden - whether to fetch hidden enrolments too
  4375. * @return array()
  4376. */
  4377. function get_role_users($roleid, $context, $parent=false, $fields='', $sort='u.lastname ASC, u.firstname ASC', $gethidden=true, $group='', $limitfrom='', $limitnum='') {
  4378. global $CFG;
  4379. if (empty($fields)) {
  4380. $fields = 'u.id, u.confirmed, u.username, u.firstname, u.lastname, '.
  4381. 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.city, '.
  4382. 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
  4383. 'u.emailstop, u.lang, u.timezone, u.lastaccess, u.mnethostid, r.name as rolename';
  4384. }
  4385. // whether this assignment is hidden
  4386. $hiddensql = $gethidden ? '': ' AND ra.hidden = 0 ';
  4387. $parentcontexts = '';
  4388. if ($parent) {
  4389. $parentcontexts = substr($context->path, 1); // kill leading slash
  4390. $parentcontexts = str_replace('/', ',', $parentcontexts);
  4391. if ($parentcontexts !== '') {
  4392. $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
  4393. }
  4394. }
  4395. if (is_array($roleid)) {
  4396. $roleselect = ' AND ra.roleid IN (' . implode(',',$roleid) .')';
  4397. } elseif (!empty($roleid)) { // should not test for int, because it can come in as a string
  4398. $roleselect = "AND ra.roleid = $roleid";
  4399. } else {
  4400. $roleselect = '';
  4401. }
  4402. if ($group) {
  4403. $groupjoin = "JOIN {$CFG->prefix}groups_members gm
  4404. ON gm.userid = u.id";
  4405. $groupselect = " AND gm.groupid = $group ";
  4406. } else {
  4407. $groupjoin = '';
  4408. $groupselect = '';
  4409. }
  4410. $SQL = "SELECT $fields, ra.roleid
  4411. FROM {$CFG->prefix}role_assignments ra
  4412. JOIN {$CFG->prefix}user u
  4413. ON u.id = ra.userid
  4414. JOIN {$CFG->prefix}role r
  4415. ON ra.roleid = r.id
  4416. $groupjoin
  4417. WHERE (ra.contextid = $context->id $parentcontexts)
  4418. $roleselect
  4419. $groupselect
  4420. $hiddensql
  4421. ORDER BY $sort
  4422. "; // join now so that we can just use fullname() later
  4423. return get_records_sql($SQL, $limitfrom, $limitnum);
  4424. }
  4425. /**
  4426. * Counts all the users assigned this role in this context or higher
  4427. * @param int roleid (can also be an array of ints!)
  4428. * @param int contextid
  4429. * @param bool parent if true, get list of users assigned in higher context too
  4430. * @return array()
  4431. */
  4432. function count_role_users($roleid, $context, $parent=false) {
  4433. global $CFG;
  4434. if ($parent) {
  4435. if ($contexts = get_parent_contexts($context)) {
  4436. $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
  4437. } else {
  4438. $parentcontexts = '';
  4439. }
  4440. } else {
  4441. $parentcontexts = '';
  4442. }
  4443. $rolesql = '';
  4444. if (is_numeric($roleid)) {
  4445. $rolesql = "AND r.roleid = $roleid";
  4446. }
  4447. else if (is_array($roleid)) {
  4448. $rolesql = "AND r.roleid IN (" . implode(',', $roleid) . ")";
  4449. }
  4450. $SQL = "SELECT count(u.id)
  4451. FROM {$CFG->prefix}role_assignments r
  4452. JOIN {$CFG->prefix}user u
  4453. ON u.id = r.userid
  4454. WHERE (r.contextid = $context->id $parentcontexts)
  4455. $rolesql
  4456. AND u.deleted = 0";
  4457. return count_records_sql($SQL);
  4458. }
  4459. /**
  4460. * This function gets the list of courses that this user has a particular capability in.
  4461. * It is still not very efficient.
  4462. * @param string $capability Capability in question
  4463. * @param int $userid User ID or null for current user
  4464. * @param bool $doanything True if 'doanything' is permitted (default)
  4465. * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
  4466. * otherwise use a comma-separated list of the fields you require, not including id
  4467. * @param string $orderby If set, use a comma-separated list of fields from course
  4468. * table with sql modifiers (DESC) if needed
  4469. * @return array Array of courses, may have zero entries. Or false if query failed.
  4470. */
  4471. function get_user_capability_course($capability, $userid=NULL,$doanything=true,$fieldsexceptid='',$orderby='') {
  4472. // Convert fields list and ordering
  4473. $fieldlist='';
  4474. if($fieldsexceptid) {
  4475. $fields=explode(',',$fieldsexceptid);
  4476. foreach($fields as $field) {
  4477. $fieldlist.=',c.'.$field;
  4478. }
  4479. }
  4480. if($orderby) {
  4481. $fields=explode(',',$orderby);
  4482. $orderby='';
  4483. foreach($fields as $field) {
  4484. if($orderby) {
  4485. $orderby.=',';
  4486. }
  4487. $orderby.='c.'.$field;
  4488. }
  4489. $orderby='ORDER BY '.$orderby;
  4490. }
  4491. // Obtain a list of everything relevant about all courses including context.
  4492. // Note the result can be used directly as a context (we are going to), the course
  4493. // fields are just appended.
  4494. global $CFG;
  4495. $rs=get_recordset_sql("
  4496. SELECT
  4497. x.*,c.id AS courseid$fieldlist
  4498. FROM
  4499. {$CFG->prefix}course c
  4500. INNER JOIN {$CFG->prefix}context x ON c.id=x.instanceid AND x.contextlevel=".CONTEXT_COURSE."
  4501. $orderby
  4502. ");
  4503. if(!$rs) {
  4504. return false;
  4505. }
  4506. // Check capability for each course in turn
  4507. $courses=array();
  4508. while($coursecontext=rs_fetch_next_record($rs)) {
  4509. if(has_capability($capability,$coursecontext,$userid,$doanything)) {
  4510. // We've got the capability. Make the record look like a course record
  4511. // and store it
  4512. $coursecontext->id=$coursecontext->courseid;
  4513. unset($coursecontext->courseid);
  4514. unset($coursecontext->contextlevel);
  4515. unset($coursecontext->instanceid);
  4516. $courses[]=$coursecontext;
  4517. }
  4518. }
  4519. return $courses;
  4520. }
  4521. /** This function finds the roles assigned directly to this context only
  4522. * i.e. no parents role
  4523. * @param object $context
  4524. * @return array
  4525. */
  4526. function get_roles_on_exact_context($context) {
  4527. global $CFG;
  4528. return get_records_sql("SELECT r.*
  4529. FROM {$CFG->prefix}role_assignments ra,
  4530. {$CFG->prefix}role r
  4531. WHERE ra.roleid = r.id
  4532. AND ra.contextid = $context->id");
  4533. }
  4534. /**
  4535. * Switches the current user to another role for the current session and only
  4536. * in the given context.
  4537. *
  4538. * The caller *must* check
  4539. * - that this op is allowed
  4540. * - that the requested role can be assigned in this ctx
  4541. * (hint, use get_assignable_roles_for_switchrole())
  4542. * - that the requested role is NOT $CFG->defaultuserroleid
  4543. *
  4544. * To "unswitch" pass 0 as the roleid.
  4545. *
  4546. * This function *will* modify $USER->access - beware
  4547. *
  4548. * @param integer $roleid
  4549. * @param object $context
  4550. * @return bool
  4551. */
  4552. function role_switch($roleid, $context) {
  4553. global $USER, $CFG;
  4554. //
  4555. // Plan of action
  4556. //
  4557. // - Add the ghost RA to $USER->access
  4558. // as $USER->access['rsw'][$path] = $roleid
  4559. //
  4560. // - Make sure $USER->access['rdef'] has the roledefs
  4561. // it needs to honour the switcheroo
  4562. //
  4563. // Roledefs will get loaded "deep" here - down to the last child
  4564. // context. Note that
  4565. //
  4566. // - When visiting subcontexts, our selective accessdata loading
  4567. // will still work fine - though those ra/rdefs will be ignored
  4568. // appropriately while the switch is in place
  4569. //
  4570. // - If a switcheroo happens at a category with tons of courses
  4571. // (that have many overrides for switched-to role), the session
  4572. // will get... quite large. Sometimes you just can't win.
  4573. //
  4574. // To un-switch just unset($USER->access['rsw'][$path])
  4575. //
  4576. // Add the switch RA
  4577. if (!isset($USER->access['rsw'])) {
  4578. $USER->access['rsw'] = array();
  4579. }
  4580. if ($roleid == 0) {
  4581. unset($USER->access['rsw'][$context->path]);
  4582. if (empty($USER->access['rsw'])) {
  4583. unset($USER->access['rsw']);
  4584. }
  4585. return true;
  4586. }
  4587. $USER->access['rsw'][$context->path]=$roleid;
  4588. // Load roledefs
  4589. $USER->access = get_role_access_bycontext($roleid, $context,
  4590. $USER->access);
  4591. /* DO WE NEED THIS AT ALL???
  4592. // Add some permissions we are really going
  4593. // to always need, even if the role doesn't have them!
  4594. $USER->capabilities[$context->id]['moodle/course:view'] = CAP_ALLOW;
  4595. */
  4596. return true;
  4597. }
  4598. // get any role that has an override on exact context
  4599. function get_roles_with_override_on_context($context) {
  4600. global $CFG;
  4601. return get_records_sql("SELECT r.*
  4602. FROM {$CFG->prefix}role_capabilities rc,
  4603. {$CFG->prefix}role r
  4604. WHERE rc.roleid = r.id
  4605. AND rc.contextid = $context->id");
  4606. }
  4607. // get all capabilities for this role on this context (overrids)
  4608. function get_capabilities_from_role_on_context($role, $context) {
  4609. global $CFG;
  4610. return get_records_sql("SELECT *
  4611. FROM {$CFG->prefix}role_capabilities
  4612. WHERE contextid = $context->id
  4613. AND roleid = $role->id");
  4614. }
  4615. // find out which roles has assignment on this context
  4616. function get_roles_with_assignment_on_context($context) {
  4617. global $CFG;
  4618. return get_records_sql("SELECT r.*
  4619. FROM {$CFG->prefix}role_assignments ra,
  4620. {$CFG->prefix}role r
  4621. WHERE ra.roleid = r.id
  4622. AND ra.contextid = $context->id");
  4623. }
  4624. /**
  4625. * Find all user assignemnt of users for this role, on this context
  4626. */
  4627. function get_users_from_role_on_context($role, $context) {
  4628. global $CFG;
  4629. return get_records_sql("SELECT *
  4630. FROM {$CFG->prefix}role_assignments
  4631. WHERE contextid = $context->id
  4632. AND roleid = $role->id");
  4633. }
  4634. /**
  4635. * Simple function returning a boolean true if roles exist, otherwise false
  4636. */
  4637. function user_has_role_assignment($userid, $roleid, $contextid=0) {
  4638. if ($contextid) {
  4639. return record_exists('role_assignments', 'userid', $userid, 'roleid', $roleid, 'contextid', $contextid);
  4640. } else {
  4641. return record_exists('role_assignments', 'userid', $userid, 'roleid', $roleid);
  4642. }
  4643. }
  4644. /**
  4645. * Get role name or alias if exists and format the text.
  4646. * @param object $role role object
  4647. * @param object $coursecontext
  4648. * @return $string name of role in course context
  4649. */
  4650. function role_get_name($role, $coursecontext) {
  4651. if ($r = get_record('role_names','roleid', $role->id,'contextid', $coursecontext->id)) {
  4652. return strip_tags(format_string($r->name));
  4653. } else {
  4654. return strip_tags(format_string($role->name));
  4655. }
  4656. }
  4657. /**
  4658. * Prepare list of roles for display, apply aliases and format text
  4659. * @param array $roleoptions array roleid=>rolename
  4660. * @param object $context
  4661. * @return array of role names
  4662. */
  4663. function role_fix_names($roleoptions, $context, $rolenamedisplay=ROLENAME_ALIAS) {
  4664. if ($rolenamedisplay != ROLENAME_ORIGINAL && !empty($context->id)) {
  4665. if ($context->contextlevel == CONTEXT_MODULE || $context->contextlevel == CONTEXT_BLOCK) { // find the parent course context
  4666. if ($parentcontextid = array_shift(get_parent_contexts($context))) {
  4667. $context = get_context_instance_by_id($parentcontextid);
  4668. }
  4669. }
  4670. if ($aliasnames = get_records('role_names', 'contextid', $context->id)) {
  4671. if ($rolenamedisplay == ROLENAME_ALIAS) {
  4672. foreach ($aliasnames as $alias) {
  4673. if (isset($roleoptions[$alias->roleid])) {
  4674. $roleoptions[$alias->roleid] = format_string($alias->name);
  4675. }
  4676. }
  4677. } else if ($rolenamedisplay == ROLENAME_BOTH) {
  4678. foreach ($aliasnames as $alias) {
  4679. if (isset($roleoptions[$alias->roleid])) {
  4680. $roleoptions[$alias->roleid] = format_string($alias->name).' ('.format_string($roleoptions[$alias->roleid]).')';
  4681. }
  4682. }
  4683. }
  4684. }
  4685. }
  4686. foreach ($roleoptions as $rid => $name) {
  4687. $roleoptions[$rid] = strip_tags(format_string($name));
  4688. }
  4689. return $roleoptions;
  4690. }
  4691. /**
  4692. * This function helps admin/roles/manage.php etc to detect if a new line should be printed
  4693. * when we read in a new capability
  4694. * most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
  4695. * but when we are in grade, all reports/import/export capabilites should be together
  4696. * @param string a - component string a
  4697. * @param string b - component string b
  4698. * @return bool - whether 2 component are in different "sections"
  4699. */
  4700. function component_level_changed($cap, $comp, $contextlevel) {
  4701. if ($cap->component == 'enrol/authorize' && $comp =='enrol/authorize') {
  4702. return false;
  4703. }
  4704. if (strstr($cap->component, '/') && strstr($comp, '/')) {
  4705. $compsa = explode('/', $cap->component);
  4706. $compsb = explode('/', $comp);
  4707. // list of system reports
  4708. if (($compsa[0] == 'report') && ($compsb[0] == 'report')) {
  4709. return false;
  4710. }
  4711. // we are in gradebook, still
  4712. if (($compsa[0] == 'gradeexport' || $compsa[0] == 'gradeimport' || $compsa[0] == 'gradereport') &&
  4713. ($compsb[0] == 'gradeexport' || $compsb[0] == 'gradeimport' || $compsb[0] == 'gradereport')) {
  4714. return false;
  4715. }
  4716. if (($compsa[0] == 'coursereport') && ($compsb[0] == 'coursereport')) {
  4717. return false;
  4718. }
  4719. }
  4720. return ($cap->component != $comp || $cap->contextlevel != $contextlevel);
  4721. }
  4722. /**
  4723. * Populate context.path and context.depth where missing.
  4724. * @param bool $force force a complete rebuild of the path and depth fields.
  4725. * @param bool $feedback display feedback (during upgrade usually)
  4726. * @return void
  4727. */
  4728. function build_context_path($force=false, $feedback=false) {
  4729. global $CFG;
  4730. require_once($CFG->libdir.'/ddllib.php');
  4731. // System context
  4732. $sitectx = get_system_context(!$force);
  4733. $base = '/'.$sitectx->id;
  4734. // Sitecourse
  4735. $sitecoursectx = get_record('context',
  4736. 'contextlevel', CONTEXT_COURSE,
  4737. 'instanceid', SITEID);
  4738. if ($force || $sitecoursectx->path !== "$base/{$sitecoursectx->id}") {
  4739. set_field('context', 'path', "$base/{$sitecoursectx->id}",
  4740. 'id', $sitecoursectx->id);
  4741. set_field('context', 'depth', 2,
  4742. 'id', $sitecoursectx->id);
  4743. $sitecoursectx = get_record('context',
  4744. 'contextlevel', CONTEXT_COURSE,
  4745. 'instanceid', SITEID);
  4746. }
  4747. $ctxemptyclause = " AND (ctx.path IS NULL
  4748. OR ctx.depth=0) ";
  4749. $emptyclause = " AND ({$CFG->prefix}context.path IS NULL
  4750. OR {$CFG->prefix}context.depth=0) ";
  4751. if ($force) {
  4752. $ctxemptyclause = $emptyclause = '';
  4753. }
  4754. /* MDL-11347:
  4755. * - mysql does not allow to use FROM in UPDATE statements
  4756. * - using two tables after UPDATE works in mysql, but might give unexpected
  4757. * results in pg 8 (depends on configuration)
  4758. * - using table alias in UPDATE does not work in pg < 8.2
  4759. */
  4760. if ($CFG->dbfamily == 'mysql') {
  4761. $updatesql = "UPDATE {$CFG->prefix}context ct, {$CFG->prefix}context_temp temp
  4762. SET ct.path = temp.path,
  4763. ct.depth = temp.depth
  4764. WHERE ct.id = temp.id";
  4765. } else if ($CFG->dbfamily == 'oracle') {
  4766. $updatesql = "UPDATE {$CFG->prefix}context ct
  4767. SET (ct.path, ct.depth) =
  4768. (SELECT temp.path, temp.depth
  4769. FROM {$CFG->prefix}context_temp temp
  4770. WHERE temp.id=ct.id)
  4771. WHERE EXISTS (SELECT 'x'
  4772. FROM {$CFG->prefix}context_temp temp
  4773. WHERE temp.id = ct.id)";
  4774. } else {
  4775. $updatesql = "UPDATE {$CFG->prefix}context
  4776. SET path = temp.path,
  4777. depth = temp.depth
  4778. FROM {$CFG->prefix}context_temp temp
  4779. WHERE temp.id={$CFG->prefix}context.id";
  4780. }
  4781. $udelsql = "TRUNCATE TABLE {$CFG->prefix}context_temp";
  4782. // Top level categories
  4783. $sql = "UPDATE {$CFG->prefix}context
  4784. SET depth=2, path=" . sql_concat("'$base/'", 'id') . "
  4785. WHERE contextlevel=".CONTEXT_COURSECAT."
  4786. AND EXISTS (SELECT 'x'
  4787. FROM {$CFG->prefix}course_categories cc
  4788. WHERE cc.id = {$CFG->prefix}context.instanceid
  4789. AND cc.depth=1)
  4790. $emptyclause";
  4791. execute_sql($sql, $feedback);
  4792. execute_sql($udelsql, $feedback);
  4793. // Deeper categories - one query per depthlevel
  4794. $maxdepth = get_field_sql("SELECT MAX(depth)
  4795. FROM {$CFG->prefix}course_categories");
  4796. for ($n=2;$n<=$maxdepth;$n++) {
  4797. $sql = "INSERT INTO {$CFG->prefix}context_temp (id, path, depth)
  4798. SELECT ctx.id, ".sql_concat('pctx.path', "'/'", 'ctx.id').", $n+1
  4799. FROM {$CFG->prefix}context ctx
  4800. JOIN {$CFG->prefix}course_categories c ON ctx.instanceid=c.id
  4801. JOIN {$CFG->prefix}context pctx ON c.parent=pctx.instanceid
  4802. WHERE ctx.contextlevel=".CONTEXT_COURSECAT."
  4803. AND pctx.contextlevel=".CONTEXT_COURSECAT."
  4804. AND c.depth=$n
  4805. AND NOT EXISTS (SELECT 'x'
  4806. FROM {$CFG->prefix}context_temp temp
  4807. WHERE temp.id = ctx.id)
  4808. $ctxemptyclause";
  4809. execute_sql($sql, $feedback);
  4810. // this is needed after every loop
  4811. // MDL-11532
  4812. execute_sql($updatesql, $feedback);
  4813. execute_sql($udelsql, $feedback);
  4814. }
  4815. // Courses -- except sitecourse
  4816. $sql = "INSERT INTO {$CFG->prefix}context_temp (id, path, depth)
  4817. SELECT ctx.id, ".sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
  4818. FROM {$CFG->prefix}context ctx
  4819. JOIN {$CFG->prefix}course c ON ctx.instanceid=c.id
  4820. JOIN {$CFG->prefix}context pctx ON c.category=pctx.instanceid
  4821. WHERE ctx.contextlevel=".CONTEXT_COURSE."
  4822. AND c.id!=".SITEID."
  4823. AND pctx.contextlevel=".CONTEXT_COURSECAT."
  4824. AND NOT EXISTS (SELECT 'x'
  4825. FROM {$CFG->prefix}context_temp temp
  4826. WHERE temp.id = ctx.id)
  4827. $ctxemptyclause";
  4828. execute_sql($sql, $feedback);
  4829. execute_sql($updatesql, $feedback);
  4830. execute_sql($udelsql, $feedback);
  4831. // Module instances
  4832. $sql = "INSERT INTO {$CFG->prefix}context_temp (id, path, depth)
  4833. SELECT ctx.id, ".sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
  4834. FROM {$CFG->prefix}context ctx
  4835. JOIN {$CFG->prefix}course_modules cm ON ctx.instanceid=cm.id
  4836. JOIN {$CFG->prefix}context pctx ON cm.course=pctx.instanceid
  4837. WHERE ctx.contextlevel=".CONTEXT_MODULE."
  4838. AND pctx.contextlevel=".CONTEXT_COURSE."
  4839. AND NOT EXISTS (SELECT 'x'
  4840. FROM {$CFG->prefix}context_temp temp
  4841. WHERE temp.id = ctx.id)
  4842. $ctxemptyclause";
  4843. execute_sql($sql, $feedback);
  4844. execute_sql($updatesql, $feedback);
  4845. execute_sql($udelsql, $feedback);
  4846. // Blocks - non-pinned course-view only
  4847. $sql = "INSERT INTO {$CFG->prefix}context_temp (id, path, depth)
  4848. SELECT ctx.id, ".sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
  4849. FROM {$CFG->prefix}context ctx
  4850. JOIN {$CFG->prefix}block_instance bi ON ctx.instanceid = bi.id
  4851. JOIN {$CFG->prefix}context pctx ON bi.pageid=pctx.instanceid
  4852. WHERE ctx.contextlevel=".CONTEXT_BLOCK."
  4853. AND pctx.contextlevel=".CONTEXT_COURSE."
  4854. AND bi.pagetype='course-view'
  4855. AND NOT EXISTS (SELECT 'x'
  4856. FROM {$CFG->prefix}context_temp temp
  4857. WHERE temp.id = ctx.id)
  4858. $ctxemptyclause";
  4859. execute_sql($sql, $feedback);
  4860. execute_sql($updatesql, $feedback);
  4861. execute_sql($udelsql, $feedback);
  4862. // Blocks - others
  4863. $sql = "UPDATE {$CFG->prefix}context
  4864. SET depth=2, path=".sql_concat("'$base/'", 'id')."
  4865. WHERE contextlevel=".CONTEXT_BLOCK."
  4866. AND EXISTS (SELECT 'x'
  4867. FROM {$CFG->prefix}block_instance bi
  4868. WHERE bi.id = {$CFG->prefix}context.instanceid
  4869. AND bi.pagetype!='course-view')
  4870. $emptyclause ";
  4871. execute_sql($sql, $feedback);
  4872. // User
  4873. $sql = "UPDATE {$CFG->prefix}context
  4874. SET depth=2, path=".sql_concat("'$base/'", 'id')."
  4875. WHERE contextlevel=".CONTEXT_USER."
  4876. AND EXISTS (SELECT 'x'
  4877. FROM {$CFG->prefix}user u
  4878. WHERE u.id = {$CFG->prefix}context.instanceid)
  4879. $emptyclause ";
  4880. execute_sql($sql, $feedback);
  4881. // Personal TODO
  4882. //TODO: fix group contexts
  4883. // reset static course cache - it might have incorrect cached data
  4884. global $context_cache, $context_cache_id;
  4885. $context_cache = array();
  4886. $context_cache_id = array();
  4887. }
  4888. /**
  4889. * Update the path field of the context and
  4890. * all the dependent subcontexts that follow
  4891. * the move.
  4892. *
  4893. * The most important thing here is to be as
  4894. * DB efficient as possible. This op can have a
  4895. * massive impact in the DB.
  4896. *
  4897. * @param obj current context obj
  4898. * @param obj newparent new parent obj
  4899. *
  4900. */
  4901. function context_moved($context, $newparent) {
  4902. global $CFG;
  4903. $frompath = $context->path;
  4904. $newpath = $newparent->path . '/' . $context->id;
  4905. $setdepth = '';
  4906. if (($newparent->depth +1) != $context->depth) {
  4907. $setdepth = ", depth= depth + ({$newparent->depth} - {$context->depth}) + 1";
  4908. }
  4909. $sql = "UPDATE {$CFG->prefix}context
  4910. SET path='$newpath'
  4911. $setdepth
  4912. WHERE path='$frompath'";
  4913. execute_sql($sql,false);
  4914. $len = strlen($frompath);
  4915. /// MDL-16655 - Substring MSSQL function *requires* 3rd parameter
  4916. $substr3rdparam = '';
  4917. if ($CFG->dbfamily == 'mssql') {
  4918. $substr3rdparam = ', len(path)';
  4919. }
  4920. $sql = "UPDATE {$CFG->prefix}context
  4921. SET path = ".sql_concat("'$newpath'", sql_substr() .'(path, '.$len.' +1'.$substr3rdparam.')')."
  4922. $setdepth
  4923. WHERE path LIKE '{$frompath}/%'";
  4924. execute_sql($sql,false);
  4925. mark_context_dirty($frompath);
  4926. mark_context_dirty($newpath);
  4927. }
  4928. /**
  4929. * Turn the ctx* fields in an objectlike record
  4930. * into a context subobject. This allows
  4931. * us to SELECT from major tables JOINing with
  4932. * context at no cost, saving a ton of context
  4933. * lookups...
  4934. */
  4935. function make_context_subobj($rec) {
  4936. $ctx = new StdClass;
  4937. $ctx->id = $rec->ctxid; unset($rec->ctxid);
  4938. $ctx->path = $rec->ctxpath; unset($rec->ctxpath);
  4939. $ctx->depth = $rec->ctxdepth; unset($rec->ctxdepth);
  4940. $ctx->contextlevel = $rec->ctxlevel; unset($rec->ctxlevel);
  4941. $ctx->instanceid = $rec->id;
  4942. $rec->context = $ctx;
  4943. return $rec;
  4944. }
  4945. /**
  4946. * Do some basic, quick checks to see whether $rec->context looks like a
  4947. * valid context object.
  4948. *
  4949. * @param object $rec a think that has a context, for example a course,
  4950. * course category, course modules, etc.
  4951. * @param integer $contextlevel the type of thing $rec is, one of the CONTEXT_... constants.
  4952. * @return boolean whether $rec->context looks like the correct context object
  4953. * for this thing.
  4954. */
  4955. function is_context_subobj_valid($rec, $contextlevel) {
  4956. return isset($rec->context) && isset($rec->context->id) &&
  4957. isset($rec->context->path) && isset($rec->context->depth) &&
  4958. isset($rec->context->contextlevel) && isset($rec->context->instanceid) &&
  4959. $rec->context->contextlevel == $contextlevel && $rec->context->instanceid == $rec->id;
  4960. }
  4961. /**
  4962. * When you have a record (for example a $category, $course, $user or $cm that may,
  4963. * or may not, have come from a place that does make_context_subobj, you can use
  4964. * this method to ensure that $rec->context is present and correct before you continue.
  4965. *
  4966. * @param object $rec a thing that has an associated context.
  4967. * @param integer $contextlevel the type of thing $rec is, one of the CONTEXT_... constants.
  4968. */
  4969. function ensure_context_subobj_present(&$rec, $contextlevel) {
  4970. if (!is_context_subobj_valid($rec, $contextlevel)) {
  4971. $rec->context = get_context_instance($contextlevel, $rec->id);
  4972. }
  4973. }
  4974. /**
  4975. * Fetch recent dirty contexts to know cheaply whether our $USER->access
  4976. * is stale and needs to be reloaded.
  4977. *
  4978. * Uses cache_flags
  4979. * @param int $time
  4980. * @return array of dirty contexts
  4981. */
  4982. function get_dirty_contexts($time) {
  4983. return get_cache_flags('accesslib/dirtycontexts', $time-2);
  4984. }
  4985. /**
  4986. * Mark a context as dirty (with timestamp)
  4987. * so as to force reloading of the context.
  4988. * @param string $path context path
  4989. */
  4990. function mark_context_dirty($path) {
  4991. global $CFG, $DIRTYCONTEXTS;
  4992. // only if it is a non-empty string
  4993. if (is_string($path) && $path !== '') {
  4994. set_cache_flag('accesslib/dirtycontexts', $path, 1, time()+$CFG->sessiontimeout);
  4995. if (isset($DIRTYCONTEXTS)) {
  4996. $DIRTYCONTEXTS[$path] = 1;
  4997. }
  4998. }
  4999. }
  5000. /**
  5001. * Will walk the contextpath to answer whether
  5002. * the contextpath is dirty
  5003. *
  5004. * @param array $contexts array of strings
  5005. * @param obj/array dirty contexts from get_dirty_contexts()
  5006. * @return bool
  5007. */
  5008. function is_contextpath_dirty($pathcontexts, $dirty) {
  5009. $path = '';
  5010. foreach ($pathcontexts as $ctx) {
  5011. $path = $path.'/'.$ctx;
  5012. if (isset($dirty[$path])) {
  5013. return true;
  5014. }
  5015. }
  5016. return false;
  5017. }
  5018. /**
  5019. *
  5020. * switch role order (used in admin/roles/manage.php)
  5021. *
  5022. * @param int $first id of role to move down
  5023. * @param int $second id of role to move up
  5024. *
  5025. * @return bool success or failure
  5026. */
  5027. function switch_roles($first, $second) {
  5028. $status = true;
  5029. //first find temorary sortorder number
  5030. $tempsort = count_records('role') + 3;
  5031. while (get_record('role','sortorder', $tempsort)) {
  5032. $tempsort += 3;
  5033. }
  5034. $r1 = new object();
  5035. $r1->id = $first->id;
  5036. $r1->sortorder = $tempsort;
  5037. $r2 = new object();
  5038. $r2->id = $second->id;
  5039. $r2->sortorder = $first->sortorder;
  5040. if (!update_record('role', $r1)) {
  5041. debugging("Can not update role with ID $r1->id!");
  5042. $status = false;
  5043. }
  5044. if (!update_record('role', $r2)) {
  5045. debugging("Can not update role with ID $r2->id!");
  5046. $status = false;
  5047. }
  5048. $r1->sortorder = $second->sortorder;
  5049. if (!update_record('role', $r1)) {
  5050. debugging("Can not update role with ID $r1->id!");
  5051. $status = false;
  5052. }
  5053. return $status;
  5054. }
  5055. /**
  5056. * duplicates all the base definitions of a role
  5057. *
  5058. * @param object $sourcerole role to copy from
  5059. * @param int $targetrole id of role to copy to
  5060. *
  5061. * @return void
  5062. */
  5063. function role_cap_duplicate($sourcerole, $targetrole) {
  5064. global $CFG;
  5065. $systemcontext = get_context_instance(CONTEXT_SYSTEM);
  5066. $caps = get_records_sql("SELECT * FROM {$CFG->prefix}role_capabilities
  5067. WHERE roleid = $sourcerole->id
  5068. AND contextid = $systemcontext->id");
  5069. // adding capabilities
  5070. foreach ($caps as $cap) {
  5071. unset($cap->id);
  5072. $cap->roleid = $targetrole;
  5073. insert_record('role_capabilities', $cap);
  5074. }
  5075. }?>