3 ///////////////////////////////////////////////////////////////////////////
5 // NOTICE OF COPYRIGHT //
7 // Moodle - Modular Object-Oriented Dynamic Learning Environment //
8 // http://moodle.org //
10 // Copyright (C) 1999-2004 Martin Dougiamas http://dougiamas.com //
12 // This program is free software; you can redistribute it and/or modify //
13 // it under the terms of the GNU General Public License as published by //
14 // the Free Software Foundation; either version 2 of the License, or //
15 // (at your option) any later version. //
17 // This program is distributed in the hope that it will be useful, //
18 // but WITHOUT ANY WARRANTY; without even the implied warranty of //
19 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
20 // GNU General Public License for more details: //
22 // http://www.gnu.org/copyleft/gpl.html //
24 ///////////////////////////////////////////////////////////////////////////
27 * Public API vs internals
28 * -----------------------
30 * General users probably only care about
33 * - get_context_instance()
34 * - get_context_instance_by_id()
35 * - get_parent_contexts()
36 * - get_child_contexts()
38 * Whether the user can do something...
40 * - require_capability()
41 * - require_login() (from moodlelib)
43 * What courses has this user access to?
44 * - get_user_courses_bycap()
46 * What users can do X in this course or context?
47 * - get_context_users_bycap()
48 * - get_context_users_byrole()
51 * - enrol_into_course()
52 * - role_assign()/role_unassign()
56 * - load_all_capabilities()
57 * - reload_all_capabilities()
59 * - has_capability_in_accessdata()
61 * - get_user_access_sitewide()
62 * - get_user_access_bycontext()
63 * - get_role_access_bycontext()
68 * - "ctx" means context
73 * Access control data is held in the "accessdata" array
74 * which - for the logged-in user, will be in $USER->access
76 * For other users can be generated and passed around (but see
77 * the $ACCESS global).
79 * $accessdata is a multidimensional array, holding
80 * role assignments (RAs), role-capabilities-perm sets
81 * (role defs) and a list of courses we have loaded
84 * Things are keyed on "contextpaths" (the path field of
85 * the context table) for fast walking up/down the tree.
87 * $accessdata[ra][$contextpath]= array($roleid)
88 * [$contextpath]= array($roleid)
89 * [$contextpath]= array($roleid)
91 * Role definitions are stored like this
92 * (no cap merge is done - so it's compact)
94 * $accessdata[rdef][$contextpath:$roleid][mod/forum:viewpost] = 1
95 * [mod/forum:editallpost] = -1
96 * [mod/forum:startdiscussion] = -1000
98 * See how has_capability_in_accessdata() walks up/down the tree.
100 * Normally - specially for the logged-in user, we only load
101 * rdef and ra down to the course level, but not below. This
102 * keeps accessdata small and compact. Below-the-course ra/rdef
103 * are loaded as needed. We keep track of which courses we
104 * have loaded ra/rdef in
106 * $accessdata[loaded] = array($contextpath, $contextpath)
111 * For the logged-in user, accessdata is long-lived.
113 * On each pageload we load $DIRTYPATHS which lists
114 * context paths affected by changes. Any check at-or-below
115 * a dirty context will trigger a transparent reload of accessdata.
117 * Changes at the sytem level will force the reload for everyone.
121 * The default role assignment is not in the DB, so we
122 * add it manually to accessdata.
124 * This means that functions that work directly off the
125 * DB need to ensure that the default role caps
126 * are dealt with appropriately.
130 require_once $CFG->dirroot
.'/lib/blocklib.php';
132 // permission definitions
133 define('CAP_INHERIT', 0);
134 define('CAP_ALLOW', 1);
135 define('CAP_PREVENT', -1);
136 define('CAP_PROHIBIT', -1000);
138 // context definitions
139 define('CONTEXT_SYSTEM', 10);
140 define('CONTEXT_PERSONAL', 20);
141 define('CONTEXT_USER', 30);
142 define('CONTEXT_COURSECAT', 40);
143 define('CONTEXT_COURSE', 50);
144 define('CONTEXT_GROUP', 60);
145 define('CONTEXT_MODULE', 70);
146 define('CONTEXT_BLOCK', 80);
148 // capability risks - see http://docs.moodle.org/en/Hardening_new_Roles_system
149 define('RISK_MANAGETRUST', 0x0001);
150 define('RISK_CONFIG', 0x0002);
151 define('RISK_XSS', 0x0004);
152 define('RISK_PERSONAL', 0x0008);
153 define('RISK_SPAM', 0x0010);
155 require_once($CFG->dirroot
.'/group/lib.php');
157 $context_cache = array(); // Cache of all used context objects for performance (by level and instance)
158 $context_cache_id = array(); // Index to above cache by id
161 function get_role_context_caps($roleid, $context) {
162 //this is really slow!!!! - do not use above course context level!
164 $result[$context->id
] = array();
166 // first emulate the parent context capabilities merging into context
167 $searchcontexts = array_reverse(get_parent_contexts($context));
168 array_push($searchcontexts, $context->id
);
169 foreach ($searchcontexts as $cid) {
170 if ($capabilities = get_records_select('role_capabilities', "roleid = $roleid AND contextid = $cid")) {
171 foreach ($capabilities as $cap) {
172 if (!array_key_exists($cap->capability
, $result[$context->id
])) {
173 $result[$context->id
][$cap->capability
] = 0;
175 $result[$context->id
][$cap->capability
] +
= $cap->permission
;
180 // now go through the contexts bellow given context
181 $searchcontexts = array_keys(get_child_contexts($context));
182 foreach ($searchcontexts as $cid) {
183 if ($capabilities = get_records_select('role_capabilities', "roleid = $roleid AND contextid = $cid")) {
184 foreach ($capabilities as $cap) {
185 if (!array_key_exists($cap->contextid
, $result)) {
186 $result[$cap->contextid
] = array();
188 $result[$cap->contextid
][$cap->capability
] = $cap->permission
;
197 * Gets the accessdata for role "sitewide"
198 * (system down to course)
202 function get_role_access($roleid, $accessdata=NULL) {
206 /* Get it in 1 cheap DB query...
207 * - relevant role caps at the root and down
208 * to the course level - but not below
210 if (is_null($accessdata)) {
211 $accessdata = array(); // named list
212 $accessdata['ra'] = array();
213 $accessdata['rdef'] = array();
214 $accessdata['loaded'] = array();
217 $base = '/' . SYSCONTEXTID
;
220 // Overrides for the role IN ANY CONTEXTS
221 // down to COURSE - not below -
223 $sql = "SELECT ctx.path,
224 rc.capability, rc.permission
225 FROM {$CFG->prefix}context ctx
226 JOIN {$CFG->prefix}role_capabilities rc
227 ON rc.contextid=ctx.id
228 WHERE rc.roleid = {$roleid}
229 AND ctx.contextlevel <= ".CONTEXT_COURSE
."
230 ORDER BY ctx.depth, ctx.path";
231 if ($rs = get_recordset_sql($sql)) {
232 if ($rs->RecordCount()) {
233 while ($rd = rs_fetch_next_record($rs)) {
234 $k = "{$rd->path}:{$roleid}";
235 $accessdata['rdef'][$k][$rd->capability
] = $rd->permission
;
246 * Gets the accessdata for role "sitewide"
247 * (system down to course)
251 function get_default_frontpage_role_access($roleid, $accessdata=NULL) {
255 $frontpagecontext = get_context_instance(CONTEXT_COURSE
, SITEID
);
256 $base = '/'. SYSCONTEXTID
.'/'. $frontpagecontext->id
;
259 // Overrides for the role in any contexts related to the course
261 $sql = "SELECT ctx.path,
262 rc.capability, rc.permission
263 FROM {$CFG->prefix}context ctx
264 JOIN {$CFG->prefix}role_capabilities rc
265 ON rc.contextid=ctx.id
266 WHERE rc.roleid = {$roleid}
267 AND (ctx.id = ".SYSCONTEXTID
." OR ctx.path LIKE '$base/%')
268 AND ctx.contextlevel <= ".CONTEXT_COURSE
."
269 ORDER BY ctx.depth, ctx.path";
271 if ($rs = get_recordset_sql($sql)) {
272 if ($rs->RecordCount()) {
273 while ($rd = rs_fetch_next_record($rs)) {
274 $k = "{$rd->path}:{$roleid}";
275 $accessdata['rdef'][$k][$rd->capability
] = $rd->permission
;
287 * Get the id for the not-logged-in role - or set it up if needed
290 function get_notloggedin_roleid($return=false) {
293 if (empty($CFG->notloggedinroleid
)) { // Let's set the default to the guest role
294 if ($role = get_guest_role()) {
295 set_config('notloggedinroleid', $role->id
);
301 return $CFG->notloggedinroleid
;
304 return (get_record('role','id', $CFG->notloggedinas
));
308 * Get the default guest role
309 * @return object role
311 function get_guest_role() {
314 if (empty($CFG->guestroleid
)) {
315 if ($roles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW
)) {
316 $guestrole = array_shift($roles); // Pick the first one
317 set_config('guestroleid', $guestrole->id
);
320 debugging('Can not find any guest role!');
324 if ($guestrole = get_record('role','id', $CFG->guestroleid
)) {
327 //somebody is messing with guest roles, remove incorrect setting and try to find a new one
328 set_config('guestroleid', '');
329 return get_guest_role();
334 function has_capability($capability, $context=NULL, $userid=NULL, $doanything=true) {
335 global $USER, $CONTEXT, $ACCESS, $CFG, $DIRTYCONTEXTS;
337 /// Make sure we know the current context
338 if (empty($context)) { // Use default CONTEXT if none specified
339 if (empty($CONTEXT)) {
345 if (empty($CONTEXT)) {
349 if (is_null($userid) ||
$userid===0) {
354 $basepath = '/' . SYSCONTEXTID
;
355 if (empty($context->path
)) {
356 $contexts[] = SYSCONTEXTID
;
357 $context->path
= $basepath;
358 if (isset($context->id
) && $context->id
==! SYSCONTEXTID
) {
359 $contexts[] = $context->id
;
360 $context->path
.= '/' . $context->id
;
363 $contexts = explode('/', $context->path
);
364 array_shift($contexts);
367 if ($USER->id
=== 0 && !isset($USER->access
)) {
368 load_all_capabilities();
371 if (defined('FULLME') && FULLME
=== 'cron' && !isset($USER->access
)) {
373 // In cron, some modules setup a 'fake' $USER,
374 // ensure we load the appropriate accessdata.
375 // Also: set $DIRTYCONTEXTS to empty
377 if (!isset($ACCESS)) {
380 if (!isset($ACCESS[$userid])) {
381 load_user_accessdata($userid);
383 $USER->access
= $ACCESS[$userid];
384 $DIRTYCONTEXTS = array();
387 // Careful check for staleness...
389 if (!isset($DIRTYCONTEXTS)) {
390 // Load dirty contexts list
391 $DIRTYCONTEXTS = get_dirty_contexts($USER->access
['time']);
393 // Check basepath only once, when
394 // we load the dirty contexts...
395 if (isset($DIRTYCONTEXTS[$basepath])) {
396 // sitewide change, dirty
400 // Check for staleness in the whole parenthood
401 if ($clean && !is_contextpath_clean($context->path
, $DIRTYCONTEXTS)) {
405 // reload all capabilities - preserving loginas, roleswitches, etc
406 // and then cleanup any marks of dirtyness... at least from our short
408 reload_all_capabilities();
409 $DIRTYCONTEXTS = array();
413 // divulge how many times we are called
414 //// error_log("has_capability: id:{$context->id} path:{$context->path} userid:$userid cap:$capability");
416 if ($USER->id
=== $userid) {
418 // For the logged in user, we have $USER->access
419 // which will have all RAs and caps preloaded for
420 // course and above contexts.
422 // Contexts below courses && contexts that do not
423 // hang from courses are loaded into $USER->access
424 // on demand, and listed in $USER->access[loaded]
426 if ($context->contextlevel
<= CONTEXT_COURSE
) {
427 // Course and above are always preloaded
428 return has_capability_in_accessdata($capability, $context, $USER->access
, $doanything);
430 // Load accessdata for below-the-course contexts
431 if (!path_inaccessdata($context->path
,$USER->access
)) {
432 error_log("loading access for context {$context->path} for $capability at {$context->contextlevel} {$context->id}");
433 // $bt = debug_backtrace();
434 // error_log("bt {$bt[0]['file']} {$bt[0]['line']}");
435 $USER->access
= get_user_access_bycontext($USER->id
, $context,
438 return has_capability_in_accessdata($capability, $context, $USER->access
, $doanything);
441 if (!isset($ACCESS)) {
444 if (!isset($ACCESS[$userid])) {
445 load_user_accessdata($userid);
447 if ($context->contextlevel
<= CONTEXT_COURSE
) {
448 // Course and above are always preloaded
449 return has_capability_in_accessdata($capability, $context, $ACCESS[$userid], $doanything);
451 // Load accessdata for below-the-course contexts as needed
452 if (!path_inaccessdata($context->path
,$ACCESS[$userid])) {
453 error_log("loading access for context {$context->path} for $capability at {$context->contextlevel} {$context->id}");
454 // $bt = debug_backtrace();
455 // error_log("bt {$bt[0]['file']} {$bt[0]['line']}");
456 $ACCESS[$userid] = get_user_access_bycontext($userid, $context,
459 return has_capability_in_accessdata($capability, $context, $ACCESS[$userid], $doanything);
463 * Uses 1 DB query to answer whether a user is an admin at the sitelevel.
464 * It depends on DB schema >=1.7 but does not depend on the new datastructures
465 * in v1.9 (context.path, or $USER->access)
467 * Will return true if the userid has any of
468 * - moodle/site:config
469 * - moodle/legacy:admin
470 * - moodle/site:doanything
473 * @returns bool $isadmin
475 function is_siteadmin($userid) {
478 $sql = "SELECT SUM(rc.permission)
479 FROM " . $CFG->prefix
. "role_capabilities rc
480 JOIN " . $CFG->prefix
. "context ctx
481 ON ctx.id=rc.contextid
482 JOIN " . $CFG->prefix
. "role_assignments ra
483 ON ra.roleid=rc.roleid AND ra.contextid=ctx.id
484 WHERE ctx.contextlevel=10
485 AND ra.userid={$userid}
486 AND rc.capability IN ('moodle/site:config', 'moodle/legacy:admin', 'moodle/site:doanything')
487 GROUP BY rc.capability
488 HAVING SUM(rc.permission) > 0";
490 $isadmin = record_exists_sql($sql);
494 function get_course_from_path ($path) {
495 // assume that nothing is more than 1 course deep
496 if (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
502 function path_inaccessdata($path, $accessdata) {
504 // assume that contexts hang from sys or from a course
505 // this will only work well with stuff that hangs from a course
506 if (in_array($path, $accessdata['loaded'], true)) {
507 error_log("found it!");
510 $base = '/' . SYSCONTEXTID
;
511 while (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
513 if ($path === $base) {
516 if (in_array($path, $accessdata['loaded'], true)) {
524 * Walk the accessdata array and return true/false.
525 * Deals with prohibits, roleswitching, aggregating
528 * The main feature of here is being FAST and with no
533 * Switch Roles exits early
534 * -----------------------
535 * cap checks within a switchrole need to exit early
536 * in our bottom up processing so they don't "see" that
537 * there are real RAs that can do all sorts of things.
539 * Switch Role merges with default role
540 * ------------------------------------
541 * If you are a teacher in course X, you have at least
542 * teacher-in-X + defaultloggedinuser-sitewide. So in the
543 * course you'll have techer+defaultloggedinuser.
544 * We try to mimic that in switchrole.
546 * Local-most role definition and role-assignment wins
547 * ---------------------------------------------------
548 * So if the local context has said 'allow', it wins
549 * over a high-level context that says 'deny'.
550 * This is applied when walking rdefs, and RAs.
551 * Only at the same context the values are SUM()med.
553 * The exception is CAP_PROHIBIT.
555 * "Guest default role" exception
556 * ------------------------------
558 * See MDL-7513 and $ignoreguest below for details.
562 * IF we are being asked about moodle/legacy:guest
563 * OR moodle/course:view
564 * FOR a real, logged-in user
565 * AND we reached the top of the path in ra and rdef
566 * AND that role has moodle/legacy:guest === 1...
567 * THEN we act as if we hadn't seen it.
572 * - Document how it works
573 * - Rewrite in ASM :-)
576 function has_capability_in_accessdata($capability, $context, $accessdata, $doanything) {
580 $path = $context->path
;
582 // build $contexts as a list of "paths" of the current
583 // contexts and parents with the order top-to-bottom
584 $contexts = array($path);
585 while (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
587 array_unshift($contexts, $path);
590 $ignoreguest = false;
591 if (isset($accessdata['dr'])
592 && ($capability == 'moodle/course:view'
593 ||
$capability == 'moodle/legacy:guest')) {
594 // At the base, ignore rdefs where moodle/legacy:guest
596 $ignoreguest = $accessdata['dr'];
600 $cc = count($contexts);
605 // role-switches loop
607 if (isset($accessdata['rsw'])) {
608 // check for isset() is fast
609 // empty() is slow...
610 if (empty($accessdata['rsw'])) {
611 unset($accessdata['rsw']); // keep things fast and unambiguous
614 // From the bottom up...
615 for ($n=$cc-1;$n>=0;$n--) {
616 $ctxp = $contexts[$n];
617 if (isset($accessdata['rsw'][$ctxp])) {
618 // Found a switchrole assignment
619 // check for that role _plus_ the default user role
620 $ras = array($accessdata['rsw'][$ctxp],$CFG->defaultuserroleid
);
621 for ($rn=0;$rn<2;$rn++
) {
623 // Walk the path for capabilities
624 // from the bottom up...
625 for ($m=$cc-1;$m>=0;$m--) {
626 $capctxp = $contexts[$m];
627 if (isset($accessdata['rdef']["{$capctxp}:$roleid"][$capability])) {
628 $perm = $accessdata['rdef']["{$capctxp}:$roleid"][$capability];
629 // The most local permission (first to set) wins
630 // the only exception is CAP_PROHIBIT
633 } elseif ($perm == CAP_PROHIBIT
) {
640 // As we are dealing with a switchrole,
641 // we return _here_, do _not_ walk up
642 // the hierarchy any further
645 // didn't find it as an explicit cap,
646 // but maybe the user candoanything in this context...
647 return has_capability_in_accessdata('moodle/site:doanything', $context, $accessdata, false);
660 // Main loop for normal RAs
661 // From the bottom up...
663 for ($n=$cc-1;$n>=0;$n--) {
664 $ctxp = $contexts[$n];
665 if (isset($accessdata['ra'][$ctxp])) {
666 // Found role assignments on this leaf
667 $ras = $accessdata['ra'][$ctxp];
670 for ($rn=0;$rn<$rc;$rn++
) {
673 // Walk the path for capabilities
674 // from the bottom up...
675 for ($m=$cc-1;$m>=0;$m--) {
676 $capctxp = $contexts[$m];
677 // ignore some guest caps
678 // at base ra and rdef
679 if ($ignoreguest == $roleid
682 && isset($accessdata['rdef']["{$capctxp}:$roleid"]['moodle/legacy:guest'])
683 && $accessdata['rdef']["{$capctxp}:$roleid"]['moodle/legacy:guest'] > 0) {
686 if (isset($accessdata['rdef']["{$capctxp}:$roleid"][$capability])) {
687 $perm = $accessdata['rdef']["{$capctxp}:$roleid"][$capability];
688 // The most local permission (first to set) wins
689 // the only exception is CAP_PROHIBIT
690 if ($rolecan === 0) {
692 } elseif ($perm == CAP_PROHIBIT
) {
698 // Permissions at the same
699 // ctxlevel are added together
702 // The most local RAs with a defined
703 // permission ($ctxcan) win, except
707 } elseif ($ctxcan == CAP_PROHIBIT
) {
716 // didn't find it as an explicit cap,
717 // but maybe the user candoanything in this context...
718 return has_capability_in_accessdata('moodle/site:doanything', $context, $accessdata, false);
728 function aggregate_roles_from_accessdata($context, $accessdata) {
730 $path = $context->path
;
732 // build $contexts as a list of "paths" of the current
733 // contexts and parents with the order top-to-bottom
734 $contexts = array($path);
735 while (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
737 array_unshift($contexts, $path);
740 $cc = count($contexts);
743 // From the bottom up...
744 for ($n=$cc-1;$n>=0;$n--) {
745 $ctxp = $contexts[$n];
746 if (isset($accessdata['ra'][$ctxp]) && count($accessdata['ra'][$ctxp])) {
747 // Found assignments on this leaf
748 $addroles = $accessdata['ra'][$ctxp];
749 $roles = array_merge($roles, $addroles);
753 return array_unique($roles);
757 * This is an easy to use function, combining has_capability() with require_course_login().
758 * And will call those where needed.
760 * It checks for a capability assertion being true. If it isn't
761 * then the page is terminated neatly with a standard error message.
763 * If the user is not logged in, or is using 'guest' access or other special "users,
764 * it provides a logon prompt.
766 * @param string $capability - name of the capability
767 * @param object $context - a context object (record from context table)
768 * @param integer $userid - a userid number
769 * @param bool $doanything - if false, ignore do anything
770 * @param string $errorstring - an errorstring
771 * @param string $stringfile - which stringfile to get it from
773 function require_capability($capability, $context=NULL, $userid=NULL, $doanything=true,
774 $errormessage='nopermissions', $stringfile='') {
778 /// If the current user is not logged in, then make sure they are (if needed)
780 if (is_null($userid) && !isset($USER->access
)) {
781 if ($context && ($context->contextlevel
== CONTEXT_COURSE
)) {
782 require_login($context->instanceid
);
783 } else if ($context && ($context->contextlevel
== CONTEXT_MODULE
)) {
784 if ($cm = get_record('course_modules','id',$context->instanceid
)) {
785 if (!$course = get_record('course', 'id', $cm->course
)) {
786 error('Incorrect course.');
788 require_course_login($course, true, $cm);
793 } else if ($context && ($context->contextlevel
== CONTEXT_SYSTEM
)) {
794 if (!empty($CFG->forcelogin
)) {
803 /// OK, if they still don't have the capability then print a nice error message
805 if (!has_capability($capability, $context, $userid, $doanything)) {
806 $capabilityname = get_capability_string($capability);
807 print_error($errormessage, $stringfile, '', $capabilityname);
812 * Get an array of courses (with magic extra bits)
813 * where the accessdata and in DB enrolments show
814 * that the cap requested is available.
816 * The main use is for get_my_courses().
820 * - $fields is an array of fieldnames to ADD
821 * so name the fields you really need, which will
822 * be added and uniq'd
824 * - the course records have $c->context which is a fully
825 * valid context object. Saves you a query per course!
827 * - the course records have $c->categorypath to make
828 * category lookups cheap
830 * - current implementation is split in -
832 * - if the user has the cap systemwide, stupidly
833 * grab *every* course for a capcheck. This eats
834 * a TON of bandwidth, specially on large sites
835 * with separate DBs...
837 * - otherwise, fetch "likely" courses with a wide net
838 * that should get us _cheaply_ at least the courses we need, and some
839 * we won't - we get courses that...
840 * - are in a category where user has the cap
841 * - or where use has a role-assignment (any kind)
842 * - or where the course has an override on for this cap
844 * - walk the courses recordset checking the caps oneach one
845 * the checks are all in memory and quite fast
846 * (though we could implement a specialised variant of the
847 * has_capability_in_accessdata() code to speed it up)
849 * @param string $capability - name of the capability
850 * @param array $accessdata - accessdata session array
851 * @param bool $doanything - if false, ignore do anything
852 * @param string $sort - sorting fields - prefix each fieldname with "c."
853 * @param array $fields - additional fields you are interested in...
854 * @param int $limit - set if you want to limit the number of courses
855 * @return array $courses - ordered array of course objects - see notes above
858 function get_user_courses_bycap($userid, $cap, $accessdata, $doanything, $sort='c.sortorder ASC', $fields=NULL, $limit=0) {
862 // Slim base fields, let callers ask for what they need...
863 $basefields = array('id', 'sortorder', 'shortname', 'idnumber');
865 if (!is_null($fields)) {
866 $fields = array_merge($basefields, $fields);
867 $fields = array_unique($fields);
869 $fields = $basefields;
871 $coursefields = 'c.' .implode(',c.', $fields);
875 $sort = "ORDER BY $sort";
878 $sysctx = get_context_instance(CONTEXT_SYSTEM
);
879 if (has_capability_in_accessdata($cap, $sysctx, $accessdata, $doanything)) {
881 // Apparently the user has the cap sitewide, so walk *every* course
882 // (the cap checks are moderately fast, but this moves massive bandwidth w the db)
885 $sql = "SELECT $coursefields,
886 ctx.id AS ctxid, ctx.path AS ctxpath,
887 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel,
888 cc.path AS categorypath
889 FROM {$CFG->prefix}course c
890 JOIN {$CFG->prefix}course_categories cc
892 JOIN {$CFG->prefix}context ctx
893 ON (c.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE
.")
895 $rs = get_recordset_sql($sql);
898 // narrow down where we have the caps to a few contexts
899 // this will be a combination of
900 // - categories where we have the rights
901 // - courses where we have an explicit enrolment OR that have an override
904 FROM {$CFG->prefix}context ctx
905 WHERE ctx.contextlevel=".CONTEXT_COURSECAT
."
907 $rs = get_recordset_sql($sql);
909 if ($rs->RecordCount()) {
910 while ($catctx = rs_fetch_next_record($rs)) {
911 if ($catctx->path
!= ''
912 && has_capability_in_accessdata($cap, $catctx, $accessdata, $doanything)) {
913 $catpaths[] = $catctx->path
;
919 if (count($catpaths)) {
920 $cc = count($catpaths);
921 for ($n=0;$n<$cc;$n++
) {
922 $catpaths[$n] = "ctx.path LIKE '{$catpaths[$n]}/%'";
924 $catclause = 'OR (' . implode(' OR ', $catpaths) .')';
930 $capany = " OR rc.capability='moodle/site:doanything'";
933 // Note here that we *have* to have the compound clauses
934 // in the LEFT OUTER JOIN condition for them to return NULL
935 // appropriately and narrow things down...
937 $sql = "SELECT $coursefields,
938 ctx.id AS ctxid, ctx.path AS ctxpath,
939 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel,
940 cc.path AS categorypath
941 FROM {$CFG->prefix}course c
942 JOIN {$CFG->prefix}course_categories cc
944 JOIN {$CFG->prefix}context ctx
945 ON (c.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE
.")
946 LEFT OUTER JOIN {$CFG->prefix}role_assignments ra
947 ON (ra.contextid=ctx.id AND ra.userid=$userid)
948 LEFT OUTER JOIN {$CFG->prefix}role_capabilities rc
949 ON (rc.contextid=ctx.id AND (rc.capability='$cap' $capany))
950 WHERE ra.id IS NOT NULL
954 $rs = get_recordset_sql($sql);
957 $cc = 0; // keep count
958 if ($rs->RecordCount()) {
959 while ($c = rs_fetch_next_record($rs)) {
960 // build the context obj
961 $c = make_context_subobj($c);
963 if (has_capability_in_accessdata($cap, $c->context
, $accessdata, $doanything)) {
965 if ($limit > 0 && $cc++
> $limit) {
976 * Draft - use for the course participants list page
978 * Uses 1 DB query (cheap too - 2~7ms).
981 * - implement additional where clauses
983 * - get course participants list to use it!
985 * returns a users array, both sorted _and_ keyed
986 * on id (as get_my_courses() does)
988 * as a bonus, every user record comes with its own
989 * personal context, as our callers need it straight away
990 * {save 1 dbquery per user! yay!}
993 function get_context_users_byrole ($context, $roleid, $fields=NULL, $where=NULL, $sort=NULL, $limit=0) {
996 // Slim base fields, let callers ask for what they need...
997 $basefields = array('id', 'username');
999 if (!is_null($fields)) {
1000 $fields = array_merge($basefields, $fields);
1001 $fields = array_unique($fields);
1003 $fields = $basefields;
1005 $userfields = 'u.' .implode(',u.', $fields);
1007 $contexts = substr($context->path
, 1); // kill leading slash
1008 $contexts = str_replace('/', ',', $contexts);
1010 $sql = "SELECT $userfields,
1011 ctx.id AS ctxid, ctx.path AS ctxpath,
1012 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
1013 FROM {$CFG->prefix}user u
1014 JOIN {$CFG->prefix}context ctx
1015 ON (u.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_USER
.")
1016 JOIN {$CFG->prefix}role_assignments ra
1018 WHERE ra.roleid = $roleid
1019 AND ra.contextid IN ($contexts)";
1021 $rs = get_recordset_sql($sql);
1024 $cc = 0; // keep count
1025 if ($rs->RecordCount()) {
1026 while ($u = rs_fetch_next_record($rs)) {
1027 // build the context obj
1028 $u = make_context_subobj($u);
1031 if ($limit > 0 && $cc++
> $limit) {
1041 * Draft - use for the course participants list page
1043 * Uses 2 fast DB queries
1046 * - automagically exclude roles that can-doanything sitewide (See callers)
1047 * - perhaps also allow sitewide do-anything via flag
1048 * - implement additional where clauses
1050 * - get course participants list to use it!
1052 * returns a users array, both sorted _and_ keyed
1053 * on id (as get_my_courses() does)
1055 * as a bonus, every user record comes with its own
1056 * personal context, as our callers need it straight away
1057 * {save 1 dbquery per user! yay!}
1060 function get_context_users_bycap ($context, $capability='moodle/course:view', $fields=NULL, $where=NULL, $sort=NULL, $limit=0) {
1065 // - Get all the *interesting* roles -- those that
1066 // have some rolecap entry in our ctx.path contexts
1068 // - Get all RAs for any of those roles in any of our
1069 // interesting contexts, with userid & perm data
1070 // in a nice (per user?) order
1072 // - Walk the resultset, computing the permissions
1073 // - actually - this is all a SQL subselect
1075 // - Fetch user records against the subselect
1078 // Slim base fields, let callers ask for what they need...
1079 $basefields = array('id', 'username');
1081 if (!is_null($fields)) {
1082 $fields = array_merge($basefields, $fields);
1083 $fields = array_unique($fields);
1085 $fields = $basefields;
1087 $userfields = 'u.' .implode(',u.', $fields);
1089 $contexts = substr($context->path
, 1); // kill leading slash
1090 $contexts = str_replace('/', ',', $contexts);
1093 $sql = "SELECT DISTINCT rc.roleid
1094 FROM {$CFG->prefix}role_capabilities rc
1095 WHERE rc.capability = '$capability'
1096 AND rc.contextid IN ($contexts)";
1097 $rs = get_recordset_sql($sql);
1098 if ($rs->RecordCount()) {
1099 while ($u = rs_fetch_next_record($rs)) {
1100 $roles[] = $u->roleid
;
1104 $roles = implode(',', $roles);
1107 // User permissions subselect SQL
1109 // - the open join condition to
1110 // role_capabilities
1112 // - because both rc and ra entries are
1113 // _at or above_ our context, we don't care
1114 // about their depth, we just need to sum them
1116 $sql = "SELECT ra.userid, SUM(rc.permission) AS permission
1117 FROM {$CFG->prefix}role_assignments ra
1118 JOIN {$CFG->prefix}role_capabilities rc
1119 ON (ra.roleid = rc.roleid AND rc.contextid IN ($contexts))
1120 WHERE ra.contextid IN ($contexts)
1121 AND ra.roleid IN ($roles)
1122 GROUP BY ra.userid";
1125 $sql = "SELECT $userfields,
1126 ctx.id AS ctxid, ctx.path AS ctxpath,
1127 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
1128 FROM {$CFG->prefix}user u
1129 JOIN {$CFG->prefix}context ctx
1130 ON (u.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_USER
.")
1133 WHERE up.permission > 0 AND u.username != 'guest'";
1135 $rs = get_recordset_sql($sql);
1138 $cc = 0; // keep count
1139 if ($rs->RecordCount()) {
1140 while ($u = rs_fetch_next_record($rs)) {
1141 // build the context obj
1142 $u = make_context_subobj($u);
1145 if ($limit > 0 && $cc++
> $limit) {
1155 * It will return a nested array showing role assignments
1156 * all relevant role capabilities for the user at
1157 * site/metacourse/course_category/course levels
1159 * We do _not_ delve deeper than courses because the number of
1160 * overrides at the module/block levels is HUGE.
1162 * [ra] => [/path/] = array(roleid, roleid)
1163 * [rdef] => [/path/:roleid][capability]=permission
1164 * [loaded] => array('/path', '/path')
1166 * @param $userid integer - the id of the user
1169 function get_user_access_sitewide($userid) {
1173 // this flag has not been set!
1174 // (not clean install, or upgraded successfully to 1.7 and up)
1175 if (empty($CFG->rolesactive
)) {
1179 /* Get in 3 cheap DB queries...
1180 * - role assignments - with role_caps
1181 * - relevant role caps
1182 * - above this user's RAs
1183 * - below this user's RAs - limited to course level
1186 $accessdata = array(); // named list
1187 $accessdata['ra'] = array();
1188 $accessdata['rdef'] = array();
1189 $accessdata['loaded'] = array();
1191 $sitectx = get_field('context', 'id','contextlevel', CONTEXT_SYSTEM
);
1192 $base = "/$sitectx";
1195 // Role assignments - and any rolecaps directly linked
1196 // because it's cheap to read rolecaps here over many
1199 $sql = "SELECT ctx.path, ra.roleid, rc.capability, rc.permission
1200 FROM {$CFG->prefix}role_assignments ra
1201 JOIN {$CFG->prefix}context ctx
1202 ON ra.contextid=ctx.id
1203 LEFT OUTER JOIN {$CFG->prefix}role_capabilities rc
1204 ON (rc.roleid=ra.roleid AND rc.contextid=ra.contextid)
1205 WHERE ra.userid = $userid AND ctx.contextlevel <= ".CONTEXT_COURSE
."
1206 ORDER BY ctx.depth, ctx.path";
1207 $rs = get_recordset_sql($sql);
1209 // raparents collects paths & roles we need to walk up
1210 // the parenthood to build the rdef
1212 // the array will bulk up a bit with dups
1213 // which we'll later clear up
1215 $raparents = array();
1217 if ($rs->RecordCount()) {
1218 while ($ra = rs_fetch_next_record($rs)) {
1219 // RAs leafs are arrays to support multi
1220 // role assignments...
1221 if (!isset($accessdata['ra'][$ra->path
])) {
1222 $accessdata['ra'][$ra->path
] = array();
1224 // only add if is not a repeat caused
1225 // by capability join...
1226 // (this check is cheaper than in_array())
1227 if ($lastseen !== $ra->path
.':'.$ra->roleid
) {
1228 $lastseen = $ra->path
.':'.$ra->roleid
;
1229 array_push($accessdata['ra'][$ra->path
], $ra->roleid
);
1230 $parentids = explode('/', $ra->path
);
1231 array_shift($parentids); // drop empty leading "context"
1232 array_pop($parentids); // drop _this_ context
1234 if (isset($raparents[$ra->roleid
])) {
1235 $raparents[$ra->roleid
] = array_merge($raparents[$ra->roleid
],
1238 $raparents[$ra->roleid
] = $parentids;
1241 // Always add the roleded
1242 if (!empty($ra->capability
)) {
1243 $k = "{$ra->path}:{$ra->roleid}";
1244 $accessdata['rdef'][$k][$ra->capability
] = $ra->permission
;
1251 // Walk up the tree to grab all the roledefs
1252 // of interest to our user...
1253 // NOTE: we use a series of IN clauses here - which
1254 // might explode on huge sites with very convoluted nesting of
1255 // categories... - extremely unlikely that the number of categories
1256 // and roletypes is so large that we hit the limits of IN()
1258 foreach ($raparents as $roleid=>$contexts) {
1259 $contexts = implode(',', array_unique($contexts));
1260 if ($contexts ==! '') {
1261 $clauses[] = "(roleid=$roleid AND contextid IN ($contexts))";
1264 $clauses = implode(" OR ", $clauses);
1265 if ($clauses !== '') {
1266 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
1267 FROM {$CFG->prefix}role_capabilities rc
1268 JOIN {$CFG->prefix}context ctx
1269 ON rc.contextid=ctx.id
1271 ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
1273 $rs = get_recordset_sql($sql);
1276 if ($rs->RecordCount()) {
1277 while ($rd = rs_fetch_next_record($rs)) {
1278 $k = "{$rd->path}:{$rd->roleid}";
1279 $accessdata['rdef'][$k][$rd->capability
] = $rd->permission
;
1287 // Overrides for the role assignments IN SUBCONTEXTS
1288 // (though we still do _not_ go below the course level.
1290 // NOTE that the JOIN w sctx is with 3-way triangulation to
1291 // catch overrides to the applicable role in any subcontext, based
1292 // on the path field of the parent.
1294 $sql = "SELECT sctx.path, ra.roleid,
1295 ctx.path AS parentpath,
1296 rco.capability, rco.permission
1297 FROM {$CFG->prefix}role_assignments ra
1298 JOIN {$CFG->prefix}context ctx
1299 ON ra.contextid=ctx.id
1300 JOIN {$CFG->prefix}context sctx
1301 ON (sctx.path LIKE " . sql_concat('ctx.path',"'/%'"). " )
1302 JOIN {$CFG->prefix}role_capabilities rco
1303 ON (rco.roleid=ra.roleid AND rco.contextid=sctx.id)
1304 WHERE ra.userid = $userid
1305 AND sctx.contextlevel <= ".CONTEXT_COURSE
."
1306 ORDER BY sctx.depth, sctx.path, ra.roleid";
1308 $rs = get_recordset_sql($sql);
1309 if ($rs->RecordCount()) {
1310 while ($rd = rs_fetch_next_record($rs)) {
1311 $k = "{$rd->path}:{$rd->roleid}";
1312 $accessdata['rdef'][$k][$rd->capability
] = $rd->permission
;
1322 * It add to the access ctrl array the data
1323 * needed by a user for a given context
1325 * @param $userid integer - the id of the user
1326 * @param $context context obj - needs path!
1327 * @param $accessdata array accessdata array
1330 function get_user_access_bycontext($userid, $context, $accessdata=NULL) {
1336 /* Get the additional RAs and relevant rolecaps
1337 * - role assignments - with role_caps
1338 * - relevant role caps
1339 * - above this user's RAs
1340 * - below this user's RAs - limited to course level
1343 // Roles already in use in this context
1344 if (is_null($accessdata)) {
1345 $accessdata = array(); // named list
1346 $accessdata['ra'] = array();
1347 $accessdata['rdef'] = array();
1348 $accessdata['loaded'] = array();
1351 $base = "/" . SYSCONTEXTID
;
1354 // Replace $context with the target context we will
1355 // load. Normally, this will be a course context, but
1356 // may be a different top-level context.
1361 // - BLOCK/PERSON/USER/COURSE(sitecourse) hanging from SYSTEM
1362 // - BLOCK/MODULE/GROUP hanging from a course
1364 // For course contexts, we _already_ have the RAs
1365 // but the cost of re-fetching is minimal so we don't care.
1367 if ($context->contextlevel
!== CONTEXT_COURSE
1368 && $context->path
!== "$base/{$context->id}") {
1369 // Case BLOCK/MODULE/GROUP hanging from a course
1370 // Assumption: the course _must_ be our parent
1371 // If we ever see stuff nested further this needs to
1372 // change to do 1 query over the exploded path to
1373 // find out which one is the course
1374 $targetid = array_pop(explode('/',get_course_from_path($context->path
)));
1375 $context = get_context_instance_by_id($targetid);
1380 // Role assignments in the context and below
1382 $sql = "SELECT ctx.path, ra.roleid
1383 FROM {$CFG->prefix}role_assignments ra
1384 JOIN {$CFG->prefix}context ctx
1385 ON ra.contextid=ctx.id
1386 WHERE ra.userid = $userid
1387 AND (ctx.path = '{$context->path}' OR ctx.path LIKE '{$context->path}/%')
1388 ORDER BY ctx.depth, ctx.path";
1389 $rs = get_recordset_sql($sql);
1394 $localroles = array();
1395 if ($rs->RecordCount()) {
1396 while ($ra = rs_fetch_next_record($rs)) {
1397 if (!isset($accessdata['ra'][$ra->path
])) {
1398 $accessdata['ra'][$ra->path
] = array();
1400 array_push($accessdata['ra'][$ra->path
], $ra->roleid
);
1401 array_push($localroles, $ra->roleid
);
1407 // Walk up and down the tree to grab all the roledefs
1408 // of interest to our user...
1411 // - we use IN() but the number of roles is very limited.
1413 $courseroles = aggregate_roles_from_accessdata($context, $accessdata);
1415 // Do we have any interesting "local" roles?
1416 $localroles = array_diff($localroles,$courseroles); // only "new" local roles
1417 $wherelocalroles='';
1418 if (count($localroles)) {
1419 // Role defs for local roles in 'higher' contexts...
1420 $contexts = substr($context->path
, 1); // kill leading slash
1421 $contexts = str_replace('/', ',', $contexts);
1422 $localroleids = implode(',',$localroles);
1423 $wherelocalroles="OR (rc.roleid IN ({$localroleids})
1424 AND ctx.id IN ($contexts))" ;
1427 // We will want overrides for all of them
1429 if ($roleids = implode(',',array_merge($courseroles,$localroles))) {
1430 $whereroles = "rc.roleid IN ($roleids) AND";
1432 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
1433 FROM {$CFG->prefix}role_capabilities rc
1434 JOIN {$CFG->prefix}context ctx
1435 ON rc.contextid=ctx.id
1437 (ctx.id={$context->id} OR ctx.path LIKE '{$context->path}/%'))
1439 ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
1441 if ($rs = get_recordset_sql($sql)) {
1442 if ($rs->RecordCount()) {
1443 while ($rd = rs_fetch_next_record($rs)) {
1444 $k = "{$rd->path}:{$rd->roleid}";
1445 $accessdata['rdef'][$k][$rd->capability
] = $rd->permission
;
1450 debugging('Bad SQL encountered!');
1453 // TODO: compact capsets?
1455 error_log("loaded {$context->path}");
1456 $accessdata['loaded'][] = $context->path
;
1462 * It add to the access ctrl array the data
1463 * needed by a role for a given context.
1465 * The data is added in the rdef key.
1467 * This role-centric function is useful for role_switching
1468 * and to get an overview of what a role gets under a
1469 * given context and below...
1471 * @param $roleid integer - the id of the user
1472 * @param $context context obj - needs path!
1473 * @param $accessdata accessdata array
1476 function get_role_access_bycontext($roleid, $context, $accessdata=NULL) {
1480 /* Get the relevant rolecaps into rdef
1481 * - relevant role caps
1482 * - at ctx and above
1486 if (is_null($accessdata)) {
1487 $accessdata = array(); // named list
1488 $accessdata['ra'] = array();
1489 $accessdata['rdef'] = array();
1490 $accessdata['loaded'] = array();
1493 $contexts = substr($context->path
, 1); // kill leading slash
1494 $contexts = str_replace('/', ',', $contexts);
1497 // Walk up and down the tree to grab all the roledefs
1498 // of interest to our role...
1500 // NOTE: we use an IN clauses here - which
1501 // might explode on huge sites with very convoluted nesting of
1502 // categories... - extremely unlikely that the number of nested
1503 // categories is so large that we hit the limits of IN()
1505 $sql = "SELECT ctx.path, rc.capability, rc.permission
1506 FROM {$CFG->prefix}role_capabilities rc
1507 JOIN {$CFG->prefix}context ctx
1508 ON rc.contextid=ctx.id
1509 WHERE rc.roleid=$roleid AND
1510 ( ctx.id IN ($contexts) OR
1511 ctx.path LIKE '{$context->path}/%' )
1512 ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
1514 $rs = get_recordset_sql($sql);
1515 if ($rs->RecordCount()) {
1516 while ($rd = rs_fetch_next_record($rs)) {
1517 $k = "{$rd->path}:{$roleid}";
1518 $accessdata['rdef'][$k][$rd->capability
] = $rd->permission
;
1527 * Load accessdata for a user
1528 * into the $ACCESS global
1530 * Used by has_capability() - but feel free
1531 * to call it if you are about to run a BIG
1532 * cron run across a bazillion users.
1534 * TODO: share rdef tree to save mem
1537 function load_user_accessdata($userid) {
1538 global $ACCESS,$CFG;
1540 if (!isset($ACCESS)) {
1543 $base = '/'.SYSCONTEXTID
;
1545 $accessdata = get_user_access_sitewide($userid);
1548 // provide "default role" & set 'dr'
1550 $accessdata = get_role_access($CFG->defaultuserroleid
, $accessdata);
1551 if (!isset($accessdata['ra'][$base])) {
1552 $accessdata['ra'][$base] = array($CFG->defaultuserroleid
);
1554 array_push($accessdata['ra'][$base], $CFG->defaultuserroleid
);
1556 $accessdata['dr'] = $CFG->defaultuserroleid
;
1559 // provide "default frontpage role"
1561 if ($CFG->defaultfrontpageroleid
) {
1562 $base = '/'. SYSCONTEXTID
.'/'. $frontpagecontext->id
;
1563 $accessdata = get_default_frontpage_role_access($CFG->defaultfrongpageroleid
, $accessdata);
1564 if (!isset($accessdata['ra'][$base])) {
1565 $accessdata['ra'][$base] = array($CFG->defaultfrongpageroleid
);
1567 array_push($accessdata['ra'][$base], $CFG->defaultfrongpageroleid
);
1570 $ACCESS[$userid] = $accessdata;
1575 * A convenience function to completely load all the capabilities
1576 * for the current user. This is what gets called from login, for example.
1578 function load_all_capabilities() {
1581 $base = '/'.SYSCONTEXTID
;
1583 if (isguestuser()) {
1584 $guest = get_guest_role();
1587 $USER->access
= get_role_access($guest->id
);
1588 // Put the ghost enrolment in place...
1589 $USER->access
['ra'][$base] = array($guest->id
);
1592 } else if (isloggedin()) {
1594 check_enrolment_plugins($USER);
1596 $accessdata = get_user_access_sitewide($USER->id
);
1599 // provide "default role" & set 'dr'
1601 $accessdata = get_role_access($CFG->defaultuserroleid
, $accessdata);
1602 if (!isset($accessdata['ra'][$base])) {
1603 $accessdata['ra'][$base] = array($CFG->defaultuserroleid
);
1605 array_push($accessdata['ra'][$base], $CFG->defaultuserroleid
);
1607 $accessdata['dr'] = $CFG->defaultuserroleid
;
1609 $frontpagecontext = get_context_instance(CONTEXT_COURSE
, SITEID
);
1612 // provide "default frontpage role"
1615 if ($CFG->defaultfrontpageroleid
) {
1616 $base = '/'. SYSCONTEXTID
.'/'. $frontpagecontext->id
;
1617 $accessdata = get_default_frontpage_role_access($CFG->defaultfrontpageroleid
, $accessdata);
1618 if (!isset($accessdata['ra'][$base])) {
1619 $accessdata['ra'][$base] = array($CFG->defaultfrontpageroleid
);
1621 array_push($accessdata['ra'][$base], $CFG->defaultfrontpageroleid
);
1624 $USER->access
= $accessdata;
1627 if ($roleid = get_notloggedin_roleid()) {
1628 $USER->access
= get_role_access($roleid);
1629 $USER->access
['ra'][$base] = array($roleid);
1633 // Timestamp to read
1634 // dirty context timestamps
1635 $USER->access
['time'] = time();
1637 // Clear to force a refresh
1638 unset($USER->mycourses
);
1642 * A convenience function to completely reload all the capabilities
1643 * for the current user when roles have been updated in a relevant
1644 * context -- but PRESERVING switchroles and loginas.
1646 * That is - completely transparent to the user.
1648 * Note: rewrites $USER->access completely.
1651 function reload_all_capabilities() {
1654 error_log("reloading");
1657 if (isset($USER->access
['rsw'])) {
1658 $sw = $USER->access
['rsw'];
1659 error_log(print_r($sw,1));
1662 unset($USER->access
);
1663 unset($USER->mycourses
);
1665 load_all_capabilities();
1667 foreach ($sw as $path => $roleid) {
1668 $context = get_record('context', 'path', $path);
1669 role_switch($roleid, $context);
1675 * Adds a temp role to an accessdata array.
1677 * Useful for the "temporary guest" access
1678 * we grant to logged-in users.
1680 * Note - assumes a course context!
1683 function load_temp_role($context, $roleid, $accessdata) {
1688 // Load rdefs for the role in -
1690 // - all the parents
1691 // - and below - IOWs overrides...
1694 // turn the path into a list of context ids
1695 $contexts = substr($context->path
, 1); // kill leading slash
1696 $contexts = str_replace('/', ',', $contexts);
1698 $sql = "SELECT ctx.path,
1699 rc.capability, rc.permission
1700 FROM {$CFG->prefix}context ctx
1701 JOIN {$CFG->prefix}role_capabilities rc
1702 ON rc.contextid=ctx.id
1703 WHERE (ctx.id IN ($contexts)
1704 OR ctx.path LIKE '{$context->path}/%')
1705 AND rc.roleid = {$roleid}
1706 ORDER BY ctx.depth, ctx.path";
1707 $rs = get_recordset_sql($sql);
1708 if ($rs->RecordCount()) {
1709 while ($rd = rs_fetch_next_record($rs)) {
1710 $k = "{$rd->path}:{$roleid}";
1711 $accessdata['rdef'][$k][$rd->capability
] = $rd->permission
;
1717 // Say we loaded everything for the course context
1718 // - which we just did - if the user gets a proper
1719 // RA in this session, this data will need to be reloaded,
1720 // but that is handled by the complete accessdata reload
1722 array_push($accessdata['loaded'], $context->path
);
1727 if (isset($accessdata['ra'][$context->path
])) {
1728 array_push($accessdata['ra'][$context->path
], $roleid);
1730 $accessdata['ra'][$context->path
] = array($roleid);
1738 * Check all the login enrolment information for the given user object
1739 * by querying the enrolment plugins
1741 function check_enrolment_plugins(&$user) {
1744 static $inprogress; // To prevent this function being called more than once in an invocation
1746 if (!empty($inprogress[$user->id
])) {
1750 $inprogress[$user->id
] = true; // Set the flag
1752 require_once($CFG->dirroot
.'/enrol/enrol.class.php');
1754 if (!($plugins = explode(',', $CFG->enrol_plugins_enabled
))) {
1755 $plugins = array($CFG->enrol
);
1758 foreach ($plugins as $plugin) {
1759 $enrol = enrolment_factory
::factory($plugin);
1760 if (method_exists($enrol, 'setup_enrolments')) { /// Plugin supports Roles (Moodle 1.7 and later)
1761 $enrol->setup_enrolments($user);
1762 } else { /// Run legacy enrolment methods
1763 if (method_exists($enrol, 'get_student_courses')) {
1764 $enrol->get_student_courses($user);
1766 if (method_exists($enrol, 'get_teacher_courses')) {
1767 $enrol->get_teacher_courses($user);
1770 /// deal with $user->students and $user->teachers stuff
1771 unset($user->student
);
1772 unset($user->teacher
);
1777 unset($inprogress[$user->id
]); // Unset the flag
1781 * A print form function. This should either grab all the capabilities from
1782 * files or a central table for that particular module instance, then present
1783 * them in check boxes. Only relevant capabilities should print for known
1785 * @param $mod - module id of the mod
1787 function print_capabilities($modid=0) {
1790 $capabilities = array();
1793 // We are in a module specific context.
1795 // Get the mod's name.
1796 // Call the function that grabs the file and parse.
1797 $cm = get_record('course_modules', 'id', $modid);
1798 $module = get_record('modules', 'id', $cm->module
);
1801 // Print all capabilities.
1802 foreach ($capabilities as $capability) {
1803 // Prints the check box component.
1810 * Installs the roles system.
1811 * This function runs on a fresh install as well as on an upgrade from the old
1812 * hard-coded student/teacher/admin etc. roles to the new roles system.
1814 function moodle_install_roles() {
1818 /// Create a system wide context for assignemnt.
1819 $systemcontext = $context = get_context_instance(CONTEXT_SYSTEM
);
1822 /// Create default/legacy roles and capabilities.
1823 /// (1 legacy capability per legacy role at system level).
1825 $adminrole = create_role(addslashes(get_string('administrator')), 'admin',
1826 addslashes(get_string('administratordescription')), 'moodle/legacy:admin');
1827 $coursecreatorrole = create_role(addslashes(get_string('coursecreators')), 'coursecreator',
1828 addslashes(get_string('coursecreatorsdescription')), 'moodle/legacy:coursecreator');
1829 $editteacherrole = create_role(addslashes(get_string('defaultcourseteacher')), 'editingteacher',
1830 addslashes(get_string('defaultcourseteacherdescription')), 'moodle/legacy:editingteacher');
1831 $noneditteacherrole = create_role(addslashes(get_string('noneditingteacher')), 'teacher',
1832 addslashes(get_string('noneditingteacherdescription')), 'moodle/legacy:teacher');
1833 $studentrole = create_role(addslashes(get_string('defaultcoursestudent')), 'student',
1834 addslashes(get_string('defaultcoursestudentdescription')), 'moodle/legacy:student');
1835 $guestrole = create_role(addslashes(get_string('guest')), 'guest',
1836 addslashes(get_string('guestdescription')), 'moodle/legacy:guest');
1837 $userrole = create_role(addslashes(get_string('authenticateduser')), 'user',
1838 addslashes(get_string('authenticateduserdescription')), 'moodle/legacy:user');
1840 /// Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles
1842 if (!assign_capability('moodle/site:doanything', CAP_ALLOW
, $adminrole, $systemcontext->id
)) {
1843 error('Could not assign moodle/site:doanything to the admin role');
1845 if (!update_capabilities()) {
1846 error('Had trouble upgrading the core capabilities for the Roles System');
1849 /// Look inside user_admin, user_creator, user_teachers, user_students and
1850 /// assign above new roles. If a user has both teacher and student role,
1851 /// only teacher role is assigned. The assignment should be system level.
1853 $dbtables = $db->MetaTables('TABLES');
1855 /// Set up the progress bar
1857 $usertables = array('user_admins', 'user_coursecreators', 'user_teachers', 'user_students');
1859 $totalcount = $progresscount = 0;
1860 foreach ($usertables as $usertable) {
1861 if (in_array($CFG->prefix
.$usertable, $dbtables)) {
1862 $totalcount +
= count_records($usertable);
1866 print_progress(0, $totalcount, 5, 1, 'Processing role assignments');
1868 /// Upgrade the admins.
1869 /// Sort using id ASC, first one is primary admin.
1871 if (in_array($CFG->prefix
.'user_admins', $dbtables)) {
1872 if ($rs = get_recordset_sql('SELECT * from '.$CFG->prefix
.'user_admins ORDER BY ID ASC')) {
1873 while ($admin = rs_fetch_next_record($rs)) {
1874 role_assign($adminrole, $admin->userid
, 0, $systemcontext->id
);
1876 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1881 // This is a fresh install.
1885 /// Upgrade course creators.
1886 if (in_array($CFG->prefix
.'user_coursecreators', $dbtables)) {
1887 if ($rs = get_recordset('user_coursecreators')) {
1888 while ($coursecreator = rs_fetch_next_record($rs)) {
1889 role_assign($coursecreatorrole, $coursecreator->userid
, 0, $systemcontext->id
);
1891 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1898 /// Upgrade editting teachers and non-editting teachers.
1899 if (in_array($CFG->prefix
.'user_teachers', $dbtables)) {
1900 if ($rs = get_recordset('user_teachers')) {
1901 while ($teacher = rs_fetch_next_record($rs)) {
1903 // removed code here to ignore site level assignments
1904 // since the contexts are separated now
1906 // populate the user_lastaccess table
1907 $access = new object();
1908 $access->timeaccess
= $teacher->timeaccess
;
1909 $access->userid
= $teacher->userid
;
1910 $access->courseid
= $teacher->course
;
1911 insert_record('user_lastaccess', $access);
1913 // assign the default student role
1914 $coursecontext = get_context_instance(CONTEXT_COURSE
, $teacher->course
); // needs cache
1916 if ($teacher->authority
== 0) {
1922 if ($teacher->editall
) { // editting teacher
1923 role_assign($editteacherrole, $teacher->userid
, 0, $coursecontext->id
, 0, 0, $hiddenteacher);
1925 role_assign($noneditteacherrole, $teacher->userid
, 0, $coursecontext->id
, 0, 0, $hiddenteacher);
1928 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1935 /// Upgrade students.
1936 if (in_array($CFG->prefix
.'user_students', $dbtables)) {
1937 if ($rs = get_recordset('user_students')) {
1938 while ($student = rs_fetch_next_record($rs)) {
1940 // populate the user_lastaccess table
1941 $access = new object;
1942 $access->timeaccess
= $student->timeaccess
;
1943 $access->userid
= $student->userid
;
1944 $access->courseid
= $student->course
;
1945 insert_record('user_lastaccess', $access);
1947 // assign the default student role
1948 $coursecontext = get_context_instance(CONTEXT_COURSE
, $student->course
);
1949 role_assign($studentrole, $student->userid
, 0, $coursecontext->id
);
1951 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1958 /// Upgrade guest (only 1 entry).
1959 if ($guestuser = get_record('user', 'username', 'guest')) {
1960 role_assign($guestrole, $guestuser->id
, 0, $systemcontext->id
);
1962 print_progress($totalcount, $totalcount, 5, 1, 'Processing role assignments');
1965 /// Insert the correct records for legacy roles
1966 allow_assign($adminrole, $adminrole);
1967 allow_assign($adminrole, $coursecreatorrole);
1968 allow_assign($adminrole, $noneditteacherrole);
1969 allow_assign($adminrole, $editteacherrole);
1970 allow_assign($adminrole, $studentrole);
1971 allow_assign($adminrole, $guestrole);
1973 allow_assign($coursecreatorrole, $noneditteacherrole);
1974 allow_assign($coursecreatorrole, $editteacherrole);
1975 allow_assign($coursecreatorrole, $studentrole);
1976 allow_assign($coursecreatorrole, $guestrole);
1978 allow_assign($editteacherrole, $noneditteacherrole);
1979 allow_assign($editteacherrole, $studentrole);
1980 allow_assign($editteacherrole, $guestrole);
1982 /// Set up default permissions for overrides
1983 allow_override($adminrole, $adminrole);
1984 allow_override($adminrole, $coursecreatorrole);
1985 allow_override($adminrole, $noneditteacherrole);
1986 allow_override($adminrole, $editteacherrole);
1987 allow_override($adminrole, $studentrole);
1988 allow_override($adminrole, $guestrole);
1989 allow_override($adminrole, $userrole);
1992 /// Delete the old user tables when we are done
1994 drop_table(new XMLDBTable('user_students'));
1995 drop_table(new XMLDBTable('user_teachers'));
1996 drop_table(new XMLDBTable('user_coursecreators'));
1997 drop_table(new XMLDBTable('user_admins'));
2002 * Returns array of all legacy roles.
2004 function get_legacy_roles() {
2006 'admin' => 'moodle/legacy:admin',
2007 'coursecreator' => 'moodle/legacy:coursecreator',
2008 'editingteacher' => 'moodle/legacy:editingteacher',
2009 'teacher' => 'moodle/legacy:teacher',
2010 'student' => 'moodle/legacy:student',
2011 'guest' => 'moodle/legacy:guest',
2012 'user' => 'moodle/legacy:user'
2016 function get_legacy_type($roleid) {
2017 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
2018 $legacyroles = get_legacy_roles();
2021 foreach($legacyroles as $ltype=>$lcap) {
2022 $localoverride = get_local_override($roleid, $sitecontext->id
, $lcap);
2023 if (!empty($localoverride->permission
) and $localoverride->permission
== CAP_ALLOW
) {
2024 //choose first selected legacy capability - reset the rest
2025 if (empty($result)) {
2028 unassign_capability($lcap, $roleid);
2037 * Assign the defaults found in this capabality definition to roles that have
2038 * the corresponding legacy capabilities assigned to them.
2039 * @param $legacyperms - an array in the format (example):
2040 * 'guest' => CAP_PREVENT,
2041 * 'student' => CAP_ALLOW,
2042 * 'teacher' => CAP_ALLOW,
2043 * 'editingteacher' => CAP_ALLOW,
2044 * 'coursecreator' => CAP_ALLOW,
2045 * 'admin' => CAP_ALLOW
2046 * @return boolean - success or failure.
2048 function assign_legacy_capabilities($capability, $legacyperms) {
2050 $legacyroles = get_legacy_roles();
2052 foreach ($legacyperms as $type => $perm) {
2054 $systemcontext = get_context_instance(CONTEXT_SYSTEM
);
2056 if (!array_key_exists($type, $legacyroles)) {
2057 error('Incorrect legacy role definition for type: '.$type);
2060 if ($roles = get_roles_with_capability($legacyroles[$type], CAP_ALLOW
)) {
2061 foreach ($roles as $role) {
2062 // Assign a site level capability.
2063 if (!assign_capability($capability, $perm, $role->id
, $systemcontext->id
)) {
2074 * Checks to see if a capability is a legacy capability.
2075 * @param $capabilityname
2078 function islegacy($capabilityname) {
2079 if (strpos($capabilityname, 'moodle/legacy') === 0) {
2088 /**********************************
2089 * Context Manipulation functions *
2090 **********************************/
2093 * Create a new context record for use by all roles-related stuff
2094 * assumes that the caller has done the homework.
2097 * @param $instanceid
2099 * @return object newly created context
2101 function create_context($contextlevel, $instanceid) {
2105 if ($contextlevel == CONTEXT_SYSTEM
) {
2106 return create_system_context();
2109 $context = new object();
2110 $context->contextlevel
= $contextlevel;
2111 $context->instanceid
= $instanceid;
2113 // Define $context->path based on the parent
2114 // context. In other words... Who is your daddy?
2115 $basepath = '/' . SYSCONTEXTID
;
2118 switch ($contextlevel) {
2119 case CONTEXT_COURSECAT
:
2120 $sql = "SELECT ctx.path, ctx.depth
2121 FROM {$CFG->prefix}context ctx
2122 JOIN {$CFG->prefix}course_categories cc
2123 ON (cc.parent=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT
.")
2124 WHERE cc.id={$instanceid}";
2125 if ($p = get_record_sql($sql)) {
2126 $basepath = $p->path
;
2127 $basedepth = $p->depth
;
2131 case CONTEXT_COURSE
:
2132 $sql = "SELECT ctx.path, ctx.depth
2133 FROM {$CFG->prefix}context ctx
2134 JOIN {$CFG->prefix}course c
2135 ON (c.category=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT
.")
2136 WHERE c.id={$instanceid} AND c.id !=" . SITEID
;
2137 if ($p = get_record_sql($sql)) {
2138 $basepath = $p->path
;
2139 $basedepth = $p->depth
;
2143 case CONTEXT_MODULE
:
2144 $sql = "SELECT ctx.path, ctx.depth
2145 FROM {$CFG->prefix}context ctx
2146 JOIN {$CFG->prefix}course_modules cm
2147 ON (cm.course=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE
.")
2148 WHERE cm.id={$instanceid}";
2149 $p = get_record_sql($sql);
2150 $basepath = $p->path
;
2151 $basedepth = $p->depth
;
2155 // Only non-pinned & course-page based
2156 $sql = "SELECT ctx.path, ctx.depth
2157 FROM {$CFG->prefix}context ctx
2158 JOIN {$CFG->prefix}block_instance bi
2159 ON (bi.pageid=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE
.")
2160 WHERE bi.id={$instanceid} AND bi.pagetype='course-view'";
2161 if ($p = get_record_sql($sql)) {
2162 $basepath = $p->path
;
2163 $basedepth = $p->depth
;
2167 // default to basepath
2169 case CONTEXT_PERSONAL
:
2170 // default to basepath
2174 $context->depth
= $basedepth+
1;
2176 if ($id = insert_record('context',$context)) {
2177 // can't set the path till we know the id!
2178 set_field('context', 'path', $basepath . '/' . $id,
2180 $c = get_context_instance_by_id($id);
2183 debugging('Error: could not insert new context level "'.
2184 s($contextlevel).'", instance "'.
2185 s($instanceid).'".');
2191 * This hacky function is needed because we can not change system context instanceid using normal upgrade routine.
2193 function create_system_context() {
2194 if ($context = get_record('context', 'contextlevel', CONTEXT_SYSTEM
, 'instanceid', SITEID
)) {
2195 // we are going to change instanceid of system context to 0 now
2196 $context->instanceid
= 0;
2197 update_record('context', $context);
2198 //context rel not affected
2202 $context = new object();
2203 $context->contextlevel
= CONTEXT_SYSTEM
;
2204 $context->instanceid
= 0;
2205 if ($context->id
= insert_record('context',$context)) {
2208 debugging('Can not create system context');
2214 * Remove a context record and any dependent entries
2216 * @param $instanceid
2218 * @return bool properly deleted
2220 function delete_context($contextlevel, $instanceid) {
2221 if ($context = get_context_instance($contextlevel, $instanceid)) {
2222 mark_context_dirty($context->path
);
2223 return delete_records('context', 'id', $context->id
) &&
2224 delete_records('role_assignments', 'contextid', $context->id
) &&
2225 delete_records('role_capabilities', 'contextid', $context->id
);
2231 * Remove stale context records
2235 function cleanup_contexts() {
2238 $sql = " SELECT " . CONTEXT_COURSECAT
. " AS level,
2239 c.instanceid AS instanceid
2240 FROM {$CFG->prefix}context c
2241 LEFT OUTER JOIN {$CFG->prefix}course_categories AS t
2242 ON c.instanceid = t.id
2243 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_COURSECAT
. "
2245 SELECT " . CONTEXT_COURSE
. " AS level,
2246 c.instanceid AS instanceid
2247 FROM {$CFG->prefix}context c
2248 LEFT OUTER JOIN {$CFG->prefix}course AS t
2249 ON c.instanceid = t.id
2250 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_COURSE
. "
2252 SELECT " . CONTEXT_MODULE
. " AS level,
2253 c.instanceid AS instanceid
2254 FROM {$CFG->prefix}context c
2255 LEFT OUTER JOIN {$CFG->prefix}course_modules AS t
2256 ON c.instanceid = t.id
2257 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_MODULE
. "
2259 SELECT " . CONTEXT_USER
. " AS level,
2260 c.instanceid AS instanceid
2261 FROM {$CFG->prefix}context c
2262 LEFT OUTER JOIN {$CFG->prefix}user AS t
2263 ON c.instanceid = t.id
2264 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_USER
. "
2266 SELECT " . CONTEXT_BLOCK
. " AS level,
2267 c.instanceid AS instanceid
2268 FROM {$CFG->prefix}context c
2269 LEFT OUTER JOIN {$CFG->prefix}block_instance AS t
2270 ON c.instanceid = t.id
2271 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_BLOCK
. "
2273 SELECT " . CONTEXT_GROUP
. " AS level,
2274 c.instanceid AS instanceid
2275 FROM {$CFG->prefix}context c
2276 LEFT OUTER JOIN {$CFG->prefix}groups AS t
2277 ON c.instanceid = t.id
2278 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_GROUP
. "
2280 $rs = get_recordset_sql($sql);
2281 if ($rs->RecordCount()) {
2284 while ($tx && $ctx = rs_fetch_next_record($rs)) {
2285 $tx = $tx && delete_context($ctx->level
, $ctx->instanceid
);
2299 * Get the context instance as an object. This function will create the
2300 * context instance if it does not exist yet.
2301 * @param integer $level The context level, for example CONTEXT_COURSE, or CONTEXT_MODULE.
2302 * @param integer $instance The instance id. For $level = CONTEXT_COURSE, this would be $course->id,
2303 * for $level = CONTEXT_MODULE, this would be $cm->id. And so on.
2304 * @return object The context object.
2306 function get_context_instance($contextlevel=NULL, $instance=0) {
2308 global $context_cache, $context_cache_id, $CONTEXT;
2309 static $allowed_contexts = array(CONTEXT_SYSTEM
, CONTEXT_PERSONAL
, CONTEXT_USER
, CONTEXT_COURSECAT
, CONTEXT_COURSE
, CONTEXT_GROUP
, CONTEXT_MODULE
, CONTEXT_BLOCK
);
2311 if ($contextlevel === 'clearcache') {
2312 // TODO: Remove for v2.0
2313 // No longer needed, but we'll catch it to avoid erroring out on custom code.
2314 // This used to be a fix for MDL-9016
2315 // "Restoring into existing course, deleting first
2316 // deletes context and doesn't recreate it"
2320 /// If no level is supplied then return the current global context if there is one
2321 if (empty($contextlevel)) {
2322 if (empty($CONTEXT)) {
2323 //fatal error, code must be fixed
2324 error("Error: get_context_instance() called without a context");
2330 /// Backwards compatibility with obsoleted (CONTEXT_SYSTEM, SITEID)
2331 if ($contextlevel == CONTEXT_SYSTEM
) {
2335 /// check allowed context levels
2336 if (!in_array($contextlevel, $allowed_contexts)) {
2337 // fatal error, code must be fixed - probably typo or switched parameters
2338 error('Error: get_context_instance() called with incorrect context level "'.s($contextlevel).'"');
2342 if (isset($context_cache[$contextlevel][$instance])) { // Already cached
2343 return $context_cache[$contextlevel][$instance];
2346 /// Get it from the database, or create it
2347 if (!$context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance)) {
2348 create_context($contextlevel, $instance);
2349 $context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance);
2352 /// Only add to cache if context isn't empty.
2353 if (!empty($context)) {
2354 $context_cache[$contextlevel][$instance] = $context; // Cache it for later
2355 $context_cache_id[$context->id
] = $context; // Cache it for later
2363 * Get a context instance as an object, from a given context id.
2364 * @param $id a context id.
2365 * @return object The context object.
2367 function get_context_instance_by_id($id) {
2369 global $context_cache, $context_cache_id;
2371 if (isset($context_cache_id[$id])) { // Already cached
2372 return $context_cache_id[$id];
2375 if ($context = get_record('context', 'id', $id)) { // Update the cache and return
2376 $context_cache[$context->contextlevel
][$context->instanceid
] = $context;
2377 $context_cache_id[$context->id
] = $context;
2386 * Get the local override (if any) for a given capability in a role in a context
2389 * @param $capability
2391 function get_local_override($roleid, $contextid, $capability) {
2392 return get_record('role_capabilities', 'roleid', $roleid, 'capability', $capability, 'contextid', $contextid);
2397 /************************************
2398 * DB TABLE RELATED FUNCTIONS *
2399 ************************************/
2402 * function that creates a role
2403 * @param name - role name
2404 * @param shortname - role short name
2405 * @param description - role description
2406 * @param legacy - optional legacy capability
2407 * @return id or false
2409 function create_role($name, $shortname, $description, $legacy='') {
2411 // check for duplicate role name
2413 if ($role = get_record('role','name', $name)) {
2414 error('there is already a role with this name!');
2417 if ($role = get_record('role','shortname', $shortname)) {
2418 error('there is already a role with this shortname!');
2421 $role = new object();
2422 $role->name
= $name;
2423 $role->shortname
= $shortname;
2424 $role->description
= $description;
2426 //find free sortorder number
2427 $role->sortorder
= count_records('role');
2428 while (get_record('role','sortorder', $role->sortorder
)) {
2429 $role->sortorder +
= 1;
2432 if (!$context = get_context_instance(CONTEXT_SYSTEM
)) {
2436 if ($id = insert_record('role', $role)) {
2438 assign_capability($legacy, CAP_ALLOW
, $id, $context->id
);
2441 /// By default, users with role:manage at site level
2442 /// should be able to assign users to this new role, and override this new role's capabilities
2444 // find all admin roles
2445 if ($adminroles = get_roles_with_capability('moodle/role:manage', CAP_ALLOW
, $context)) {
2446 // foreach admin role
2447 foreach ($adminroles as $arole) {
2448 // write allow_assign and allow_overrid
2449 allow_assign($arole->id
, $id);
2450 allow_override($arole->id
, $id);
2462 * function that deletes a role and cleanups up after it
2463 * @param roleid - id of role to delete
2466 function delete_role($roleid) {
2470 // mdl 10149, check if this is the last active admin role
2471 // if we make the admin role not deletable then this part can go
2473 $systemcontext = get_context_instance(CONTEXT_SYSTEM
);
2475 if ($role = get_record('role', 'id', $roleid)) {
2476 if (record_exists('role_capabilities', 'contextid', $systemcontext->id
, 'roleid', $roleid, 'capability', 'moodle/site:doanything')) {
2477 // deleting an admin role
2479 if ($adminroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW
, $systemcontext)) {
2480 foreach ($adminroles as $adminrole) {
2481 if ($adminrole->id
!= $roleid) {
2482 // some other admin role
2483 if (record_exists('role_assignments', 'roleid', $adminrole->id
, 'contextid', $systemcontext->id
)) {
2484 // found another admin role with at least 1 user assigned
2491 if ($status !== true) {
2492 error ('You can not delete this role because there is no other admin roles with users assigned');
2497 // first unssign all users
2498 if (!role_unassign($roleid)) {
2499 debugging("Error while unassigning all users from role with ID $roleid!");
2503 // cleanup all references to this role, ignore errors
2506 // MDL-10679 find all contexts where this role has an override
2507 $contexts = get_records_sql("SELECT contextid, contextid
2508 FROM {$CFG->prefix}role_capabilities
2509 WHERE roleid = $roleid");
2511 delete_records('role_capabilities', 'roleid', $roleid);
2513 delete_records('role_allow_assign', 'roleid', $roleid);
2514 delete_records('role_allow_assign', 'allowassign', $roleid);
2515 delete_records('role_allow_override', 'roleid', $roleid);
2516 delete_records('role_allow_override', 'allowoverride', $roleid);
2517 delete_records('role_names', 'roleid', $roleid);
2520 // finally delete the role itself
2521 if ($success and !delete_records('role', 'id', $roleid)) {
2522 debugging("Could not delete role record with ID $roleid!");
2530 * Function to write context specific overrides, or default capabilities.
2531 * @param module - string name
2532 * @param capability - string name
2533 * @param contextid - context id
2534 * @param roleid - role id
2535 * @param permission - int 1,-1 or -1000
2536 * should not be writing if permission is 0
2538 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite=false) {
2542 if (empty($permission) ||
$permission == CAP_INHERIT
) { // if permission is not set
2543 unassign_capability($capability, $roleid, $contextid);
2547 $existing = get_record('role_capabilities', 'contextid', $contextid, 'roleid', $roleid, 'capability', $capability);
2549 if ($existing and !$overwrite) { // We want to keep whatever is there already
2554 $cap->contextid
= $contextid;
2555 $cap->roleid
= $roleid;
2556 $cap->capability
= $capability;
2557 $cap->permission
= $permission;
2558 $cap->timemodified
= time();
2559 $cap->modifierid
= empty($USER->id
) ?
0 : $USER->id
;
2562 $cap->id
= $existing->id
;
2563 return update_record('role_capabilities', $cap);
2565 $c = get_record('context', 'id', $contextid);
2566 return insert_record('role_capabilities', $cap);
2571 * Unassign a capability from a role.
2572 * @param $roleid - the role id
2573 * @param $capability - the name of the capability
2574 * @return boolean - success or failure
2576 function unassign_capability($capability, $roleid, $contextid=NULL) {
2578 if (isset($contextid)) {
2579 // delete from context rel, if this is the last override in this context
2580 $status = delete_records('role_capabilities', 'capability', $capability,
2581 'roleid', $roleid, 'contextid', $contextid);
2583 $status = delete_records('role_capabilities', 'capability', $capability,
2591 * Get the roles that have a given capability assigned to it. This function
2592 * does not resolve the actual permission of the capability. It just checks
2593 * for assignment only.
2594 * @param $capability - capability name (string)
2595 * @param $permission - optional, the permission defined for this capability
2596 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT
2597 * @return array or role objects
2599 function get_roles_with_capability($capability, $permission=NULL, $context='') {
2604 if ($contexts = get_parent_contexts($context)) {
2605 $listofcontexts = '('.implode(',', $contexts).')';
2607 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
2608 $listofcontexts = '('.$sitecontext->id
.')'; // must be site
2610 $contextstr = "AND (rc.contextid = '$context->id' OR rc.contextid IN $listofcontexts)";
2615 $selectroles = "SELECT r.*
2616 FROM {$CFG->prefix}role r,
2617 {$CFG->prefix}role_capabilities rc
2618 WHERE rc.capability = '$capability'
2619 AND rc.roleid = r.id $contextstr";
2621 if (isset($permission)) {
2622 $selectroles .= " AND rc.permission = '$permission'";
2624 return get_records_sql($selectroles);
2629 * This function makes a role-assignment (a role for a user or group in a particular context)
2630 * @param $roleid - the role of the id
2631 * @param $userid - userid
2632 * @param $groupid - group id
2633 * @param $contextid - id of the context
2634 * @param $timestart - time this assignment becomes effective
2635 * @param $timeend - time this assignemnt ceases to be effective
2637 * @return id - new id of the assigment
2639 function role_assign($roleid, $userid, $groupid, $contextid, $timestart=0, $timeend=0, $hidden=0, $enrol='manual',$timemodified='') {
2642 debugging("Assign roleid $roleid userid $userid contextid $contextid", DEBUG_DEVELOPER
);
2644 /// Do some data validation
2646 if (empty($roleid)) {
2647 debugging('Role ID not provided');
2651 if (empty($userid) && empty($groupid)) {
2652 debugging('Either userid or groupid must be provided');
2656 if ($userid && !record_exists('user', 'id', $userid)) {
2657 debugging('User ID '.intval($userid).' does not exist!');
2661 if ($groupid && !groups_group_exists($groupid)) {
2662 debugging('Group ID '.intval($groupid).' does not exist!');
2666 if (!$context = get_context_instance_by_id($contextid)) {
2667 debugging('Context ID '.intval($contextid).' does not exist!');
2671 if (($timestart and $timeend) and ($timestart > $timeend)) {
2672 debugging('The end time can not be earlier than the start time');
2676 if (!$timemodified) {
2677 $timemodified = time();
2680 /// Check for existing entry
2682 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id
, 'userid', $userid);
2684 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id
, 'groupid', $groupid);
2688 $newra = new object;
2690 if (empty($ra)) { // Create a new entry
2691 $newra->roleid
= $roleid;
2692 $newra->contextid
= $context->id
;
2693 $newra->userid
= $userid;
2694 $newra->hidden
= $hidden;
2695 $newra->enrol
= $enrol;
2696 /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
2697 /// by repeating queries with the same exact parameters in a 100 secs time window
2698 $newra->timestart
= round($timestart, -2);
2699 $newra->timeend
= $timeend;
2700 $newra->timemodified
= $timemodified;
2701 $newra->modifierid
= empty($USER->id
) ?
0 : $USER->id
;
2703 $success = insert_record('role_assignments', $newra);
2705 } else { // We already have one, just update it
2707 $newra->id
= $ra->id
;
2708 $newra->hidden
= $hidden;
2709 $newra->enrol
= $enrol;
2710 /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
2711 /// by repeating queries with the same exact parameters in a 100 secs time window
2712 $newra->timestart
= round($timestart, -2);
2713 $newra->timeend
= $timeend;
2714 $newra->timemodified
= $timemodified;
2715 $newra->modifierid
= empty($USER->id
) ?
0 : $USER->id
;
2717 $success = update_record('role_assignments', $newra);
2720 if ($success) { /// Role was assigned, so do some other things
2722 /// If the user is the current user, then reload the capabilities too.
2723 if (!empty($USER->id
) && $USER->id
== $userid) {
2724 load_all_capabilities();
2727 /// Ask all the modules if anything needs to be done for this user
2728 if ($mods = get_list_of_plugins('mod')) {
2729 foreach ($mods as $mod) {
2730 include_once($CFG->dirroot
.'/mod/'.$mod.'/lib.php');
2731 $functionname = $mod.'_role_assign';
2732 if (function_exists($functionname)) {
2733 $functionname($userid, $context, $roleid);
2739 /// now handle metacourse role assignments if in course context
2740 if ($success and $context->contextlevel
== CONTEXT_COURSE
) {
2741 if ($parents = get_records('course_meta', 'child_course', $context->instanceid
)) {
2742 foreach ($parents as $parent) {
2743 sync_metacourse($parent->parent_course
);
2753 * Deletes one or more role assignments. You must specify at least one parameter.
2758 * @param $enrol unassign only if enrolment type matches, NULL means anything
2759 * @return boolean - success or failure
2761 function role_unassign($roleid=0, $userid=0, $groupid=0, $contextid=0, $enrol=NULL) {
2767 $args = array('roleid', 'userid', 'groupid', 'contextid');
2769 foreach ($args as $arg) {
2771 $select[] = $arg.' = '.$
$arg;
2774 if (!empty($enrol)) {
2775 $select[] = "enrol='$enrol'";
2779 if ($ras = get_records_select('role_assignments', implode(' AND ', $select))) {
2780 $mods = get_list_of_plugins('mod');
2781 foreach($ras as $ra) {
2782 /// infinite loop protection when deleting recursively
2783 if (!$ra = get_record('role_assignments', 'id', $ra->id
)) {
2786 $success = delete_records('role_assignments', 'id', $ra->id
) and $success;
2788 /// If the user is the current user, then reload the capabilities too.
2789 if (!empty($USER->id
) && $USER->id
== $ra->userid
) {
2790 load_all_capabilities();
2792 $context = get_record('context', 'id', $ra->contextid
);
2794 /// Ask all the modules if anything needs to be done for this user
2795 foreach ($mods as $mod) {
2796 include_once($CFG->dirroot
.'/mod/'.$mod.'/lib.php');
2797 $functionname = $mod.'_role_unassign';
2798 if (function_exists($functionname)) {
2799 $functionname($ra->userid
, $context); // watch out, $context might be NULL if something goes wrong
2803 /// now handle metacourse role unassigment and removing from goups if in course context
2804 if (!empty($context) and $context->contextlevel
== CONTEXT_COURSE
) {
2806 // cleanup leftover course groups/subscriptions etc when user has
2807 // no capability to view course
2808 // this may be slow, but this is the proper way of doing it
2809 if (!has_capability('moodle/course:view', $context, $ra->userid
)) {
2810 // remove from groups
2811 if ($groups = groups_get_all_groups($context->instanceid
)) {
2812 foreach ($groups as $group) {
2813 delete_records('groups_members', 'groupid', $group->id
, 'userid', $ra->userid
);
2817 // delete lastaccess records
2818 delete_records('user_lastaccess', 'userid', $ra->userid
, 'courseid', $context->instanceid
);
2821 //unassign roles in metacourses if needed
2822 if ($parents = get_records('course_meta', 'child_course', $context->instanceid
)) {
2823 foreach ($parents as $parent) {
2824 sync_metacourse($parent->parent_course
);
2836 * A convenience function to take care of the common case where you
2837 * just want to enrol someone using the default role into a course
2839 * @param object $course
2840 * @param object $user
2841 * @param string $enrol - the plugin used to do this enrolment
2843 function enrol_into_course($course, $user, $enrol) {
2845 $timestart = time();
2846 // remove time part from the timestamp and keep only the date part
2847 $timestart = make_timestamp(date('Y', $timestart), date('m', $timestart), date('d', $timestart), 0, 0, 0);
2848 if ($course->enrolperiod
) {
2849 $timeend = $timestart +
$course->enrolperiod
;
2854 if ($role = get_default_course_role($course)) {
2856 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
2858 if (!role_assign($role->id
, $user->id
, 0, $context->id
, $timestart, $timeend, 0, $enrol)) {
2862 // force accessdata refresh for users visiting this context...
2863 mark_context_dirty($context->path
);
2865 email_welcome_message_to_user($course, $user);
2867 add_to_log($course->id
, 'course', 'enrol', 'view.php?id='.$course->id
, $user->id
);
2876 * Loads the capability definitions for the component (from file). If no
2877 * capabilities are defined for the component, we simply return an empty array.
2878 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2879 * @return array of capabilities
2881 function load_capability_def($component) {
2884 if ($component == 'moodle') {
2885 $defpath = $CFG->libdir
.'/db/access.php';
2886 $varprefix = 'moodle';
2888 $compparts = explode('/', $component);
2890 if ($compparts[0] == 'block') {
2891 // Blocks are an exception. Blocks directory is 'blocks', and not
2892 // 'block'. So we need to jump through hoops.
2893 $defpath = $CFG->dirroot
.'/'.$compparts[0].
2894 's/'.$compparts[1].'/db/access.php';
2895 $varprefix = $compparts[0].'_'.$compparts[1];
2897 } else if ($compparts[0] == 'format') {
2898 // Similar to the above, course formats are 'format' while they
2899 // are stored in 'course/format'.
2900 $defpath = $CFG->dirroot
.'/course/'.$component.'/db/access.php';
2901 $varprefix = $compparts[0].'_'.$compparts[1];
2903 } else if ($compparts[0] == 'gradeimport') {
2904 $defpath = $CFG->dirroot
.'/grade/import/'.$compparts[1].'/db/access.php';
2905 $varprefix = $compparts[0].'_'.$compparts[1];
2907 } else if ($compparts[0] == 'gradeexport') {
2908 $defpath = $CFG->dirroot
.'/grade/export/'.$compparts[1].'/db/access.php';
2909 $varprefix = $compparts[0].'_'.$compparts[1];
2911 } else if ($compparts[0] == 'gradereport') {
2912 $defpath = $CFG->dirroot
.'/grade/report/'.$compparts[1].'/db/access.php';
2913 $varprefix = $compparts[0].'_'.$compparts[1];
2916 $defpath = $CFG->dirroot
.'/'.$component.'/db/access.php';
2917 $varprefix = str_replace('/', '_', $component);
2920 $capabilities = array();
2922 if (file_exists($defpath)) {
2924 $capabilities = $
{$varprefix.'_capabilities'};
2926 return $capabilities;
2931 * Gets the capabilities that have been cached in the database for this
2933 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2934 * @return array of capabilities
2936 function get_cached_capabilities($component='moodle') {
2937 if ($component == 'moodle') {
2938 $storedcaps = get_records_select('capabilities',
2939 "name LIKE 'moodle/%:%'");
2941 $storedcaps = get_records_select('capabilities',
2942 "name LIKE '$component:%'");
2948 * Returns default capabilities for given legacy role type.
2950 * @param string legacy role name
2953 function get_default_capabilities($legacyrole) {
2954 if (!$allcaps = get_records('capabilities')) {
2955 error('Error: no capabilitites defined!');
2958 $defaults = array();
2959 $components = array();
2960 foreach ($allcaps as $cap) {
2961 if (!in_array($cap->component
, $components)) {
2962 $components[] = $cap->component
;
2963 $alldefs = array_merge($alldefs, load_capability_def($cap->component
));
2966 foreach($alldefs as $name=>$def) {
2967 if (isset($def['legacy'][$legacyrole])) {
2968 $defaults[$name] = $def['legacy'][$legacyrole];
2973 $defaults['moodle/legacy:'.$legacyrole] = CAP_ALLOW
;
2974 if ($legacyrole == 'admin') {
2975 $defaults['moodle/site:doanything'] = CAP_ALLOW
;
2981 * Reset role capabilitites to default according to selected legacy capability.
2982 * If several legacy caps selected, use the first from get_default_capabilities.
2983 * If no legacy selected, removes all capabilities.
2985 * @param int @roleid
2987 function reset_role_capabilities($roleid) {
2988 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
2989 $legacyroles = get_legacy_roles();
2991 $defaultcaps = array();
2992 foreach($legacyroles as $ltype=>$lcap) {
2993 $localoverride = get_local_override($roleid, $sitecontext->id
, $lcap);
2994 if (!empty($localoverride->permission
) and $localoverride->permission
== CAP_ALLOW
) {
2995 //choose first selected legacy capability
2996 $defaultcaps = get_default_capabilities($ltype);
3001 delete_records('role_capabilities', 'roleid', $roleid);
3002 if (!empty($defaultcaps)) {
3003 foreach($defaultcaps as $cap=>$permission) {
3004 assign_capability($cap, $permission, $roleid, $sitecontext->id
);
3010 * Updates the capabilities table with the component capability definitions.
3011 * If no parameters are given, the function updates the core moodle
3014 * Note that the absence of the db/access.php capabilities definition file
3015 * will cause any stored capabilities for the component to be removed from
3018 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
3021 function update_capabilities($component='moodle') {
3023 $storedcaps = array();
3025 $filecaps = load_capability_def($component);
3026 $cachedcaps = get_cached_capabilities($component);
3028 foreach ($cachedcaps as $cachedcap) {
3029 array_push($storedcaps, $cachedcap->name
);
3030 // update risk bitmasks and context levels in existing capabilities if needed
3031 if (array_key_exists($cachedcap->name
, $filecaps)) {
3032 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name
])) {
3033 $filecaps[$cachedcap->name
]['riskbitmask'] = 0; // no risk if not specified
3035 if ($cachedcap->riskbitmask
!= $filecaps[$cachedcap->name
]['riskbitmask']) {
3036 $updatecap = new object();
3037 $updatecap->id
= $cachedcap->id
;
3038 $updatecap->riskbitmask
= $filecaps[$cachedcap->name
]['riskbitmask'];
3039 if (!update_record('capabilities', $updatecap)) {
3044 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name
])) {
3045 $filecaps[$cachedcap->name
]['contextlevel'] = 0; // no context level defined
3047 if ($cachedcap->contextlevel
!= $filecaps[$cachedcap->name
]['contextlevel']) {
3048 $updatecap = new object();
3049 $updatecap->id
= $cachedcap->id
;
3050 $updatecap->contextlevel
= $filecaps[$cachedcap->name
]['contextlevel'];
3051 if (!update_record('capabilities', $updatecap)) {
3059 // Are there new capabilities in the file definition?
3062 foreach ($filecaps as $filecap => $def) {
3064 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
3065 if (!array_key_exists('riskbitmask', $def)) {
3066 $def['riskbitmask'] = 0; // no risk if not specified
3068 $newcaps[$filecap] = $def;
3071 // Add new capabilities to the stored definition.
3072 foreach ($newcaps as $capname => $capdef) {
3073 $capability = new object;
3074 $capability->name
= $capname;
3075 $capability->captype
= $capdef['captype'];
3076 $capability->contextlevel
= $capdef['contextlevel'];
3077 $capability->component
= $component;
3078 $capability->riskbitmask
= $capdef['riskbitmask'];
3080 if (!insert_record('capabilities', $capability, false, 'id')) {
3085 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $storedcaps)){
3086 if ($rolecapabilities = get_records('role_capabilities', 'capability', $capdef['clonepermissionsfrom'])){
3087 foreach ($rolecapabilities as $rolecapability){
3088 //assign_capability will update rather than insert if capability exists
3089 if (!assign_capability($capname, $rolecapability->permission
,
3090 $rolecapability->roleid
, $rolecapability->contextid
, true)){
3091 notify('Could not clone capabilities for '.$capname);
3095 // Do we need to assign the new capabilities to roles that have the
3096 // legacy capabilities moodle/legacy:* as well?
3097 // we ignore legacy key if we have cloned permissions
3098 } else if (isset($capdef['legacy']) && is_array($capdef['legacy']) &&
3099 !assign_legacy_capabilities($capname, $capdef['legacy'])) {
3100 notify('Could not assign legacy capabilities for '.$capname);
3103 // Are there any capabilities that have been removed from the file
3104 // definition that we need to delete from the stored capabilities and
3105 // role assignments?
3106 capabilities_cleanup($component, $filecaps);
3113 * Deletes cached capabilities that are no longer needed by the component.
3114 * Also unassigns these capabilities from any roles that have them.
3115 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
3116 * @param $newcapdef - array of the new capability definitions that will be
3117 * compared with the cached capabilities
3118 * @return int - number of deprecated capabilities that have been removed
3120 function capabilities_cleanup($component, $newcapdef=NULL) {
3124 if ($cachedcaps = get_cached_capabilities($component)) {
3125 foreach ($cachedcaps as $cachedcap) {
3126 if (empty($newcapdef) ||
3127 array_key_exists($cachedcap->name
, $newcapdef) === false) {
3129 // Remove from capabilities cache.
3130 if (!delete_records('capabilities', 'name', $cachedcap->name
)) {
3131 error('Could not delete deprecated capability '.$cachedcap->name
);
3135 // Delete from roles.
3136 if($roles = get_roles_with_capability($cachedcap->name
)) {
3137 foreach($roles as $role) {
3138 if (!unassign_capability($cachedcap->name
, $role->id
)) {
3139 error('Could not unassign deprecated capability '.
3140 $cachedcap->name
.' from role '.$role->name
);
3147 return $removedcount;
3158 * prints human readable context identifier.
3160 function print_context_name($context, $withprefix = true, $short = false) {
3163 switch ($context->contextlevel
) {
3165 case CONTEXT_SYSTEM
: // by now it's a definite an inherit
3166 $name = get_string('coresystem');
3169 case CONTEXT_PERSONAL
:
3170 $name = get_string('personal');
3174 if ($user = get_record('user', 'id', $context->instanceid
)) {
3176 $name = get_string('user').': ';
3178 $name .= fullname($user);
3182 case CONTEXT_COURSECAT
: // Coursecat -> coursecat or site
3183 if ($category = get_record('course_categories', 'id', $context->instanceid
)) {
3185 $name = get_string('category').': ';
3187 $name .=format_string($category->name
);
3191 case CONTEXT_COURSE
: // 1 to 1 to course cat
3192 if ($course = get_record('course', 'id', $context->instanceid
)) {
3194 if ($context->instanceid
== SITEID
) {
3195 $name = get_string('site').': ';
3197 $name = get_string('course').': ';
3201 $name .=format_string($course->shortname
);
3203 $name .=format_string($course->fullname
);
3209 case CONTEXT_GROUP
: // 1 to 1 to course
3210 if ($name = groups_get_group_name($context->instanceid
)) {
3212 $name = get_string('group').': '. $name;
3217 case CONTEXT_MODULE
: // 1 to 1 to course
3218 if ($cm = get_record('course_modules','id',$context->instanceid
)) {
3219 if ($module = get_record('modules','id',$cm->module
)) {
3220 if ($mod = get_record($module->name
, 'id', $cm->instance
)) {
3222 $name = get_string('activitymodule').': ';
3224 $name .= $mod->name
;
3230 case CONTEXT_BLOCK
: // not necessarily 1 to 1 to course
3231 if ($blockinstance = get_record('block_instance','id',$context->instanceid
)) {
3232 if ($block = get_record('block','id',$blockinstance->blockid
)) {
3234 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
3235 require_once("$CFG->dirroot/blocks/$block->name/block_$block->name.php");
3236 $blockname = "block_$block->name";
3237 if ($blockobject = new $blockname()) {
3239 $name = get_string('block').': ';
3241 $name .= $blockobject->title
;
3248 error ('This is an unknown context (' . $context->contextlevel
. ') in print_context_name!');
3257 * Extracts the relevant capabilities given a contextid.
3258 * All case based, example an instance of forum context.
3259 * Will fetch all forum related capabilities, while course contexts
3260 * Will fetch all capabilities
3261 * @param object context
3265 * `name` varchar(150) NOT NULL,
3266 * `captype` varchar(50) NOT NULL,
3267 * `contextlevel` int(10) NOT NULL,
3268 * `component` varchar(100) NOT NULL,
3270 function fetch_context_capabilities($context) {
3274 $sort = 'ORDER BY contextlevel,component,id'; // To group them sensibly for display
3276 switch ($context->contextlevel
) {
3278 case CONTEXT_SYSTEM
: // all
3279 $SQL = "select * from {$CFG->prefix}capabilities";
3282 case CONTEXT_PERSONAL
:
3283 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_PERSONAL
;
3288 FROM {$CFG->prefix}capabilities
3289 WHERE contextlevel = ".CONTEXT_USER
;
3292 case CONTEXT_COURSECAT
: // all
3293 $SQL = "select * from {$CFG->prefix}capabilities";
3296 case CONTEXT_COURSE
: // all
3297 $SQL = "select * from {$CFG->prefix}capabilities";
3300 case CONTEXT_GROUP
: // group caps
3303 case CONTEXT_MODULE
: // mod caps
3304 $cm = get_record('course_modules', 'id', $context->instanceid
);
3305 $module = get_record('modules', 'id', $cm->module
);
3307 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_MODULE
."
3308 and component = 'mod/$module->name'";
3311 case CONTEXT_BLOCK
: // block caps
3312 $cb = get_record('block_instance', 'id', $context->instanceid
);
3313 $block = get_record('block', 'id', $cb->blockid
);
3315 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_BLOCK
."
3316 and ( component = 'block/$block->name' or component = 'moodle')";
3323 if (!$records = get_records_sql($SQL.' '.$sort)) {
3327 /// the rest of code is a bit hacky, think twice before modifying it :-(
3329 // special sorting of core system capabiltites and enrollments
3330 if (in_array($context->contextlevel
, array(CONTEXT_SYSTEM
, CONTEXT_COURSECAT
, CONTEXT_COURSE
))) {
3332 foreach ($records as $key=>$record) {
3333 if (preg_match('|^moodle/|', $record->name
) and $record->contextlevel
== CONTEXT_SYSTEM
) {
3334 $first[$key] = $record;
3335 unset($records[$key]);
3336 } else if (count($first)){
3340 if (count($first)) {
3341 $records = $first +
$records; // merge the two arrays keeping the keys
3344 $contextindependentcaps = fetch_context_independent_capabilities();
3345 $records = array_merge($contextindependentcaps, $records);
3354 * Gets the context-independent capabilities that should be overrridable in
3356 * @return array of capability records from the capabilities table.
3358 function fetch_context_independent_capabilities() {
3360 //only CONTEXT_SYSTEM capabilities here or it will break the hack in fetch_context_capabilities()
3361 $contextindependentcaps = array(
3362 'moodle/site:accessallgroups'
3367 foreach ($contextindependentcaps as $capname) {
3368 $record = get_record('capabilities', 'name', $capname);
3369 array_push($records, $record);
3376 * This function pulls out all the resolved capabilities (overrides and
3377 * defaults) of a role used in capability overrides in contexts at a given
3379 * @param obj $context
3380 * @param int $roleid
3381 * @param bool self - if set to true, resolve till this level, else stop at immediate parent level
3384 function role_context_capabilities($roleid, $context, $cap='') {
3387 $contexts = get_parent_contexts($context);
3388 $contexts[] = $context->id
;
3389 $contexts = '('.implode(',', $contexts).')';
3392 $search = " AND rc.capability = '$cap' ";
3398 FROM {$CFG->prefix}role_capabilities rc,
3399 {$CFG->prefix}context c
3400 WHERE rc.contextid in $contexts
3401 AND rc.roleid = $roleid
3402 AND rc.contextid = c.id $search
3403 ORDER BY c.contextlevel DESC,
3404 rc.capability DESC";
3406 $capabilities = array();
3408 if ($records = get_records_sql($SQL)) {
3409 // We are traversing via reverse order.
3410 foreach ($records as $record) {
3411 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
3412 if (!isset($capabilities[$record->capability
]) ||
$record->permission
<-500) {
3413 $capabilities[$record->capability
] = $record->permission
;
3417 return $capabilities;
3421 * Recursive function which, given a context, find all parent context ids,
3422 * and return the array in reverse order, i.e. parent first, then grand
3425 * @param object $context
3428 function get_parent_contexts($context) {
3430 if ($context->path
== '') {
3434 $parentcontexts = substr($context->path
, 1); // kill leading slash
3435 $parentcontexts = explode('/', $parentcontexts);
3436 array_pop($parentcontexts); // and remove its own id
3438 return array_reverse($parentcontexts);
3443 * Recursive function which, given a context, find all its children context ids.
3445 * When called for a course context, it will return the modules and blocks
3446 * displayed in the course page.
3448 * For course category contexts it will return categories and courses. It will
3449 * NOT recurse into courses - if you want to do that, call it on the returned
3452 * If called on a course context it _will_ populate the cache with the appropriate
3455 * @param object $context.
3456 * @return array of child records
3458 function get_child_contexts($context) {
3460 global $CFG, $context_cache;
3462 // We *MUST* populate the context_cache as the callers
3463 // will probably ask for the full record anyway soon after
3464 // soon after calling us ;-)
3466 switch ($context->contextlevel
) {
3473 case CONTEXT_MODULE
:
3483 case CONTEXT_COURSE
:
3485 // - module instances - easy
3487 // - blocks assigned to the course-view page explicitly - easy
3488 // - blocks pinned (note! we get all of them here, regardless of vis)
3489 $sql = " SELECT ctx.*
3490 FROM {$CFG->prefix}context ctx
3491 WHERE ctx.path LIKE '{$context->path}/%'
3492 AND ctx.contextlevel IN (".CONTEXT_MODULE
.",".CONTEXT_BLOCK
.")
3495 FROM {$CFG->prefix}context ctx
3496 JOIN {$CFG->prefix}groups g
3497 ON (ctx.instanceid=g.id AND ctx.contextlevel=".CONTEXT_GROUP
.")
3498 WHERE g.courseid={$context->instanceid}
3501 FROM {$CFG->prefix}context ctx
3502 JOIN {$CFG->prefix}block_pinned b
3503 ON (ctx.instanceid=b.blockid AND ctx.contextlevel=".CONTEXT_BLOCK
.")
3504 WHERE b.pagetype='course-view'
3506 $rs = get_recordset_sql($sql);
3508 if ($rs->RecordCount()) {
3509 while ($rec = rs_fetch_next_record($rs)) {
3510 $records[$rec->id
] = $rec;
3511 $context_cache[$rec->contextlevel
][$rec->instanceid
] = $rec;
3518 case CONTEXT_COURSECAT
:
3522 $sql = " SELECT ctx.*
3523 FROM {$CFG->prefix}context ctx
3524 WHERE ctx.path LIKE '{$context->path}/%'
3525 AND ctx.contextlevel IN (".CONTEXT_COURSECAT
.",".CONTEXT_COURSE
.")
3527 $rs = get_recordset_sql($sql);
3529 if ($rs->RecordCount()) {
3530 while ($rec = rs_fetch_next_record($rs)) {
3531 $records[$rec->id
] = $rec;
3532 $context_cache[$rec->contextlevel
][$rec->instanceid
] = $rec;
3544 case CONTEXT_PERSONAL
:
3549 case CONTEXT_SYSTEM
:
3550 // Just get all the contexts except for CONTEXT_SYSTEM level
3551 // and hope we don't OOM in the process - don't cache
3552 $sql = 'SELECT c.*'.
3553 'FROM '.$CFG->prefix
.'context AS c '.
3554 'WHERE contextlevel != '.CONTEXT_SYSTEM
;
3556 return get_records_sql($sql);
3560 error('This is an unknown context (' . $context->contextlevel
. ') in get_child_contexts!');
3567 * Gets a string for sql calls, searching for stuff in this context or above
3568 * @param object $context
3571 function get_related_contexts_string($context) {
3572 if ($parents = get_parent_contexts($context)) {
3573 return (' IN ('.$context->id
.','.implode(',', $parents).')');
3575 return (' ='.$context->id
);
3580 * Returns the human-readable, translated version of the capability.
3581 * Basically a big switch statement.
3582 * @param $capabilityname - e.g. mod/choice:readresponses
3584 function get_capability_string($capabilityname) {
3586 // Typical capabilityname is mod/choice:readresponses
3588 $names = split('/', $capabilityname);
3589 $stringname = $names[1]; // choice:readresponses
3590 $components = split(':', $stringname);
3591 $componentname = $components[0]; // choice
3593 switch ($names[0]) {
3595 $string = get_string($stringname, $componentname);
3599 $string = get_string($stringname, 'block_'.$componentname);
3603 $string = get_string($stringname, 'role');
3607 $string = get_string($stringname, 'enrol_'.$componentname);
3611 $string = get_string($stringname, 'format_'.$componentname);
3615 $string = get_string($stringname, 'gradeexport_'.$componentname);
3619 $string = get_string($stringname, 'gradeimport_'.$componentname);
3623 $string = get_string($stringname, 'gradereport_'.$componentname);
3627 $string = get_string($stringname);
3636 * This gets the mod/block/course/core etc strings.
3638 * @param $contextlevel
3640 function get_component_string($component, $contextlevel) {
3642 switch ($contextlevel) {
3644 case CONTEXT_SYSTEM
:
3645 if (preg_match('|^enrol/|', $component)) {
3646 $langname = str_replace('/', '_', $component);
3647 $string = get_string('enrolname', $langname);
3648 } else if (preg_match('|^block/|', $component)) {
3649 $langname = str_replace('/', '_', $component);
3650 $string = get_string('blockname', $langname);
3652 $string = get_string('coresystem');
3656 case CONTEXT_PERSONAL
:
3657 $string = get_string('personal');
3661 $string = get_string('users');
3664 case CONTEXT_COURSECAT
:
3665 $string = get_string('categories');
3668 case CONTEXT_COURSE
:
3669 if (preg_match('|^gradeimport/|', $component)
3670 ||
preg_match('|^gradeexport/|', $component)
3671 ||
preg_match('|^gradereport/|', $component)) {
3672 $string = get_string('gradebook', 'admin');
3674 $string = get_string('course');
3679 $string = get_string('group');
3682 case CONTEXT_MODULE
:
3683 $string = get_string('modulename', basename($component));
3687 if( $component == 'moodle' ){
3688 $string = get_string('block');
3690 $string = get_string('blockname', 'block_'.basename($component));
3695 error ('This is an unknown context $contextlevel (' . $contextlevel . ') in get_component_string!');
3703 * Gets the list of roles assigned to this context and up (parents)
3704 * @param object $context
3705 * @param view - set to true when roles are pulled for display only
3706 * this is so that we can filter roles with no visible
3707 * assignment, for example, you might want to "hide" all
3708 * course creators when browsing the course participants
3712 function get_roles_used_in_context($context, $view = false) {
3716 // filter for roles with all hidden assignments
3717 // no need to return when only pulling roles for reviewing
3718 // e.g. participants page.
3719 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))?
' AND ra.hidden = 0 ':'';
3720 $contextlist = get_related_contexts_string($context);
3722 $sql = "SELECT DISTINCT r.id,
3726 FROM {$CFG->prefix}role_assignments ra,
3727 {$CFG->prefix}role r
3728 WHERE r.id = ra.roleid
3729 AND ra.contextid $contextlist
3731 ORDER BY r.sortorder ASC";
3733 return get_records_sql($sql);
3736 /** this function is used to print roles column in user profile page.
3738 * @param int contextid
3741 function get_user_roles_in_context($userid, $contextid){
3745 $SQL = 'select * from '.$CFG->prefix
.'role_assignments ra, '.$CFG->prefix
.'role r where ra.userid='.$userid.' and ra.contextid='.$contextid.' and ra.roleid = r.id';
3746 if ($roles = get_records_sql($SQL)) {
3747 foreach ($roles as $userrole) {
3748 $rolestring .= '<a href="'.$CFG->wwwroot
.'/user/index.php?contextid='.$userrole->contextid
.'&roleid='.$userrole->roleid
.'">'.$userrole->name
.'</a>, ';
3752 return rtrim($rolestring, ', ');
3757 * Checks if a user can override capabilities of a particular role in this context
3758 * @param object $context
3759 * @param int targetroleid - the id of the role you want to override
3762 function user_can_override($context, $targetroleid) {
3763 // first check if user has override capability
3764 // if not return false;
3765 if (!has_capability('moodle/role:override', $context)) {
3768 // pull out all active roles of this user from this context(or above)
3769 if ($userroles = get_user_roles($context)) {
3770 foreach ($userroles as $userrole) {
3771 // if any in the role_allow_override table, then it's ok
3772 if (get_record('role_allow_override', 'roleid', $userrole->roleid
, 'allowoverride', $targetroleid)) {
3783 * Checks if a user can assign users to a particular role in this context
3784 * @param object $context
3785 * @param int targetroleid - the id of the role you want to assign users to
3788 function user_can_assign($context, $targetroleid) {
3790 // first check if user has override capability
3791 // if not return false;
3792 if (!has_capability('moodle/role:assign', $context)) {
3795 // pull out all active roles of this user from this context(or above)
3796 if ($userroles = get_user_roles($context)) {
3797 foreach ($userroles as $userrole) {
3798 // if any in the role_allow_override table, then it's ok
3799 if (get_record('role_allow_assign', 'roleid', $userrole->roleid
, 'allowassign', $targetroleid)) {
3808 /** Returns all site roles in correct sort order.
3811 function get_all_roles() {
3812 return get_records('role', '', '', 'sortorder ASC');
3816 * gets all the user roles assigned in this context, or higher contexts
3817 * this is mainly used when checking if a user can assign a role, or overriding a role
3818 * i.e. we need to know what this user holds, in order to verify against allow_assign and
3819 * allow_override tables
3820 * @param object $context
3821 * @param int $userid
3822 * @param view - set to true when roles are pulled for display only
3823 * this is so that we can filter roles with no visible
3824 * assignment, for example, you might want to "hide" all
3825 * course creators when browsing the course participants
3829 function get_user_roles($context, $userid=0, $checkparentcontexts=true, $order='c.contextlevel DESC, r.sortorder ASC', $view=false) {
3831 global $USER, $CFG, $db;
3833 if (empty($userid)) {
3834 if (empty($USER->id
)) {
3837 $userid = $USER->id
;
3839 // set up hidden sql
3840 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))?
' AND ra.hidden = 0 ':'';
3842 if ($checkparentcontexts && ($parents = get_parent_contexts($context))) {
3843 $contexts = ' ra.contextid IN ('.implode(',' , $parents).','.$context->id
.')';
3845 $contexts = ' ra.contextid = \''.$context->id
.'\'';
3848 return get_records_sql('SELECT ra.*, r.name, r.shortname
3849 FROM '.$CFG->prefix
.'role_assignments ra,
3850 '.$CFG->prefix
.'role r,
3851 '.$CFG->prefix
.'context c
3852 WHERE ra.userid = '.$userid.
3853 ' AND ra.roleid = r.id
3854 AND ra.contextid = c.id
3855 AND '.$contexts . $hiddensql .
3856 ' ORDER BY '.$order);
3860 * Creates a record in the allow_override table
3861 * @param int sroleid - source roleid
3862 * @param int troleid - target roleid
3863 * @return int - id or false
3865 function allow_override($sroleid, $troleid) {
3866 $record = new object();
3867 $record->roleid
= $sroleid;
3868 $record->allowoverride
= $troleid;
3869 return insert_record('role_allow_override', $record);
3873 * Creates a record in the allow_assign table
3874 * @param int sroleid - source roleid
3875 * @param int troleid - target roleid
3876 * @return int - id or false
3878 function allow_assign($sroleid, $troleid) {
3879 $record = new object;
3880 $record->roleid
= $sroleid;
3881 $record->allowassign
= $troleid;
3882 return insert_record('role_allow_assign', $record);
3886 * Gets a list of roles that this user can assign in this context
3887 * @param object $context
3888 * @param string $field
3891 function get_assignable_roles ($context, $field="name") {
3896 $ras = get_user_roles($context);
3898 foreach ($ras as $ra) {
3899 $roleids[] = $ra->roleid
;
3903 if (count($roleids)===0) {
3907 $roleids = implode(',',$roleids);
3909 // The subselect scopes the DISTINCT down to
3910 // the role ids - a DISTINCT over the whole of
3911 // the role table is much more expensive on some DBs
3912 $sql = "SELECT r.id, r.$field
3913 FROM {$CFG->prefix}role r
3914 JOIN ( SELECT DISTINCT allowassign as allowedrole
3915 FROM {$CFG->prefix}role_allow_assign raa
3916 WHERE raa.roleid IN ($roleids) ) ar
3917 ON r.id=ar.allowedrole
3918 ORDER BY sortorder ASC";
3920 $rs = get_recordset_sql($sql);
3922 if ($rs->RecordCount()) {
3923 while ($r = rs_fetch_next_record($rs)) {
3924 $roles[$r->id
] = $r->{$field};
3931 * Gets a list of roles that this user can override in this context
3932 * @param object $context
3935 function get_overridable_roles($context) {
3939 if ($roles = get_all_roles()) {
3940 foreach ($roles as $role) {
3941 if (user_can_override($context, $role->id
)) {
3942 $options[$role->id
] = strip_tags(format_string($role->name
, true));
3951 * Returns a role object that is the default role for new enrolments
3954 * @param object $course
3955 * @return object $role
3957 function get_default_course_role($course) {
3960 /// First let's take the default role the course may have
3961 if (!empty($course->defaultrole
)) {
3962 if ($role = get_record('role', 'id', $course->defaultrole
)) {
3967 /// Otherwise the site setting should tell us
3968 if ($CFG->defaultcourseroleid
) {
3969 if ($role = get_record('role', 'id', $CFG->defaultcourseroleid
)) {
3974 /// It's unlikely we'll get here, but just in case, try and find a student role
3975 if ($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW
)) {
3976 return array_shift($studentroles); /// Take the first one
3984 * who has this capability in this context
3985 * does not handling user level resolving!!!
3986 * (!)pleaes note if $fields is empty this function attempts to get u.*
3987 * which can get rather large.
3988 * i.e 1 person has 2 roles 1 allow, 1 prevent, this will not work properly
3989 * @param $context - object
3990 * @param $capability - string capability
3991 * @param $fields - fields to be pulled
3992 * @param $sort - the sort order
3993 * @param $limitfrom - number of records to skip (offset)
3994 * @param $limitnum - number of records to fetch
3995 * @param $groups - single group or array of groups - only return
3996 * users who are in one of these group(s).
3997 * @param $exceptions - list of users to exclude
3998 * @param view - set to true when roles are pulled for display only
3999 * this is so that we can filter roles with no visible
4000 * assignment, for example, you might want to "hide" all
4001 * course creators when browsing the course participants
4003 * @param boolean $useviewallgroups if $groups is set the return users who
4004 * have capability both $capability and moodle/site:accessallgroups
4005 * in this context, as well as users who have $capability and who are
4008 function get_users_by_capability($context, $capability, $fields='', $sort='',
4009 $limitfrom='', $limitnum='', $groups='', $exceptions='', $doanything=true,
4010 $view=false, $useviewallgroups=false) {
4013 /// check for front page course, and see if default front page role has the required capability
4015 $frontpagectx = get_context_instance(CONTEXT_COURSE
, SITEID
);
4016 if ($CFG->defaultfrontpageroleid
&& ($context->id
== $frontpagectx->id ||
strstr($context->path
, '/'.$frontpagectx->id
.'/'))) {
4017 $roles = get_roles_with_capability($capability, CAP_ALLOW
, $context);
4018 if (in_array($CFG->defaultfrontpageroleid
, array_keys($roles))) {
4019 return get_records_sql("SELECT $fields FROM {$CFG->prefix}user ORDER BY $sort, $limitfrom, $limitnum");
4023 /// Sorting out groups
4025 if (is_array($groups)) {
4026 $grouptest = 'gm.groupid IN (' . implode(',', $groups) . ')';
4028 $grouptest = 'gm.groupid = ' . $groups;
4030 $grouptest = 'ra.userid IN (SELECT userid FROM ' .
4031 $CFG->prefix
. 'groups_members gm WHERE ' . $grouptest . ')';
4033 if ($useviewallgroups) {
4034 $viewallgroupsusers = get_users_by_capability($context,
4035 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
4036 $groupsql = ' AND (' . $grouptest . ' OR ra.userid IN (' .
4037 implode(',', array_keys($viewallgroupsusers)) . '))';
4039 $groupsql = ' AND ' . $grouptest;
4045 /// Sorting out exceptions
4046 $exceptionsql = $exceptions ?
"AND u.id NOT IN ($exceptions)" : '';
4048 /// Set up default fields
4049 if (empty($fields)) {
4050 $fields = 'u.*, ul.timeaccess as lastaccess, ra.hidden';
4053 /// Set up default sort
4055 $sort = 'ul.timeaccess';
4058 $sortby = $sort ?
" ORDER BY $sort " : '';
4059 /// Set up hidden sql
4060 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))?
' AND ra.hidden = 0 ':'';
4062 /// If context is a course, then construct sql for ul
4063 if ($context->contextlevel
== CONTEXT_COURSE
) {
4064 $courseid = $context->instanceid
;
4065 $coursesql1 = "AND ul.courseid = $courseid";
4070 /// Sorting out roles with this capability set
4071 if ($possibleroles = get_roles_with_capability($capability, CAP_ALLOW
, $context)) {
4073 if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM
)) {
4074 return false; // Something is seriously wrong
4076 $doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW
, $sitecontext);
4079 $validroleids = array();
4080 foreach ($possibleroles as $possiblerole) {
4082 if (isset($doanythingroles[$possiblerole->id
])) { // We don't want these included
4086 if ($caps = role_context_capabilities($possiblerole->id
, $context, $capability)) { // resolved list
4087 if (isset($caps[$capability]) && $caps[$capability] > 0) { // resolved capability > 0
4088 $validroleids[] = $possiblerole->id
;
4092 if (empty($validroleids)) {
4095 $roleids = '('.implode(',', $validroleids).')';
4097 return false; // No need to continue, since no roles have this capability set
4100 /// Construct the main SQL
4101 $select = " SELECT $fields";
4102 $from = " FROM {$CFG->prefix}user u
4103 INNER JOIN {$CFG->prefix}role_assignments ra ON ra.userid = u.id
4104 INNER JOIN {$CFG->prefix}role r ON r.id = ra.roleid
4105 LEFT OUTER JOIN {$CFG->prefix}user_lastaccess ul ON (ul.userid = u.id $coursesql1)";
4106 $where = " WHERE ra.contextid ".get_related_contexts_string($context)."
4108 AND ra.roleid in $roleids
4113 return get_records_sql($select.$from.$where.$sortby, $limitfrom, $limitnum);
4117 * gets all the users assigned this role in this context or higher
4118 * @param int roleid (can also be an array of ints!)
4119 * @param int contextid
4120 * @param bool parent if true, get list of users assigned in higher context too
4121 * @param string fields - fields from user (u.) , role assignment (ra) or role (r.)
4122 * @param string sort - sort from user (u.) , role assignment (ra) or role (r.)
4123 * @param bool gethidden - whether to fetch hidden enrolments too
4126 function get_role_users($roleid, $context, $parent=false, $fields='', $sort='u.lastname ASC', $gethidden=true, $group='') {
4129 if (empty($fields)) {
4130 $fields = 'u.id, u.confirmed, u.username, u.firstname, u.lastname, '.
4131 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.city, '.
4132 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
4133 'u.emailstop, u.lang, u.timezone, r.name as rolename';
4136 // whether this assignment is hidden
4137 $hiddensql = $gethidden ?
'': ' AND ra.hidden = 0 ';
4139 $parentcontexts = '';
4141 $parentcontexts = substr($context->path
, 1); // kill leading slash
4142 $parentcontexts = str_replace('/', ',', $parentcontexts);
4143 if ($parentcontexts !== '') {
4144 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
4148 if (is_array($roleid)) {
4149 $roleselect = ' AND ra.roleid IN (' . implode(',',$roleid) .')';
4150 } elseif (is_int($roleid)) {
4151 $roleselect = "AND ra.roleid = $roleid";
4157 $groupjoin = "JOIN {$CFG->prefix}groups_members gm
4158 ON gm.userid = u.id";
4159 $groupselect = " AND gm.groupid = $group ";
4165 $SQL = "SELECT $fields, ra.roleid
4166 FROM {$CFG->prefix}role_assignments ra
4167 JOIN {$CFG->prefix}user u
4169 JOIN {$CFG->prefix}role r
4172 WHERE (ra.contextid = $context->id $parentcontexts)
4177 "; // join now so that we can just use fullname() later
4178 return get_records_sql($SQL);
4182 * Counts all the users assigned this role in this context or higher
4184 * @param int contextid
4185 * @param bool parent if true, get list of users assigned in higher context too
4188 function count_role_users($roleid, $context, $parent=false) {
4192 if ($contexts = get_parent_contexts($context)) {
4193 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
4195 $parentcontexts = '';
4198 $parentcontexts = '';
4201 $SQL = "SELECT count(*)
4202 FROM {$CFG->prefix}role_assignments r
4203 WHERE (r.contextid = $context->id $parentcontexts)
4204 AND r.roleid = $roleid";
4206 return count_records_sql($SQL);
4210 * This function gets the list of courses that this user has a particular capability in.
4211 * It is still not very efficient.
4212 * @param string $capability Capability in question
4213 * @param int $userid User ID or null for current user
4214 * @param bool $doanything True if 'doanything' is permitted (default)
4215 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
4216 * otherwise use a comma-separated list of the fields you require, not including id
4217 * @param string $orderby If set, use a comma-separated list of fields from course
4218 * table with sql modifiers (DESC) if needed
4219 * @return array Array of courses, may have zero entries. Or false if query failed.
4221 function get_user_capability_course($capability, $userid=NULL,$doanything=true,$fieldsexceptid='',$orderby='') {
4222 // Convert fields list and ordering
4224 if($fieldsexceptid) {
4225 $fields=explode(',',$fieldsexceptid);
4226 foreach($fields as $field) {
4227 $fieldlist.=',c.'.$field;
4231 $fields=explode(',',$orderby);
4233 foreach($fields as $field) {
4237 $orderby.='c.'.$field;
4239 $orderby='ORDER BY '.$orderby;
4242 // Obtain a list of everything relevant about all courses including context.
4243 // Note the result can be used directly as a context (we are going to), the course
4244 // fields are just appended.
4246 $rs=get_recordset_sql("
4248 x.*,c.id AS courseid$fieldlist
4250 {$CFG->prefix}course c
4251 INNER JOIN {$CFG->prefix}context x ON c.id=x.instanceid AND x.contextlevel=".CONTEXT_COURSE
."
4258 // Check capability for each course in turn
4260 while($coursecontext=rs_fetch_next_record($rs)) {
4261 if(has_capability($capability,$coursecontext,$userid,$doanything)) {
4262 // We've got the capability. Make the record look like a course record
4264 $coursecontext->id
=$coursecontext->courseid
;
4265 unset($coursecontext->courseid
);
4266 unset($coursecontext->contextlevel
);
4267 unset($coursecontext->instanceid
);
4268 $courses[]=$coursecontext;
4274 /** This function finds the roles assigned directly to this context only
4275 * i.e. no parents role
4276 * @param object $context
4279 function get_roles_on_exact_context($context) {
4283 return get_records_sql("SELECT r.*
4284 FROM {$CFG->prefix}role_assignments ra,
4285 {$CFG->prefix}role r
4286 WHERE ra.roleid = r.id
4287 AND ra.contextid = $context->id");
4292 * Switches the current user to another role for the current session and only
4293 * in the given context.
4295 * The caller *must* check
4296 * - that this op is allowed
4297 * - that the requested role can be assigned in this ctx
4298 * (hint, use get_assignable_roles())
4299 * - that the requested role is NOT $CFG->defaultuserroleid
4301 * To "unswitch" pass 0 as the roleid.
4303 * This function *will* modify $USER->access - beware
4305 * @param integer $roleid
4306 * @param object $context
4309 function role_switch($roleid, $context) {
4315 // - Add the ghost RA to $USER->access
4316 // as $USER->access['rsw'][$path] = $roleid
4318 // - Make sure $USER->access['rdef'] has the roledefs
4319 // it needs to honour the switcheroo
4321 // Roledefs will get loaded "deep" here - down to the last child
4322 // context. Note that
4324 // - When visiting subcontexts, our selective accessdata loading
4325 // will still work fine - though those ra/rdefs will be ignored
4326 // appropriately while the switch is in place
4328 // - If a switcheroo happens at a category with tons of courses
4329 // (that have many overrides for switched-to role), the session
4330 // will get... quite large. Sometimes you just can't win.
4332 // To un-switch just unset($USER->access['rsw'][$path])
4335 // Add the switch RA
4336 if (!isset($USER->access
['rsw'])) {
4337 $USER->access
['rsw'] = array();
4341 unset($USER->access
['rsw'][$context->path
]);
4342 if (empty($USER->access
['rsw'])) {
4343 unset($USER->access
['rsw']);
4348 $USER->access
['rsw'][$context->path
]=$roleid;
4351 $USER->access
= get_role_access_bycontext($roleid, $context,
4354 /* DO WE NEED THIS AT ALL???
4355 // Add some permissions we are really going
4356 // to always need, even if the role doesn't have them!
4358 $USER->capabilities[$context->id]['moodle/course:view'] = CAP_ALLOW;
4365 // get any role that has an override on exact context
4366 function get_roles_with_override_on_context($context) {
4370 return get_records_sql("SELECT r.*
4371 FROM {$CFG->prefix}role_capabilities rc,
4372 {$CFG->prefix}role r
4373 WHERE rc.roleid = r.id
4374 AND rc.contextid = $context->id");
4377 // get all capabilities for this role on this context (overrids)
4378 function get_capabilities_from_role_on_context($role, $context) {
4382 return get_records_sql("SELECT *
4383 FROM {$CFG->prefix}role_capabilities
4384 WHERE contextid = $context->id
4385 AND roleid = $role->id");
4388 // find out which roles has assignment on this context
4389 function get_roles_with_assignment_on_context($context) {
4393 return get_records_sql("SELECT r.*
4394 FROM {$CFG->prefix}role_assignments ra,
4395 {$CFG->prefix}role r
4396 WHERE ra.roleid = r.id
4397 AND ra.contextid = $context->id");
4403 * Find all user assignemnt of users for this role, on this context
4405 function get_users_from_role_on_context($role, $context) {
4409 return get_records_sql("SELECT *
4410 FROM {$CFG->prefix}role_assignments
4411 WHERE contextid = $context->id
4412 AND roleid = $role->id");
4416 * Simple function returning a boolean true if roles exist, otherwise false
4418 function user_has_role_assignment($userid, $roleid, $contextid=0) {
4421 return record_exists('role_assignments', 'userid', $userid, 'roleid', $roleid, 'contextid', $contextid);
4423 return record_exists('role_assignments', 'userid', $userid, 'roleid', $roleid);
4427 // gets the custom name of the role in course
4428 // TODO: proper documentation
4429 function role_get_name($role, $context) {
4431 if ($r = get_record('role_names','roleid', $role->id
,'contextid', $context->id
)) {
4432 return format_string($r->text
);
4434 return format_string($role->name
);
4439 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
4440 * when we read in a new capability
4441 * most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
4442 * but when we are in grade, all reports/import/export capabilites should be together
4443 * @param string a - component string a
4444 * @param string b - component string b
4445 * @return bool - whether 2 component are in different "sections"
4447 function component_level_changed($cap, $comp, $contextlevel) {
4449 if ($cap->component
== 'enrol/authorize' && $comp =='enrol/authorize') {
4453 if (strstr($cap->component
, '/') && strstr($comp, '/')) {
4454 $compsa = explode('/', $cap->component
);
4455 $compsb = explode('/', $comp);
4459 // we are in gradebook, still
4460 if (($compsa[0] == 'gradeexport' ||
$compsa[0] == 'gradeimport' ||
$compsa[0] == 'gradereport') &&
4461 ($compsb[0] == 'gradeexport' ||
$compsb[0] == 'gradeimport' ||
$compsb[0] == 'gradereport')) {
4466 return ($cap->component
!= $comp ||
$cap->contextlevel
!= $contextlevel);
4470 * Populate context.path and context.depth where missing.
4472 * Use $force=true to force a complete rebuild of
4473 * the path and depth fields.
4476 function build_context_path($force=false) {
4478 require_once($CFG->libdir
.'/ddllib.php');
4481 $sitectx = get_record('context', 'contextlevel', CONTEXT_SYSTEM
);
4482 $base = '/' . $sitectx->id
;
4484 if ($force ||
$sitectx->path
!== $base) {
4485 set_field('context', 'path', $base, 'id', $sitectx->id
);
4486 set_field('context', 'depth', 1, 'id', $sitectx->id
);
4487 $sitectx = get_record('context', 'contextlevel', CONTEXT_SYSTEM
);
4491 $sitecoursectx = get_record('context',
4492 'contextlevel', CONTEXT_COURSE
,
4493 'instanceid', SITEID
);
4494 if ($force ||
$sitecoursectx->path
!== "$base/{$sitecoursectx->id}") {
4495 set_field('context', 'path', "$base/{$sitecoursectx->id}",
4496 'id', $sitecoursectx->id
);
4497 set_field('context', 'depth', 2,
4498 'id', $sitecoursectx->id
);
4499 $sitecoursectx = get_record('context',
4500 'contextlevel', CONTEXT_COURSE
,
4501 'instanceid', SITEID
);
4504 $ctxemptyclause = " AND (ctx.depth IS NULL
4506 $emptyclause = " AND ({$CFG->prefix}context.depth IS NULL
4507 OR {$CFG->prefix}context.depth=0) ";
4509 $ctxemptyclause = $emptyclause = '';
4513 * - mysql does not allow to use FROM in UPDATE statements
4514 * - using two tables after UPDATE works in mysql, but might give unexpected
4515 * results in pg 8 (depends on configuration)
4516 * - using table alias in UPDATE does not work in pg < 8.2
4518 if ($CFG->dbfamily
== 'mysql') {
4519 $updatesql = "UPDATE {$CFG->prefix}context ct, {$CFG->prefix}context_temp temp
4520 SET ct.path = temp.path,
4521 ct.depth = temp.depth
4522 WHERE ct.id = temp.id";
4523 } else if ($CFG->dbfamily
== 'oracle') {
4524 $updatesql = "UPDATE {$CFG->prefix}context ct
4525 SET (ct.path, ct.depth) =
4526 (SELECT temp.path, temp.depth
4527 FROM {$CFG->prefix}$temptable temp
4528 WHERE temp.id=ct.id)
4529 WHERE EXISTS (SELECT 'x'
4530 FROM {$CFG->prefix}$temptable temp
4531 WHERE temp.id = ct.id)";
4533 $updatesql = "UPDATE {$CFG->prefix}context
4534 SET path = temp.path,
4536 FROM {$CFG->prefix}context_temp temp
4537 WHERE temp.id={$CFG->prefix}context.id";
4540 $udelsql = "TRUNCATE TABLE {$CFG->prefix}context_temp";
4542 // Top level categories
4543 $sql = "UPDATE {$CFG->prefix}context
4544 SET depth=2, path=" . sql_concat("'$base/'", 'id') . "
4545 WHERE contextlevel=".CONTEXT_COURSECAT
."
4546 AND EXISTS (SELECT 'x'
4547 FROM {$CFG->prefix}course_categories cc
4548 WHERE cc.id = {$CFG->prefix}context.instanceid
4552 execute_sql($sql, $force);
4554 execute_sql($udelsql, $force);
4556 // Deeper categories - one query per depthlevel
4557 $maxdepth = get_field_sql("SELECT MAX(depth)
4558 FROM {$CFG->prefix}course_categories");
4559 for ($n=2;$n<=$maxdepth;$n++
) {
4560 $sql = "INSERT INTO {$CFG->prefix}context_temp (id, path, depth)
4561 SELECT ctx.id, ".sql_concat('pctx.path', "'/'", 'ctx.id').", $n+1
4562 FROM {$CFG->prefix}context ctx
4563 JOIN {$CFG->prefix}course_categories c ON ctx.instanceid=c.id
4564 JOIN {$CFG->prefix}context pctx ON c.parent=pctx.instanceid
4565 WHERE ctx.contextlevel=".CONTEXT_COURSECAT
."
4566 AND pctx.contextlevel=".CONTEXT_COURSECAT
."
4568 AND NOT EXISTS (SELECT 'x'
4569 FROM {$CFG->prefix}context_temp temp
4570 WHERE temp.id = ctx.id)
4572 execute_sql($sql, $force);
4575 execute_sql($updatesql, $force);
4576 execute_sql($udelsql, $force);
4578 // Courses -- except sitecourse
4579 $sql = "INSERT INTO {$CFG->prefix}context_temp (id, path, depth)
4580 SELECT ctx.id, ".sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
4581 FROM {$CFG->prefix}context ctx
4582 JOIN {$CFG->prefix}course c ON ctx.instanceid=c.id
4583 JOIN {$CFG->prefix}context pctx ON c.category=pctx.instanceid
4584 WHERE ctx.contextlevel=".CONTEXT_COURSE
."
4585 AND c.id!=".SITEID
."
4586 AND pctx.contextlevel=".CONTEXT_COURSECAT
."
4587 AND NOT EXISTS (SELECT 'x'
4588 FROM {$CFG->prefix}context_temp temp
4589 WHERE temp.id = ctx.id)
4591 execute_sql($sql, $force);
4593 execute_sql($updatesql, $force);
4594 execute_sql($udelsql, $force);
4597 $sql = "INSERT INTO {$CFG->prefix}context_temp (id, path, depth)
4598 SELECT ctx.id, ".sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
4599 FROM {$CFG->prefix}context ctx
4600 JOIN {$CFG->prefix}course_modules cm ON ctx.instanceid=cm.id
4601 JOIN {$CFG->prefix}context pctx ON cm.course=pctx.instanceid
4602 WHERE ctx.contextlevel=".CONTEXT_MODULE
."
4603 AND pctx.contextlevel=".CONTEXT_COURSE
."
4604 AND NOT EXISTS (SELECT 'x'
4605 FROM {$CFG->prefix}context_temp temp
4606 WHERE temp.id = ctx.id)
4608 execute_sql($sql, $force);
4610 execute_sql($updatesql, $force);
4611 execute_sql($udelsql, $force);
4613 // Blocks - non-pinned course-view only
4614 $sql = "INSERT INTO {$CFG->prefix}context_temp (id, path, depth)
4615 SELECT ctx.id, ".sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
4616 FROM {$CFG->prefix}context ctx
4617 JOIN {$CFG->prefix}block_instance bi ON ctx.instanceid = bi.id
4618 JOIN {$CFG->prefix}context pctx ON bi.pageid=pctx.instanceid
4619 WHERE ctx.contextlevel=".CONTEXT_BLOCK
."
4620 AND pctx.contextlevel=".CONTEXT_COURSE
."
4621 AND bi.pagetype='course-view'
4622 AND NOT EXISTS (SELECT 'x'
4623 FROM {$CFG->prefix}context_temp temp
4624 WHERE temp.id = ctx.id)
4626 execute_sql($sql, $force);
4628 execute_sql($updatesql, $force);
4629 execute_sql($udelsql, $force);
4632 $sql = "UPDATE {$CFG->prefix}context
4633 SET depth=2, path=".sql_concat("'$base/'", 'id')."
4634 WHERE contextlevel=".CONTEXT_BLOCK
."
4635 AND EXISTS (SELECT 'x'
4636 FROM {$CFG->prefix}block_instance bi
4637 WHERE bi.id = {$CFG->prefix}context.instanceid
4638 AND bi.pagetype!='course-view')
4640 execute_sql($sql, $force);
4643 $sql = "UPDATE {$CFG->prefix}context
4644 SET depth=2, path=".sql_concat("'$base/'", 'id')."
4645 WHERE contextlevel=".CONTEXT_USER
."
4646 AND EXISTS (SELECT 'x'
4647 FROM {$CFG->prefix}user u
4648 WHERE u.id = {$CFG->prefix}context.instanceid)
4650 execute_sql($sql, $force);
4654 //TODO: fix group contexts
4658 * Update the path field of the context and
4659 * all the dependent subcontexts that follow
4662 * The most important thing here is to be as
4663 * DB efficient as possible. This op can have a
4664 * massive impact in the DB.
4666 * @param obj current context obj
4667 * @param obj newparent new parent obj
4670 function context_moved($context, $newparent) {
4673 $frompath = $context->path
;
4674 $newpath = $newparent->path
. '/' . $context->id
;
4677 if (($newparent->depth +
1) != $context->depth
) {
4678 $setdepth = ", depth= depth + ({$newparent->depth} - {$context->depth}) + 1";
4680 $sql = "UPDATE {$CFG->prefix}context
4683 WHERE path='$frompath'";
4684 execute_sql($sql,false);
4686 $len = strlen($frompath);
4687 $sql = "UPDATE {$CFG->prefix}context
4688 SET path = ".sql_concat("'$newpath'", 'SUBSTR(path, {$len} +1)')."
4690 WHERE path LIKE '{$frompath}/%'";
4691 execute_sql($sql,false);
4693 mark_context_dirty($frompath);
4694 mark_context_dirty($newpath);
4699 * Turn the ctx* fields in an objectlike record
4700 * into a context subobject. This allows
4701 * us to SELECT from major tables JOINing with
4702 * context at no cost, saving a ton of context
4705 function make_context_subobj($rec) {
4706 $ctx = new StdClass
;
4707 $ctx->id
= $rec->ctxid
; unset($rec->ctxid
);
4708 $ctx->path
= $rec->ctxpath
; unset($rec->ctxpath
);
4709 $ctx->depth
= $rec->ctxdepth
; unset($rec->ctxdepth
);
4710 $ctx->contextlevel
= $rec->ctxlevel
; unset($rec->ctxlevel
);
4711 $ctx->instanceid
= $rec->id
;
4713 $rec->context
= $ctx;
4718 * Fetch recent dirty contexts to know cheaply whether our $USER->access
4719 * is stale and needs to be reloaded.
4721 * Uses config_plugins.
4724 function get_dirty_contexts($time) {
4727 $sql = "SELECT name, value
4728 FROM {$CFG->prefix}config_plugins
4729 WHERE plugin='accesslib/dirtycontexts'
4730 AND value > ($time - 2)";
4731 if ($ctx = get_records_sql($sql)) {
4738 * Mark a context as dirty (with timestamp)
4739 * so as to force reloading of the context.
4742 function mark_context_dirty($path) {
4744 // only if it is a non-empty string
4745 if (is_string($path) && $path !== '') {
4746 set_config($path, time(), 'accesslib/dirtycontexts');
4751 * Cleanup all the old/stale dirty contexts.
4752 * Any context exceeding our session
4753 * timeout is stale. We only keep these for ongoing
4757 function cleanup_dirty_contexts() {
4760 $sql = "plugin='accesslib/dirtycontexts' AND
4761 value < " . time() - $CFG->sessiontimeout
;
4762 delete_records_select('config_plugins', $sql);
4766 * Will walk the contextpath to answer whether
4767 * the contextpath is clean
4769 * NOTE: it will *NOT* test the base path
4770 * as it assumes that the caller has checked
4773 * @param string path
4774 * @param obj/array dirty from get_dirty_contexts()
4777 function is_contextpath_clean($path, $dirty) {
4779 $basepath = '/' . SYSCONTEXTID
;
4781 // all clean, no dirt!
4782 if (count($dirty) === 0) {
4786 // is _this_ context dirty?
4787 if (isset($dirty[$path])) {
4790 while (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
4791 $path = $matches[1];
4792 if ($path === $basepath) {
4793 // we don't test basepath
4794 // assume caller did it already
4797 if (isset($dirty[$path])) {