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
32 * - get_context_instance()
34 * - require_capability()
35 * - get_user_courses_bycap()
36 * - get_context_users_bycap()
37 * - get_parent_contexts()
38 * - enrol_into_course()
39 * - role_assign()/role_unassign()
50 * Access control data is held in the "accessdata" array
51 * which - for the logged-in user, will be in $USER->access
53 * For other users can be generated and passed around (but see
54 * the $ACCESS global).
56 * accessdata ($ad) is a multidimensional array, holding
57 * role assignments (RAs), role-capabilities-perm sets
58 * (role defs) and a list of courses we have loaded
61 * Things are keyed on "contextpaths" (the path field of
62 * the context table) for fast walking up/down the tree.
64 * $ad[ra][$contextpath]= array($roleid)
65 * [$contextpath]= array($roleid)
66 * [$contextpath]= array($roleid)
68 * Role definitions are stored like this
69 * (no cap merge is done - so it's compact)
71 * $ad[rdef][$contextpath:$roleid][mod/forum:viewpost] = 1
72 * [mod/forum:editallpost] = -1
73 * [mod/forum:startdiscussion] = -1000
75 * See how has_cap_fad() walks up/down the tree.
77 * Normally - specially for the logged-in user, we only load
78 * rdef and ra down to the course level, but not below. This
79 * keeps accessdata small and compact. Below-the-course ra/rdef
80 * are loaded as needed. We keep track of which courses we
81 * have loaded ra/rdef in
83 * $ad[loaded] = array($contextpath, $contextpath)
88 * For the logged-in user, accessdata is long-lived.
90 * On each pageload we load $DIRTYPATHS which lists
91 * context paths affected by changes. Any check at-or-below
92 * a dirty context will trigger a transparent reload of accessdata.
94 * Changes at the sytem level will force the reload for everyone.
98 * The default role assignment is not in the DB, so we
99 * add it manually to accessdata.
101 * This means that functions that work directly off the
102 * DB need to ensure that the default role caps
103 * are dealt with appropriately.
107 require_once $CFG->dirroot
.'/lib/blocklib.php';
109 // permission definitions
110 define('CAP_INHERIT', 0);
111 define('CAP_ALLOW', 1);
112 define('CAP_PREVENT', -1);
113 define('CAP_PROHIBIT', -1000);
115 // context definitions
116 define('CONTEXT_SYSTEM', 10);
117 define('CONTEXT_PERSONAL', 20);
118 define('CONTEXT_USER', 30);
119 define('CONTEXT_COURSECAT', 40);
120 define('CONTEXT_COURSE', 50);
121 define('CONTEXT_GROUP', 60);
122 define('CONTEXT_MODULE', 70);
123 define('CONTEXT_BLOCK', 80);
125 // capability risks - see http://docs.moodle.org/en/Hardening_new_Roles_system
126 define('RISK_MANAGETRUST', 0x0001);
127 define('RISK_CONFIG', 0x0002);
128 define('RISK_XSS', 0x0004);
129 define('RISK_PERSONAL', 0x0008);
130 define('RISK_SPAM', 0x0010);
132 require_once($CFG->dirroot
.'/group/lib.php');
134 $context_cache = array(); // Cache of all used context objects for performance (by level and instance)
135 $context_cache_id = array(); // Index to above cache by id
138 function get_role_context_caps($roleid, $context) {
139 //this is really slow!!!! - do not use above course context level!
141 $result[$context->id
] = array();
143 // first emulate the parent context capabilities merging into context
144 $searchcontexts = array_reverse(get_parent_contexts($context));
145 array_push($searchcontexts, $context->id
);
146 foreach ($searchcontexts as $cid) {
147 if ($capabilities = get_records_select('role_capabilities', "roleid = $roleid AND contextid = $cid")) {
148 foreach ($capabilities as $cap) {
149 if (!array_key_exists($cap->capability
, $result[$context->id
])) {
150 $result[$context->id
][$cap->capability
] = 0;
152 $result[$context->id
][$cap->capability
] +
= $cap->permission
;
157 // now go through the contexts bellow given context
158 $searchcontexts = array_keys(get_child_contexts($context));
159 foreach ($searchcontexts as $cid) {
160 if ($capabilities = get_records_select('role_capabilities', "roleid = $roleid AND contextid = $cid")) {
161 foreach ($capabilities as $cap) {
162 if (!array_key_exists($cap->contextid
, $result)) {
163 $result[$cap->contextid
] = array();
165 $result[$cap->contextid
][$cap->capability
] = $cap->permission
;
174 * Gets the accessdata for role "sitewide"
175 * (system down to course)
179 function get_role_access($roleid, $acc=NULL) {
183 /* Get it in 1 cheap DB query...
184 * - relevant role caps at the root and down
185 * to the course level - but not below
188 $acc = array(); // named list
189 $acc['ra'] = array();
190 $acc['rdef'] = array();
191 $acc['loaded'] = array();
194 $base = '/' . SYSCONTEXTID
;
197 // Overrides for the role IN ANY CONTEXTS
198 // down to COURSE - not below -
200 $sql = "SELECT ctx.path,
201 rc.capability, rc.permission
202 FROM {$CFG->prefix}context ctx
203 JOIN {$CFG->prefix}role_capabilities rc
204 ON rc.contextid=ctx.id
205 WHERE rc.roleid = {$roleid}
206 AND ctx.contextlevel <= ".CONTEXT_COURSE
."
207 ORDER BY ctx.depth, ctx.path";
208 $rs = get_recordset_sql($sql);
209 if ($rs->RecordCount()) {
210 while ($rd = rs_fetch_next_record($rs)) {
211 $k = "{$rd->path}:{$roleid}";
212 $acc['rdef'][$k][$rd->capability
] = $rd->permission
;
222 * Get the id for the not-logged-in role - or set it up if needed
225 function get_notloggedin_roleid($return=false) {
228 if (empty($CFG->notloggedinroleid
)) { // Let's set the default to the guest role
229 if ($role = get_guest_role()) {
230 set_config('notloggedinroleid', $role->id
);
236 return $CFG->notloggedinroleid
;
239 return (get_record('role','id', $CFG->notloggedinas
));
243 * Get the default guest role
244 * @return object role
246 function get_guest_role() {
249 if (empty($CFG->guestroleid
)) {
250 if ($roles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW
)) {
251 $guestrole = array_shift($roles); // Pick the first one
252 set_config('guestroleid', $guestrole->id
);
255 debugging('Can not find any guest role!');
259 if ($guestrole = get_record('role','id', $CFG->guestroleid
)) {
262 //somebody is messing with guest roles, remove incorrect setting and try to find a new one
263 set_config('guestroleid', '');
264 return get_guest_role();
269 function has_capability($capability, $context=NULL, $userid=NULL, $doanything=true) {
270 global $USER, $CONTEXT, $ACCESS, $CFG, $DIRTYCONTEXTS;
272 /// Make sure we know the current context
273 if (empty($context)) { // Use default CONTEXT if none specified
274 if (empty($CONTEXT)) {
280 if (empty($CONTEXT)) {
284 if (is_null($userid) ||
$userid===0) {
289 $basepath = '/' . SYSCONTEXTID
;
290 if (empty($context->path
)) {
291 $contexts[] = SYSCONTEXTID
;
292 $context->path
= $basepath;
293 if (isset($context->id
) && $context->id
==! SYSCONTEXTID
) {
294 $contexts[] = $context->id
;
295 $context->path
.= '/' . $context->id
;
298 $contexts = explode('/', $context->path
);
299 array_shift($contexts);
302 if ($USER->id
=== 0 && !isset($USER->access
)) {
303 load_all_capabilities();
306 if (defined('FULLME') && FULLME
=== 'cron' && !isset($USER->access
)) {
308 // In cron, some modules setup a 'fake' $USER,
309 // ensure we load the appropriate accessdata.
310 // Also: set $DIRTYCONTEXTS to empty
312 if (!isset($ACCESS)) {
315 if (!isset($ACCESS[$userid])) {
316 load_user_accessdata($userid);
318 $USER->access
= $ACCESS[$userid];
319 $DIRTYCONTEXTS = array();
322 // Careful check for staleness...
324 if (!isset($DIRTYCONTEXTS)) {
325 // Load dirty contexts list
326 $DIRTYCONTEXTS = get_dirty_contexts($USER->access
['time']);
328 // Check basepath only once, when
329 // we load the dirty contexts...
330 if (isset($DIRTYCONTEXTS[$basepath])) {
331 // sitewide change, dirty
335 // Check for staleness in the whole parenthood
336 if ($clean && !is_contextpath_clean($context->path
, $DIRTYCONTEXTS)) {
340 // reload all capabilities - preserving loginas, roleswitches, etc
341 // and then cleanup any marks of dirtyness... at least from our short
343 reload_all_capabilities();
344 $DIRTYCONTEXTS = array();
348 // divulge how many times we are called
349 //// error_log("has_capability: id:{$context->id} path:{$context->path} userid:$userid cap:$capability");
351 if ($USER->id
=== $userid) {
353 // For the logged in user, we have $USER->access
354 // which will have all RAs and caps preloaded for
355 // course and above contexts.
357 // Contexts below courses && contexts that do not
358 // hang from courses are loaded into $USER->access
359 // on demand, and listed in $USER->access[loaded]
361 if ($context->contextlevel
<= CONTEXT_COURSE
) {
362 // Course and above are always preloaded
363 return has_cap_fad($capability, $context,
364 $USER->access
, $doanything);
366 // Load accessdata for below-the-course contexts
367 if (!path_inaccessdata($context->path
,$USER->access
)) {
368 error_log("loading access for context {$context->path} for $capability at {$context->contextlevel} {$context->id}");
369 // $bt = debug_backtrace();
370 // error_log("bt {$bt[0]['file']} {$bt[0]['line']}");
371 $USER->access
= get_user_access_bycontext($USER->id
, $context,
374 return has_cap_fad($capability, $context,
375 $USER->access
, $doanything);
379 if (!isset($ACCESS)) {
382 if (!isset($ACCESS[$userid])) {
383 load_user_accessdata($userid);
385 if ($context->contextlevel
<= CONTEXT_COURSE
) {
386 // Course and above are always preloaded
387 return has_cap_fad($capability, $context,
388 $ACCESS[$userid], $doanything);
390 // Load accessdata for below-the-course contexts as needed
391 if (!path_inaccessdata($context->path
,$ACCESS[$userid])) {
392 error_log("loading access for context {$context->path} for $capability at {$context->contextlevel} {$context->id}");
393 // $bt = debug_backtrace();
394 // error_log("bt {$bt[0]['file']} {$bt[0]['line']}");
395 $ACCESS[$userid] = get_user_access_bycontext($userid, $context,
398 return has_cap_fad($capability, $context,
399 $ACCESS[$userid], $doanything);
403 * Uses 1 DB query to answer whether a user is an admin at the sitelevel.
404 * It depends on DB schema >=1.7 but does not depend on the new datastructures
405 * in v1.9 (context.path, or $USER->access)
407 * Will return true if the userid has any of
408 * - moodle/site:config
409 * - moodle/legacy:admin
410 * - moodle/site:doanything
413 * @returns bool $isadmin
415 function is_siteadmin($userid) {
418 $sql = "SELECT COUNT(u.id)
420 JOIN mdl_role_assignments ra
423 ON ctx.id=ra.contextid
424 JOIN mdl_role_capabilities rc
425 ON (ra.roleid=rc.roleid AND rc.contextid=ctx.id)
426 WHERE ctx.contextlevel=10
427 AND rc.capability IN ('moodle/site:config', 'moodle/legacy:admin', 'moodle/site:doanything')
430 $isadmin = (get_field_sql($sql) > 0);
434 function get_course_from_path ($path) {
435 // assume that nothing is more than 1 course deep
436 if (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
442 function path_inaccessdata($path, $ad) {
444 // assume that contexts hang from sys or from a course
445 // this will only work well with stuff that hangs from a course
446 if (in_array($path, $ad['loaded'], true)) {
447 error_log("found it!");
450 $base = '/' . SYSCONTEXTID
;
451 while (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
453 if ($path === $base) {
456 if (in_array($path, $ad['loaded'], true)) {
464 * Walk the accessdata array and return true/false.
465 * Deals with prohibits, roleswitching, aggregating
468 * The main feature of here is being FAST and with no
473 * Switch Roles exits early
474 * -----------------------
475 * cap checks within a switchrole need to exit early
476 * in our bottom up processing so they don't "see" that
477 * there are real RAs that can do all sorts of things.
479 * Switch Role merges with default role
480 * ------------------------------------
481 * If you are a teacher in course X, you have at least
482 * teacher-in-X + defaultloggedinuser-sitewide. So in the
483 * course you'll have techer+defaultloggedinuser.
484 * We try to mimic that in switchrole.
486 * Local-most role definition and role-assignment wins
487 * ---------------------------------------------------
488 * So if the local context has said 'allow', it wins
489 * over a high-level context that says 'deny'.
490 * This is applied when walking rdefs, and RAs.
491 * Only at the same context the values are SUM()med.
493 * The exception is CAP_PROHIBIT.
495 * "Guest default role" exception
496 * ------------------------------
498 * See MDL-7513 and $ignoreguest below for details.
502 * IF we are being asked about moodle/legacy:guest
503 * OR moodle/course:view
504 * FOR a real, logged-in user
505 * AND we reached the top of the path in ra and rdef
506 * AND that role has moodle/legacy:guest === 1...
507 * THEN we act as if we hadn't seen it.
512 * - Document how it works
513 * - Rewrite in ASM :-)
516 function has_cap_fad($capability, $context, $ad, $doanything) {
520 $path = $context->path
;
522 // build $contexts as a list of "paths" of the current
523 // contexts and parents with the order top-to-bottom
524 $contexts = array($path);
525 while (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
527 array_unshift($contexts, $path);
530 $ignoreguest = false;
532 && ($capability == 'moodle/course:view'
533 ||
$capability == 'moodle/legacy:guest')) {
534 // At the base, ignore rdefs where moodle/legacy:guest
536 $ignoreguest = $ad['dr'];
540 $cc = count($contexts);
545 // role-switches loop
547 if (isset($ad['rsw'])) {
548 // check for isset() is fast
549 // empty() is slow...
550 if (empty($ad['rsw'])) {
551 unset($ad['rsw']); // keep things fast and unambiguous
554 // From the bottom up...
555 for ($n=$cc-1;$n>=0;$n--) {
556 $ctxp = $contexts[$n];
557 if (isset($ad['rsw'][$ctxp])) {
558 // Found a switchrole assignment
559 // check for that role _plus_ the default user role
560 $ras = array($ad['rsw'][$ctxp],$CFG->defaultuserroleid
);
561 for ($rn=0;$rn<2;$rn++
) {
563 // Walk the path for capabilities
564 // from the bottom up...
565 for ($m=$cc-1;$m>=0;$m--) {
566 $capctxp = $contexts[$m];
567 if (isset($ad['rdef']["{$capctxp}:$roleid"][$capability])) {
568 $perm = $ad['rdef']["{$capctxp}:$roleid"][$capability];
569 // The most local permission (first to set) wins
570 // the only exception is CAP_PROHIBIT
573 } elseif ($perm == CAP_PROHIBIT
) {
580 // As we are dealing with a switchrole,
581 // we return _here_, do _not_ walk up
582 // the hierarchy any further
585 // didn't find it as an explicit cap,
586 // but maybe the user candoanything in this context...
587 return has_cap_fad('moodle/site:doanything', $context,
601 // Main loop for normal RAs
602 // From the bottom up...
604 for ($n=$cc-1;$n>=0;$n--) {
605 $ctxp = $contexts[$n];
606 if (isset($ad['ra'][$ctxp])) {
607 // Found role assignments on this leaf
608 $ras = $ad['ra'][$ctxp];
611 for ($rn=0;$rn<$rc;$rn++
) {
614 // Walk the path for capabilities
615 // from the bottom up...
616 for ($m=$cc-1;$m>=0;$m--) {
617 $capctxp = $contexts[$m];
618 // ignore some guest caps
619 // at base ra and rdef
620 if ($ignoreguest == $roleid
623 && isset($ad['rdef']["{$capctxp}:$roleid"]['moodle/legacy:guest'])
624 && $ad['rdef']["{$capctxp}:$roleid"]['moodle/legacy:guest'] > 0) {
627 if (isset($ad['rdef']["{$capctxp}:$roleid"][$capability])) {
628 $perm = $ad['rdef']["{$capctxp}:$roleid"][$capability];
629 // The most local permission (first to set) wins
630 // the only exception is CAP_PROHIBIT
631 if ($rolecan === 0) {
633 } elseif ($perm == CAP_PROHIBIT
) {
639 // Permissions at the same
640 // ctxlevel are added together
643 // The most local RAs with a defined
644 // permission ($ctxcan) win, except
648 } elseif ($ctxcan == CAP_PROHIBIT
) {
657 // didn't find it as an explicit cap,
658 // but maybe the user candoanything in this context...
659 return has_cap_fad('moodle/site:doanything', $context,
670 function aggr_roles_fad($context, $ad) {
672 $path = $context->path
;
674 // build $contexts as a list of "paths" of the current
675 // contexts and parents with the order top-to-bottom
676 $contexts = array($path);
677 while (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
679 array_unshift($contexts, $path);
682 $cc = count($contexts);
685 // From the bottom up...
686 for ($n=$cc-1;$n>=0;$n--) {
687 $ctxp = $contexts[$n];
688 if (isset($ad['ra'][$ctxp]) && count($ad['ra'][$ctxp])) {
689 // Found assignments on this leaf
690 $addroles = $ad['ra'][$ctxp];
691 $roles = array_merge($roles, $addroles);
695 return array_unique($roles);
699 * This is an easy to use function, combining has_capability() with require_course_login().
700 * And will call those where needed.
702 * It checks for a capability assertion being true. If it isn't
703 * then the page is terminated neatly with a standard error message.
705 * If the user is not logged in, or is using 'guest' access or other special "users,
706 * it provides a logon prompt.
708 * @param string $capability - name of the capability
709 * @param object $context - a context object (record from context table)
710 * @param integer $userid - a userid number
711 * @param bool $doanything - if false, ignore do anything
712 * @param string $errorstring - an errorstring
713 * @param string $stringfile - which stringfile to get it from
715 function require_capability($capability, $context=NULL, $userid=NULL, $doanything=true,
716 $errormessage='nopermissions', $stringfile='') {
720 /// If the current user is not logged in, then make sure they are (if needed)
722 if (is_null($userid) && !isset($USER->access
)) {
723 if ($context && ($context->contextlevel
== CONTEXT_COURSE
)) {
724 require_login($context->instanceid
);
725 } else if ($context && ($context->contextlevel
== CONTEXT_MODULE
)) {
726 if ($cm = get_record('course_modules','id',$context->instanceid
)) {
727 if (!$course = get_record('course', 'id', $cm->course
)) {
728 error('Incorrect course.');
730 require_course_login($course, true, $cm);
735 } else if ($context && ($context->contextlevel
== CONTEXT_SYSTEM
)) {
736 if (!empty($CFG->forcelogin
)) {
745 /// OK, if they still don't have the capability then print a nice error message
747 if (!has_capability($capability, $context, $userid, $doanything)) {
748 $capabilityname = get_capability_string($capability);
749 print_error($errormessage, $stringfile, '', $capabilityname);
754 * Get an array of courses (with magic extra bits)
755 * where the accessdata and in DB enrolments show
756 * that the cap requested is available.
758 * The main use is for get_my_courses().
762 * - $fields is an array of fieldnames to ADD
763 * so name the fields you really need, which will
764 * be added and uniq'd
766 * - the course records have $c->context which is a fully
767 * valid context object. Saves you a query per course!
769 * - the course records have $c->categorypath to make
770 * category lookups cheap
772 * - current implementation is split in -
774 * - if the user has the cap systemwide, stupidly
775 * grab *every* course for a capcheck. This eats
776 * a TON of bandwidth, specially on large sites
777 * with separate DBs...
779 * - otherwise, fetch "likely" courses with a wide net
780 * that should get us _cheaply_ at least the courses we need, and some
781 * we won't - we get courses that...
782 * - are in a category where user has the cap
783 * - or where use has a role-assignment (any kind)
784 * - or where the course has an override on for this cap
786 * - walk the courses recordset checking the caps oneach one
787 * the checks are all in memory and quite fast
788 * (though we could implement a specialised variant of the
789 * has_cap_fad() code to speed it up)
791 * @param string $capability - name of the capability
792 * @param array $accessdata - access session array
793 * @param bool $doanything - if false, ignore do anything
794 * @param string $sort - sorting fields - prefix each fieldname with "c."
795 * @param array $fields - additional fields you are interested in...
796 * @param int $limit - set if you want to limit the number of courses
797 * @return array $courses - ordered array of course objects - see notes above
800 function get_user_courses_bycap($userid, $cap, $ad, $doanything, $sort='c.sortorder ASC', $fields=NULL, $limit=0) {
804 // Slim base fields, let callers ask for what they need...
805 $basefields = array('id', 'sortorder', 'shortname', 'idnumber');
807 if (!is_null($fields)) {
808 $fields = array_merge($basefields, $fields);
809 $fields = array_unique($fields);
811 $fields = $basefields;
813 $coursefields = 'c.' .implode(',c.', $fields);
817 $sort = "ORDER BY $sort";
820 $sysctx = get_context_instance(CONTEXT_SYSTEM
);
821 if (has_cap_fad($cap, $sysctx, $ad, $doanything)) {
823 // Apparently the user has the cap sitewide, so walk *every* course
824 // (the cap checks are moderately fast, but this moves massive bandwidth w the db)
827 $sql = "SELECT $coursefields,
828 ctx.id AS ctxid, ctx.path AS ctxpath, ctx.depth as ctxdepth,
829 cc.path AS categorypath
830 FROM {$CFG->prefix}course c
831 JOIN {$CFG->prefix}course_categories cc
833 JOIN {$CFG->prefix}context ctx
834 ON (c.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE
.")
836 $rs = get_recordset_sql($sql);
839 // narrow down where we have the caps to a few contexts
840 // this will be a combination of
841 // - categories where we have the rights
842 // - courses where we have an explicit enrolment OR that have an override
845 FROM {$CFG->prefix}context ctx
846 WHERE ctx.contextlevel=".CONTEXT_COURSECAT
."
848 $rs = get_recordset_sql($sql);
850 if ($rs->RecordCount()) {
851 while ($catctx = rs_fetch_next_record($rs)) {
852 if ($catctx->path
!= ''
853 && has_cap_fad($cap, $catctx, $ad, $doanything)) {
854 $catpaths[] = $catctx->path
;
860 if (count($catpaths)) {
861 $cc = count($catpaths);
862 for ($n=0;$n<$cc;$n++
) {
863 $catpaths[$n] = "ctx.path LIKE '{$catpaths[$n]}/%'";
865 $catclause = 'OR (' . implode(' OR ', $catpaths) .')';
871 $capany = " OR rc.capability='moodle/site:doanything'";
874 // Note here that we *have* to have the compound clauses
875 // in the LEFT OUTER JOIN condition for them to return NULL
876 // appropriately and narrow things down...
878 $sql = "SELECT $coursefields,
879 ctx.id AS ctxid, ctx.path AS ctxpath, ctx.depth as ctxdepth,
880 cc.path AS categorypath
881 FROM {$CFG->prefix}course c
882 JOIN {$CFG->prefix}course_categories cc
884 JOIN {$CFG->prefix}context ctx
885 ON (c.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE
.")
886 LEFT OUTER JOIN {$CFG->prefix}role_assignments ra
887 ON (ra.contextid=ctx.id AND ra.userid=$userid)
888 LEFT OUTER JOIN {$CFG->prefix}role_capabilities rc
889 ON (rc.contextid=ctx.id AND (rc.capability='$cap' $capany))
890 WHERE ra.id IS NOT NULL
894 $rs = get_recordset_sql($sql);
897 $cc = 0; // keep count
898 if ($rs->RecordCount()) {
899 while ($c = rs_fetch_next_record($rs)) {
900 // build the context obj
901 $c = make_context_subobj($c);
903 if (has_cap_fad($cap, $c->context
, $ad, $doanything)) {
905 if ($limit > 0 && $cc++
> $limit) {
916 * Draft - use for the course participants list page
918 * Uses 1 DB query (cheap too - 2~7ms).
921 * - implement additional where clauses
923 * - get course participants list to use it!
925 * returns a users array, both sorted _and_ keyed
926 * on id (as get_my_courses() does)
928 * as a bonus, every user record comes with its own
929 * personal context, as our callers need it straight away
930 * {save 1 dbquery per user! yay!}
933 function get_context_users_byrole ($context, $roleid, $fields=NULL, $where=NULL, $sort=NULL, $limit=0) {
936 // Slim base fields, let callers ask for what they need...
937 $basefields = array('id', 'username');
939 if (!is_null($fields)) {
940 $fields = array_merge($basefields, $fields);
941 $fields = array_unique($fields);
943 $fields = $basefields;
945 $userfields = 'u.' .implode(',u.', $fields);
947 $contexts = substr($context->path
, 1); // kill leading slash
948 $contexts = str_replace('/', ',', $contexts);
950 $sql = "SELECT $userfields,
951 ctx.id AS ctxid, ctx.path AS ctxpath, ctx.depth as ctxdepth
952 FROM {$CFG->prefix}user u
953 JOIN {$CFG->prefix}context ctx
954 ON (u.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_USER
.")
955 JOIN {$CFG->prefix}role_assignments ra
957 WHERE ra.roleid = $roleid
958 AND ra.contextid IN ($contexts)";
960 $rs = get_recordset_sql($sql);
963 $cc = 0; // keep count
964 if ($rs->RecordCount()) {
965 while ($u = rs_fetch_next_record($rs)) {
966 // build the context obj
967 $u = make_context_subobj($u);
970 if ($limit > 0 && $cc++
> $limit) {
980 * Draft - use for the course participants list page
982 * Uses 2 fast DB queries
985 * - automagically exclude roles that can-doanything sitewide (See callers)
986 * - perhaps also allow sitewide do-anything via flag
987 * - implement additional where clauses
989 * - get course participants list to use it!
991 * returns a users array, both sorted _and_ keyed
992 * on id (as get_my_courses() does)
994 * as a bonus, every user record comes with its own
995 * personal context, as our callers need it straight away
996 * {save 1 dbquery per user! yay!}
999 function get_context_users_bycap ($context, $capability='moodle/course:view', $fields=NULL, $where=NULL, $sort=NULL, $limit=0) {
1004 // - Get all the *interesting* roles -- those that
1005 // have some rolecap entry in our ctx.path contexts
1007 // - Get all RAs for any of those roles in any of our
1008 // interesting contexts, with userid & perm data
1009 // in a nice (per user?) order
1011 // - Walk the resultset, computing the permissions
1012 // - actually - this is all a SQL subselect
1014 // - Fetch user records against the subselect
1017 // Slim base fields, let callers ask for what they need...
1018 $basefields = array('id', 'username');
1020 if (!is_null($fields)) {
1021 $fields = array_merge($basefields, $fields);
1022 $fields = array_unique($fields);
1024 $fields = $basefields;
1026 $userfields = 'u.' .implode(',u.', $fields);
1028 $contexts = substr($context->path
, 1); // kill leading slash
1029 $contexts = str_replace('/', ',', $contexts);
1032 $sql = "SELECT DISTINCT rc.roleid
1033 FROM {$CFG->prefix}role_capabilities rc
1034 WHERE rc.capability = '$capability'
1035 AND rc.contextid IN ($contexts)";
1036 $rs = get_recordset_sql($sql);
1037 if ($rs->RecordCount()) {
1038 while ($u = rs_fetch_next_record($rs)) {
1039 $roles[] = $u->roleid
;
1043 $roles = implode(',', $roles);
1046 // User permissions subselect SQL
1048 // - the open join condition to
1049 // role_capabilities
1051 // - because both rc and ra entries are
1052 // _at or above_ our context, we don't care
1053 // about their depth, we just need to sum them
1055 $sql = "SELECT ra.userid, SUM(rc.permission) AS permission
1056 FROM {$CFG->prefix}role_assignments ra
1057 JOIN {$CFG->prefix}role_capabilities rc
1058 ON (ra.roleid = rc.roleid AND rc.contextid IN ($contexts))
1059 WHERE ra.contextid IN ($contexts)
1060 AND ra.roleid IN ($roles)
1061 GROUP BY ra.userid";
1064 $sql = "SELECT $userfields,
1065 ctx.id AS ctxid, ctx.path AS ctxpath, ctx.depth as ctxdepth
1066 FROM {$CFG->prefix}user u
1067 JOIN {$CFG->prefix}context ctx
1068 ON (u.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_USER
.")
1071 WHERE up.permission > 0 AND u.username != 'guest'";
1073 $rs = get_recordset_sql($sql);
1076 $cc = 0; // keep count
1077 if ($rs->RecordCount()) {
1078 while ($u = rs_fetch_next_record($rs)) {
1079 // build the context obj
1080 $u = make_context_subobj($u);
1083 if ($limit > 0 && $cc++
> $limit) {
1093 * It will return a nested array showing role assignments
1094 * all relevant role capabilities for the user at
1095 * site/metacourse/course_category/course levels
1097 * We do _not_ delve deeper than courses because the number of
1098 * overrides at the module/block levels is HUGE.
1100 * [ra] => [/path/] = array(roleid, roleid)
1101 * [rdef] => [/path/:roleid][capability]=permission
1102 * [loaded] => array('/path', '/path')
1104 * @param $userid integer - the id of the user
1107 function get_user_access_sitewide($userid) {
1111 // this flag has not been set!
1112 // (not clean install, or upgraded successfully to 1.7 and up)
1113 if (empty($CFG->rolesactive
)) {
1117 /* Get in 3 cheap DB queries...
1118 * - role assignments - with role_caps
1119 * - relevant role caps
1120 * - above this user's RAs
1121 * - below this user's RAs - limited to course level
1124 $acc = array(); // named list
1125 $acc['ra'] = array();
1126 $acc['rdef'] = array();
1127 $acc['loaded'] = array();
1129 $sitectx = get_field('context', 'id','contextlevel', CONTEXT_SYSTEM
);
1130 $base = "/$sitectx";
1133 // Role assignments - and any rolecaps directly linked
1134 // because it's cheap to read rolecaps here over many
1137 $sql = "SELECT ctx.path, ra.roleid, rc.capability, rc.permission
1138 FROM {$CFG->prefix}role_assignments ra
1139 JOIN {$CFG->prefix}context ctx
1140 ON ra.contextid=ctx.id
1141 LEFT OUTER JOIN {$CFG->prefix}role_capabilities rc
1142 ON (rc.roleid=ra.roleid AND rc.contextid=ra.contextid)
1143 WHERE ra.userid = $userid AND ctx.contextlevel <= ".CONTEXT_COURSE
."
1144 ORDER BY ctx.depth, ctx.path";
1145 $rs = get_recordset_sql($sql);
1147 // raparents collects paths & roles we need to walk up
1148 // the parenthood to build the rdef
1150 // the array will bulk up a bit with dups
1151 // which we'll later clear up
1153 $raparents = array();
1155 if ($rs->RecordCount()) {
1156 while ($ra = rs_fetch_next_record($rs)) {
1157 // RAs leafs are arrays to support multi
1158 // role assignments...
1159 if (!isset($acc['ra'][$ra->path
])) {
1160 $acc['ra'][$ra->path
] = array();
1162 // only add if is not a repeat caused
1163 // by capability join...
1164 // (this check is cheaper than in_array())
1165 if ($lastseen !== $ra->path
.':'.$ra->roleid
) {
1166 $lastseen = $ra->path
.':'.$ra->roleid
;
1167 array_push($acc['ra'][$ra->path
], $ra->roleid
);
1168 $parentids = explode('/', $ra->path
);
1169 array_shift($parentids); // drop empty leading "context"
1170 array_pop($parentids); // drop _this_ context
1172 if (isset($raparents[$ra->roleid
])) {
1173 $raparents[$ra->roleid
] = array_merge($raparents[$ra->roleid
],
1176 $raparents[$ra->roleid
] = $parentids;
1179 // Always add the roleded
1180 if (!empty($ra->capability
)) {
1181 $k = "{$ra->path}:{$ra->roleid}";
1182 $acc['rdef'][$k][$ra->capability
] = $ra->permission
;
1189 // Walk up the tree to grab all the roledefs
1190 // of interest to our user...
1191 // NOTE: we use a series of IN clauses here - which
1192 // might explode on huge sites with very convoluted nesting of
1193 // categories... - extremely unlikely that the number of categories
1194 // and roletypes is so large that we hit the limits of IN()
1196 foreach ($raparents as $roleid=>$contexts) {
1197 $contexts = implode(',', array_unique($contexts));
1198 if ($contexts ==! '') {
1199 $clauses[] = "(roleid=$roleid AND contextid IN ($contexts))";
1202 $clauses = implode(" OR ", $clauses);
1203 if ($clauses !== '') {
1204 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
1205 FROM {$CFG->prefix}role_capabilities rc
1206 JOIN {$CFG->prefix}context ctx
1207 ON rc.contextid=ctx.id
1209 ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
1211 $rs = get_recordset_sql($sql);
1214 if ($rs->RecordCount()) {
1215 while ($rd = rs_fetch_next_record($rs)) {
1216 $k = "{$rd->path}:{$rd->roleid}";
1217 $acc['rdef'][$k][$rd->capability
] = $rd->permission
;
1225 // Overrides for the role assignments IN SUBCONTEXTS
1226 // (though we still do _not_ go below the course level.
1228 // NOTE that the JOIN w sctx is with 3-way triangulation to
1229 // catch overrides to the applicable role in any subcontext, based
1230 // on the path field of the parent.
1232 $sql = "SELECT sctx.path, ra.roleid,
1233 ctx.path AS parentpath,
1234 rco.capability, rco.permission
1235 FROM {$CFG->prefix}role_assignments ra
1236 JOIN {$CFG->prefix}context ctx
1237 ON ra.contextid=ctx.id
1238 JOIN {$CFG->prefix}context sctx
1239 ON (sctx.path LIKE " . sql_concat('ctx.path',"'/%'"). " )
1240 JOIN {$CFG->prefix}role_capabilities rco
1241 ON (rco.roleid=ra.roleid AND rco.contextid=sctx.id)
1242 WHERE ra.userid = $userid
1243 AND sctx.contextlevel <= ".CONTEXT_COURSE
."
1244 ORDER BY sctx.depth, sctx.path, ra.roleid";
1245 if ($rs->RecordCount()) {
1246 while ($rd = rs_fetch_next_record($rs)) {
1247 $k = "{$rd->path}:{$rd->roleid}";
1248 $acc['rdef'][$k][$rd->capability
] = $rd->permission
;
1258 * It add to the access ctrl array the data
1259 * needed by a user for a given context
1261 * @param $userid integer - the id of the user
1262 * @param $context context obj - needs path!
1263 * @param $acc access array
1266 function get_user_access_bycontext($userid, $context, $acc=NULL) {
1272 /* Get the additional RAs and relevant rolecaps
1273 * - role assignments - with role_caps
1274 * - relevant role caps
1275 * - above this user's RAs
1276 * - below this user's RAs - limited to course level
1279 // Roles already in use in this context
1280 $knownroles = array();
1281 if (is_null($acc)) {
1282 $acc = array(); // named list
1283 $acc['ra'] = array();
1284 $acc['rdef'] = array();
1285 $acc['loaded'] = array();
1287 $knownroles = aggr_roles_fad($context, $acc);
1290 $base = "/" . SYSCONTEXTID
;
1292 // Determine the course context we'll go
1293 // after, though we are usually called
1294 // with a lower ctx. We have 3 easy cases
1297 // - BLOCK/PERSON/USER/COURSE(sitecourse) hanging from SYSTEM
1298 // - BLOCK/MODULE/GROUP hanging from a course
1300 // For course contexts, we _already_ have the RAs
1301 // but the cost of re-fetching is minimal so we don't care.
1304 if ($context->contextlevel
=== CONTEXT_COURSE
) {
1305 $targetpath = $context->path
;
1306 $targetlevel = $context->contextlevel
;
1307 } elseif ($context->path
=== "$base/{$context->id}") {
1308 $targetpath = $context->path
;
1309 $targetlevel = $context->contextlevel
;
1311 // Assumption: the course _must_ be our parent
1312 // If we ever see stuff nested further this needs to
1313 // change to do 1 query over the exploded path to
1314 // find out which one is the course
1315 $targetpath = get_course_from_path($context->path
);
1316 $targetlevel = CONTEXT_COURSE
;
1320 // Role assignments in the context and below - and any rolecaps directly linked
1321 // because it's cheap to read rolecaps here over many
1324 $sql = "SELECT ctx.path, ra.roleid, rc.capability, rc.permission
1325 FROM {$CFG->prefix}role_assignments ra
1326 JOIN {$CFG->prefix}context ctx
1327 ON ra.contextid=ctx.id
1328 LEFT OUTER JOIN {$CFG->prefix}role_capabilities rc
1329 ON (rc.roleid=ra.roleid AND rc.contextid=ra.contextid)
1330 WHERE ra.userid = $userid
1331 AND (ctx.path = '$targetpath' OR ctx.path LIKE '{$targetpath}/%')
1332 ORDER BY ctx.depth, ctx.path";
1333 $rs = get_recordset_sql($sql);
1336 // raparent collects paths & roles we need to walk up
1338 // Here we only collect "different" role assignments
1339 // that - if found - we have to walk up the parenthood
1340 // to build the rdef.
1342 // raparents array might have a few duplicates
1343 // which we'll later clear up
1345 $raparents = array();
1346 $newroles = array();
1348 if ($rs->RecordCount()) {
1349 while ($ra = rs_fetch_next_record($rs)) {
1350 if ($lastseen !== $ra->path
.':'.$ra->roleid
) {
1351 // only add if is not a repeat caused
1352 // by capability join...
1353 // (this check is cheaper than in_array())
1354 $lastseen = $ra->path
.':'.$ra->roleid
;
1355 if (!isset($acc['ra'][$ra->path
])) {
1356 $acc['ra'][$ra->path
] = array();
1358 array_push($acc['ra'][$ra->path
], $ra->roleid
);
1359 if (!in_array($ra->roleid
, $knownroles)) {
1360 $newroles[] = $ra->roleid
;
1361 $parentids = explode('/', $ra->path
);
1362 array_pop($parentids); array_shift($parentids);
1363 if (isset($raparents[$ra->roleid
])) {
1364 $raparents[$ra->roleid
] = array_merge($raparents[$ra->roleid
], $parentids);
1366 $raparents[$ra->roleid
] = $parentids;
1370 if (!empty($ra->capability
)) {
1371 $k = "{$ra->path}:{$ra->roleid}";
1372 $acc['rdef'][$k][$ra->capability
] = $ra->permission
;
1375 $newroles = array_unique($newroles);
1380 // Walk up the tree to grab all the roledefs
1381 // of interest to our user...
1382 // NOTE: we use a series of IN clauses here - which
1383 // might explode on huge sites with very convoluted nesting of
1384 // categories... - extremely unlikely that the number of categories
1385 // and roletypes is so large that we hit the limits of IN()
1387 if (count($raparents)) {
1389 foreach ($raparents as $roleid=>$contexts) {
1390 $contexts = implode(',', array_unique($contexts));
1391 if ($contexts ==! '') {
1392 $clauses[] = "(roleid=$roleid AND contextid IN ($contexts))";
1395 $clauses = implode(" OR ", $clauses);
1396 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
1397 FROM {$CFG->prefix}role_capabilities rc
1398 JOIN {$CFG->prefix}context ctx
1399 ON rc.contextid=ctx.id
1401 ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
1403 $rs = get_recordset_sql($sql);
1405 if ($rs->RecordCount()) {
1406 while ($rd = rs_fetch_next_record($rs)) {
1407 $k = "{$rd->path}:{$rd->roleid}";
1408 $acc['rdef'][$k][$rd->capability
] = $rd->permission
;
1415 // Overrides for the relevant roles IN SUBCONTEXTS
1417 // NOTE that we use IN() but the number of roles is
1420 $roleids = implode(',', array_merge($newroles, $knownroles));
1421 $sql = "SELECT ctx.path, rc.roleid,
1422 rc.capability, rc.permission
1423 FROM {$CFG->prefix}context ctx
1424 JOIN {$CFG->prefix}role_capabilities rc
1425 ON rc.contextid=ctx.id
1426 WHERE ctx.path LIKE '{$targetpath}/%'
1427 AND rc.roleid IN ($roleids)
1428 ORDER BY ctx.depth, ctx.path, rc.roleid";
1429 $rs = get_recordset_sql($sql);
1430 if ($rs->RecordCount()) {
1431 while ($rd = rs_fetch_next_record($rs)) {
1432 $k = "{$rd->path}:{$rd->roleid}";
1433 $acc['rdef'][$k][$rd->capability
] = $rd->permission
;
1438 // TODO: compact capsets?
1440 error_log("loaded $targetpath");
1441 $acc['loaded'][] = $targetpath;
1447 * It add to the access ctrl array the data
1448 * needed by a role for a given context.
1450 * The data is added in the rdef key.
1452 * This role-centric function is useful for role_switching
1453 * and to get an overview of what a role gets under a
1454 * given context and below...
1456 * @param $roleid integer - the id of the user
1457 * @param $context context obj - needs path!
1458 * @param $acc access array
1461 function get_role_access_bycontext($roleid, $context, $acc=NULL) {
1465 /* Get the relevant rolecaps into rdef
1466 * - relevant role caps
1467 * - at ctx and above
1471 if (is_null($acc)) {
1472 $acc = array(); // named list
1473 $acc['ra'] = array();
1474 $acc['rdef'] = array();
1475 $acc['loaded'] = array();
1478 $contexts = substr($context->path
, 1); // kill leading slash
1479 $contexts = str_replace('/', ',', $contexts);
1482 // Walk up and down the tree to grab all the roledefs
1483 // of interest to our role...
1485 // NOTE: we use an IN clauses here - which
1486 // might explode on huge sites with very convoluted nesting of
1487 // categories... - extremely unlikely that the number of nested
1488 // categories is so large that we hit the limits of IN()
1490 $sql = "SELECT ctx.path, rc.capability, rc.permission
1491 FROM {$CFG->prefix}role_capabilities rc
1492 JOIN {$CFG->prefix}context ctx
1493 ON rc.contextid=ctx.id
1494 WHERE rc.roleid=$roleid AND
1495 ( ctx.id IN ($contexts) OR
1496 ctx.path LIKE '{$context->path}/%' )
1497 ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
1499 $rs = get_recordset_sql($sql);
1500 if ($rs->RecordCount()) {
1501 while ($rd = rs_fetch_next_record($rs)) {
1502 $k = "{$rd->path}:{$roleid}";
1503 $acc['rdef'][$k][$rd->capability
] = $rd->permission
;
1512 * Load accessdata for a user
1513 * into the $ACCESS global
1515 * Used by has_capability() - but feel free
1516 * to call it if you are about to run a BIG
1517 * cron run across a bazillion users.
1519 * TODO: share rdef tree to save mem
1522 function load_user_accessdata($userid) {
1523 global $ACCESS,$CFG;
1525 if (!isset($ACCESS)) {
1528 $base = '/'.SYSCONTEXTID
;
1530 $ad = get_user_access_sitewide($userid);
1533 // provide "default role" & set 'dr'
1535 $ad = get_role_access($CFG->defaultuserroleid
, $ad);
1536 if (!isset($ad['ra'][$base])) {
1537 $ad['ra'][$base] = array($CFG->defaultuserroleid
);
1539 array_push($ad['ra'][$base], $CFG->defaultuserroleid
);
1541 $ad['dr'] = $CFG->defaultuserroleid
;
1543 $ACCESS[$userid] = $ad;
1548 * A convenience function to completely load all the capabilities
1549 * for the current user. This is what gets called from login, for example.
1551 function load_all_capabilities() {
1554 $base = '/'.SYSCONTEXTID
;
1556 if (isguestuser()) {
1557 $guest = get_guest_role();
1560 $USER->access
= get_role_access($guest->id
);
1561 // Put the ghost enrolment in place...
1562 $USER->access
['ra'][$base] = array($guest->id
);
1565 } else if (isloggedin()) {
1568 $ad = get_user_access_sitewide($USER->id
);
1571 // provide "default role" & set 'dr'
1573 $ad = get_role_access($CFG->defaultuserroleid
, $ad);
1574 if (!isset($ad['ra'][$base])) {
1575 $ad['ra'][$base] = array($CFG->defaultuserroleid
);
1577 array_push($ad['ra'][$base], $CFG->defaultuserroleid
);
1579 $ad['dr'] = $CFG->defaultuserroleid
;
1581 $USER->access
= $ad;
1584 if ($roleid = get_notloggedin_roleid()) {
1585 $USER->access
= get_role_access($roleid);
1586 $USER->access
['ra'][$base] = array($roleid);
1590 // Timestamp to read
1591 // dirty context timestamps
1592 $USER->access
['time'] = time();
1594 // Clear to force a refresh
1595 unset($USER->mycourses
);
1599 * A convenience function to completely reload all the capabilities
1600 * for the current user when roles have been updated in a relevant
1601 * context -- but PRESERVING switchroles and loginas.
1603 * That is - completely transparent to the user.
1605 * Note: rewrites $USER->access completely.
1608 function reload_all_capabilities() {
1611 error_log("reloading");
1614 if (isset($USER->access
['rsw'])) {
1615 $sw = $USER->access
['rsw'];
1616 error_log(print_r($sw,1));
1619 unset($USER->access
);
1620 unset($USER->mycourses
);
1622 load_all_capabilities();
1624 foreach ($sw as $path => $roleid) {
1625 $context = get_record('context', 'path', $path);
1626 role_switch($roleid, $context);
1632 * Adds a temp role to an accessdata array.
1634 * Useful for the "temporary guest" access
1635 * we grant to logged-in users.
1637 * Note - assumes a course context!
1640 function load_temp_role($context, $roleid, $ad) {
1645 // Load rdefs for the role in -
1647 // - all the parents
1648 // - and below - IOWs overrides...
1651 // turn the path into a list of context ids
1652 $contexts = substr($context->path
, 1); // kill leading slash
1653 $contexts = str_replace('/', ',', $contexts);
1655 $sql = "SELECT ctx.path,
1656 rc.capability, rc.permission
1657 FROM {$CFG->prefix}context ctx
1658 JOIN {$CFG->prefix}role_capabilities rc
1659 ON rc.contextid=ctx.id
1660 WHERE (ctx.id IN ($contexts)
1661 OR ctx.path LIKE '{$context->path}/%')
1662 AND rc.roleid = {$roleid}
1663 ORDER BY ctx.depth, ctx.path";
1664 $rs = get_recordset_sql($sql);
1665 if ($rs->RecordCount()) {
1666 while ($rd = rs_fetch_next_record($rs)) {
1667 $k = "{$rd->path}:{$roleid}";
1668 $ad['rdef'][$k][$rd->capability
] = $rd->permission
;
1674 // Say we loaded everything for the course context
1675 // - which we just did - if the user gets a proper
1676 // RA in this session, this data will need to be reloaded,
1677 // but that is handled by the complete accessdata reload
1679 array_push($ad['loaded'], $context->path
);
1684 if (isset($ad['ra'][$context->path
])) {
1685 array_push($ad['ra'][$context->path
], $roleid);
1687 $ad['ra'][$context->path
] = array($roleid);
1695 * Check all the login enrolment information for the given user object
1696 * by querying the enrolment plugins
1698 function check_enrolment_plugins(&$user) {
1701 static $inprogress; // To prevent this function being called more than once in an invocation
1703 if (!empty($inprogress[$user->id
])) {
1707 $inprogress[$user->id
] = true; // Set the flag
1709 require_once($CFG->dirroot
.'/enrol/enrol.class.php');
1711 if (!($plugins = explode(',', $CFG->enrol_plugins_enabled
))) {
1712 $plugins = array($CFG->enrol
);
1715 foreach ($plugins as $plugin) {
1716 $enrol = enrolment_factory
::factory($plugin);
1717 if (method_exists($enrol, 'setup_enrolments')) { /// Plugin supports Roles (Moodle 1.7 and later)
1718 $enrol->setup_enrolments($user);
1719 } else { /// Run legacy enrolment methods
1720 if (method_exists($enrol, 'get_student_courses')) {
1721 $enrol->get_student_courses($user);
1723 if (method_exists($enrol, 'get_teacher_courses')) {
1724 $enrol->get_teacher_courses($user);
1727 /// deal with $user->students and $user->teachers stuff
1728 unset($user->student
);
1729 unset($user->teacher
);
1734 unset($inprogress[$user->id
]); // Unset the flag
1738 * A print form function. This should either grab all the capabilities from
1739 * files or a central table for that particular module instance, then present
1740 * them in check boxes. Only relevant capabilities should print for known
1742 * @param $mod - module id of the mod
1744 function print_capabilities($modid=0) {
1747 $capabilities = array();
1750 // We are in a module specific context.
1752 // Get the mod's name.
1753 // Call the function that grabs the file and parse.
1754 $cm = get_record('course_modules', 'id', $modid);
1755 $module = get_record('modules', 'id', $cm->module
);
1758 // Print all capabilities.
1759 foreach ($capabilities as $capability) {
1760 // Prints the check box component.
1767 * Installs the roles system.
1768 * This function runs on a fresh install as well as on an upgrade from the old
1769 * hard-coded student/teacher/admin etc. roles to the new roles system.
1771 function moodle_install_roles() {
1775 /// Create a system wide context for assignemnt.
1776 $systemcontext = $context = get_context_instance(CONTEXT_SYSTEM
);
1779 /// Create default/legacy roles and capabilities.
1780 /// (1 legacy capability per legacy role at system level).
1782 $adminrole = create_role(addslashes(get_string('administrator')), 'admin',
1783 addslashes(get_string('administratordescription')), 'moodle/legacy:admin');
1784 $coursecreatorrole = create_role(addslashes(get_string('coursecreators')), 'coursecreator',
1785 addslashes(get_string('coursecreatorsdescription')), 'moodle/legacy:coursecreator');
1786 $editteacherrole = create_role(addslashes(get_string('defaultcourseteacher')), 'editingteacher',
1787 addslashes(get_string('defaultcourseteacherdescription')), 'moodle/legacy:editingteacher');
1788 $noneditteacherrole = create_role(addslashes(get_string('noneditingteacher')), 'teacher',
1789 addslashes(get_string('noneditingteacherdescription')), 'moodle/legacy:teacher');
1790 $studentrole = create_role(addslashes(get_string('defaultcoursestudent')), 'student',
1791 addslashes(get_string('defaultcoursestudentdescription')), 'moodle/legacy:student');
1792 $guestrole = create_role(addslashes(get_string('guest')), 'guest',
1793 addslashes(get_string('guestdescription')), 'moodle/legacy:guest');
1794 $userrole = create_role(addslashes(get_string('authenticateduser')), 'user',
1795 addslashes(get_string('authenticateduserdescription')), 'moodle/legacy:user');
1797 /// Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles
1799 if (!assign_capability('moodle/site:doanything', CAP_ALLOW
, $adminrole, $systemcontext->id
)) {
1800 error('Could not assign moodle/site:doanything to the admin role');
1802 if (!update_capabilities()) {
1803 error('Had trouble upgrading the core capabilities for the Roles System');
1806 /// Look inside user_admin, user_creator, user_teachers, user_students and
1807 /// assign above new roles. If a user has both teacher and student role,
1808 /// only teacher role is assigned. The assignment should be system level.
1810 $dbtables = $db->MetaTables('TABLES');
1812 /// Set up the progress bar
1814 $usertables = array('user_admins', 'user_coursecreators', 'user_teachers', 'user_students');
1816 $totalcount = $progresscount = 0;
1817 foreach ($usertables as $usertable) {
1818 if (in_array($CFG->prefix
.$usertable, $dbtables)) {
1819 $totalcount +
= count_records($usertable);
1823 print_progress(0, $totalcount, 5, 1, 'Processing role assignments');
1825 /// Upgrade the admins.
1826 /// Sort using id ASC, first one is primary admin.
1828 if (in_array($CFG->prefix
.'user_admins', $dbtables)) {
1829 if ($rs = get_recordset_sql('SELECT * from '.$CFG->prefix
.'user_admins ORDER BY ID ASC')) {
1830 while ($admin = rs_fetch_next_record($rs)) {
1831 role_assign($adminrole, $admin->userid
, 0, $systemcontext->id
);
1833 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1838 // This is a fresh install.
1842 /// Upgrade course creators.
1843 if (in_array($CFG->prefix
.'user_coursecreators', $dbtables)) {
1844 if ($rs = get_recordset('user_coursecreators')) {
1845 while ($coursecreator = rs_fetch_next_record($rs)) {
1846 role_assign($coursecreatorrole, $coursecreator->userid
, 0, $systemcontext->id
);
1848 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1855 /// Upgrade editting teachers and non-editting teachers.
1856 if (in_array($CFG->prefix
.'user_teachers', $dbtables)) {
1857 if ($rs = get_recordset('user_teachers')) {
1858 while ($teacher = rs_fetch_next_record($rs)) {
1860 // removed code here to ignore site level assignments
1861 // since the contexts are separated now
1863 // populate the user_lastaccess table
1864 $access = new object();
1865 $access->timeaccess
= $teacher->timeaccess
;
1866 $access->userid
= $teacher->userid
;
1867 $access->courseid
= $teacher->course
;
1868 insert_record('user_lastaccess', $access);
1870 // assign the default student role
1871 $coursecontext = get_context_instance(CONTEXT_COURSE
, $teacher->course
); // needs cache
1873 if ($teacher->authority
== 0) {
1879 if ($teacher->editall
) { // editting teacher
1880 role_assign($editteacherrole, $teacher->userid
, 0, $coursecontext->id
, 0, 0, $hiddenteacher);
1882 role_assign($noneditteacherrole, $teacher->userid
, 0, $coursecontext->id
, 0, 0, $hiddenteacher);
1885 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1892 /// Upgrade students.
1893 if (in_array($CFG->prefix
.'user_students', $dbtables)) {
1894 if ($rs = get_recordset('user_students')) {
1895 while ($student = rs_fetch_next_record($rs)) {
1897 // populate the user_lastaccess table
1898 $access = new object;
1899 $access->timeaccess
= $student->timeaccess
;
1900 $access->userid
= $student->userid
;
1901 $access->courseid
= $student->course
;
1902 insert_record('user_lastaccess', $access);
1904 // assign the default student role
1905 $coursecontext = get_context_instance(CONTEXT_COURSE
, $student->course
);
1906 role_assign($studentrole, $student->userid
, 0, $coursecontext->id
);
1908 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1915 /// Upgrade guest (only 1 entry).
1916 if ($guestuser = get_record('user', 'username', 'guest')) {
1917 role_assign($guestrole, $guestuser->id
, 0, $systemcontext->id
);
1919 print_progress($totalcount, $totalcount, 5, 1, 'Processing role assignments');
1922 /// Insert the correct records for legacy roles
1923 allow_assign($adminrole, $adminrole);
1924 allow_assign($adminrole, $coursecreatorrole);
1925 allow_assign($adminrole, $noneditteacherrole);
1926 allow_assign($adminrole, $editteacherrole);
1927 allow_assign($adminrole, $studentrole);
1928 allow_assign($adminrole, $guestrole);
1930 allow_assign($coursecreatorrole, $noneditteacherrole);
1931 allow_assign($coursecreatorrole, $editteacherrole);
1932 allow_assign($coursecreatorrole, $studentrole);
1933 allow_assign($coursecreatorrole, $guestrole);
1935 allow_assign($editteacherrole, $noneditteacherrole);
1936 allow_assign($editteacherrole, $studentrole);
1937 allow_assign($editteacherrole, $guestrole);
1939 /// Set up default permissions for overrides
1940 allow_override($adminrole, $adminrole);
1941 allow_override($adminrole, $coursecreatorrole);
1942 allow_override($adminrole, $noneditteacherrole);
1943 allow_override($adminrole, $editteacherrole);
1944 allow_override($adminrole, $studentrole);
1945 allow_override($adminrole, $guestrole);
1946 allow_override($adminrole, $userrole);
1949 /// Delete the old user tables when we are done
1951 drop_table(new XMLDBTable('user_students'));
1952 drop_table(new XMLDBTable('user_teachers'));
1953 drop_table(new XMLDBTable('user_coursecreators'));
1954 drop_table(new XMLDBTable('user_admins'));
1959 * Returns array of all legacy roles.
1961 function get_legacy_roles() {
1963 'admin' => 'moodle/legacy:admin',
1964 'coursecreator' => 'moodle/legacy:coursecreator',
1965 'editingteacher' => 'moodle/legacy:editingteacher',
1966 'teacher' => 'moodle/legacy:teacher',
1967 'student' => 'moodle/legacy:student',
1968 'guest' => 'moodle/legacy:guest',
1969 'user' => 'moodle/legacy:user'
1973 function get_legacy_type($roleid) {
1974 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
1975 $legacyroles = get_legacy_roles();
1978 foreach($legacyroles as $ltype=>$lcap) {
1979 $localoverride = get_local_override($roleid, $sitecontext->id
, $lcap);
1980 if (!empty($localoverride->permission
) and $localoverride->permission
== CAP_ALLOW
) {
1981 //choose first selected legacy capability - reset the rest
1982 if (empty($result)) {
1985 unassign_capability($lcap, $roleid);
1994 * Assign the defaults found in this capabality definition to roles that have
1995 * the corresponding legacy capabilities assigned to them.
1996 * @param $legacyperms - an array in the format (example):
1997 * 'guest' => CAP_PREVENT,
1998 * 'student' => CAP_ALLOW,
1999 * 'teacher' => CAP_ALLOW,
2000 * 'editingteacher' => CAP_ALLOW,
2001 * 'coursecreator' => CAP_ALLOW,
2002 * 'admin' => CAP_ALLOW
2003 * @return boolean - success or failure.
2005 function assign_legacy_capabilities($capability, $legacyperms) {
2007 $legacyroles = get_legacy_roles();
2009 foreach ($legacyperms as $type => $perm) {
2011 $systemcontext = get_context_instance(CONTEXT_SYSTEM
);
2013 if (!array_key_exists($type, $legacyroles)) {
2014 error('Incorrect legacy role definition for type: '.$type);
2017 if ($roles = get_roles_with_capability($legacyroles[$type], CAP_ALLOW
)) {
2018 foreach ($roles as $role) {
2019 // Assign a site level capability.
2020 if (!assign_capability($capability, $perm, $role->id
, $systemcontext->id
)) {
2031 * Checks to see if a capability is a legacy capability.
2032 * @param $capabilityname
2035 function islegacy($capabilityname) {
2036 if (strpos($capabilityname, 'moodle/legacy') === 0) {
2045 /**********************************
2046 * Context Manipulation functions *
2047 **********************************/
2050 * Create a new context record for use by all roles-related stuff
2051 * assumes that the caller has done the homework.
2054 * @param $instanceid
2056 * @return object newly created context
2058 function create_context($contextlevel, $instanceid) {
2062 if ($contextlevel == CONTEXT_SYSTEM
) {
2063 return create_system_context();
2066 $context = new object();
2067 $context->contextlevel
= $contextlevel;
2068 $context->instanceid
= $instanceid;
2070 // Define $context->path based on the parent
2071 // context. In other words... Who is your daddy?
2072 $basepath = '/' . SYSCONTEXTID
;
2075 switch ($contextlevel) {
2076 case CONTEXT_COURSECAT
:
2077 $sql = "SELECT ctx.path, ctx.depth
2078 FROM {$CFG->prefix}context ctx
2079 JOIN {$CFG->prefix}course_categories cc
2080 ON (cc.parent=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT
.")
2081 WHERE cc.id={$instanceid}";
2082 if ($p = get_record_sql($sql)) {
2083 $basepath = $p->path
;
2084 $basedepth = $p->depth
;
2088 case CONTEXT_COURSE
:
2089 $sql = "SELECT ctx.path, ctx.depth
2090 FROM {$CFG->prefix}context ctx
2091 JOIN {$CFG->prefix}course c
2092 ON (c.category=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT
.")
2093 WHERE c.id={$instanceid} AND c.id !=" . SITEID
;
2094 if ($p = get_record_sql($sql)) {
2095 $basepath = $p->path
;
2096 $basedepth = $p->depth
;
2100 case CONTEXT_MODULE
:
2101 $sql = "SELECT ctx.path, ctx.depth
2102 FROM {$CFG->prefix}context ctx
2103 JOIN {$CFG->prefix}course_modules cm
2104 ON (cm.course=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE
.")
2105 WHERE cm.id={$instanceid}";
2106 $p = get_record_sql($sql);
2107 $basepath = $p->path
;
2108 $basedepth = $p->depth
;
2112 // Only non-pinned & course-page based
2113 $sql = "SELECT ctx.path, ctx.depth
2114 FROM {$CFG->prefix}context ctx
2115 JOIN {$CFG->prefix}block_instance bi
2116 ON (bi.pageid=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE
.")
2117 WHERE bi.id={$instanceid} AND bi.pagetype='course-view'";
2118 if ($p = get_record_sql($sql)) {
2119 $basepath = $p->path
;
2120 $basedepth = $p->depth
;
2124 // default to basepath
2126 case CONTEXT_PERSONAL
:
2127 // default to basepath
2131 $context->depth
= $basedepth+
1;
2133 if ($id = insert_record('context',$context)) {
2134 // can't set the path till we know the id!
2135 set_field('context', 'path', $basepath . '/' . $id,
2137 $c = get_context_instance_by_id($id);
2140 debugging('Error: could not insert new context level "'.
2141 s($contextlevel).'", instance "'.
2142 s($instanceid).'".');
2148 * This hacky function is needed because we can not change system context instanceid using normal upgrade routine.
2150 function create_system_context() {
2151 if ($context = get_record('context', 'contextlevel', CONTEXT_SYSTEM
, 'instanceid', SITEID
)) {
2152 // we are going to change instanceid of system context to 0 now
2153 $context->instanceid
= 0;
2154 update_record('context', $context);
2155 //context rel not affected
2159 $context = new object();
2160 $context->contextlevel
= CONTEXT_SYSTEM
;
2161 $context->instanceid
= 0;
2162 if ($context->id
= insert_record('context',$context)) {
2165 debugging('Can not create system context');
2171 * Remove a context record and any dependent entries
2173 * @param $instanceid
2175 * @return bool properly deleted
2177 function delete_context($contextlevel, $instanceid) {
2178 if ($context = get_context_instance($contextlevel, $instanceid)) {
2179 mark_context_dirty($context->path
);
2180 return delete_records('context', 'id', $context->id
) &&
2181 delete_records('role_assignments', 'contextid', $context->id
) &&
2182 delete_records('role_capabilities', 'contextid', $context->id
);
2188 * Remove stale context records
2192 function cleanup_contexts() {
2195 $sql = " SELECT " . CONTEXT_COURSECAT
. " AS level,
2196 c.instanceid AS instanceid
2197 FROM {$CFG->prefix}context c
2198 LEFT OUTER JOIN {$CFG->prefix}course_categories AS t
2199 ON c.instanceid = t.id
2200 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_COURSECAT
. "
2202 SELECT " . CONTEXT_COURSE
. " AS level,
2203 c.instanceid AS instanceid
2204 FROM {$CFG->prefix}context c
2205 LEFT OUTER JOIN {$CFG->prefix}course AS t
2206 ON c.instanceid = t.id
2207 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_COURSE
. "
2209 SELECT " . CONTEXT_MODULE
. " AS level,
2210 c.instanceid AS instanceid
2211 FROM {$CFG->prefix}context c
2212 LEFT OUTER JOIN {$CFG->prefix}course_modules AS t
2213 ON c.instanceid = t.id
2214 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_MODULE
. "
2216 SELECT " . CONTEXT_USER
. " AS level,
2217 c.instanceid AS instanceid
2218 FROM {$CFG->prefix}context c
2219 LEFT OUTER JOIN {$CFG->prefix}user AS t
2220 ON c.instanceid = t.id
2221 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_USER
. "
2223 SELECT " . CONTEXT_BLOCK
. " AS level,
2224 c.instanceid AS instanceid
2225 FROM {$CFG->prefix}context c
2226 LEFT OUTER JOIN {$CFG->prefix}block_instance AS t
2227 ON c.instanceid = t.id
2228 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_BLOCK
. "
2230 SELECT " . CONTEXT_GROUP
. " AS level,
2231 c.instanceid AS instanceid
2232 FROM {$CFG->prefix}context c
2233 LEFT OUTER JOIN {$CFG->prefix}groups AS t
2234 ON c.instanceid = t.id
2235 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_GROUP
. "
2237 $rs = get_recordset_sql($sql);
2238 if ($rs->RecordCount()) {
2241 while ($tx && $ctx = rs_fetch_next_record($rs)) {
2242 $tx = $tx && delete_context($ctx->level
, $ctx->instanceid
);
2256 * Get the context instance as an object. This function will create the
2257 * context instance if it does not exist yet.
2258 * @param integer $level The context level, for example CONTEXT_COURSE, or CONTEXT_MODULE.
2259 * @param integer $instance The instance id. For $level = CONTEXT_COURSE, this would be $course->id,
2260 * for $level = CONTEXT_MODULE, this would be $cm->id. And so on.
2261 * @return object The context object.
2263 function get_context_instance($contextlevel=NULL, $instance=0) {
2265 global $context_cache, $context_cache_id, $CONTEXT;
2266 static $allowed_contexts = array(CONTEXT_SYSTEM
, CONTEXT_PERSONAL
, CONTEXT_USER
, CONTEXT_COURSECAT
, CONTEXT_COURSE
, CONTEXT_GROUP
, CONTEXT_MODULE
, CONTEXT_BLOCK
);
2268 if ($contextlevel === 'clearcache') {
2269 // TODO: Remove for v2.0
2270 // No longer needed, but we'll catch it to avoid erroring out on custom code.
2271 // This used to be a fix for MDL-9016
2272 // "Restoring into existing course, deleting first
2273 // deletes context and doesn't recreate it"
2277 /// If no level is supplied then return the current global context if there is one
2278 if (empty($contextlevel)) {
2279 if (empty($CONTEXT)) {
2280 //fatal error, code must be fixed
2281 error("Error: get_context_instance() called without a context");
2287 /// Backwards compatibility with obsoleted (CONTEXT_SYSTEM, SITEID)
2288 if ($contextlevel == CONTEXT_SYSTEM
) {
2292 /// check allowed context levels
2293 if (!in_array($contextlevel, $allowed_contexts)) {
2294 // fatal error, code must be fixed - probably typo or switched parameters
2295 error('Error: get_context_instance() called with incorrect context level "'.s($contextlevel).'"');
2299 if (isset($context_cache[$contextlevel][$instance])) { // Already cached
2300 return $context_cache[$contextlevel][$instance];
2303 /// Get it from the database, or create it
2304 if (!$context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance)) {
2305 create_context($contextlevel, $instance);
2306 $context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance);
2309 /// Only add to cache if context isn't empty.
2310 if (!empty($context)) {
2311 $context_cache[$contextlevel][$instance] = $context; // Cache it for later
2312 $context_cache_id[$context->id
] = $context; // Cache it for later
2320 * Get a context instance as an object, from a given context id.
2321 * @param $id a context id.
2322 * @return object The context object.
2324 function get_context_instance_by_id($id) {
2326 global $context_cache, $context_cache_id;
2328 if (isset($context_cache_id[$id])) { // Already cached
2329 return $context_cache_id[$id];
2332 if ($context = get_record('context', 'id', $id)) { // Update the cache and return
2333 $context_cache[$context->contextlevel
][$context->instanceid
] = $context;
2334 $context_cache_id[$context->id
] = $context;
2343 * Get the local override (if any) for a given capability in a role in a context
2346 * @param $capability
2348 function get_local_override($roleid, $contextid, $capability) {
2349 return get_record('role_capabilities', 'roleid', $roleid, 'capability', $capability, 'contextid', $contextid);
2354 /************************************
2355 * DB TABLE RELATED FUNCTIONS *
2356 ************************************/
2359 * function that creates a role
2360 * @param name - role name
2361 * @param shortname - role short name
2362 * @param description - role description
2363 * @param legacy - optional legacy capability
2364 * @return id or false
2366 function create_role($name, $shortname, $description, $legacy='') {
2368 // check for duplicate role name
2370 if ($role = get_record('role','name', $name)) {
2371 error('there is already a role with this name!');
2374 if ($role = get_record('role','shortname', $shortname)) {
2375 error('there is already a role with this shortname!');
2378 $role = new object();
2379 $role->name
= $name;
2380 $role->shortname
= $shortname;
2381 $role->description
= $description;
2383 //find free sortorder number
2384 $role->sortorder
= count_records('role');
2385 while (get_record('role','sortorder', $role->sortorder
)) {
2386 $role->sortorder +
= 1;
2389 if (!$context = get_context_instance(CONTEXT_SYSTEM
)) {
2393 if ($id = insert_record('role', $role)) {
2395 assign_capability($legacy, CAP_ALLOW
, $id, $context->id
);
2398 /// By default, users with role:manage at site level
2399 /// should be able to assign users to this new role, and override this new role's capabilities
2401 // find all admin roles
2402 if ($adminroles = get_roles_with_capability('moodle/role:manage', CAP_ALLOW
, $context)) {
2403 // foreach admin role
2404 foreach ($adminroles as $arole) {
2405 // write allow_assign and allow_overrid
2406 allow_assign($arole->id
, $id);
2407 allow_override($arole->id
, $id);
2419 * function that deletes a role and cleanups up after it
2420 * @param roleid - id of role to delete
2423 function delete_role($roleid) {
2427 // mdl 10149, check if this is the last active admin role
2428 // if we make the admin role not deletable then this part can go
2430 $systemcontext = get_context_instance(CONTEXT_SYSTEM
);
2432 if ($role = get_record('role', 'id', $roleid)) {
2433 if (record_exists('role_capabilities', 'contextid', $systemcontext->id
, 'roleid', $roleid, 'capability', 'moodle/site:doanything')) {
2434 // deleting an admin role
2436 if ($adminroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW
, $systemcontext)) {
2437 foreach ($adminroles as $adminrole) {
2438 if ($adminrole->id
!= $roleid) {
2439 // some other admin role
2440 if (record_exists('role_assignments', 'roleid', $adminrole->id
, 'contextid', $systemcontext->id
)) {
2441 // found another admin role with at least 1 user assigned
2448 if ($status !== true) {
2449 error ('You can not delete this role because there is no other admin roles with users assigned');
2454 // first unssign all users
2455 if (!role_unassign($roleid)) {
2456 debugging("Error while unassigning all users from role with ID $roleid!");
2460 // cleanup all references to this role, ignore errors
2463 // MDL-10679 find all contexts where this role has an override
2464 $contexts = get_records_sql("SELECT contextid, contextid
2465 FROM {$CFG->prefix}role_capabilities
2466 WHERE roleid = $roleid");
2468 delete_records('role_capabilities', 'roleid', $roleid);
2470 delete_records('role_allow_assign', 'roleid', $roleid);
2471 delete_records('role_allow_assign', 'allowassign', $roleid);
2472 delete_records('role_allow_override', 'roleid', $roleid);
2473 delete_records('role_allow_override', 'allowoverride', $roleid);
2474 delete_records('role_names', 'roleid', $roleid);
2477 // finally delete the role itself
2478 if ($success and !delete_records('role', 'id', $roleid)) {
2479 debugging("Could not delete role record with ID $roleid!");
2487 * Function to write context specific overrides, or default capabilities.
2488 * @param module - string name
2489 * @param capability - string name
2490 * @param contextid - context id
2491 * @param roleid - role id
2492 * @param permission - int 1,-1 or -1000
2493 * should not be writing if permission is 0
2495 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite=false) {
2499 if (empty($permission) ||
$permission == CAP_INHERIT
) { // if permission is not set
2500 unassign_capability($capability, $roleid, $contextid);
2504 $existing = get_record('role_capabilities', 'contextid', $contextid, 'roleid', $roleid, 'capability', $capability);
2506 if ($existing and !$overwrite) { // We want to keep whatever is there already
2511 $cap->contextid
= $contextid;
2512 $cap->roleid
= $roleid;
2513 $cap->capability
= $capability;
2514 $cap->permission
= $permission;
2515 $cap->timemodified
= time();
2516 $cap->modifierid
= empty($USER->id
) ?
0 : $USER->id
;
2519 $cap->id
= $existing->id
;
2520 return update_record('role_capabilities', $cap);
2522 $c = get_record('context', 'id', $contextid);
2523 return insert_record('role_capabilities', $cap);
2528 * Unassign a capability from a role.
2529 * @param $roleid - the role id
2530 * @param $capability - the name of the capability
2531 * @return boolean - success or failure
2533 function unassign_capability($capability, $roleid, $contextid=NULL) {
2535 if (isset($contextid)) {
2536 // delete from context rel, if this is the last override in this context
2537 $status = delete_records('role_capabilities', 'capability', $capability,
2538 'roleid', $roleid, 'contextid', $contextid);
2540 $status = delete_records('role_capabilities', 'capability', $capability,
2548 * Get the roles that have a given capability assigned to it. This function
2549 * does not resolve the actual permission of the capability. It just checks
2550 * for assignment only.
2551 * @param $capability - capability name (string)
2552 * @param $permission - optional, the permission defined for this capability
2553 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT
2554 * @return array or role objects
2556 function get_roles_with_capability($capability, $permission=NULL, $context='') {
2561 if ($contexts = get_parent_contexts($context)) {
2562 $listofcontexts = '('.implode(',', $contexts).')';
2564 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
2565 $listofcontexts = '('.$sitecontext->id
.')'; // must be site
2567 $contextstr = "AND (rc.contextid = '$context->id' OR rc.contextid IN $listofcontexts)";
2572 $selectroles = "SELECT r.*
2573 FROM {$CFG->prefix}role r,
2574 {$CFG->prefix}role_capabilities rc
2575 WHERE rc.capability = '$capability'
2576 AND rc.roleid = r.id $contextstr";
2578 if (isset($permission)) {
2579 $selectroles .= " AND rc.permission = '$permission'";
2581 return get_records_sql($selectroles);
2586 * This function makes a role-assignment (a role for a user or group in a particular context)
2587 * @param $roleid - the role of the id
2588 * @param $userid - userid
2589 * @param $groupid - group id
2590 * @param $contextid - id of the context
2591 * @param $timestart - time this assignment becomes effective
2592 * @param $timeend - time this assignemnt ceases to be effective
2594 * @return id - new id of the assigment
2596 function role_assign($roleid, $userid, $groupid, $contextid, $timestart=0, $timeend=0, $hidden=0, $enrol='manual',$timemodified='') {
2599 debugging("Assign roleid $roleid userid $userid contextid $contextid", DEBUG_DEVELOPER
);
2601 /// Do some data validation
2603 if (empty($roleid)) {
2604 debugging('Role ID not provided');
2608 if (empty($userid) && empty($groupid)) {
2609 debugging('Either userid or groupid must be provided');
2613 if ($userid && !record_exists('user', 'id', $userid)) {
2614 debugging('User ID '.intval($userid).' does not exist!');
2618 if ($groupid && !groups_group_exists($groupid)) {
2619 debugging('Group ID '.intval($groupid).' does not exist!');
2623 if (!$context = get_context_instance_by_id($contextid)) {
2624 debugging('Context ID '.intval($contextid).' does not exist!');
2628 if (($timestart and $timeend) and ($timestart > $timeend)) {
2629 debugging('The end time can not be earlier than the start time');
2633 if (!$timemodified) {
2634 $timemodified = time();
2637 /// Check for existing entry
2639 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id
, 'userid', $userid);
2641 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id
, 'groupid', $groupid);
2645 $newra = new object;
2647 if (empty($ra)) { // Create a new entry
2648 $newra->roleid
= $roleid;
2649 $newra->contextid
= $context->id
;
2650 $newra->userid
= $userid;
2651 $newra->hidden
= $hidden;
2652 $newra->enrol
= $enrol;
2653 /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
2654 /// by repeating queries with the same exact parameters in a 100 secs time window
2655 $newra->timestart
= round($timestart, -2);
2656 $newra->timeend
= $timeend;
2657 $newra->timemodified
= $timemodified;
2658 $newra->modifierid
= empty($USER->id
) ?
0 : $USER->id
;
2660 $success = insert_record('role_assignments', $newra);
2662 } else { // We already have one, just update it
2664 $newra->id
= $ra->id
;
2665 $newra->hidden
= $hidden;
2666 $newra->enrol
= $enrol;
2667 /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
2668 /// by repeating queries with the same exact parameters in a 100 secs time window
2669 $newra->timestart
= round($timestart, -2);
2670 $newra->timeend
= $timeend;
2671 $newra->timemodified
= $timemodified;
2672 $newra->modifierid
= empty($USER->id
) ?
0 : $USER->id
;
2674 $success = update_record('role_assignments', $newra);
2677 if ($success) { /// Role was assigned, so do some other things
2679 /// If the user is the current user, then reload the capabilities too.
2680 if (!empty($USER->id
) && $USER->id
== $userid) {
2681 load_all_capabilities();
2684 /// Ask all the modules if anything needs to be done for this user
2685 if ($mods = get_list_of_plugins('mod')) {
2686 foreach ($mods as $mod) {
2687 include_once($CFG->dirroot
.'/mod/'.$mod.'/lib.php');
2688 $functionname = $mod.'_role_assign';
2689 if (function_exists($functionname)) {
2690 $functionname($userid, $context, $roleid);
2696 /// now handle metacourse role assignments if in course context
2697 if ($success and $context->contextlevel
== CONTEXT_COURSE
) {
2698 if ($parents = get_records('course_meta', 'child_course', $context->instanceid
)) {
2699 foreach ($parents as $parent) {
2700 sync_metacourse($parent->parent_course
);
2710 * Deletes one or more role assignments. You must specify at least one parameter.
2715 * @param $enrol unassign only if enrolment type matches, NULL means anything
2716 * @return boolean - success or failure
2718 function role_unassign($roleid=0, $userid=0, $groupid=0, $contextid=0, $enrol=NULL) {
2724 $args = array('roleid', 'userid', 'groupid', 'contextid');
2726 foreach ($args as $arg) {
2728 $select[] = $arg.' = '.$
$arg;
2731 if (!empty($enrol)) {
2732 $select[] = "enrol='$enrol'";
2736 if ($ras = get_records_select('role_assignments', implode(' AND ', $select))) {
2737 $mods = get_list_of_plugins('mod');
2738 foreach($ras as $ra) {
2739 /// infinite loop protection when deleting recursively
2740 if (!$ra = get_record('role_assignments', 'id', $ra->id
)) {
2743 $success = delete_records('role_assignments', 'id', $ra->id
) and $success;
2745 /// If the user is the current user, then reload the capabilities too.
2746 if (!empty($USER->id
) && $USER->id
== $ra->userid
) {
2747 load_all_capabilities();
2749 $context = get_record('context', 'id', $ra->contextid
);
2751 /// Ask all the modules if anything needs to be done for this user
2752 foreach ($mods as $mod) {
2753 include_once($CFG->dirroot
.'/mod/'.$mod.'/lib.php');
2754 $functionname = $mod.'_role_unassign';
2755 if (function_exists($functionname)) {
2756 $functionname($ra->userid
, $context); // watch out, $context might be NULL if something goes wrong
2760 /// now handle metacourse role unassigment and removing from goups if in course context
2761 if (!empty($context) and $context->contextlevel
== CONTEXT_COURSE
) {
2763 // cleanup leftover course groups/subscriptions etc when user has
2764 // no capability to view course
2765 // this may be slow, but this is the proper way of doing it
2766 if (!has_capability('moodle/course:view', $context, $ra->userid
)) {
2767 // remove from groups
2768 if ($groups = groups_get_all_groups($context->instanceid
)) {
2769 foreach ($groups as $group) {
2770 delete_records('groups_members', 'groupid', $group->id
, 'userid', $ra->userid
);
2774 // delete lastaccess records
2775 delete_records('user_lastaccess', 'userid', $ra->userid
, 'courseid', $context->instanceid
);
2778 //unassign roles in metacourses if needed
2779 if ($parents = get_records('course_meta', 'child_course', $context->instanceid
)) {
2780 foreach ($parents as $parent) {
2781 sync_metacourse($parent->parent_course
);
2793 * A convenience function to take care of the common case where you
2794 * just want to enrol someone using the default role into a course
2796 * @param object $course
2797 * @param object $user
2798 * @param string $enrol - the plugin used to do this enrolment
2800 function enrol_into_course($course, $user, $enrol) {
2802 $timestart = time();
2803 // remove time part from the timestamp and keep only the date part
2804 $timestart = make_timestamp(date('Y', $timestart), date('m', $timestart), date('d', $timestart), 0, 0, 0);
2805 if ($course->enrolperiod
) {
2806 $timeend = $timestart +
$course->enrolperiod
;
2811 if ($role = get_default_course_role($course)) {
2813 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
2815 if (!role_assign($role->id
, $user->id
, 0, $context->id
, $timestart, $timeend, 0, $enrol)) {
2819 // force accessdata refresh for users visiting this context...
2820 mark_context_dirty($context->path
);
2822 email_welcome_message_to_user($course, $user);
2824 add_to_log($course->id
, 'course', 'enrol', 'view.php?id='.$course->id
, $user->id
);
2833 * Loads the capability definitions for the component (from file). If no
2834 * capabilities are defined for the component, we simply return an empty array.
2835 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2836 * @return array of capabilities
2838 function load_capability_def($component) {
2841 if ($component == 'moodle') {
2842 $defpath = $CFG->libdir
.'/db/access.php';
2843 $varprefix = 'moodle';
2845 $compparts = explode('/', $component);
2847 if ($compparts[0] == 'block') {
2848 // Blocks are an exception. Blocks directory is 'blocks', and not
2849 // 'block'. So we need to jump through hoops.
2850 $defpath = $CFG->dirroot
.'/'.$compparts[0].
2851 's/'.$compparts[1].'/db/access.php';
2852 $varprefix = $compparts[0].'_'.$compparts[1];
2854 } else if ($compparts[0] == 'format') {
2855 // Similar to the above, course formats are 'format' while they
2856 // are stored in 'course/format'.
2857 $defpath = $CFG->dirroot
.'/course/'.$component.'/db/access.php';
2858 $varprefix = $compparts[0].'_'.$compparts[1];
2860 } else if ($compparts[0] == 'gradeimport') {
2861 $defpath = $CFG->dirroot
.'/grade/import/'.$compparts[1].'/db/access.php';
2862 $varprefix = $compparts[0].'_'.$compparts[1];
2864 } else if ($compparts[0] == 'gradeexport') {
2865 $defpath = $CFG->dirroot
.'/grade/export/'.$compparts[1].'/db/access.php';
2866 $varprefix = $compparts[0].'_'.$compparts[1];
2868 } else if ($compparts[0] == 'gradereport') {
2869 $defpath = $CFG->dirroot
.'/grade/report/'.$compparts[1].'/db/access.php';
2870 $varprefix = $compparts[0].'_'.$compparts[1];
2873 $defpath = $CFG->dirroot
.'/'.$component.'/db/access.php';
2874 $varprefix = str_replace('/', '_', $component);
2877 $capabilities = array();
2879 if (file_exists($defpath)) {
2881 $capabilities = $
{$varprefix.'_capabilities'};
2883 return $capabilities;
2888 * Gets the capabilities that have been cached in the database for this
2890 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2891 * @return array of capabilities
2893 function get_cached_capabilities($component='moodle') {
2894 if ($component == 'moodle') {
2895 $storedcaps = get_records_select('capabilities',
2896 "name LIKE 'moodle/%:%'");
2898 $storedcaps = get_records_select('capabilities',
2899 "name LIKE '$component:%'");
2905 * Returns default capabilities for given legacy role type.
2907 * @param string legacy role name
2910 function get_default_capabilities($legacyrole) {
2911 if (!$allcaps = get_records('capabilities')) {
2912 error('Error: no capabilitites defined!');
2915 $defaults = array();
2916 $components = array();
2917 foreach ($allcaps as $cap) {
2918 if (!in_array($cap->component
, $components)) {
2919 $components[] = $cap->component
;
2920 $alldefs = array_merge($alldefs, load_capability_def($cap->component
));
2923 foreach($alldefs as $name=>$def) {
2924 if (isset($def['legacy'][$legacyrole])) {
2925 $defaults[$name] = $def['legacy'][$legacyrole];
2930 $defaults['moodle/legacy:'.$legacyrole] = CAP_ALLOW
;
2931 if ($legacyrole == 'admin') {
2932 $defaults['moodle/site:doanything'] = CAP_ALLOW
;
2938 * Reset role capabilitites to default according to selected legacy capability.
2939 * If several legacy caps selected, use the first from get_default_capabilities.
2940 * If no legacy selected, removes all capabilities.
2942 * @param int @roleid
2944 function reset_role_capabilities($roleid) {
2945 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
2946 $legacyroles = get_legacy_roles();
2948 $defaultcaps = array();
2949 foreach($legacyroles as $ltype=>$lcap) {
2950 $localoverride = get_local_override($roleid, $sitecontext->id
, $lcap);
2951 if (!empty($localoverride->permission
) and $localoverride->permission
== CAP_ALLOW
) {
2952 //choose first selected legacy capability
2953 $defaultcaps = get_default_capabilities($ltype);
2958 delete_records('role_capabilities', 'roleid', $roleid);
2959 if (!empty($defaultcaps)) {
2960 foreach($defaultcaps as $cap=>$permission) {
2961 assign_capability($cap, $permission, $roleid, $sitecontext->id
);
2967 * Updates the capabilities table with the component capability definitions.
2968 * If no parameters are given, the function updates the core moodle
2971 * Note that the absence of the db/access.php capabilities definition file
2972 * will cause any stored capabilities for the component to be removed from
2975 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2978 function update_capabilities($component='moodle') {
2980 $storedcaps = array();
2982 $filecaps = load_capability_def($component);
2983 $cachedcaps = get_cached_capabilities($component);
2985 foreach ($cachedcaps as $cachedcap) {
2986 array_push($storedcaps, $cachedcap->name
);
2987 // update risk bitmasks and context levels in existing capabilities if needed
2988 if (array_key_exists($cachedcap->name
, $filecaps)) {
2989 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name
])) {
2990 $filecaps[$cachedcap->name
]['riskbitmask'] = 0; // no risk if not specified
2992 if ($cachedcap->riskbitmask
!= $filecaps[$cachedcap->name
]['riskbitmask']) {
2993 $updatecap = new object();
2994 $updatecap->id
= $cachedcap->id
;
2995 $updatecap->riskbitmask
= $filecaps[$cachedcap->name
]['riskbitmask'];
2996 if (!update_record('capabilities', $updatecap)) {
3001 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name
])) {
3002 $filecaps[$cachedcap->name
]['contextlevel'] = 0; // no context level defined
3004 if ($cachedcap->contextlevel
!= $filecaps[$cachedcap->name
]['contextlevel']) {
3005 $updatecap = new object();
3006 $updatecap->id
= $cachedcap->id
;
3007 $updatecap->contextlevel
= $filecaps[$cachedcap->name
]['contextlevel'];
3008 if (!update_record('capabilities', $updatecap)) {
3016 // Are there new capabilities in the file definition?
3019 foreach ($filecaps as $filecap => $def) {
3021 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
3022 if (!array_key_exists('riskbitmask', $def)) {
3023 $def['riskbitmask'] = 0; // no risk if not specified
3025 $newcaps[$filecap] = $def;
3028 // Add new capabilities to the stored definition.
3029 foreach ($newcaps as $capname => $capdef) {
3030 $capability = new object;
3031 $capability->name
= $capname;
3032 $capability->captype
= $capdef['captype'];
3033 $capability->contextlevel
= $capdef['contextlevel'];
3034 $capability->component
= $component;
3035 $capability->riskbitmask
= $capdef['riskbitmask'];
3037 if (!insert_record('capabilities', $capability, false, 'id')) {
3042 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $storedcaps)){
3043 if ($rolecapabilities = get_records('role_capabilities', 'capability', $capdef['clonepermissionsfrom'])){
3044 foreach ($rolecapabilities as $rolecapability){
3045 //assign_capability will update rather than insert if capability exists
3046 if (!assign_capability($capname, $rolecapability->permission
,
3047 $rolecapability->roleid
, $rolecapability->contextid
, true)){
3048 notify('Could not clone capabilities for '.$capname);
3052 // Do we need to assign the new capabilities to roles that have the
3053 // legacy capabilities moodle/legacy:* as well?
3054 // we ignore legacy key if we have cloned permissions
3055 } else if (isset($capdef['legacy']) && is_array($capdef['legacy']) &&
3056 !assign_legacy_capabilities($capname, $capdef['legacy'])) {
3057 notify('Could not assign legacy capabilities for '.$capname);
3060 // Are there any capabilities that have been removed from the file
3061 // definition that we need to delete from the stored capabilities and
3062 // role assignments?
3063 capabilities_cleanup($component, $filecaps);
3070 * Deletes cached capabilities that are no longer needed by the component.
3071 * Also unassigns these capabilities from any roles that have them.
3072 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
3073 * @param $newcapdef - array of the new capability definitions that will be
3074 * compared with the cached capabilities
3075 * @return int - number of deprecated capabilities that have been removed
3077 function capabilities_cleanup($component, $newcapdef=NULL) {
3081 if ($cachedcaps = get_cached_capabilities($component)) {
3082 foreach ($cachedcaps as $cachedcap) {
3083 if (empty($newcapdef) ||
3084 array_key_exists($cachedcap->name
, $newcapdef) === false) {
3086 // Remove from capabilities cache.
3087 if (!delete_records('capabilities', 'name', $cachedcap->name
)) {
3088 error('Could not delete deprecated capability '.$cachedcap->name
);
3092 // Delete from roles.
3093 if($roles = get_roles_with_capability($cachedcap->name
)) {
3094 foreach($roles as $role) {
3095 if (!unassign_capability($cachedcap->name
, $role->id
)) {
3096 error('Could not unassign deprecated capability '.
3097 $cachedcap->name
.' from role '.$role->name
);
3104 return $removedcount;
3115 * prints human readable context identifier.
3117 function print_context_name($context, $withprefix = true, $short = false) {
3120 switch ($context->contextlevel
) {
3122 case CONTEXT_SYSTEM
: // by now it's a definite an inherit
3123 $name = get_string('coresystem');
3126 case CONTEXT_PERSONAL
:
3127 $name = get_string('personal');
3131 if ($user = get_record('user', 'id', $context->instanceid
)) {
3133 $name = get_string('user').': ';
3135 $name .= fullname($user);
3139 case CONTEXT_COURSECAT
: // Coursecat -> coursecat or site
3140 if ($category = get_record('course_categories', 'id', $context->instanceid
)) {
3142 $name = get_string('category').': ';
3144 $name .=format_string($category->name
);
3148 case CONTEXT_COURSE
: // 1 to 1 to course cat
3149 if ($course = get_record('course', 'id', $context->instanceid
)) {
3151 if ($context->instanceid
== SITEID
) {
3152 $name = get_string('site').': ';
3154 $name = get_string('course').': ';
3158 $name .=format_string($course->shortname
);
3160 $name .=format_string($course->fullname
);
3166 case CONTEXT_GROUP
: // 1 to 1 to course
3167 if ($name = groups_get_group_name($context->instanceid
)) {
3169 $name = get_string('group').': '. $name;
3174 case CONTEXT_MODULE
: // 1 to 1 to course
3175 if ($cm = get_record('course_modules','id',$context->instanceid
)) {
3176 if ($module = get_record('modules','id',$cm->module
)) {
3177 if ($mod = get_record($module->name
, 'id', $cm->instance
)) {
3179 $name = get_string('activitymodule').': ';
3181 $name .= $mod->name
;
3187 case CONTEXT_BLOCK
: // not necessarily 1 to 1 to course
3188 if ($blockinstance = get_record('block_instance','id',$context->instanceid
)) {
3189 if ($block = get_record('block','id',$blockinstance->blockid
)) {
3191 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
3192 require_once("$CFG->dirroot/blocks/$block->name/block_$block->name.php");
3193 $blockname = "block_$block->name";
3194 if ($blockobject = new $blockname()) {
3196 $name = get_string('block').': ';
3198 $name .= $blockobject->title
;
3205 error ('This is an unknown context (' . $context->contextlevel
. ') in print_context_name!');
3214 * Extracts the relevant capabilities given a contextid.
3215 * All case based, example an instance of forum context.
3216 * Will fetch all forum related capabilities, while course contexts
3217 * Will fetch all capabilities
3218 * @param object context
3222 * `name` varchar(150) NOT NULL,
3223 * `captype` varchar(50) NOT NULL,
3224 * `contextlevel` int(10) NOT NULL,
3225 * `component` varchar(100) NOT NULL,
3227 function fetch_context_capabilities($context) {
3231 $sort = 'ORDER BY contextlevel,component,id'; // To group them sensibly for display
3233 switch ($context->contextlevel
) {
3235 case CONTEXT_SYSTEM
: // all
3236 $SQL = "select * from {$CFG->prefix}capabilities";
3239 case CONTEXT_PERSONAL
:
3240 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_PERSONAL
;
3245 FROM {$CFG->prefix}capabilities
3246 WHERE contextlevel = ".CONTEXT_USER
;
3249 case CONTEXT_COURSECAT
: // all
3250 $SQL = "select * from {$CFG->prefix}capabilities";
3253 case CONTEXT_COURSE
: // all
3254 $SQL = "select * from {$CFG->prefix}capabilities";
3257 case CONTEXT_GROUP
: // group caps
3260 case CONTEXT_MODULE
: // mod caps
3261 $cm = get_record('course_modules', 'id', $context->instanceid
);
3262 $module = get_record('modules', 'id', $cm->module
);
3264 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_MODULE
."
3265 and component = 'mod/$module->name'";
3268 case CONTEXT_BLOCK
: // block caps
3269 $cb = get_record('block_instance', 'id', $context->instanceid
);
3270 $block = get_record('block', 'id', $cb->blockid
);
3272 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_BLOCK
."
3273 and ( component = 'block/$block->name' or component = 'moodle')";
3280 if (!$records = get_records_sql($SQL.' '.$sort)) {
3284 /// the rest of code is a bit hacky, think twice before modifying it :-(
3286 // special sorting of core system capabiltites and enrollments
3287 if (in_array($context->contextlevel
, array(CONTEXT_SYSTEM
, CONTEXT_COURSECAT
, CONTEXT_COURSE
))) {
3289 foreach ($records as $key=>$record) {
3290 if (preg_match('|^moodle/|', $record->name
) and $record->contextlevel
== CONTEXT_SYSTEM
) {
3291 $first[$key] = $record;
3292 unset($records[$key]);
3293 } else if (count($first)){
3297 if (count($first)) {
3298 $records = $first +
$records; // merge the two arrays keeping the keys
3301 $contextindependentcaps = fetch_context_independent_capabilities();
3302 $records = array_merge($contextindependentcaps, $records);
3311 * Gets the context-independent capabilities that should be overrridable in
3313 * @return array of capability records from the capabilities table.
3315 function fetch_context_independent_capabilities() {
3317 //only CONTEXT_SYSTEM capabilities here or it will break the hack in fetch_context_capabilities()
3318 $contextindependentcaps = array(
3319 'moodle/site:accessallgroups'
3324 foreach ($contextindependentcaps as $capname) {
3325 $record = get_record('capabilities', 'name', $capname);
3326 array_push($records, $record);
3333 * This function pulls out all the resolved capabilities (overrides and
3334 * defaults) of a role used in capability overrides in contexts at a given
3336 * @param obj $context
3337 * @param int $roleid
3338 * @param bool self - if set to true, resolve till this level, else stop at immediate parent level
3341 function role_context_capabilities($roleid, $context, $cap='') {
3344 $contexts = get_parent_contexts($context);
3345 $contexts[] = $context->id
;
3346 $contexts = '('.implode(',', $contexts).')';
3349 $search = " AND rc.capability = '$cap' ";
3355 FROM {$CFG->prefix}role_capabilities rc,
3356 {$CFG->prefix}context c
3357 WHERE rc.contextid in $contexts
3358 AND rc.roleid = $roleid
3359 AND rc.contextid = c.id $search
3360 ORDER BY c.contextlevel DESC,
3361 rc.capability DESC";
3363 $capabilities = array();
3365 if ($records = get_records_sql($SQL)) {
3366 // We are traversing via reverse order.
3367 foreach ($records as $record) {
3368 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
3369 if (!isset($capabilities[$record->capability
]) ||
$record->permission
<-500) {
3370 $capabilities[$record->capability
] = $record->permission
;
3374 return $capabilities;
3378 * Recursive function which, given a context, find all parent context ids,
3379 * and return the array in reverse order, i.e. parent first, then grand
3382 * @param object $context
3385 function get_parent_contexts($context) {
3387 if ($context->path
== '') {
3391 $parentcontexts = substr($context->path
, 1); // kill leading slash
3392 $parentcontexts = explode('/', $parentcontexts);
3393 array_pop($parentcontexts); // and remove its own id
3395 return array_reverse($parentcontexts);
3400 * Recursive function which, given a context, find all its children context ids.
3402 * When called for a course context, it will return the modules and blocks
3403 * displayed in the course page.
3405 * For course category contexts it will return categories and courses. It will
3406 * NOT recurse into courses - if you want to do that, call it on the returned
3409 * If called on a course context it _will_ populate the cache with the appropriate
3412 * @param object $context.
3413 * @return array of child records
3415 function get_child_contexts($context) {
3417 global $CFG, $context_cache;
3419 // We *MUST* populate the context_cache as the callers
3420 // will probably ask for the full record anyway soon after
3421 // soon after calling us ;-)
3423 switch ($context->contextlevel
) {
3430 case CONTEXT_MODULE
:
3440 case CONTEXT_COURSE
:
3442 // - module instances - easy
3444 // - blocks assigned to the course-view page explicitly - easy
3445 // - blocks pinned (note! we get all of them here, regardless of vis)
3446 $sql = " SELECT ctx.*
3447 FROM {$CFG->prefix}context ctx
3448 WHERE ctx.path LIKE '{$context->path}/%'
3449 AND ctx.contextlevel IN (".CONTEXT_MODULE
.",".CONTEXT_BLOCK
.")
3452 FROM {$CFG->prefix}context ctx
3453 JOIN {$CFG->prefix}groups g
3454 ON (ctx.instanceid=g.id AND ctx.contextlevel=".CONTEXT_GROUP
.")
3455 WHERE g.courseid={$context->instanceid}
3458 FROM {$CFG->prefix}context ctx
3459 JOIN {$CFG->prefix}block_pinned b
3460 ON (ctx.instanceid=b.blockid AND ctx.contextlevel=".CONTEXT_BLOCK
.")
3461 WHERE b.pagetype='course-view'
3463 $rs = get_recordset_sql($sql);
3465 if ($rs->RecordCount()) {
3466 while ($rec = rs_fetch_next_record($rs)) {
3467 $records[$rec->id
] = $rec;
3468 $context_cache[$rec->contextlevel
][$rec->instanceid
] = $rec;
3475 case CONTEXT_COURSECAT
:
3479 $sql = " SELECT ctx.*
3480 FROM {$CFG->prefix}context ctx
3481 WHERE ctx.path LIKE '{$context->path}/%'
3482 AND ctx.contextlevel IN (".CONTEXT_COURSECAT
.",".CONTEXT_COURSE
.")
3484 $rs = get_recordset_sql($sql);
3486 if ($rs->RecordCount()) {
3487 while ($rec = rs_fetch_next_record($rs)) {
3488 $records[$rec->id
] = $rec;
3489 $context_cache[$rec->contextlevel
][$rec->instanceid
] = $rec;
3501 case CONTEXT_PERSONAL
:
3506 case CONTEXT_SYSTEM
:
3507 // Just get all the contexts except for CONTEXT_SYSTEM level
3508 // and hope we don't OOM in the process - don't cache
3509 $sql = 'SELECT c.*'.
3510 'FROM '.$CFG->prefix
.'context AS c '.
3511 'WHERE contextlevel != '.CONTEXT_SYSTEM
;
3513 return get_records_sql($sql);
3517 error('This is an unknown context (' . $context->contextlevel
. ') in get_child_contexts!');
3524 * Gets a string for sql calls, searching for stuff in this context or above
3525 * @param object $context
3528 function get_related_contexts_string($context) {
3529 if ($parents = get_parent_contexts($context)) {
3530 return (' IN ('.$context->id
.','.implode(',', $parents).')');
3532 return (' ='.$context->id
);
3537 * Returns the human-readable, translated version of the capability.
3538 * Basically a big switch statement.
3539 * @param $capabilityname - e.g. mod/choice:readresponses
3541 function get_capability_string($capabilityname) {
3543 // Typical capabilityname is mod/choice:readresponses
3545 $names = split('/', $capabilityname);
3546 $stringname = $names[1]; // choice:readresponses
3547 $components = split(':', $stringname);
3548 $componentname = $components[0]; // choice
3550 switch ($names[0]) {
3552 $string = get_string($stringname, $componentname);
3556 $string = get_string($stringname, 'block_'.$componentname);
3560 $string = get_string($stringname, 'role');
3564 $string = get_string($stringname, 'enrol_'.$componentname);
3568 $string = get_string($stringname, 'format_'.$componentname);
3572 $string = get_string($stringname, 'gradeexport_'.$componentname);
3576 $string = get_string($stringname, 'gradeimport_'.$componentname);
3580 $string = get_string($stringname, 'gradereport_'.$componentname);
3584 $string = get_string($stringname);
3593 * This gets the mod/block/course/core etc strings.
3595 * @param $contextlevel
3597 function get_component_string($component, $contextlevel) {
3599 switch ($contextlevel) {
3601 case CONTEXT_SYSTEM
:
3602 if (preg_match('|^enrol/|', $component)) {
3603 $langname = str_replace('/', '_', $component);
3604 $string = get_string('enrolname', $langname);
3605 } else if (preg_match('|^block/|', $component)) {
3606 $langname = str_replace('/', '_', $component);
3607 $string = get_string('blockname', $langname);
3609 $string = get_string('coresystem');
3613 case CONTEXT_PERSONAL
:
3614 $string = get_string('personal');
3618 $string = get_string('users');
3621 case CONTEXT_COURSECAT
:
3622 $string = get_string('categories');
3625 case CONTEXT_COURSE
:
3626 if (preg_match('|^gradeimport/|', $component)
3627 ||
preg_match('|^gradeexport/|', $component)
3628 ||
preg_match('|^gradereport/|', $component)) {
3629 $string = get_string('gradebook', 'admin');
3631 $string = get_string('course');
3636 $string = get_string('group');
3639 case CONTEXT_MODULE
:
3640 $string = get_string('modulename', basename($component));
3644 if( $component == 'moodle' ){
3645 $string = get_string('block');
3647 $string = get_string('blockname', 'block_'.basename($component));
3652 error ('This is an unknown context $contextlevel (' . $contextlevel . ') in get_component_string!');
3660 * Gets the list of roles assigned to this context and up (parents)
3661 * @param object $context
3662 * @param view - set to true when roles are pulled for display only
3663 * this is so that we can filter roles with no visible
3664 * assignment, for example, you might want to "hide" all
3665 * course creators when browsing the course participants
3669 function get_roles_used_in_context($context, $view = false) {
3673 // filter for roles with all hidden assignments
3674 // no need to return when only pulling roles for reviewing
3675 // e.g. participants page.
3676 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))?
' AND ra.hidden = 0 ':'';
3677 $contextlist = get_related_contexts_string($context);
3679 $sql = "SELECT DISTINCT r.id,
3683 FROM {$CFG->prefix}role_assignments ra,
3684 {$CFG->prefix}role r
3685 WHERE r.id = ra.roleid
3686 AND ra.contextid $contextlist
3688 ORDER BY r.sortorder ASC";
3690 return get_records_sql($sql);
3693 /** this function is used to print roles column in user profile page.
3695 * @param int contextid
3698 function get_user_roles_in_context($userid, $contextid){
3702 $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';
3703 if ($roles = get_records_sql($SQL)) {
3704 foreach ($roles as $userrole) {
3705 $rolestring .= '<a href="'.$CFG->wwwroot
.'/user/index.php?contextid='.$userrole->contextid
.'&roleid='.$userrole->roleid
.'">'.$userrole->name
.'</a>, ';
3709 return rtrim($rolestring, ', ');
3714 * Checks if a user can override capabilities of a particular role in this context
3715 * @param object $context
3716 * @param int targetroleid - the id of the role you want to override
3719 function user_can_override($context, $targetroleid) {
3720 // first check if user has override capability
3721 // if not return false;
3722 if (!has_capability('moodle/role:override', $context)) {
3725 // pull out all active roles of this user from this context(or above)
3726 if ($userroles = get_user_roles($context)) {
3727 foreach ($userroles as $userrole) {
3728 // if any in the role_allow_override table, then it's ok
3729 if (get_record('role_allow_override', 'roleid', $userrole->roleid
, 'allowoverride', $targetroleid)) {
3740 * Checks if a user can assign users to a particular role in this context
3741 * @param object $context
3742 * @param int targetroleid - the id of the role you want to assign users to
3745 function user_can_assign($context, $targetroleid) {
3747 // first check if user has override capability
3748 // if not return false;
3749 if (!has_capability('moodle/role:assign', $context)) {
3752 // pull out all active roles of this user from this context(or above)
3753 if ($userroles = get_user_roles($context)) {
3754 foreach ($userroles as $userrole) {
3755 // if any in the role_allow_override table, then it's ok
3756 if (get_record('role_allow_assign', 'roleid', $userrole->roleid
, 'allowassign', $targetroleid)) {
3765 /** Returns all site roles in correct sort order.
3768 function get_all_roles() {
3769 return get_records('role', '', '', 'sortorder ASC');
3773 * gets all the user roles assigned in this context, or higher contexts
3774 * this is mainly used when checking if a user can assign a role, or overriding a role
3775 * i.e. we need to know what this user holds, in order to verify against allow_assign and
3776 * allow_override tables
3777 * @param object $context
3778 * @param int $userid
3779 * @param view - set to true when roles are pulled for display only
3780 * this is so that we can filter roles with no visible
3781 * assignment, for example, you might want to "hide" all
3782 * course creators when browsing the course participants
3786 function get_user_roles($context, $userid=0, $checkparentcontexts=true, $order='c.contextlevel DESC, r.sortorder ASC', $view=false) {
3788 global $USER, $CFG, $db;
3790 if (empty($userid)) {
3791 if (empty($USER->id
)) {
3794 $userid = $USER->id
;
3796 // set up hidden sql
3797 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))?
' AND ra.hidden = 0 ':'';
3799 if ($checkparentcontexts && ($parents = get_parent_contexts($context))) {
3800 $contexts = ' ra.contextid IN ('.implode(',' , $parents).','.$context->id
.')';
3802 $contexts = ' ra.contextid = \''.$context->id
.'\'';
3805 return get_records_sql('SELECT ra.*, r.name, r.shortname
3806 FROM '.$CFG->prefix
.'role_assignments ra,
3807 '.$CFG->prefix
.'role r,
3808 '.$CFG->prefix
.'context c
3809 WHERE ra.userid = '.$userid.
3810 ' AND ra.roleid = r.id
3811 AND ra.contextid = c.id
3812 AND '.$contexts . $hiddensql .
3813 ' ORDER BY '.$order);
3817 * Creates a record in the allow_override table
3818 * @param int sroleid - source roleid
3819 * @param int troleid - target roleid
3820 * @return int - id or false
3822 function allow_override($sroleid, $troleid) {
3823 $record = new object();
3824 $record->roleid
= $sroleid;
3825 $record->allowoverride
= $troleid;
3826 return insert_record('role_allow_override', $record);
3830 * Creates a record in the allow_assign table
3831 * @param int sroleid - source roleid
3832 * @param int troleid - target roleid
3833 * @return int - id or false
3835 function allow_assign($sroleid, $troleid) {
3836 $record = new object;
3837 $record->roleid
= $sroleid;
3838 $record->allowassign
= $troleid;
3839 return insert_record('role_allow_assign', $record);
3843 * Gets a list of roles that this user can assign in this context
3844 * @param object $context
3845 * @param string $field
3848 function get_assignable_roles ($context, $field="name") {
3853 $ras = get_user_roles($context);
3855 foreach ($ras as $ra) {
3856 $roleids[] = $ra->roleid
;
3860 if (count($roleids)===0) {
3864 $roleids = implode(',',$roleids);
3866 // The subselect scopes the DISTINCT down to
3867 // the role ids - a DISTINCT over the whole of
3868 // the role table is much more expensive on some DBs
3869 $sql = "SELECT r.id, r.$field
3870 FROM {$CFG->prefix}role r
3871 JOIN ( SELECT DISTINCT allowassign as allowedrole
3872 FROM {$CFG->prefix}role_allow_assign raa
3873 WHERE raa.roleid IN ($roleids) ) ar
3874 ON r.id=ar.allowedrole
3875 ORDER BY sortorder ASC";
3877 $rs = get_recordset_sql($sql);
3879 if ($rs->RecordCount()) {
3880 while ($r = rs_fetch_next_record($rs)) {
3881 $roles[$r->id
] = $r->{$field};
3888 * Gets a list of roles that this user can override in this context
3889 * @param object $context
3892 function get_overridable_roles($context) {
3896 if ($roles = get_all_roles()) {
3897 foreach ($roles as $role) {
3898 if (user_can_override($context, $role->id
)) {
3899 $options[$role->id
] = strip_tags(format_string($role->name
, true));
3908 * Returns a role object that is the default role for new enrolments
3911 * @param object $course
3912 * @return object $role
3914 function get_default_course_role($course) {
3917 /// First let's take the default role the course may have
3918 if (!empty($course->defaultrole
)) {
3919 if ($role = get_record('role', 'id', $course->defaultrole
)) {
3924 /// Otherwise the site setting should tell us
3925 if ($CFG->defaultcourseroleid
) {
3926 if ($role = get_record('role', 'id', $CFG->defaultcourseroleid
)) {
3931 /// It's unlikely we'll get here, but just in case, try and find a student role
3932 if ($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW
)) {
3933 return array_shift($studentroles); /// Take the first one
3941 * who has this capability in this context
3942 * does not handling user level resolving!!!
3943 * (!)pleaes note if $fields is empty this function attempts to get u.*
3944 * which can get rather large.
3945 * i.e 1 person has 2 roles 1 allow, 1 prevent, this will not work properly
3946 * @param $context - object
3947 * @param $capability - string capability
3948 * @param $fields - fields to be pulled
3949 * @param $sort - the sort order
3950 * @param $limitfrom - number of records to skip (offset)
3951 * @param $limitnum - number of records to fetch
3952 * @param $groups - single group or array of groups - only return
3953 * users who are in one of these group(s).
3954 * @param $exceptions - list of users to exclude
3955 * @param view - set to true when roles are pulled for display only
3956 * this is so that we can filter roles with no visible
3957 * assignment, for example, you might want to "hide" all
3958 * course creators when browsing the course participants
3960 * @param boolean $useviewallgroups if $groups is set the return users who
3961 * have capability both $capability and moodle/site:accessallgroups
3962 * in this context, as well as users who have $capability and who are
3965 function get_users_by_capability($context, $capability, $fields='', $sort='',
3966 $limitfrom='', $limitnum='', $groups='', $exceptions='', $doanything=true,
3967 $view=false, $useviewallgroups=false) {
3970 /// Sorting out groups
3972 if (is_array($groups)) {
3973 $grouptest = 'gm.groupid IN (' . implode(',', $groups) . ')';
3975 $grouptest = 'gm.groupid = ' . $groups;
3977 $grouptest = 'ra.userid IN (SELECT userid FROM ' .
3978 $CFG->prefix
. 'groups_members gm WHERE ' . $grouptest . ')';
3980 if ($useviewallgroups) {
3981 $viewallgroupsusers = get_users_by_capability($context,
3982 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
3983 $groupsql = ' AND (' . $grouptest . ' OR ra.userid IN (' .
3984 implode(',', array_keys($viewallgroupsusers)) . '))';
3986 $groupsql = ' AND ' . $grouptest;
3992 /// Sorting out exceptions
3993 $exceptionsql = $exceptions ?
"AND u.id NOT IN ($exceptions)" : '';
3995 /// Set up default fields
3996 if (empty($fields)) {
3997 $fields = 'u.*, ul.timeaccess as lastaccess, ra.hidden';
4000 /// Set up default sort
4002 $sort = 'ul.timeaccess';
4005 $sortby = $sort ?
" ORDER BY $sort " : '';
4006 /// Set up hidden sql
4007 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))?
' AND ra.hidden = 0 ':'';
4009 /// If context is a course, then construct sql for ul
4010 if ($context->contextlevel
== CONTEXT_COURSE
) {
4011 $courseid = $context->instanceid
;
4012 $coursesql1 = "AND ul.courseid = $courseid";
4017 /// Sorting out roles with this capability set
4018 if ($possibleroles = get_roles_with_capability($capability, CAP_ALLOW
, $context)) {
4020 if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM
)) {
4021 return false; // Something is seriously wrong
4023 $doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW
, $sitecontext);
4026 $validroleids = array();
4027 foreach ($possibleroles as $possiblerole) {
4029 if (isset($doanythingroles[$possiblerole->id
])) { // We don't want these included
4033 if ($caps = role_context_capabilities($possiblerole->id
, $context, $capability)) { // resolved list
4034 if (isset($caps[$capability]) && $caps[$capability] > 0) { // resolved capability > 0
4035 $validroleids[] = $possiblerole->id
;
4039 if (empty($validroleids)) {
4042 $roleids = '('.implode(',', $validroleids).')';
4044 return false; // No need to continue, since no roles have this capability set
4047 /// Construct the main SQL
4048 $select = " SELECT $fields";
4049 $from = " FROM {$CFG->prefix}user u
4050 INNER JOIN {$CFG->prefix}role_assignments ra ON ra.userid = u.id
4051 INNER JOIN {$CFG->prefix}role r ON r.id = ra.roleid
4052 LEFT OUTER JOIN {$CFG->prefix}user_lastaccess ul ON (ul.userid = u.id $coursesql1)";
4053 $where = " WHERE ra.contextid ".get_related_contexts_string($context)."
4055 AND ra.roleid in $roleids
4060 return get_records_sql($select.$from.$where.$sortby, $limitfrom, $limitnum);
4064 * gets all the users assigned this role in this context or higher
4065 * @param int roleid (can also be an array of ints!)
4066 * @param int contextid
4067 * @param bool parent if true, get list of users assigned in higher context too
4068 * @param string fields - fields from user (u.) , role assignment (ra) or role (r.)
4069 * @param string sort - sort from user (u.) , role assignment (ra) or role (r.)
4070 * @param bool gethidden - whether to fetch hidden enrolments too
4073 function get_role_users($roleid, $context, $parent=false, $fields='', $sort='u.lastname ASC', $gethidden=true) {
4076 if (empty($fields)) {
4077 $fields = 'u.id, u.confirmed, u.username, u.firstname, u.lastname, '.
4078 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.city, '.
4079 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
4080 'u.emailstop, u.lang, u.timezone, r.name as rolename';
4083 // whether this assignment is hidden
4084 $hiddensql = $gethidden ?
'': ' AND ra.hidden = 0 ';
4086 $parentcontexts = '';
4088 $parentcontexts = substr($context->path
, 1); // kill leading slash
4089 $parentcontexts = str_replace('/', ',', $parentcontexts);
4090 if ($parentcontexts !== '') {
4091 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
4095 if (is_array($roleid)) {
4096 $roleselect = ' AND ra.roleid IN (' . implode(',',$roleid) .')';
4097 } elseif (is_int($roleid)) {
4098 $roleselect = "AND ra.roleid = $roleid";
4104 $groupjoin = "JOIN {$CFG->prefix}groups_members gm
4105 ON gm.userid = u.id";
4106 $groupselect = " AND gm.groupid = $group ";
4112 $SQL = "SELECT $fields, ra.roleid
4113 FROM {$CFG->prefix}role_assignments ra
4114 JOIN {$CFG->prefix}user u
4116 JOIN {$CFG->prefix}role r
4119 WHERE (ra.contextid = $context->id $parentcontexts)
4124 "; // join now so that we can just use fullname() later
4125 return get_records_sql($SQL);
4129 * Counts all the users assigned this role in this context or higher
4131 * @param int contextid
4132 * @param bool parent if true, get list of users assigned in higher context too
4135 function count_role_users($roleid, $context, $parent=false) {
4139 if ($contexts = get_parent_contexts($context)) {
4140 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
4142 $parentcontexts = '';
4145 $parentcontexts = '';
4148 $SQL = "SELECT count(*)
4149 FROM {$CFG->prefix}role_assignments r
4150 WHERE (r.contextid = $context->id $parentcontexts)
4151 AND r.roleid = $roleid";
4153 return count_records_sql($SQL);
4157 * This function gets the list of courses that this user has a particular capability in.
4158 * It is still not very efficient.
4159 * @param string $capability Capability in question
4160 * @param int $userid User ID or null for current user
4161 * @param bool $doanything True if 'doanything' is permitted (default)
4162 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
4163 * otherwise use a comma-separated list of the fields you require, not including id
4164 * @param string $orderby If set, use a comma-separated list of fields from course
4165 * table with sql modifiers (DESC) if needed
4166 * @return array Array of courses, may have zero entries. Or false if query failed.
4168 function get_user_capability_course($capability, $userid=NULL,$doanything=true,$fieldsexceptid='',$orderby='') {
4169 // Convert fields list and ordering
4171 if($fieldsexceptid) {
4172 $fields=explode(',',$fieldsexceptid);
4173 foreach($fields as $field) {
4174 $fieldlist.=',c.'.$field;
4178 $fields=explode(',',$orderby);
4180 foreach($fields as $field) {
4184 $orderby.='c.'.$field;
4186 $orderby='ORDER BY '.$orderby;
4189 // Obtain a list of everything relevant about all courses including context.
4190 // Note the result can be used directly as a context (we are going to), the course
4191 // fields are just appended.
4193 $rs=get_recordset_sql("
4195 x.*,c.id AS courseid$fieldlist
4197 {$CFG->prefix}course c
4198 INNER JOIN {$CFG->prefix}context x ON c.id=x.instanceid AND x.contextlevel=".CONTEXT_COURSE
."
4205 // Check capability for each course in turn
4207 while($coursecontext=rs_fetch_next_record($rs)) {
4208 if(has_capability($capability,$coursecontext,$userid,$doanything)) {
4209 // We've got the capability. Make the record look like a course record
4211 $coursecontext->id
=$coursecontext->courseid
;
4212 unset($coursecontext->courseid
);
4213 unset($coursecontext->contextlevel
);
4214 unset($coursecontext->instanceid
);
4215 $courses[]=$coursecontext;
4221 /** This function finds the roles assigned directly to this context only
4222 * i.e. no parents role
4223 * @param object $context
4226 function get_roles_on_exact_context($context) {
4230 return get_records_sql("SELECT r.*
4231 FROM {$CFG->prefix}role_assignments ra,
4232 {$CFG->prefix}role r
4233 WHERE ra.roleid = r.id
4234 AND ra.contextid = $context->id");
4239 * Switches the current user to another role for the current session and only
4240 * in the given context.
4242 * The caller *must* check
4243 * - that this op is allowed
4244 * - that the requested role can be assigned in this ctx
4245 * (hint, use get_assignable_roles())
4246 * - that the requested role is NOT $CFG->defaultuserroleid
4248 * To "unswitch" pass 0 as the roleid.
4250 * This function *will* modify $USER->access - beware
4252 * @param integer $roleid
4253 * @param object $context
4256 function role_switch($roleid, $context) {
4262 // - Add the ghost RA to $USER->access
4263 // as $USER->access['rsw'][$path] = $roleid
4265 // - Make sure $USER->access['rdef'] has the roledefs
4266 // it needs to honour the switcheroo
4268 // Roledefs will get loaded "deep" here - down to the last child
4269 // context. Note that
4271 // - When visiting subcontexts, our selective accessdata loading
4272 // will still work fine - though those ra/rdefs will be ignored
4273 // appropriately while the switch is in place
4275 // - If a switcheroo happens at a category with tons of courses
4276 // (that have many overrides for switched-to role), the session
4277 // will get... quite large. Sometimes you just can't win.
4279 // To un-switch just unset($USER->access['rsw'][$path])
4282 // Add the switch RA
4283 if (!isset($USER->access
['rsw'])) {
4284 $USER->access
['rsw'] = array();
4288 unset($USER->access
['rsw'][$context->path
]);
4289 if (empty($USER->access
['rsw'])) {
4290 unset($USER->access
['rsw']);
4295 $USER->access
['rsw'][$context->path
]=$roleid;
4298 $USER->access
= get_role_access_bycontext($roleid, $context,
4301 /* DO WE NEED THIS AT ALL???
4302 // Add some permissions we are really going
4303 // to always need, even if the role doesn't have them!
4305 $USER->capabilities[$context->id]['moodle/course:view'] = CAP_ALLOW;
4312 // get any role that has an override on exact context
4313 function get_roles_with_override_on_context($context) {
4317 return get_records_sql("SELECT r.*
4318 FROM {$CFG->prefix}role_capabilities rc,
4319 {$CFG->prefix}role r
4320 WHERE rc.roleid = r.id
4321 AND rc.contextid = $context->id");
4324 // get all capabilities for this role on this context (overrids)
4325 function get_capabilities_from_role_on_context($role, $context) {
4329 return get_records_sql("SELECT *
4330 FROM {$CFG->prefix}role_capabilities
4331 WHERE contextid = $context->id
4332 AND roleid = $role->id");
4335 // find out which roles has assignment on this context
4336 function get_roles_with_assignment_on_context($context) {
4340 return get_records_sql("SELECT r.*
4341 FROM {$CFG->prefix}role_assignments ra,
4342 {$CFG->prefix}role r
4343 WHERE ra.roleid = r.id
4344 AND ra.contextid = $context->id");
4350 * Find all user assignemnt of users for this role, on this context
4352 function get_users_from_role_on_context($role, $context) {
4356 return get_records_sql("SELECT *
4357 FROM {$CFG->prefix}role_assignments
4358 WHERE contextid = $context->id
4359 AND roleid = $role->id");
4363 * Simple function returning a boolean true if roles exist, otherwise false
4365 function user_has_role_assignment($userid, $roleid, $contextid=0) {
4368 return record_exists('role_assignments', 'userid', $userid, 'roleid', $roleid, 'contextid', $contextid);
4370 return record_exists('role_assignments', 'userid', $userid, 'roleid', $roleid);
4374 // gets the custom name of the role in course
4375 // TODO: proper documentation
4376 function role_get_name($role, $context) {
4378 if ($r = get_record('role_names','roleid', $role->id
,'contextid', $context->id
)) {
4379 return format_string($r->text
);
4381 return format_string($role->name
);
4386 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
4387 * when we read in a new capability
4388 * most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
4389 * but when we are in grade, all reports/import/export capabilites should be together
4390 * @param string a - component string a
4391 * @param string b - component string b
4392 * @return bool - whether 2 component are in different "sections"
4394 function component_level_changed($cap, $comp, $contextlevel) {
4396 if ($cap->component
== 'enrol/authorize' && $comp =='enrol/authorize') {
4400 if (strstr($cap->component
, '/') && strstr($comp, '/')) {
4401 $compsa = explode('/', $cap->component
);
4402 $compsb = explode('/', $comp);
4406 // we are in gradebook, still
4407 if (($compsa[0] == 'gradeexport' ||
$compsa[0] == 'gradeimport' ||
$compsa[0] == 'gradereport') &&
4408 ($compsb[0] == 'gradeexport' ||
$compsb[0] == 'gradeimport' ||
$compsb[0] == 'gradereport')) {
4413 return ($cap->component
!= $comp ||
$cap->contextlevel
!= $contextlevel);
4417 * Populate context.path and context.depth where missing.
4419 * Use $force=true to force a complete rebuild of
4420 * the path and depth fields.
4423 function build_context_path($force=false) {
4427 $sitectx = get_record('context', 'contextlevel', CONTEXT_SYSTEM
);
4428 $base = '/' . $sitectx->id
;
4430 if ($force ||
$sitectx->path
!== $base) {
4431 set_field('context', 'path', $base, 'id', $sitectx->id
);
4432 set_field('context', 'depth', 1, 'id', $sitectx->id
);
4433 $sitectx = get_record('context', 'contextlevel', CONTEXT_SYSTEM
);
4437 $sitecoursectx = get_record('context',
4438 'contextlevel', CONTEXT_COURSE
,
4439 'instanceid', SITEID
);
4440 if ($force ||
$sitecoursectx->path
!== "$base/{$sitecoursectx->id}") {
4441 set_field('context', 'path', "$base/{$sitecoursectx->id}",
4442 'id', $sitecoursectx->id
);
4443 set_field('context', 'depth', 2,
4444 'id', $sitecoursectx->id
);
4445 $sitecoursectx = get_record('context',
4446 'contextlevel', CONTEXT_COURSE
,
4447 'instanceid', SITEID
);
4450 $emptyclause = " AND path=''";
4451 if ($CFG->dbtype
==='oci8po') { // DIRTYHACK - everybody loves Oracle ;-)
4452 $emptyclause = " AND path=' '";
4457 // Top level categories
4458 $sql = "UPDATE {$CFG->prefix}context
4459 SET depth=2, path=" . sql_concat("'$base/'", 'id') . "
4460 WHERE contextlevel=".CONTEXT_COURSECAT
."
4463 FROM {$CFG->prefix}course_categories
4464 WHERE depth=1 $emptyclause )";
4465 execute_sql($sql, false);
4467 // Deeper categories - one query per depthlevel
4468 $maxdepth = get_field_sql("SELECT MAX(depth)
4469 FROM {$CFG->prefix}course_categories");
4470 for ($n=2;$n<=$maxdepth;$n++
) {
4471 $sql = "UPDATE {$CFG->prefix}context
4472 SET depth=$n+1, path=" . sql_concat('it.ppath', "'/'", 'id') . "
4473 FROM (SELECT c.id AS instanceid, pctx.path AS ppath
4474 FROM {$CFG->prefix}course_categories c
4475 JOIN {$CFG->prefix}context pctx
4476 ON (c.parent=pctx.instanceid
4477 AND pctx.contextlevel=".CONTEXT_COURSECAT
.")
4478 WHERE c.depth=$n) it
4479 WHERE contextlevel=".CONTEXT_COURSECAT
."
4480 AND {$CFG->prefix}context.instanceid=it.instanceid
4482 execute_sql($sql, false);
4485 // Courses -- except sitecourse
4486 $sql = "UPDATE {$CFG->prefix}context
4487 SET depth=it.pdepth+1, path=" . sql_concat('it.ppath', "'/'", 'id') . "
4488 FROM (SELECT c.id AS instanceid, pctx.path AS ppath,
4489 pctx.depth as pdepth
4490 FROM {$CFG->prefix}course c
4491 JOIN {$CFG->prefix}context pctx
4492 ON (c.category=pctx.instanceid
4493 AND pctx.contextlevel=".CONTEXT_COURSECAT
.")
4494 WHERE c.id != ".SITEID
.") it
4495 WHERE contextlevel=".CONTEXT_COURSE
."
4496 AND {$CFG->prefix}context.instanceid=it.instanceid
4498 execute_sql($sql, false);
4501 $sql = "UPDATE {$CFG->prefix}context
4502 SET depth=it.pdepth+1, path=" . sql_concat('it.ppath', "'/'", 'id') . "
4503 FROM (SELECT cm.id AS instanceid, pctx.path AS ppath,
4504 pctx.depth as pdepth
4505 FROM {$CFG->prefix}course_modules cm
4506 JOIN {$CFG->prefix}context pctx
4507 ON (cm.course=pctx.instanceid
4508 AND pctx.contextlevel=".CONTEXT_COURSE
.")
4510 WHERE contextlevel=".CONTEXT_MODULE
."
4511 AND {$CFG->prefix}context.instanceid=it.instanceid
4513 execute_sql($sql, false);
4515 // Blocks - non-pinned only
4516 $sql = "UPDATE {$CFG->prefix}context
4517 SET depth=it.pdepth+1, path=" . sql_concat('it.ppath', "'/'", 'id') . "
4518 FROM (SELECT bi.id AS instanceid, pctx.path AS ppath,
4519 pctx.depth as pdepth
4520 FROM {$CFG->prefix}block_instance bi
4521 JOIN {$CFG->prefix}context pctx
4522 ON (bi.pageid=pctx.instanceid
4523 AND bi.pagetype='course-view'
4524 AND pctx.contextlevel=".CONTEXT_COURSE
.")
4526 WHERE contextlevel=".CONTEXT_BLOCK
."
4527 AND {$CFG->prefix}context.instanceid=it.instanceid
4529 execute_sql($sql, false);
4532 $sql = "UPDATE {$CFG->prefix}context
4533 SET depth=2, path=".sql_concat("'$base/'", 'id')."
4534 WHERE contextlevel=".CONTEXT_USER
."
4535 AND instanceid IN (SELECT id
4536 FROM {$CFG->prefix}user)
4538 execute_sql($sql, false);
4545 * Update the path field of the context and
4546 * all the dependent subcontexts that follow
4549 * The most important thing here is to be as
4550 * DB efficient as possible. This op can have a
4551 * massive impact in the DB.
4553 * @param obj current context obj
4554 * @param obj newparent new parent obj
4557 function context_moved($context, $newparent) {
4560 $frompath = $context->path
;
4561 $newpath = $newparent->path
. '/' . $context->id
;
4564 if (($newparent->depth +
1) != $context->depth
) {
4565 $setdepth = ", depth= depth + ({$newparent->depth} - {$context->depth}) + 1";
4567 $sql = "UPDATE {$CFG->prefix}context
4570 WHERE path='$frompath'";
4571 execute_sql($sql,false);
4573 $len = strlen($frompath);
4574 $sql = "UPDATE {$CFG->prefix}context
4575 SET path = ".sql_concat("'$newpath'", 'SUBSTR(path, {$len} +1)')."
4577 WHERE path LIKE '{$frompath}/%'";
4578 execute_sql($sql,false);
4580 mark_context_dirty($frompath);
4581 mark_context_dirty($newpath);
4586 * Turn the ctx* fields in an objectlike record
4587 * into a context subobject. This allows
4588 * us to SELECT from major tables JOINing with
4589 * context at no cost, saving a ton of context
4592 function make_context_subobj($rec) {
4593 $ctx = new StdClass
;
4594 $ctx->id
= $rec->ctxid
; unset($rec->ctxid
);
4595 $ctx->path
= $rec->ctxpath
; unset($rec->ctxpath
);
4596 $ctx->depth
= $rec->ctxdepth
; unset($rec->ctxdepth
);
4597 $ctx->instanceid
= $rec->id
;
4598 $ctx->contextlevel
= CONTEXT_COURSE
;
4599 $rec->context
= $ctx;
4604 * Fetch recent dirty contexts to know cheaply whether our $USER->access
4605 * is stale and needs to be reloaded.
4607 * Uses config_plugins.
4610 function get_dirty_contexts($time) {
4613 $sql = "SELECT name, value
4614 FROM {$CFG->prefix}config_plugins
4615 WHERE plugin='accesslib/dirtycontexts'
4616 AND CAST(value AS DECIMAL) > $time";
4617 if ($ctx = get_records_sql($sql)) {
4624 * Mark a context as dirty (with timestamp)
4625 * so as to force reloading of the context.
4628 function mark_context_dirty($path) {
4630 // only if it is a non-empty string
4631 if (is_string($path) && $path !== '') {
4632 // The timestamp is 2s in the past to cover for
4633 // - race conditions within the 1s granularity
4634 // - very small clock offsets in clusters (use ntpd!)
4635 set_config($path, time()-2, 'accesslib/dirtycontexts');
4640 * Cleanup all the old/stale dirty contexts.
4641 * Any context exceeding our session
4642 * timeout is stale. We only keep these for ongoing
4646 function cleanup_dirty_contexts() {
4649 $sql = "plugin='accesslib/dirtycontexts' AND
4650 CAST(value AS DECIMAL) < " . time() - $CFG->sessiontimeout
;
4651 delete_records_select('config_plugins', $sql);
4655 * Will walk the contextpath to answer whether
4656 * the contextpath is clean
4658 * NOTE: it will *NOT* test the base path
4659 * as it assumes that the caller has checked
4662 * @param string path
4663 * @param obj/array dirty from get_dirty_contexts()
4666 function is_contextpath_clean($path, $dirty) {
4668 $basepath = '/' . SYSCONTEXTID
;
4670 // all clean, no dirt!
4671 if (count($dirty) === 0) {
4675 // is _this_ context dirty?
4676 if (isset($dirty[$path])) {
4679 while (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
4680 $path = $matches[1];
4681 if ($path === $basepath) {
4682 // we don't test basepath
4683 // assume caller did it already
4686 if (isset($dirty[$path])) {