3 * Capability session information format
5 * [context][capability]
6 * where context is the context id of the table 'context'
7 * and capability is a string defining the capability
10 * [Capabilities] => [26][mod/forum:viewpost] = 1
11 * [26][mod/forum:startdiscussion] = -8990
12 * [26][mod/forum:editallpost] = -1
13 * [273][moodle:blahblah] = 1
14 * [273][moodle:blahblahblah] = 2
17 require_once $CFG->dirroot
.'/lib/blocklib.php';
19 // permission definitions
20 define('CAP_INHERIT', 0);
21 define('CAP_ALLOW', 1);
22 define('CAP_PREVENT', -1);
23 define('CAP_PROHIBIT', -1000);
25 // context definitions
26 define('CONTEXT_SYSTEM', 10);
27 define('CONTEXT_PERSONAL', 20);
28 define('CONTEXT_USER', 30);
29 define('CONTEXT_COURSECAT', 40);
30 define('CONTEXT_COURSE', 50);
31 define('CONTEXT_GROUP', 60);
32 define('CONTEXT_MODULE', 70);
33 define('CONTEXT_BLOCK', 80);
35 // capability risks - see http://docs.moodle.org/en/Hardening_new_Roles_system
36 define('RISK_MANAGETRUST', 0x0001);
37 define('RISK_CONFIG', 0x0002);
38 define('RISK_XSS', 0x0004);
39 define('RISK_PERSONAL', 0x0008);
40 define('RISK_SPAM', 0x0010);
42 require_once($CFG->dirroot
.'/group/lib.php');
44 $context_cache = array(); // Cache of all used context objects for performance (by level and instance)
45 $context_cache_id = array(); // Index to above cache by id
48 function get_role_context_caps($roleid, $context) {
49 //this is really slow!!!! - do not use above course context level!
51 $result[$context->id
] = array();
53 // first emulate the parent context capabilities merging into context
54 $searchcontexts = array_reverse(get_parent_contexts($context));
55 array_push($searchcontexts, $context->id
);
56 foreach ($searchcontexts as $cid) {
57 if ($capabilities = get_records_select('role_capabilities', "roleid = $roleid AND contextid = $cid")) {
58 foreach ($capabilities as $cap) {
59 if (!array_key_exists($cap->capability
, $result[$context->id
])) {
60 $result[$context->id
][$cap->capability
] = 0;
62 $result[$context->id
][$cap->capability
] +
= $cap->permission
;
67 // now go through the contexts bellow given context
68 $searchcontexts = get_child_contexts($context);
69 foreach ($searchcontexts as $cid) {
70 if ($capabilities = get_records_select('role_capabilities', "roleid = $roleid AND contextid = $cid")) {
71 foreach ($capabilities as $cap) {
72 if (!array_key_exists($cap->contextid
, $result)) {
73 $result[$cap->contextid
] = array();
75 $result[$cap->contextid
][$cap->capability
] = $cap->permission
;
83 function get_role_caps($roleid) {
85 if ($capabilities = get_records_select('role_capabilities',"roleid = $roleid")) {
86 foreach ($capabilities as $cap) {
87 if (!array_key_exists($cap->contextid
, $result)) {
88 $result[$cap->contextid
] = array();
90 $result[$cap->contextid
][$cap->capability
] = $cap->permission
;
96 function merge_role_caps($caps, $mergecaps) {
97 if (empty($mergecaps)) {
105 foreach ($mergecaps as $contextid=>$capabilities) {
106 if (!array_key_exists($contextid, $caps)) {
107 $caps[$contextid] = array();
109 foreach ($capabilities as $capability=>$permission) {
110 if (!array_key_exists($capability, $caps[$contextid])) {
111 $caps[$contextid][$capability] = 0;
113 $caps[$contextid][$capability] +
= $permission;
120 * Loads the capabilities for the default guest role to the current user in a
124 function load_guest_role($return=false) {
127 static $guestrole = false;
129 if ($guestrole === false) {
130 if (!$guestrole = get_guest_role()) {
136 return get_role_caps($guestrole->id
);
138 has_capability('clearcache');
139 $USER->capabilities
= get_role_caps($guestrole->id
);
145 * Load default not logged in role capabilities when user is not logged in
148 function load_notloggedin_role($return=false) {
151 if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM
)) {
155 if (empty($CFG->notloggedinroleid
)) { // Let's set the default to the guest role
156 if ($role = get_guest_role()) {
157 set_config('notloggedinroleid', $role->id
);
164 return get_role_caps($CFG->notloggedinroleid
);
166 has_capability('clearcache');
167 $USER->capabilities
= get_role_caps($CFG->notloggedinroleid
);
173 * Load default logged in role capabilities for all logged in users
176 function load_defaultuser_role($return=false) {
179 if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM
)) {
183 if (empty($CFG->defaultuserroleid
)) { // Let's set the default to the guest role
184 if ($role = get_guest_role()) {
185 set_config('defaultuserroleid', $role->id
);
191 $capabilities = get_role_caps($CFG->defaultuserroleid
);
193 // fix the guest user heritage:
194 // If the default role is a guest role, then don't copy legacy:guest,
195 // otherwise this user could get confused with a REAL guest. Also don't copy
196 // course:view, which is a hack that's necessary because guest roles are
197 // not really handled properly (see MDL-7513)
198 if (!empty($capabilities[$sitecontext->id
]['moodle/legacy:guest'])) {
199 unset($capabilities[$sitecontext->id
]['moodle/legacy:guest']);
200 unset($capabilities[$sitecontext->id
]['moodle/course:view']);
204 return $capabilities;
206 has_capability('clearcache');
207 $USER->capabilities
= $capabilities;
214 * Get the default guest role
215 * @return object role
217 function get_guest_role() {
220 if (empty($CFG->guestroleid
)) {
221 if ($roles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW
)) {
222 $guestrole = array_shift($roles); // Pick the first one
223 set_config('guestroleid', $guestrole->id
);
226 debugging('Can not find any guest role!');
230 if ($guestrole = get_record('role','id', $CFG->guestroleid
)) {
233 //somebody is messing with guest roles, remove incorrect setting and try to find a new one
234 set_config('guestroleid', '');
235 return get_guest_role();
242 * This functions get all the course categories in proper order
243 * (!)note this only gets course category contexts, and not the site
245 * @param object $context
247 * @return array of contextids
249 function get_parent_cats($context, $type) {
254 // a category can be the parent of another category
255 // there is no limit of depth in this case
256 case CONTEXT_COURSECAT
:
257 if (!$cat = get_record('course_categories','id',$context->instanceid
)) {
261 while (!empty($cat->parent
)) {
262 if (!$context = get_context_instance(CONTEXT_COURSECAT
, $cat->parent
)) {
265 $parents[] = $context->id
;
266 $cat = get_record('course_categories','id',$cat->parent
);
270 // a course always fall into a category, unless it's a site course
271 // this happens when SITEID == $course->id
272 // in this case the parent of the course is site context
274 if (!$course = get_record('course', 'id', $context->instanceid
)) {
277 if (!$catinstance = get_context_instance(CONTEXT_COURSECAT
, $course->category
)) {
281 $parents[] = $catinstance->id
;
283 if (!$cat = get_record('course_categories','id',$course->category
)) {
286 // Yu: Separating site and site course context
287 if ($course->id
== SITEID
) {
291 while (!empty($cat->parent
)) {
292 if (!$context = get_context_instance(CONTEXT_COURSECAT
, $cat->parent
)) {
295 $parents[] = $context->id
;
296 $cat = get_record('course_categories','id',$cat->parent
);
303 return array_reverse($parents);
309 * This function checks for a capability assertion being true. If it isn't
310 * then the page is terminated neatly with a standard error message
311 * @param string $capability - name of the capability
312 * @param object $context - a context object (record from context table)
313 * @param integer $userid - a userid number
314 * @param bool $doanything - if false, ignore do anything
315 * @param string $errorstring - an errorstring
316 * @param string $stringfile - which stringfile to get it from
318 function require_capability($capability, $context=NULL, $userid=NULL, $doanything=true,
319 $errormessage='nopermissions', $stringfile='') {
323 /// If the current user is not logged in, then make sure they are (if needed)
325 if (empty($userid) and empty($USER->capabilities
)) {
326 if ($context && ($context->contextlevel
== CONTEXT_COURSE
)) {
327 require_login($context->instanceid
);
328 } else if ($context && ($context->contextlevel
== CONTEXT_MODULE
)) {
329 if ($cm = get_record('course_modules','id',$context->instanceid
)) {
330 if (!$course = get_record('course', 'id', $cm->course
)) {
331 error('Incorrect course.');
333 require_course_login($course, true, $cm);
338 } else if ($context && ($context->contextlevel
== CONTEXT_SYSTEM
)) {
339 if (!empty($CFG->forcelogin
)) {
348 /// OK, if they still don't have the capability then print a nice error message
350 if (!has_capability($capability, $context, $userid, $doanything)) {
351 $capabilityname = get_capability_string($capability);
352 print_error($errormessage, $stringfile, '', $capabilityname);
358 * This function returns whether the current user has the capability of performing a function
359 * For example, we can do has_capability('mod/forum:replypost',$cm) in forum
360 * only one of the 4 (moduleinstance, courseid, site, userid) would be set at 1 time
361 * This is a recursive funciton.
363 * @param string $capability - name of the capability (or debugcache or clearcache)
364 * @param object $context - a context object (record from context table)
365 * @param integer $userid - a userid number
366 * @param bool $doanything - if false, ignore do anything
369 function has_capability($capability, $context=NULL, $userid=NULL, $doanything=true) {
371 global $USER, $CONTEXT, $CFG;
373 static $capcache = array(); // Cache of capabilities
378 if ($capability == 'clearcache') {
379 $capcache = array(); // Clear ALL the capability cache
383 /// Some sanity checks
384 if (debugging('',DEBUG_DEVELOPER
)) {
385 if ($capability == 'debugcache') {
386 print_object($capcache);
389 if (!record_exists('capabilities', 'name', $capability)) {
390 debugging('Capability "'.$capability.'" was not found! This should be fixed in code.');
392 if ($doanything != true and $doanything != false) {
393 debugging('Capability parameter "doanything" is wierd ("'.$doanything.'"). This should be fixed in code.');
395 if (!is_object($context) && $context !== NULL) {
396 debugging('Incorrect context parameter "'.$context.'" for has_capability(), object expected! This should be fixed in code.');
400 /// Make sure we know the current context
401 if (empty($context)) { // Use default CONTEXT if none specified
402 if (empty($CONTEXT)) {
407 } else { // A context was given to us
408 if (empty($CONTEXT)) {
409 $CONTEXT = $context; // Store FIRST used context in this global as future default
413 /// Check and return cache in case we've processed this one before.
414 $requsteduser = empty($userid) ?
$USER->id
: $userid; // find out the requested user id, $USER->id might have been changed
415 $cachekey = $capability.'_'.$context->id
.'_'.intval($requsteduser).'_'.intval($doanything);
417 if (isset($capcache[$cachekey])) {
418 return $capcache[$cachekey];
422 /// Load up the capabilities list or item as necessary
424 if (empty($USER->id
) or ($userid != $USER->id
) or empty($USER->capabilities
)) {
426 //caching - helps user switching in cron
427 static $guestuserid = false; // guest user id
428 static $guestcaps = false; // guest caps
429 static $defcaps = false; // default user caps - this might help cron
431 if ($guestuserid === false) {
432 $guestuserid = get_field('user', 'id', 'username', 'guest');
435 if ($userid == $guestuserid) {
436 if ($guestcaps === false) {
437 $guestcaps = load_guest_role(true);
439 $capabilities = $guestcaps;
442 // This big SQL is expensive! We reduce it a little by avoiding checking for changed enrolments (false)
443 $capabilities = load_user_capability($capability, $context, $userid, false);
444 if ($defcaps === false) {
445 $defcaps = load_defaultuser_role(true);
447 $capabilities = merge_role_caps($capabilities, $defcaps);
450 } else { //$USER->id == $userid and needed capabilities already present
451 $capabilities = $USER->capabilities
;
454 } else { // no userid
455 if (empty($USER->capabilities
)) {
456 load_all_capabilities(); // expensive - but we have to do it once anyway
458 $capabilities = $USER->capabilities
;
462 /// We act a little differently when switchroles is active
464 $switchroleactive = false; // Assume it isn't active in this context
467 /// First deal with the "doanything" capability
471 /// First make sure that we aren't in a "switched role"
473 if (!empty($USER->switchrole
)) { // Switchrole is active somewhere!
474 if (!empty($USER->switchrole
[$context->id
])) { // Because of current context
475 $switchroleactive = true;
476 } else { // Check parent contexts
477 if ($parentcontextids = get_parent_contexts($context)) {
478 foreach ($parentcontextids as $parentcontextid) {
479 if (!empty($USER->switchrole
[$parentcontextid])) { // Yep, switchroles active here
480 $switchroleactive = true;
488 /// Check the site context for doanything (most common) first
490 if (empty($switchroleactive)) { // Ignore site setting if switchrole is active
491 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
492 if (isset($capabilities[$sitecontext->id
]['moodle/site:doanything'])) {
493 $result = (0 < $capabilities[$sitecontext->id
]['moodle/site:doanything']);
494 $capcache[$cachekey] = $result;
498 /// If it's not set at site level, it is possible to be set on other levels
499 /// Though this usage is not common and can cause risks
500 switch ($context->contextlevel
) {
502 case CONTEXT_COURSECAT
:
503 // Check parent cats.
504 $parentcats = get_parent_cats($context, CONTEXT_COURSECAT
);
505 foreach ($parentcats as $parentcat) {
506 if (isset($capabilities[$parentcat]['moodle/site:doanything'])) {
507 $result = (0 < $capabilities[$parentcat]['moodle/site:doanything']);
508 $capcache[$cachekey] = $result;
516 $parentcats = get_parent_cats($context, CONTEXT_COURSE
);
518 foreach ($parentcats as $parentcat) {
519 if (isset($capabilities[$parentcat]['do_anything'])) {
520 $result = (0 < $capabilities[$parentcat]['do_anything']);
521 $capcache[$cachekey] = $result;
529 $courseid = groups_get_course($context->instanceid
);
530 $courseinstance = get_context_instance(CONTEXT_COURSE
, $courseid);
532 $parentcats = get_parent_cats($courseinstance, CONTEXT_COURSE
);
533 foreach ($parentcats as $parentcat) {
534 if (isset($capabilities[$parentcat]['do_anything'])) {
535 $result = (0 < $capabilities[$parentcat]['do_anything']);
536 $capcache[$cachekey] = $result;
542 if (isset($capabilities[$courseinstance->id
]['do_anything'])) {
543 $result = (0 < $capabilities[$courseinstance->id
]['do_anything']);
544 $capcache[$cachekey] = $result;
552 $cm = get_record('course_modules', 'id', $context->instanceid
);
553 $courseinstance = get_context_instance(CONTEXT_COURSE
, $cm->course
);
555 if ($parentcats = get_parent_cats($courseinstance, CONTEXT_COURSE
)) {
556 foreach ($parentcats as $parentcat) {
557 if (isset($capabilities[$parentcat]['do_anything'])) {
558 $result = (0 < $capabilities[$parentcat]['do_anything']);
559 $capcache[$cachekey] = $result;
565 if (isset($capabilities[$courseinstance->id
]['do_anything'])) {
566 $result = (0 < $capabilities[$courseinstance->id
]['do_anything']);
567 $capcache[$cachekey] = $result;
574 // not necessarily 1 to 1 to course.
575 $block = get_record('block_instance','id',$context->instanceid
);
576 if ($block->pagetype
== 'course-view') {
577 $courseinstance = get_context_instance(CONTEXT_COURSE
, $block->pageid
); // needs check
578 $parentcats = get_parent_cats($courseinstance, CONTEXT_COURSE
);
580 foreach ($parentcats as $parentcat) {
581 if (isset($capabilities[$parentcat]['do_anything'])) {
582 $result = (0 < $capabilities[$parentcat]['do_anything']);
583 $capcache[$cachekey] = $result;
588 if (isset($capabilities[$courseinstance->id
]['do_anything'])) {
589 $result = (0 < $capabilities[$courseinstance->id
]['do_anything']);
590 $capcache[$cachekey] = $result;
593 } else { // if not course-view type of blocks, check site
594 if (isset($capabilities[$sitecontext->id
]['do_anything'])) {
595 $result = (0 < $capabilities[$sitecontext->id
]['do_anything']);
596 $capcache[$cachekey] = $result;
603 // CONTEXT_SYSTEM: CONTEXT_PERSONAL: CONTEXT_USER:
604 // Do nothing, because the parents are site context
605 // which has been checked already
610 if (isset($capabilities[$context->id
]['do_anything'])) {
611 $result = (0 < $capabilities[$context->id
]['do_anything']);
612 $capcache[$cachekey] = $result;
616 // do_anything has not been set, we now look for it the normal way.
617 $result = (0 < capability_search($capability, $context, $capabilities, $switchroleactive));
618 $capcache[$cachekey] = $result;
625 * In a separate function so that we won't have to deal with do_anything.
626 * again. Used by function has_capability().
627 * @param $capability - capability string
628 * @param $context - the context object
629 * @param $capabilities - either $USER->capability or loaded array (for other users)
630 * @return permission (int)
632 function capability_search($capability, $context, $capabilities, $switchroleactive=false) {
636 if (!isset($context->id
)) {
639 // if already set in the array explicitly, no need to look for it in parent
640 // context any longer
641 if (isset($capabilities[$context->id
][$capability])) {
642 return ($capabilities[$context->id
][$capability]);
645 /* Then, we check the cache recursively */
648 switch ($context->contextlevel
) {
650 case CONTEXT_SYSTEM
: // by now it's a definite an inherit
654 case CONTEXT_PERSONAL
:
655 $parentcontext = get_context_instance(CONTEXT_SYSTEM
);
656 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
660 $parentcontext = get_context_instance(CONTEXT_SYSTEM
);
661 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
664 case CONTEXT_COURSECAT
: // Coursecat -> coursecat or site
665 $coursecat = get_record('course_categories','id',$context->instanceid
);
666 if (!empty($coursecat->parent
)) { // return parent value if it exists
667 $parentcontext = get_context_instance(CONTEXT_COURSECAT
, $coursecat->parent
);
668 } else { // else return site value
669 $parentcontext = get_context_instance(CONTEXT_SYSTEM
);
671 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
674 case CONTEXT_COURSE
: // 1 to 1 to course cat
675 if (empty($switchroleactive)) {
676 // find the course cat, and return its value
677 $course = get_record('course','id',$context->instanceid
);
678 if ($course->id
== SITEID
) { // In 1.8 we've separated site course and system
679 $parentcontext = get_context_instance(CONTEXT_SYSTEM
);
681 $parentcontext = get_context_instance(CONTEXT_COURSECAT
, $course->category
);
683 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
687 case CONTEXT_GROUP
: // 1 to 1 to course
688 $courseid = groups_get_course($context->instanceid
);
689 $parentcontext = get_context_instance(CONTEXT_COURSE
, $courseid);
690 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
693 case CONTEXT_MODULE
: // 1 to 1 to course
694 $cm = get_record('course_modules','id',$context->instanceid
);
695 $parentcontext = get_context_instance(CONTEXT_COURSE
, $cm->course
);
696 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
699 case CONTEXT_BLOCK
: // not necessarily 1 to 1 to course
700 $block = get_record('block_instance','id',$context->instanceid
);
701 if ($block->pagetype
== 'course-view') {
702 $parentcontext = get_context_instance(CONTEXT_COURSE
, $block->pageid
); // needs check
704 $parentcontext = get_context_instance(CONTEXT_SYSTEM
);
706 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
710 error ('This is an unknown context (' . $context->contextlevel
. ') in capability_search!');
718 * auxillary function for load_user_capabilities()
719 * checks if context c1 is a parent (or itself) of context c2
720 * @param int $c1 - context id of context 1
721 * @param int $c2 - context id of context 2
724 function is_parent_context($c1, $c2) {
725 static $parentsarray;
727 // context can be itself and this is ok
732 if (isset($parentsarray[$c1][$c2])) {
733 return $parentsarray[$c1][$c2];
736 if (!$co2 = get_record('context', 'id', $c2)) {
740 if (!$parents = get_parent_contexts($co2)) {
744 foreach ($parents as $parent) {
745 $parentsarray[$parent][$c2] = true;
748 if (in_array($c1, $parents)) {
750 } else { // else not a parent, set the cache anyway
751 $parentsarray[$c1][$c2] = false;
758 * auxillary function for load_user_capabilities()
759 * handler in usort() to sort contexts according to level
760 * @param object contexta
761 * @param object contextb
764 function roles_context_cmp($contexta, $contextb) {
765 if ($contexta->contextlevel
== $contextb->contextlevel
) {
768 return ($contexta->contextlevel
< $contextb->contextlevel
) ?
-1 : 1;
772 * It will build an array of all the capabilities at each level
773 * i.e. site/metacourse/course_category/course/moduleinstance
774 * Note we should only load capabilities if they are explicitly assigned already,
775 * we should not load all module's capability!
777 * [Capabilities] => [26][forum_post] = 1
778 * [26][forum_start] = -8990
779 * [26][forum_edit] = -1
780 * [273][blah blah] = 1
781 * [273][blah blah blah] = 2
783 * @param $capability string - Only get a specific capability (string)
784 * @param $context object - Only get capabilities for a specific context object
785 * @param $userid integer - the id of the user whose capabilities we want to load
786 * @param $checkenrolments boolean - Should we check enrolment plugins (potentially expensive)
787 * @return array of permissions (or nothing if they get assigned to $USER)
789 function load_user_capability($capability='', $context=NULL, $userid=NULL, $checkenrolments=true) {
793 // this flag has not been set!
794 // (not clean install, or upgraded successfully to 1.7 and up)
795 if (empty($CFG->rolesactive
)) {
799 if (empty($userid)) {
800 if (empty($USER->id
)) { // We have no user to get capabilities for
801 debugging('User not logged in for load_user_capability!');
804 unset($USER->capabilities
); // We don't want possible older capabilites hanging around
806 if ($checkenrolments) { // Call "enrol" system to ensure that we have the correct picture
807 check_enrolment_plugins($USER);
811 $otheruserid = false;
813 if (!$user = get_record('user', 'id', $userid)) {
814 debugging('Non-existent userid in load_user_capability!');
818 if ($checkenrolments) { // Call "enrol" system to ensure that we have the correct picture
819 check_enrolment_plugins($user);
822 $otheruserid = $userid;
826 /// First we generate a list of all relevant contexts of the user
828 $usercontexts = array();
830 if ($context) { // if context is specified
831 $usercontexts = get_parent_contexts($context);
832 $usercontexts[] = $context->id
; // Add the current context as well
833 } else { // else, we load everything
834 if ($userroles = get_records('role_assignments','userid',$userid)) {
835 foreach ($userroles as $userrole) {
836 if (!in_array($userrole->contextid
, $usercontexts)) {
837 $usercontexts[] = $userrole->contextid
;
843 /// Set up SQL fragments for searching contexts
846 $listofcontexts = '('.implode(',', $usercontexts).')';
847 $searchcontexts1 = "c1.id IN $listofcontexts AND";
849 $searchcontexts1 = '';
853 // the doanything may override the requested capability
854 $capsearch = " AND (rc.capability = '$capability' OR rc.capability = 'moodle/site:doanything') ";
859 /// Then we use 1 giant SQL to bring out all relevant capabilities.
860 /// The first part gets the capabilities of orginal role.
861 /// The second part gets the capabilities of overriden roles.
863 $siteinstance = get_context_instance(CONTEXT_SYSTEM
);
864 $capabilities = array(); // Reinitialize.
866 // SQL for normal capabilities
867 $SQL1 = "SELECT rc.capability, c1.id as id1, c1.id as id2, (c1.contextlevel * 100) AS aggrlevel,
868 SUM(rc.permission) AS sum
870 {$CFG->prefix}role_assignments ra,
871 {$CFG->prefix}role_capabilities rc,
872 {$CFG->prefix}context c1
874 ra.contextid=c1.id AND
875 ra.roleid=rc.roleid AND
876 ra.userid=$userid AND
878 rc.contextid=$siteinstance->id
881 rc.capability, c1.id, c1.contextlevel * 100
883 SUM(rc.permission) != 0
887 SELECT rc.capability, c1.id as id1, c2.id as id2, (c1.contextlevel * 100 + c2.contextlevel) AS aggrlevel,
888 SUM(rc.permission) AS sum
890 {$CFG->prefix}role_assignments ra LEFT JOIN
891 {$CFG->prefix}role_capabilities rc on ra.roleid = rc.roleid LEFT JOIN
892 {$CFG->prefix}context c1 on ra.contextid = c1.id LEFT JOIN
893 {$CFG->prefix}context c2 on rc.contextid = c2.id LEFT JOIN
894 {$CFG->prefix}context_rel cr on cr.c1 = c2.id
896 ra.userid=$userid AND
898 rc.contextid != $siteinstance->id
902 rc.capability, c1.id, c2.id, c1.contextlevel * 100 + c2.contextlevel
904 SUM(rc.permission) != 0
908 if (!$rs = get_recordset_sql($SQL1)) {
909 error("Query failed in load_user_capability.");
912 if ($rs && $rs->RecordCount() > 0) {
913 while ($caprec = rs_fetch_next_record($rs)) {
914 $array = (array)$caprec;
915 $temprecord = new object;
917 foreach ($array as $key=>$val) {
918 if ($key == 'aggrlevel') {
919 $temprecord->contextlevel
= $val;
921 $temprecord->{$key} = $val;
924 $capabilities[] = $temprecord;
930 // this is take out because we have no way of making sure c1 is indeed related to c2 (parent)
931 // if we do not group by sum, it is possible to have multiple records of rc.capability, c1.id, c2.id, tuple having
932 // different values, we can maually sum it when we go through the list
936 $SQL2 = "SELECT rc.capability, c1.id as id1, c2.id as id2, (c1.contextlevel * 100 + c2.contextlevel) AS aggrlevel,
939 {$CFG->prefix}role_assignments ra,
940 {$CFG->prefix}role_capabilities rc,
941 {$CFG->prefix}context c1,
942 {$CFG->prefix}context c2
944 ra.contextid=c1.id AND
945 ra.roleid=rc.roleid AND
946 ra.userid=$userid AND
947 rc.contextid=c2.id AND
949 rc.contextid != $siteinstance->id
953 rc.capability, (c1.contextlevel * 100 + c2.contextlevel), c1.id, c2.id, rc.permission
959 if (!$rs = get_recordset_sql($SQL2)) {
960 error("Query failed in load_user_capability.");
963 if ($rs && $rs->RecordCount() > 0) {
964 while ($caprec = rs_fetch_next_record($rs)) {
965 $array = (array)$caprec;
966 $temprecord = new object;
968 foreach ($array as $key=>$val) {
969 if ($key == 'aggrlevel') {
970 $temprecord->contextlevel = $val;
972 $temprecord->{$key} = $val;
975 // for overrides, we have to make sure that context2 is a child of context1
976 // otherwise the combination makes no sense
977 //if (is_parent_context($temprecord->id1, $temprecord->id2)) {
978 $capabilities[] = $temprecord;
979 //} // only write if relevant
984 // this step sorts capabilities according to the contextlevel
985 // it is very important because the order matters when we
986 // go through each capabilities later. (i.e. higher level contextlevel
987 // will override lower contextlevel settings
988 usort($capabilities, 'roles_context_cmp');
990 /* so up to this point we should have somethign like this
991 * $capabilities[1] ->contextlevel = 1000
992 ->module = 0 // changed from SITEID in 1.8 (??)
993 ->capability = do_anything
994 ->id = 1 (id is the context id)
997 * $capabilities[2] ->contextlevel = 1000
998 ->module = 0 // changed from SITEID in 1.8 (??)
999 ->capability = post_messages
1003 * $capabilittes[3] ->contextlevel = 3000
1005 ->capability = view_course_activities
1009 * $capabilittes[4] ->contextlevel = 3000
1011 ->capability = view_course_activities
1013 ->sum = 0 (this is another course)
1015 * $capabilities[5] ->contextlevel = 3050
1017 ->capability = view_course_activities
1018 ->id = 25 (override in course 25)
1021 * now we proceed to write the session array, going from top to bottom
1022 * at anypoint, we need to go up and check parent to look for prohibit
1024 // print_object($capabilities);
1026 /* This is where we write to the actualy capabilities array
1027 * what we need to do from here on is
1028 * going down the array from lowest level to highest level
1029 * 1) recursively check for prohibit,
1030 * if any, we write prohibit
1031 * else, we write the value
1032 * 2) at an override level, we overwrite current level
1033 * if it's not set to prohibit already, and if different
1034 * ........ that should be it ........
1037 // This is the flag used for detecting the current context level. Since we are going through
1038 // the array in ascending order of context level. For normal capabilities, there should only
1039 // be 1 value per (capability, contextlevel, context), because they are already summed. But,
1040 // for overrides, since we are processing them separate, we need to sum the relevcant entries.
1041 // We set this flag when we hit a new level.
1042 // If the flag is already set, we keep adding (summing), otherwise, we just override previous
1043 // settings (from lower level contexts)
1044 $capflags = array(); // (contextid, contextlevel, capability)
1045 $usercap = array(); // for other user's capabilities
1046 foreach ($capabilities as $capability) {
1048 if (!$context = get_context_instance_by_id($capability->id2
)) {
1049 continue; // incorrect stale context
1052 if (!empty($otheruserid)) { // we are pulling out other user's capabilities, do not write to session
1054 if (capability_prohibits($capability->capability
, $context, $capability->sum
, $usercap)) {
1055 $usercap[$capability->id2
][$capability->capability
] = CAP_PROHIBIT
;
1058 if (isset($usercap[$capability->id2
][$capability->capability
])) { // use isset because it can be sum 0
1059 if (!empty($capflags[$capability->id2
][$capability->contextlevel
][$capability->capability
])) {
1060 $usercap[$capability->id2
][$capability->capability
] +
= $capability->sum
;
1061 } else { // else we override, and update flag
1062 $usercap[$capability->id2
][$capability->capability
] = $capability->sum
;
1063 $capflags[$capability->id2
][$capability->contextlevel
][$capability->capability
] = true;
1066 $usercap[$capability->id2
][$capability->capability
] = $capability->sum
;
1067 $capflags[$capability->id2
][$capability->contextlevel
][$capability->capability
] = true;
1072 if (capability_prohibits($capability->capability
, $context, $capability->sum
)) { // if any parent or parent's parent is set to prohibit
1073 $USER->capabilities
[$capability->id2
][$capability->capability
] = CAP_PROHIBIT
;
1077 // if no parental prohibit set
1078 // just write to session, i am not sure this is correct yet
1079 // since 3050 shows up after 3000, and 3070 shows up after 3050,
1080 // it should be ok just to overwrite like this, provided that there's no
1081 // parental prohibits
1082 // we need to write even if it's 0, because it could be an inherit override
1083 if (isset($USER->capabilities
[$capability->id2
][$capability->capability
])) {
1084 if (!empty($capflags[$capability->id2
][$capability->contextlevel
][$capability->capability
])) {
1085 $USER->capabilities
[$capability->id2
][$capability->capability
] +
= $capability->sum
;
1086 } else { // else we override, and update flag
1087 $USER->capabilities
[$capability->id2
][$capability->capability
] = $capability->sum
;
1088 $capflags[$capability->id2
][$capability->contextlevel
][$capability->capability
] = true;
1091 $USER->capabilities
[$capability->id2
][$capability->capability
] = $capability->sum
;
1092 $capflags[$capability->id2
][$capability->contextlevel
][$capability->capability
] = true;
1097 // now we don't care about the huge array anymore, we can dispose it.
1098 unset($capabilities);
1101 if (!empty($otheruserid)) {
1102 return $usercap; // return the array
1108 * A convenience function to completely load all the capabilities
1109 * for the current user. This is what gets called from login, for example.
1111 function load_all_capabilities() {
1114 //caching - helps user switching in cron
1115 static $defcaps = false;
1117 unset($USER->mycourses
); // Reset a cache used by get_my_courses
1119 if (isguestuser()) {
1120 load_guest_role(); // All non-guest users get this by default
1122 } else if (isloggedin()) {
1123 if ($defcaps === false) {
1124 $defcaps = load_defaultuser_role(true);
1127 load_user_capability();
1129 // when in "course login as" - load only course caqpabilitites (it may not always work as expected)
1130 if (!empty($USER->realuser
) and $USER->loginascontext
->contextlevel
!= CONTEXT_SYSTEM
) {
1131 $children = get_child_contexts($USER->loginascontext
);
1132 $children[] = $USER->loginascontext
->id
;
1133 foreach ($USER->capabilities
as $conid => $caps) {
1134 if (!in_array($conid, $children)) {
1135 unset($USER->capabilities
[$conid]);
1140 // handle role switching in courses
1141 if (!empty($USER->switchrole
)) {
1142 foreach ($USER->switchrole
as $contextid => $roleid) {
1143 $context = get_context_instance_by_id($contextid);
1145 // first prune context and any child contexts
1146 $children = get_child_contexts($context);
1147 foreach ($children as $childid) {
1148 unset($USER->capabilities
[$childid]);
1150 unset($USER->capabilities
[$contextid]);
1152 // now merge all switched role caps in context and bellow
1153 $swithccaps = get_role_context_caps($roleid, $context);
1154 $USER->capabilities
= merge_role_caps($USER->capabilities
, $swithccaps);
1158 if (isset($USER->capabilities
)) {
1159 $USER->capabilities
= merge_role_caps($USER->capabilities
, $defcaps);
1161 $USER->capabilities
= $defcaps;
1165 load_notloggedin_role();
1171 * Check all the login enrolment information for the given user object
1172 * by querying the enrolment plugins
1174 function check_enrolment_plugins(&$user) {
1177 static $inprogress; // To prevent this function being called more than once in an invocation
1179 if (!empty($inprogress[$user->id
])) {
1183 $inprogress[$user->id
] = true; // Set the flag
1185 require_once($CFG->dirroot
.'/enrol/enrol.class.php');
1187 if (!($plugins = explode(',', $CFG->enrol_plugins_enabled
))) {
1188 $plugins = array($CFG->enrol
);
1191 foreach ($plugins as $plugin) {
1192 $enrol = enrolment_factory
::factory($plugin);
1193 if (method_exists($enrol, 'setup_enrolments')) { /// Plugin supports Roles (Moodle 1.7 and later)
1194 $enrol->setup_enrolments($user);
1195 } else { /// Run legacy enrolment methods
1196 if (method_exists($enrol, 'get_student_courses')) {
1197 $enrol->get_student_courses($user);
1199 if (method_exists($enrol, 'get_teacher_courses')) {
1200 $enrol->get_teacher_courses($user);
1203 /// deal with $user->students and $user->teachers stuff
1204 unset($user->student
);
1205 unset($user->teacher
);
1210 unset($inprogress[$user->id
]); // Unset the flag
1215 * This is a recursive function that checks whether the capability in this
1216 * context, or the parent capabilities are set to prohibit.
1218 * At this point, we can probably just use the values already set in the
1219 * session variable, since we are going down the level. Any prohit set in
1220 * parents would already reflect in the session.
1222 * @param $capability - capability name
1223 * @param $sum - sum of all capabilities values
1224 * @param $context - the context object
1225 * @param $array - when loading another user caps, their caps are not stored in session but an array
1227 function capability_prohibits($capability, $context, $sum='', $array='') {
1230 // caching, mainly to save unnecessary sqls
1231 static $prohibits; //[capability][contextid]
1232 if (isset($prohibits[$capability][$context->id
])) {
1233 return $prohibits[$capability][$context->id
];
1236 if (empty($context->id
)) {
1237 $prohibits[$capability][$context->id
] = false;
1241 if (empty($capability)) {
1242 $prohibits[$capability][$context->id
] = false;
1246 if ($sum < (CAP_PROHIBIT
/2)) {
1247 // If this capability is set to prohibit.
1248 $prohibits[$capability][$context->id
] = true;
1252 if (!empty($array)) {
1253 if (isset($array[$context->id
][$capability])
1254 && $array[$context->id
][$capability] < (CAP_PROHIBIT
/2)) {
1255 $prohibits[$capability][$context->id
] = true;
1259 // Else if set in session.
1260 if (isset($USER->capabilities
[$context->id
][$capability])
1261 && $USER->capabilities
[$context->id
][$capability] < (CAP_PROHIBIT
/2)) {
1262 $prohibits[$capability][$context->id
] = true;
1266 switch ($context->contextlevel
) {
1268 case CONTEXT_SYSTEM
:
1269 // By now it's a definite an inherit.
1273 case CONTEXT_PERSONAL
:
1274 $parent = get_context_instance(CONTEXT_SYSTEM
);
1275 $prohibits[$capability][$context->id
] = capability_prohibits($capability, $parent);
1276 return $prohibits[$capability][$context->id
];
1280 $parent = get_context_instance(CONTEXT_SYSTEM
);
1281 $prohibits[$capability][$context->id
] = capability_prohibits($capability, $parent);
1282 return $prohibits[$capability][$context->id
];
1285 case CONTEXT_COURSECAT
:
1286 // Coursecat -> coursecat or site.
1287 if (!$coursecat = get_record('course_categories','id',$context->instanceid
)) {
1288 $prohibits[$capability][$context->id
] = false;
1291 if (!empty($coursecat->parent
)) {
1292 // return parent value if exist.
1293 $parent = get_context_instance(CONTEXT_COURSECAT
, $coursecat->parent
);
1295 // Return site value.
1296 $parent = get_context_instance(CONTEXT_SYSTEM
);
1298 $prohibits[$capability][$context->id
] = capability_prohibits($capability, $parent);
1299 return $prohibits[$capability][$context->id
];
1302 case CONTEXT_COURSE
:
1303 // 1 to 1 to course cat.
1304 // Find the course cat, and return its value.
1305 if (!$course = get_record('course','id',$context->instanceid
)) {
1306 $prohibits[$capability][$context->id
] = false;
1309 // Yu: Separating site and site course context
1310 if ($course->id
== SITEID
) {
1311 $parent = get_context_instance(CONTEXT_SYSTEM
);
1313 $parent = get_context_instance(CONTEXT_COURSECAT
, $course->category
);
1315 $prohibits[$capability][$context->id
] = capability_prohibits($capability, $parent);
1316 return $prohibits[$capability][$context->id
];
1320 // 1 to 1 to course.
1321 if (!$courseid = groups_get_course($context->instanceid
)) {
1322 $prohibits[$capability][$context->id
] = false;
1325 $parent = get_context_instance(CONTEXT_COURSE
, $courseid);
1326 $prohibits[$capability][$context->id
] = capability_prohibits($capability, $parent);
1327 return $prohibits[$capability][$context->id
];
1330 case CONTEXT_MODULE
:
1331 // 1 to 1 to course.
1332 if (!$cm = get_record('course_modules','id',$context->instanceid
)) {
1333 $prohibits[$capability][$context->id
] = false;
1336 $parent = get_context_instance(CONTEXT_COURSE
, $cm->course
);
1337 $prohibits[$capability][$context->id
] = capability_prohibits($capability, $parent);
1338 return $prohibits[$capability][$context->id
];
1342 // 1 to 1 to course.
1343 if (!$block = get_record('block_instance','id',$context->instanceid
)) {
1344 $prohibits[$capability][$context->id
] = false;
1347 if ($block->pagetype
== 'course-view') {
1348 $parent = get_context_instance(CONTEXT_COURSE
, $block->pageid
); // needs check
1350 $parent = get_context_instance(CONTEXT_SYSTEM
);
1352 $prohibits[$capability][$context->id
] = capability_prohibits($capability, $parent);
1353 return $prohibits[$capability][$context->id
];
1357 print_error('unknowncontext');
1364 * A print form function. This should either grab all the capabilities from
1365 * files or a central table for that particular module instance, then present
1366 * them in check boxes. Only relevant capabilities should print for known
1368 * @param $mod - module id of the mod
1370 function print_capabilities($modid=0) {
1373 $capabilities = array();
1376 // We are in a module specific context.
1378 // Get the mod's name.
1379 // Call the function that grabs the file and parse.
1380 $cm = get_record('course_modules', 'id', $modid);
1381 $module = get_record('modules', 'id', $cm->module
);
1384 // Print all capabilities.
1385 foreach ($capabilities as $capability) {
1386 // Prints the check box component.
1393 * Installs the roles system.
1394 * This function runs on a fresh install as well as on an upgrade from the old
1395 * hard-coded student/teacher/admin etc. roles to the new roles system.
1397 function moodle_install_roles() {
1401 /// Create a system wide context for assignemnt.
1402 $systemcontext = $context = get_context_instance(CONTEXT_SYSTEM
);
1405 /// Create default/legacy roles and capabilities.
1406 /// (1 legacy capability per legacy role at system level).
1408 $adminrole = create_role(addslashes(get_string('administrator')), 'admin',
1409 addslashes(get_string('administratordescription')), 'moodle/legacy:admin');
1410 $coursecreatorrole = create_role(addslashes(get_string('coursecreators')), 'coursecreator',
1411 addslashes(get_string('coursecreatorsdescription')), 'moodle/legacy:coursecreator');
1412 $editteacherrole = create_role(addslashes(get_string('defaultcourseteacher')), 'editingteacher',
1413 addslashes(get_string('defaultcourseteacherdescription')), 'moodle/legacy:editingteacher');
1414 $noneditteacherrole = create_role(addslashes(get_string('noneditingteacher')), 'teacher',
1415 addslashes(get_string('noneditingteacherdescription')), 'moodle/legacy:teacher');
1416 $studentrole = create_role(addslashes(get_string('defaultcoursestudent')), 'student',
1417 addslashes(get_string('defaultcoursestudentdescription')), 'moodle/legacy:student');
1418 $guestrole = create_role(addslashes(get_string('guest')), 'guest',
1419 addslashes(get_string('guestdescription')), 'moodle/legacy:guest');
1420 $userrole = create_role(addslashes(get_string('authenticateduser')), 'user',
1421 addslashes(get_string('authenticateduserdescription')), 'moodle/legacy:user');
1423 /// Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles
1425 if (!assign_capability('moodle/site:doanything', CAP_ALLOW
, $adminrole, $systemcontext->id
)) {
1426 error('Could not assign moodle/site:doanything to the admin role');
1428 if (!update_capabilities()) {
1429 error('Had trouble upgrading the core capabilities for the Roles System');
1432 /// Look inside user_admin, user_creator, user_teachers, user_students and
1433 /// assign above new roles. If a user has both teacher and student role,
1434 /// only teacher role is assigned. The assignment should be system level.
1436 $dbtables = $db->MetaTables('TABLES');
1438 /// Set up the progress bar
1440 $usertables = array('user_admins', 'user_coursecreators', 'user_teachers', 'user_students');
1442 $totalcount = $progresscount = 0;
1443 foreach ($usertables as $usertable) {
1444 if (in_array($CFG->prefix
.$usertable, $dbtables)) {
1445 $totalcount +
= count_records($usertable);
1449 print_progress(0, $totalcount, 5, 1, 'Processing role assignments');
1451 /// Upgrade the admins.
1452 /// Sort using id ASC, first one is primary admin.
1454 if (in_array($CFG->prefix
.'user_admins', $dbtables)) {
1455 if ($rs = get_recordset_sql('SELECT * from '.$CFG->prefix
.'user_admins ORDER BY ID ASC')) {
1456 while ($admin = rs_fetch_next_record($rs)) {
1457 role_assign($adminrole, $admin->userid
, 0, $systemcontext->id
);
1459 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1464 // This is a fresh install.
1468 /// Upgrade course creators.
1469 if (in_array($CFG->prefix
.'user_coursecreators', $dbtables)) {
1470 if ($rs = get_recordset('user_coursecreators')) {
1471 while ($coursecreator = rs_fetch_next_record($rs)) {
1472 role_assign($coursecreatorrole, $coursecreator->userid
, 0, $systemcontext->id
);
1474 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1481 /// Upgrade editting teachers and non-editting teachers.
1482 if (in_array($CFG->prefix
.'user_teachers', $dbtables)) {
1483 if ($rs = get_recordset('user_teachers')) {
1484 while ($teacher = rs_fetch_next_record($rs)) {
1486 // removed code here to ignore site level assignments
1487 // since the contexts are separated now
1489 // populate the user_lastaccess table
1490 $access = new object();
1491 $access->timeaccess
= $teacher->timeaccess
;
1492 $access->userid
= $teacher->userid
;
1493 $access->courseid
= $teacher->course
;
1494 insert_record('user_lastaccess', $access);
1496 // assign the default student role
1497 $coursecontext = get_context_instance(CONTEXT_COURSE
, $teacher->course
); // needs cache
1499 if ($teacher->authority
== 0) {
1505 if ($teacher->editall
) { // editting teacher
1506 role_assign($editteacherrole, $teacher->userid
, 0, $coursecontext->id
, 0, 0, $hiddenteacher);
1508 role_assign($noneditteacherrole, $teacher->userid
, 0, $coursecontext->id
, 0, 0, $hiddenteacher);
1511 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1518 /// Upgrade students.
1519 if (in_array($CFG->prefix
.'user_students', $dbtables)) {
1520 if ($rs = get_recordset('user_students')) {
1521 while ($student = rs_fetch_next_record($rs)) {
1523 // populate the user_lastaccess table
1524 $access = new object;
1525 $access->timeaccess
= $student->timeaccess
;
1526 $access->userid
= $student->userid
;
1527 $access->courseid
= $student->course
;
1528 insert_record('user_lastaccess', $access);
1530 // assign the default student role
1531 $coursecontext = get_context_instance(CONTEXT_COURSE
, $student->course
);
1532 role_assign($studentrole, $student->userid
, 0, $coursecontext->id
);
1534 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1541 /// Upgrade guest (only 1 entry).
1542 if ($guestuser = get_record('user', 'username', 'guest')) {
1543 role_assign($guestrole, $guestuser->id
, 0, $systemcontext->id
);
1545 print_progress($totalcount, $totalcount, 5, 1, 'Processing role assignments');
1548 /// Insert the correct records for legacy roles
1549 allow_assign($adminrole, $adminrole);
1550 allow_assign($adminrole, $coursecreatorrole);
1551 allow_assign($adminrole, $noneditteacherrole);
1552 allow_assign($adminrole, $editteacherrole);
1553 allow_assign($adminrole, $studentrole);
1554 allow_assign($adminrole, $guestrole);
1556 allow_assign($coursecreatorrole, $noneditteacherrole);
1557 allow_assign($coursecreatorrole, $editteacherrole);
1558 allow_assign($coursecreatorrole, $studentrole);
1559 allow_assign($coursecreatorrole, $guestrole);
1561 allow_assign($editteacherrole, $noneditteacherrole);
1562 allow_assign($editteacherrole, $studentrole);
1563 allow_assign($editteacherrole, $guestrole);
1565 /// Set up default permissions for overrides
1566 allow_override($adminrole, $adminrole);
1567 allow_override($adminrole, $coursecreatorrole);
1568 allow_override($adminrole, $noneditteacherrole);
1569 allow_override($adminrole, $editteacherrole);
1570 allow_override($adminrole, $studentrole);
1571 allow_override($adminrole, $guestrole);
1572 allow_override($adminrole, $userrole);
1575 /// Delete the old user tables when we are done
1577 drop_table(new XMLDBTable('user_students'));
1578 drop_table(new XMLDBTable('user_teachers'));
1579 drop_table(new XMLDBTable('user_coursecreators'));
1580 drop_table(new XMLDBTable('user_admins'));
1585 * Returns array of all legacy roles.
1587 function get_legacy_roles() {
1589 'admin' => 'moodle/legacy:admin',
1590 'coursecreator' => 'moodle/legacy:coursecreator',
1591 'editingteacher' => 'moodle/legacy:editingteacher',
1592 'teacher' => 'moodle/legacy:teacher',
1593 'student' => 'moodle/legacy:student',
1594 'guest' => 'moodle/legacy:guest',
1595 'user' => 'moodle/legacy:user'
1599 function get_legacy_type($roleid) {
1600 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
1601 $legacyroles = get_legacy_roles();
1604 foreach($legacyroles as $ltype=>$lcap) {
1605 $localoverride = get_local_override($roleid, $sitecontext->id
, $lcap);
1606 if (!empty($localoverride->permission
) and $localoverride->permission
== CAP_ALLOW
) {
1607 //choose first selected legacy capability - reset the rest
1608 if (empty($result)) {
1611 unassign_capability($lcap, $roleid);
1620 * Assign the defaults found in this capabality definition to roles that have
1621 * the corresponding legacy capabilities assigned to them.
1622 * @param $legacyperms - an array in the format (example):
1623 * 'guest' => CAP_PREVENT,
1624 * 'student' => CAP_ALLOW,
1625 * 'teacher' => CAP_ALLOW,
1626 * 'editingteacher' => CAP_ALLOW,
1627 * 'coursecreator' => CAP_ALLOW,
1628 * 'admin' => CAP_ALLOW
1629 * @return boolean - success or failure.
1631 function assign_legacy_capabilities($capability, $legacyperms) {
1633 $legacyroles = get_legacy_roles();
1635 foreach ($legacyperms as $type => $perm) {
1637 $systemcontext = get_context_instance(CONTEXT_SYSTEM
);
1639 if (!array_key_exists($type, $legacyroles)) {
1640 error('Incorrect legacy role definition for type: '.$type);
1643 if ($roles = get_roles_with_capability($legacyroles[$type], CAP_ALLOW
)) {
1644 foreach ($roles as $role) {
1645 // Assign a site level capability.
1646 if (!assign_capability($capability, $perm, $role->id
, $systemcontext->id
)) {
1657 * Checks to see if a capability is a legacy capability.
1658 * @param $capabilityname
1661 function islegacy($capabilityname) {
1662 if (strpos($capabilityname, 'moodle/legacy') === 0) {
1671 /**********************************
1672 * Context Manipulation functions *
1673 **********************************/
1676 * Create a new context record for use by all roles-related stuff
1678 * @param $instanceid
1680 * @return object newly created context (or existing one with a debug warning)
1682 function create_context($contextlevel, $instanceid) {
1683 if (!$context = get_record('context','contextlevel',$contextlevel,'instanceid',$instanceid)) {
1684 if (!validate_context($contextlevel, $instanceid)) {
1685 debugging('Error: Invalid context creation request for level "'.s($contextlevel).'", instance "'.s($instanceid).'".');
1688 if ($contextlevel == CONTEXT_SYSTEM
) {
1689 return create_system_context();
1692 $context = new object();
1693 $context->contextlevel
= $contextlevel;
1694 $context->instanceid
= $instanceid;
1695 if ($id = insert_record('context',$context)) {
1696 // we need to populate context_rel for every new context inserted
1697 $c = get_record('context','id',$id);
1698 insert_context_rel ($c);
1701 debugging('Error: could not insert new context level "'.s($contextlevel).'", instance "'.s($instanceid).'".');
1705 debugging('Warning: Context id "'.s($context->id
).'" not created, because it already exists.');
1711 * This hacky function is needed because we can not change system context instanceid using normal upgrade routine.
1713 function create_system_context() {
1714 if ($context = get_record('context', 'contextlevel', CONTEXT_SYSTEM
, 'instanceid', SITEID
)) {
1715 // we are going to change instanceid of system context to 0 now
1716 $context->instanceid
= 0;
1717 update_record('context', $context);
1718 //context rel not affected
1722 $context = new object();
1723 $context->contextlevel
= CONTEXT_SYSTEM
;
1724 $context->instanceid
= 0;
1725 if ($context->id
= insert_record('context',$context)) {
1726 // we need not to populate context_rel for system context
1729 debugging('Can not create system context');
1735 * Create a new context record for use by all roles-related stuff
1737 * @param $instanceid
1739 * @return true if properly deleted
1741 function delete_context($contextlevel, $instanceid) {
1742 if ($context = get_context_instance($contextlevel, $instanceid)) {
1743 delete_records('context_rel', 'c2', $context->id
); // might not be a parent
1744 return delete_records('context', 'id', $context->id
) &&
1745 delete_records('role_assignments', 'contextid', $context->id
) &&
1746 delete_records('role_capabilities', 'contextid', $context->id
) &&
1747 delete_records('context_rel', 'c1', $context->id
);
1753 * Validate that object with instanceid really exists in given context level.
1755 * return if instanceid object exists
1757 function validate_context($contextlevel, $instanceid) {
1758 switch ($contextlevel) {
1760 case CONTEXT_SYSTEM
:
1761 return ($instanceid == 0);
1763 case CONTEXT_PERSONAL
:
1764 return (boolean
)count_records('user', 'id', $instanceid);
1767 return (boolean
)count_records('user', 'id', $instanceid);
1769 case CONTEXT_COURSECAT
:
1770 if ($instanceid == 0) {
1771 return true; // site course category
1773 return (boolean
)count_records('course_categories', 'id', $instanceid);
1775 case CONTEXT_COURSE
:
1776 return (boolean
)count_records('course', 'id', $instanceid);
1779 return groups_group_exists($instanceid);
1781 case CONTEXT_MODULE
:
1782 return (boolean
)count_records('course_modules', 'id', $instanceid);
1785 return (boolean
)count_records('block_instance', 'id', $instanceid);
1793 * Get the context instance as an object. This function will create the
1794 * context instance if it does not exist yet.
1798 function get_context_instance($contextlevel=NULL, $instance=0) {
1800 global $context_cache, $context_cache_id, $CONTEXT;
1801 static $allowed_contexts = array(CONTEXT_SYSTEM
, CONTEXT_PERSONAL
, CONTEXT_USER
, CONTEXT_COURSECAT
, CONTEXT_COURSE
, CONTEXT_GROUP
, CONTEXT_MODULE
, CONTEXT_BLOCK
);
1803 // Yu: Separating site and site course context - removed CONTEXT_COURSE override when SITEID
1806 if ($contextlevel == 'clearcache') {
1808 $context_cache = array();
1809 $context_cache_id = array();
1814 /// If no level is supplied then return the current global context if there is one
1815 if (empty($contextlevel)) {
1816 if (empty($CONTEXT)) {
1817 //fatal error, code must be fixed
1818 error("Error: get_context_instance() called without a context");
1824 /// Backwards compatibility with obsoleted (CONTEXT_SYSTEM, SITEID)
1825 if ($contextlevel == CONTEXT_SYSTEM
) {
1829 /// check allowed context levels
1830 if (!in_array($contextlevel, $allowed_contexts)) {
1831 // fatal error, code must be fixed - probably typo or switched parameters
1832 error('Error: get_context_instance() called with incorrect context level "'.s($contextlevel).'"');
1836 if (isset($context_cache[$contextlevel][$instance])) { // Already cached
1837 return $context_cache[$contextlevel][$instance];
1840 /// Get it from the database, or create it
1841 if (!$context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance)) {
1842 create_context($contextlevel, $instance);
1843 $context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance);
1846 /// Only add to cache if context isn't empty.
1847 if (!empty($context)) {
1848 $context_cache[$contextlevel][$instance] = $context; // Cache it for later
1849 $context_cache_id[$context->id
] = $context; // Cache it for later
1857 * Get a context instance as an object, from a given id.
1860 function get_context_instance_by_id($id) {
1862 global $context_cache, $context_cache_id;
1864 if (isset($context_cache_id[$id])) { // Already cached
1865 return $context_cache_id[$id];
1868 if ($context = get_record('context', 'id', $id)) { // Update the cache and return
1869 $context_cache[$context->contextlevel
][$context->instanceid
] = $context;
1870 $context_cache_id[$context->id
] = $context;
1879 * Get the local override (if any) for a given capability in a role in a context
1882 * @param $capability
1884 function get_local_override($roleid, $contextid, $capability) {
1885 return get_record('role_capabilities', 'roleid', $roleid, 'capability', $capability, 'contextid', $contextid);
1890 /************************************
1891 * DB TABLE RELATED FUNCTIONS *
1892 ************************************/
1895 * function that creates a role
1896 * @param name - role name
1897 * @param shortname - role short name
1898 * @param description - role description
1899 * @param legacy - optional legacy capability
1900 * @return id or false
1902 function create_role($name, $shortname, $description, $legacy='') {
1904 // check for duplicate role name
1906 if ($role = get_record('role','name', $name)) {
1907 error('there is already a role with this name!');
1910 if ($role = get_record('role','shortname', $shortname)) {
1911 error('there is already a role with this shortname!');
1914 $role = new object();
1915 $role->name
= $name;
1916 $role->shortname
= $shortname;
1917 $role->description
= $description;
1919 //find free sortorder number
1920 $role->sortorder
= count_records('role');
1921 while (get_record('role','sortorder', $role->sortorder
)) {
1922 $role->sortorder +
= 1;
1925 if (!$context = get_context_instance(CONTEXT_SYSTEM
)) {
1929 if ($id = insert_record('role', $role)) {
1931 assign_capability($legacy, CAP_ALLOW
, $id, $context->id
);
1934 /// By default, users with role:manage at site level
1935 /// should be able to assign users to this new role, and override this new role's capabilities
1937 // find all admin roles
1938 if ($adminroles = get_roles_with_capability('moodle/role:manage', CAP_ALLOW
, $context)) {
1939 // foreach admin role
1940 foreach ($adminroles as $arole) {
1941 // write allow_assign and allow_overrid
1942 allow_assign($arole->id
, $id);
1943 allow_override($arole->id
, $id);
1955 * function that deletes a role and cleanups up after it
1956 * @param roleid - id of role to delete
1959 function delete_role($roleid) {
1962 // first unssign all users
1963 if (!role_unassign($roleid)) {
1964 debugging("Error while unassigning all users from role with ID $roleid!");
1968 // cleanup all references to this role, ignore errors
1970 delete_records('role_capabilities', 'roleid', $roleid);
1971 delete_records('role_allow_assign', 'roleid', $roleid);
1972 delete_records('role_allow_assign', 'allowassign', $roleid);
1973 delete_records('role_allow_override', 'roleid', $roleid);
1974 delete_records('role_allow_override', 'allowoverride', $roleid);
1975 delete_records('role_names', 'roleid', $roleid);
1978 // finally delete the role itself
1979 if ($success and !delete_records('role', 'id', $roleid)) {
1980 debugging("Could not delete role record with ID $roleid!");
1988 * Function to write context specific overrides, or default capabilities.
1989 * @param module - string name
1990 * @param capability - string name
1991 * @param contextid - context id
1992 * @param roleid - role id
1993 * @param permission - int 1,-1 or -1000
1994 * should not be writing if permission is 0
1996 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite=false) {
2000 if (empty($permission) ||
$permission == CAP_INHERIT
) { // if permission is not set
2001 unassign_capability($capability, $roleid, $contextid);
2005 $existing = get_record('role_capabilities', 'contextid', $contextid, 'roleid', $roleid, 'capability', $capability);
2007 if ($existing and !$overwrite) { // We want to keep whatever is there already
2012 $cap->contextid
= $contextid;
2013 $cap->roleid
= $roleid;
2014 $cap->capability
= $capability;
2015 $cap->permission
= $permission;
2016 $cap->timemodified
= time();
2017 $cap->modifierid
= empty($USER->id
) ?
0 : $USER->id
;
2020 $cap->id
= $existing->id
;
2021 return update_record('role_capabilities', $cap);
2023 return insert_record('role_capabilities', $cap);
2029 * Unassign a capability from a role.
2030 * @param $roleid - the role id
2031 * @param $capability - the name of the capability
2032 * @return boolean - success or failure
2034 function unassign_capability($capability, $roleid, $contextid=NULL) {
2036 if (isset($contextid)) {
2037 $status = delete_records('role_capabilities', 'capability', $capability,
2038 'roleid', $roleid, 'contextid', $contextid);
2040 $status = delete_records('role_capabilities', 'capability', $capability,
2048 * Get the roles that have a given capability assigned to it. This function
2049 * does not resolve the actual permission of the capability. It just checks
2050 * for assignment only.
2051 * @param $capability - capability name (string)
2052 * @param $permission - optional, the permission defined for this capability
2053 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT
2054 * @return array or role objects
2056 function get_roles_with_capability($capability, $permission=NULL, $context='') {
2061 if ($contexts = get_parent_contexts($context)) {
2062 $listofcontexts = '('.implode(',', $contexts).')';
2064 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
2065 $listofcontexts = '('.$sitecontext->id
.')'; // must be site
2067 $contextstr = "AND (rc.contextid = '$context->id' OR rc.contextid IN $listofcontexts)";
2072 $selectroles = "SELECT r.*
2073 FROM {$CFG->prefix}role r,
2074 {$CFG->prefix}role_capabilities rc
2075 WHERE rc.capability = '$capability'
2076 AND rc.roleid = r.id $contextstr";
2078 if (isset($permission)) {
2079 $selectroles .= " AND rc.permission = '$permission'";
2081 return get_records_sql($selectroles);
2086 * This function makes a role-assignment (a role for a user or group in a particular context)
2087 * @param $roleid - the role of the id
2088 * @param $userid - userid
2089 * @param $groupid - group id
2090 * @param $contextid - id of the context
2091 * @param $timestart - time this assignment becomes effective
2092 * @param $timeend - time this assignemnt ceases to be effective
2094 * @return id - new id of the assigment
2096 function role_assign($roleid, $userid, $groupid, $contextid, $timestart=0, $timeend=0, $hidden=0, $enrol='manual') {
2099 debugging("Assign roleid $roleid userid $userid contextid $contextid", DEBUG_DEVELOPER
);
2101 /// Do some data validation
2103 if (empty($roleid)) {
2104 debugging('Role ID not provided');
2108 if (empty($userid) && empty($groupid)) {
2109 debugging('Either userid or groupid must be provided');
2113 if ($userid && !record_exists('user', 'id', $userid)) {
2114 debugging('User ID '.intval($userid).' does not exist!');
2118 if ($groupid && !groups_group_exists($groupid)) {
2119 debugging('Group ID '.intval($groupid).' does not exist!');
2123 if (!$context = get_context_instance_by_id($contextid)) {
2124 debugging('Context ID '.intval($contextid).' does not exist!');
2128 if (($timestart and $timeend) and ($timestart > $timeend)) {
2129 debugging('The end time can not be earlier than the start time');
2134 /// Check for existing entry
2136 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id
, 'userid', $userid);
2138 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id
, 'groupid', $groupid);
2142 $newra = new object;
2144 if (empty($ra)) { // Create a new entry
2145 $newra->roleid
= $roleid;
2146 $newra->contextid
= $context->id
;
2147 $newra->userid
= $userid;
2148 $newra->hidden
= $hidden;
2149 $newra->enrol
= $enrol;
2150 /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
2151 /// by repeating queries with the same exact parameters in a 100 secs time window
2152 $newra->timestart
= round($timestart, -2);
2153 $newra->timeend
= $timeend;
2154 $newra->timemodified
= time();
2155 $newra->modifierid
= empty($USER->id
) ?
0 : $USER->id
;
2157 $success = insert_record('role_assignments', $newra);
2159 } else { // We already have one, just update it
2161 $newra->id
= $ra->id
;
2162 $newra->hidden
= $hidden;
2163 $newra->enrol
= $enrol;
2164 /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
2165 /// by repeating queries with the same exact parameters in a 100 secs time window
2166 $newra->timestart
= round($timestart, -2);
2167 $newra->timeend
= $timeend;
2168 $newra->timemodified
= time();
2169 $newra->modifierid
= empty($USER->id
) ?
0 : $USER->id
;
2171 $success = update_record('role_assignments', $newra);
2174 if ($success) { /// Role was assigned, so do some other things
2176 /// If the user is the current user, then reload the capabilities too.
2177 if (!empty($USER->id
) && $USER->id
== $userid) {
2178 load_all_capabilities();
2181 /// Ask all the modules if anything needs to be done for this user
2182 if ($mods = get_list_of_plugins('mod')) {
2183 foreach ($mods as $mod) {
2184 include_once($CFG->dirroot
.'/mod/'.$mod.'/lib.php');
2185 $functionname = $mod.'_role_assign';
2186 if (function_exists($functionname)) {
2187 $functionname($userid, $context, $roleid);
2192 /// Make sure they have an entry in user_lastaccess for courses they can access
2193 // role_add_lastaccess_entries($userid, $context);
2196 /// now handle metacourse role assignments if in course context
2197 if ($success and $context->contextlevel
== CONTEXT_COURSE
) {
2198 if ($parents = get_records('course_meta', 'child_course', $context->instanceid
)) {
2199 foreach ($parents as $parent) {
2200 sync_metacourse($parent->parent_course
);
2210 * Deletes one or more role assignments. You must specify at least one parameter.
2215 * @param $enrol unassign only if enrolment type matches, NULL means anything
2216 * @return boolean - success or failure
2218 function role_unassign($roleid=0, $userid=0, $groupid=0, $contextid=0, $enrol=NULL) {
2224 $args = array('roleid', 'userid', 'groupid', 'contextid');
2226 foreach ($args as $arg) {
2228 $select[] = $arg.' = '.$
$arg;
2231 if (!empty($enrol)) {
2232 $select[] = "enrol='$enrol'";
2236 if ($ras = get_records_select('role_assignments', implode(' AND ', $select))) {
2237 $mods = get_list_of_plugins('mod');
2238 foreach($ras as $ra) {
2239 /// infinite loop protection when deleting recursively
2240 if (!$ra = get_record('role_assignments', 'id', $ra->id
)) {
2243 $success = delete_records('role_assignments', 'id', $ra->id
) and $success;
2245 /// If the user is the current user, then reload the capabilities too.
2246 if (!empty($USER->id
) && $USER->id
== $ra->userid
) {
2247 load_all_capabilities();
2249 $context = get_record('context', 'id', $ra->contextid
);
2251 /// Ask all the modules if anything needs to be done for this user
2252 foreach ($mods as $mod) {
2253 include_once($CFG->dirroot
.'/mod/'.$mod.'/lib.php');
2254 $functionname = $mod.'_role_unassign';
2255 if (function_exists($functionname)) {
2256 $functionname($ra->userid
, $context); // watch out, $context might be NULL if something goes wrong
2260 /// now handle metacourse role unassigment and removing from goups if in course context
2261 if (!empty($context) and $context->contextlevel
== CONTEXT_COURSE
) {
2262 //remove from groups when user has no role
2263 $roles = get_user_roles($context, $ra->userid
, true);
2264 if (empty($roles)) {
2265 if ($groups = get_groups($context->instanceid
, $ra->userid
)) {
2266 foreach ($groups as $group) {
2267 delete_records('groups_members', 'groupid', $group->id
, 'userid', $ra->userid
);
2271 //unassign roles in metacourses if needed
2272 if ($parents = get_records('course_meta', 'child_course', $context->instanceid
)) {
2273 foreach ($parents as $parent) {
2274 sync_metacourse($parent->parent_course
);
2286 * A convenience function to take care of the common case where you
2287 * just want to enrol someone using the default role into a course
2289 * @param object $course
2290 * @param object $user
2291 * @param string $enrol - the plugin used to do this enrolment
2293 function enrol_into_course($course, $user, $enrol) {
2295 $timestart = time();
2296 if ($course->enrolperiod
) {
2297 $timeend = time() +
$course->enrolperiod
;
2302 if ($role = get_default_course_role($course)) {
2304 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
2306 if (!role_assign($role->id
, $user->id
, 0, $context->id
, $timestart, $timeend, 0, $enrol)) {
2310 email_welcome_message_to_user($course, $user);
2312 add_to_log($course->id
, 'course', 'enrol', 'view.php?id='.$course->id
, $user->id
);
2321 * Add last access times to user_lastaccess as required
2324 * @return boolean - success or failure
2326 function role_add_lastaccess_entries($userid, $context) {
2330 if (empty($context->contextlevel
)) {
2334 $lastaccess = new object; // Reusable object below
2335 $lastaccess->userid
= $userid;
2336 $lastaccess->timeaccess
= 0;
2338 switch ($context->contextlevel
) {
2340 case CONTEXT_SYSTEM
: // For the whole site
2341 if ($courses = get_record('course')) {
2342 foreach ($courses as $course) {
2343 $lastaccess->courseid
= $course->id
;
2344 role_set_lastaccess($lastaccess);
2349 case CONTEXT_CATEGORY
: // For a whole category
2350 if ($courses = get_record('course', 'category', $context->instanceid
)) {
2351 foreach ($courses as $course) {
2352 $lastaccess->courseid
= $course->id
;
2353 role_set_lastaccess($lastaccess);
2356 if ($categories = get_record('course_categories', 'parent', $context->instanceid
)) {
2357 foreach ($categories as $category) {
2358 $subcontext = get_context_instance(CONTEXT_CATEGORY
, $category->id
);
2359 role_add_lastaccess_entries($userid, $subcontext);
2365 case CONTEXT_COURSE
: // For a whole course
2366 if ($course = get_record('course', 'id', $context->instanceid
)) {
2367 $lastaccess->courseid
= $course->id
;
2368 role_set_lastaccess($lastaccess);
2375 * Delete last access times from user_lastaccess as required
2378 * @return boolean - success or failure
2380 function role_remove_lastaccess_entries($userid, $context) {
2388 * Loads the capability definitions for the component (from file). If no
2389 * capabilities are defined for the component, we simply return an empty array.
2390 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2391 * @return array of capabilities
2393 function load_capability_def($component) {
2396 if ($component == 'moodle') {
2397 $defpath = $CFG->libdir
.'/db/access.php';
2398 $varprefix = 'moodle';
2400 $compparts = explode('/', $component);
2402 if ($compparts[0] == 'block') {
2403 // Blocks are an exception. Blocks directory is 'blocks', and not
2404 // 'block'. So we need to jump through hoops.
2405 $defpath = $CFG->dirroot
.'/'.$compparts[0].
2406 's/'.$compparts[1].'/db/access.php';
2407 $varprefix = $compparts[0].'_'.$compparts[1];
2408 } else if ($compparts[0] == 'format') {
2409 // Similar to the above, course formats are 'format' while they
2410 // are stored in 'course/format'.
2411 $defpath = $CFG->dirroot
.'/course/'.$component.'/db/access.php';
2412 $varprefix = $compparts[0].'_'.$compparts[1];
2414 $defpath = $CFG->dirroot
.'/'.$component.'/db/access.php';
2415 $varprefix = str_replace('/', '_', $component);
2418 $capabilities = array();
2420 if (file_exists($defpath)) {
2422 $capabilities = $
{$varprefix.'_capabilities'};
2424 return $capabilities;
2429 * Gets the capabilities that have been cached in the database for this
2431 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2432 * @return array of capabilities
2434 function get_cached_capabilities($component='moodle') {
2435 if ($component == 'moodle') {
2436 $storedcaps = get_records_select('capabilities',
2437 "name LIKE 'moodle/%:%'");
2439 $storedcaps = get_records_select('capabilities',
2440 "name LIKE '$component:%'");
2446 * Returns default capabilities for given legacy role type.
2448 * @param string legacy role name
2451 function get_default_capabilities($legacyrole) {
2452 if (!$allcaps = get_records('capabilities')) {
2453 error('Error: no capabilitites defined!');
2456 $defaults = array();
2457 $components = array();
2458 foreach ($allcaps as $cap) {
2459 if (!in_array($cap->component
, $components)) {
2460 $components[] = $cap->component
;
2461 $alldefs = array_merge($alldefs, load_capability_def($cap->component
));
2464 foreach($alldefs as $name=>$def) {
2465 if (isset($def['legacy'][$legacyrole])) {
2466 $defaults[$name] = $def['legacy'][$legacyrole];
2471 $defaults['moodle/legacy:'.$legacyrole] = CAP_ALLOW
;
2472 if ($legacyrole == 'admin') {
2473 $defaults['moodle/site:doanything'] = CAP_ALLOW
;
2479 * Reset role capabilitites to default according to selected legacy capability.
2480 * If several legacy caps selected, use the first from get_default_capabilities.
2481 * If no legacy selected, removes all capabilities.
2483 * @param int @roleid
2485 function reset_role_capabilities($roleid) {
2486 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
2487 $legacyroles = get_legacy_roles();
2489 $defaultcaps = array();
2490 foreach($legacyroles as $ltype=>$lcap) {
2491 $localoverride = get_local_override($roleid, $sitecontext->id
, $lcap);
2492 if (!empty($localoverride->permission
) and $localoverride->permission
== CAP_ALLOW
) {
2493 //choose first selected legacy capability
2494 $defaultcaps = get_default_capabilities($ltype);
2499 delete_records('role_capabilities', 'roleid', $roleid);
2500 if (!empty($defaultcaps)) {
2501 foreach($defaultcaps as $cap=>$permission) {
2502 assign_capability($cap, $permission, $roleid, $sitecontext->id
);
2508 * Updates the capabilities table with the component capability definitions.
2509 * If no parameters are given, the function updates the core moodle
2512 * Note that the absence of the db/access.php capabilities definition file
2513 * will cause any stored capabilities for the component to be removed from
2516 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2519 function update_capabilities($component='moodle') {
2521 $storedcaps = array();
2523 $filecaps = load_capability_def($component);
2524 $cachedcaps = get_cached_capabilities($component);
2526 foreach ($cachedcaps as $cachedcap) {
2527 array_push($storedcaps, $cachedcap->name
);
2528 // update risk bitmasks and context levels in existing capabilities if needed
2529 if (array_key_exists($cachedcap->name
, $filecaps)) {
2530 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name
])) {
2531 $filecaps[$cachedcap->name
]['riskbitmask'] = 0; // no risk if not specified
2533 if ($cachedcap->riskbitmask
!= $filecaps[$cachedcap->name
]['riskbitmask']) {
2534 $updatecap = new object();
2535 $updatecap->id
= $cachedcap->id
;
2536 $updatecap->riskbitmask
= $filecaps[$cachedcap->name
]['riskbitmask'];
2537 if (!update_record('capabilities', $updatecap)) {
2542 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name
])) {
2543 $filecaps[$cachedcap->name
]['contextlevel'] = 0; // no context level defined
2545 if ($cachedcap->contextlevel
!= $filecaps[$cachedcap->name
]['contextlevel']) {
2546 $updatecap = new object();
2547 $updatecap->id
= $cachedcap->id
;
2548 $updatecap->contextlevel
= $filecaps[$cachedcap->name
]['contextlevel'];
2549 if (!update_record('capabilities', $updatecap)) {
2557 // Are there new capabilities in the file definition?
2560 foreach ($filecaps as $filecap => $def) {
2562 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2563 if (!array_key_exists('riskbitmask', $def)) {
2564 $def['riskbitmask'] = 0; // no risk if not specified
2566 $newcaps[$filecap] = $def;
2569 // Add new capabilities to the stored definition.
2570 foreach ($newcaps as $capname => $capdef) {
2571 $capability = new object;
2572 $capability->name
= $capname;
2573 $capability->captype
= $capdef['captype'];
2574 $capability->contextlevel
= $capdef['contextlevel'];
2575 $capability->component
= $component;
2576 $capability->riskbitmask
= $capdef['riskbitmask'];
2578 if (!insert_record('capabilities', $capability, false, 'id')) {
2582 // Do we need to assign the new capabilities to roles that have the
2583 // legacy capabilities moodle/legacy:* as well?
2584 if (isset($capdef['legacy']) && is_array($capdef['legacy']) &&
2585 !assign_legacy_capabilities($capname, $capdef['legacy'])) {
2586 notify('Could not assign legacy capabilities for '.$capname);
2589 // Are there any capabilities that have been removed from the file
2590 // definition that we need to delete from the stored capabilities and
2591 // role assignments?
2592 capabilities_cleanup($component, $filecaps);
2599 * Deletes cached capabilities that are no longer needed by the component.
2600 * Also unassigns these capabilities from any roles that have them.
2601 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2602 * @param $newcapdef - array of the new capability definitions that will be
2603 * compared with the cached capabilities
2604 * @return int - number of deprecated capabilities that have been removed
2606 function capabilities_cleanup($component, $newcapdef=NULL) {
2610 if ($cachedcaps = get_cached_capabilities($component)) {
2611 foreach ($cachedcaps as $cachedcap) {
2612 if (empty($newcapdef) ||
2613 array_key_exists($cachedcap->name
, $newcapdef) === false) {
2615 // Remove from capabilities cache.
2616 if (!delete_records('capabilities', 'name', $cachedcap->name
)) {
2617 error('Could not delete deprecated capability '.$cachedcap->name
);
2621 // Delete from roles.
2622 if($roles = get_roles_with_capability($cachedcap->name
)) {
2623 foreach($roles as $role) {
2624 if (!unassign_capability($cachedcap->name
, $role->id
)) {
2625 error('Could not unassign deprecated capability '.
2626 $cachedcap->name
.' from role '.$role->name
);
2633 return $removedcount;
2644 * prints human readable context identifier.
2646 function print_context_name($context) {
2649 switch ($context->contextlevel
) {
2651 case CONTEXT_SYSTEM
: // by now it's a definite an inherit
2652 $name = get_string('coresystem');
2655 case CONTEXT_PERSONAL
:
2656 $name = get_string('personal');
2660 if ($user = get_record('user', 'id', $context->instanceid
)) {
2661 $name = get_string('user').': '.fullname($user);
2665 case CONTEXT_COURSECAT
: // Coursecat -> coursecat or site
2666 if ($category = get_record('course_categories', 'id', $context->instanceid
)) {
2667 $name = get_string('category').': '. format_string($category->name
);
2671 case CONTEXT_COURSE
: // 1 to 1 to course cat
2672 if ($course = get_record('course', 'id', $context->instanceid
)) {
2674 if ($context->instanceid
== SITEID
) {
2675 $name = get_string('site').': '. format_string($course->fullname
);
2677 $name = get_string('course').': '. format_string($course->fullname
);
2682 case CONTEXT_GROUP
: // 1 to 1 to course
2683 if ($name = groups_get_group_name($context->instanceid
)) {
2684 $name = get_string('group').': '. $name;
2688 case CONTEXT_MODULE
: // 1 to 1 to course
2689 if ($cm = get_record('course_modules','id',$context->instanceid
)) {
2690 if ($module = get_record('modules','id',$cm->module
)) {
2691 if ($mod = get_record($module->name
, 'id', $cm->instance
)) {
2692 $name = get_string('activitymodule').': '.$mod->name
;
2698 case CONTEXT_BLOCK
: // 1 to 1 to course
2699 if ($blockinstance = get_record('block_instance','id',$context->instanceid
)) {
2700 if ($block = get_record('block','id',$blockinstance->blockid
)) {
2702 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
2703 require_once("$CFG->dirroot/blocks/$block->name/block_$block->name.php");
2704 $blockname = "block_$block->name";
2705 if ($blockobject = new $blockname()) {
2706 $name = $blockobject->title
.' ('.get_string('block').')';
2713 error ('This is an unknown context (' . $context->contextlevel
. ') in print_context_name!');
2722 * Extracts the relevant capabilities given a contextid.
2723 * All case based, example an instance of forum context.
2724 * Will fetch all forum related capabilities, while course contexts
2725 * Will fetch all capabilities
2726 * @param object context
2730 * `name` varchar(150) NOT NULL,
2731 * `captype` varchar(50) NOT NULL,
2732 * `contextlevel` int(10) NOT NULL,
2733 * `component` varchar(100) NOT NULL,
2735 function fetch_context_capabilities($context) {
2739 $sort = 'ORDER BY contextlevel,component,id'; // To group them sensibly for display
2741 switch ($context->contextlevel
) {
2743 case CONTEXT_SYSTEM
: // all
2744 $SQL = "select * from {$CFG->prefix}capabilities";
2747 case CONTEXT_PERSONAL
:
2748 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_PERSONAL
;
2753 FROM {$CFG->prefix}capabilities
2754 WHERE contextlevel = ".CONTEXT_USER
;
2757 case CONTEXT_COURSECAT
: // all
2758 $SQL = "select * from {$CFG->prefix}capabilities";
2761 case CONTEXT_COURSE
: // all
2762 $SQL = "select * from {$CFG->prefix}capabilities";
2765 case CONTEXT_GROUP
: // group caps
2768 case CONTEXT_MODULE
: // mod caps
2769 $cm = get_record('course_modules', 'id', $context->instanceid
);
2770 $module = get_record('modules', 'id', $cm->module
);
2772 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_MODULE
."
2773 and component = 'mod/$module->name'";
2776 case CONTEXT_BLOCK
: // block caps
2777 $cb = get_record('block_instance', 'id', $context->instanceid
);
2778 $block = get_record('block', 'id', $cb->blockid
);
2780 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_BLOCK
."
2781 and component = 'block/$block->name'";
2788 if (!$records = get_records_sql($SQL.' '.$sort)) {
2792 /// the rest of code is a bit hacky, think twice before modifying it :-(
2794 // special sorting of core system capabiltites and enrollments
2795 if (in_array($context->contextlevel
, array(CONTEXT_SYSTEM
, CONTEXT_COURSECAT
, CONTEXT_COURSE
))) {
2797 foreach ($records as $key=>$record) {
2798 if (preg_match('|^moodle/|', $record->name
) and $record->contextlevel
== CONTEXT_SYSTEM
) {
2799 $first[$key] = $record;
2800 unset($records[$key]);
2801 } else if (count($first)){
2805 if (count($first)) {
2806 $records = $first +
$records; // merge the two arrays keeping the keys
2809 $contextindependentcaps = fetch_context_independent_capabilities();
2810 $records = array_merge($contextindependentcaps, $records);
2819 * Gets the context-independent capabilities that should be overrridable in
2821 * @return array of capability records from the capabilities table.
2823 function fetch_context_independent_capabilities() {
2825 //only CONTEXT_SYSTEM capabilities here or it will break the hack in fetch_context_capabilities()
2826 $contextindependentcaps = array(
2827 'moodle/site:accessallgroups'
2832 foreach ($contextindependentcaps as $capname) {
2833 $record = get_record('capabilities', 'name', $capname);
2834 array_push($records, $record);
2841 * This function pulls out all the resolved capabilities (overrides and
2842 * defaults) of a role used in capability overrides in contexts at a given
2844 * @param obj $context
2845 * @param int $roleid
2846 * @param bool self - if set to true, resolve till this level, else stop at immediate parent level
2849 function role_context_capabilities($roleid, $context, $cap='') {
2852 $contexts = get_parent_contexts($context);
2853 $contexts[] = $context->id
;
2854 $contexts = '('.implode(',', $contexts).')';
2857 $search = " AND rc.capability = '$cap' ";
2863 FROM {$CFG->prefix}role_capabilities rc,
2864 {$CFG->prefix}context c
2865 WHERE rc.contextid in $contexts
2866 AND rc.roleid = $roleid
2867 AND rc.contextid = c.id $search
2868 ORDER BY c.contextlevel DESC,
2869 rc.capability DESC";
2871 $capabilities = array();
2873 if ($records = get_records_sql($SQL)) {
2874 // We are traversing via reverse order.
2875 foreach ($records as $record) {
2876 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2877 if (!isset($capabilities[$record->capability
]) ||
$record->permission
<-500) {
2878 $capabilities[$record->capability
] = $record->permission
;
2882 return $capabilities;
2886 * Recursive function which, given a context, find all parent context ids,
2887 * and return the array in reverse order, i.e. parent first, then grand
2889 * @param object $context
2892 function get_parent_contexts($context) {
2894 static $pcontexts; // cache
2895 if (isset($pcontexts[$context->id
])) {
2896 return ($pcontexts[$context->id
]);
2899 switch ($context->contextlevel
) {
2901 case CONTEXT_SYSTEM
: // no parent
2905 case CONTEXT_PERSONAL
:
2906 if (!$parent = get_context_instance(CONTEXT_SYSTEM
)) {
2909 $res = array($parent->id
);
2910 $pcontexts[$context->id
] = $res;
2916 if (!$parent = get_context_instance(CONTEXT_SYSTEM
)) {
2919 $res = array($parent->id
);
2920 $pcontexts[$context->id
] = $res;
2925 case CONTEXT_COURSECAT
: // Coursecat -> coursecat or site
2926 if (!$coursecat = get_record('course_categories','id',$context->instanceid
)) {
2929 if (!empty($coursecat->parent
)) { // return parent value if exist
2930 $parent = get_context_instance(CONTEXT_COURSECAT
, $coursecat->parent
);
2931 $res = array_merge(array($parent->id
), get_parent_contexts($parent));
2932 $pcontexts[$context->id
] = $res;
2934 } else { // else return site value
2935 $parent = get_context_instance(CONTEXT_SYSTEM
);
2936 $res = array($parent->id
);
2937 $pcontexts[$context->id
] = $res;
2942 case CONTEXT_COURSE
: // 1 to 1 to course cat
2943 if (!$course = get_record('course','id',$context->instanceid
)) {
2946 if ($course->id
!= SITEID
) {
2947 $parent = get_context_instance(CONTEXT_COURSECAT
, $course->category
);
2948 $res = array_merge(array($parent->id
), get_parent_contexts($parent));
2951 // Yu: Separating site and site course context
2952 $parent = get_context_instance(CONTEXT_SYSTEM
);
2953 $res = array($parent->id
);
2954 $pcontexts[$context->id
] = $res;
2959 case CONTEXT_GROUP
: // 1 to 1 to course
2960 if (! $group = groups_get_group($context->instanceid
)) {
2963 if ($parent = get_context_instance(CONTEXT_COURSE
, $group->courseid
)) {
2964 $res = array_merge(array($parent->id
), get_parent_contexts($parent));
2965 $pcontexts[$context->id
] = $res;
2972 case CONTEXT_MODULE
: // 1 to 1 to course
2973 if (!$cm = get_record('course_modules','id',$context->instanceid
)) {
2976 if ($parent = get_context_instance(CONTEXT_COURSE
, $cm->course
)) {
2977 $res = array_merge(array($parent->id
), get_parent_contexts($parent));
2978 $pcontexts[$context->id
] = $res;
2985 case CONTEXT_BLOCK
: // 1 to 1 to course
2986 if (!$block = get_record('block_instance','id',$context->instanceid
)) {
2989 // fix for MDL-9656, block parents are not necessarily courses
2990 if ($block->pagetype
== 'course-view') {
2991 $parent = get_context_instance(CONTEXT_COURSE
, $block->pageid
);
2993 $parent = get_context_instance(CONTEXT_SYSTEM
);
2997 $res = array_merge(array($parent->id
), get_parent_contexts($parent));
2998 $pcontexts[$context->id
] = $res;
3006 error('This is an unknown context (' . $context->contextlevel
. ') in get_parent_contexts!');
3013 * Recursive function which, given a context, find all its children context ids.
3014 * @param object $context.
3015 * @return array of children context ids.
3017 function get_child_contexts($context) {
3020 $children = array();
3022 switch ($context->contextlevel
) {
3029 case CONTEXT_MODULE
:
3039 case CONTEXT_COURSE
:
3040 // Find all block instances for the course.
3041 $page = new page_course
;
3042 $page->id
= $context->instanceid
;
3043 $page->type
= 'course-view';
3044 if ($blocks = blocks_get_by_page_pinned($page)) {
3045 foreach ($blocks['l'] as $leftblock) {
3046 if ($child = get_context_instance(CONTEXT_BLOCK
, $leftblock->id
)) {
3047 array_push($children, $child->id
);
3050 foreach ($blocks['r'] as $rightblock) {
3051 if ($child = get_context_instance(CONTEXT_BLOCK
, $rightblock->id
)) {
3052 array_push($children, $child->id
);
3056 // Find all module instances for the course.
3057 if ($modules = get_records('course_modules', 'course', $context->instanceid
)) {
3058 foreach ($modules as $module) {
3059 if ($child = get_context_instance(CONTEXT_MODULE
, $module->id
)) {
3060 array_push($children, $child->id
);
3064 // Find all group instances for the course.
3065 if ($groupids = groups_get_groups($context->instanceid
)) {
3066 foreach ($groupids as $groupid) {
3067 if ($child = get_context_instance(CONTEXT_GROUP
, $groupid)) {
3068 array_push($children, $child->id
);
3075 case CONTEXT_COURSECAT
:
3076 // We need to get the contexts for:
3077 // 1) The subcategories of the given category
3078 // 2) The courses in the given category and all its subcategories
3079 // 3) All the child contexts for these courses
3081 $categories = get_all_subcategories($context->instanceid
);
3083 // Add the contexts for all the subcategories.
3084 foreach ($categories as $catid) {
3085 if ($catci = get_context_instance(CONTEXT_COURSECAT
, $catid)) {
3086 array_push($children, $catci->id
);
3090 // Add the parent category as well so we can find the contexts
3092 array_unshift($categories, $context->instanceid
);
3094 foreach ($categories as $catid) {
3095 // Find all courses for the category.
3096 if ($courses = get_records('course', 'category', $catid)) {
3097 foreach ($courses as $course) {
3098 if ($courseci = get_context_instance(CONTEXT_COURSE
, $course->id
)) {
3099 array_push($children, $courseci->id
);
3100 $children = array_merge($children, get_child_contexts($courseci));
3113 case CONTEXT_PERSONAL
:
3118 case CONTEXT_SYSTEM
:
3119 // Just get all the contexts except for CONTEXT_SYSTEM level.
3120 $sql = 'SELECT c.id '.
3121 'FROM '.$CFG->prefix
.'context AS c '.
3122 'WHERE contextlevel != '.CONTEXT_SYSTEM
;
3124 $contexts = get_records_sql($sql);
3125 foreach ($contexts as $cid) {
3126 array_push($children, $cid->id
);
3132 error('This is an unknown context (' . $context->contextlevel
. ') in get_child_contexts!');
3139 * Gets a string for sql calls, searching for stuff in this context or above
3140 * @param object $context
3143 function get_related_contexts_string($context) {
3144 if ($parents = get_parent_contexts($context)) {
3145 return (' IN ('.$context->id
.','.implode(',', $parents).')');
3147 return (' ='.$context->id
);
3153 * This function gets the capability of a role in a given context.
3154 * It is needed when printing override forms.
3155 * @param int $contextid
3156 * @param string $capability
3157 * @param array $capabilities - array loaded using role_context_capabilities
3158 * @return int (allow, prevent, prohibit, inherit)
3160 function get_role_context_capability($contextid, $capability, $capabilities) {
3161 if (isset($capabilities[$contextid][$capability])) {
3162 return $capabilities[$contextid][$capability];
3171 * Returns the human-readable, translated version of the capability.
3172 * Basically a big switch statement.
3173 * @param $capabilityname - e.g. mod/choice:readresponses
3175 function get_capability_string($capabilityname) {
3177 // Typical capabilityname is mod/choice:readresponses
3179 $names = split('/', $capabilityname);
3180 $stringname = $names[1]; // choice:readresponses
3181 $components = split(':', $stringname);
3182 $componentname = $components[0]; // choice
3184 switch ($names[0]) {
3186 $string = get_string($stringname, $componentname);
3190 $string = get_string($stringname, 'block_'.$componentname);
3194 $string = get_string($stringname, 'role');
3198 $string = get_string($stringname, 'enrol_'.$componentname);
3202 $string = get_string($stringname, 'format_'.$componentname);
3206 $string = get_string($stringname);
3215 * This gets the mod/block/course/core etc strings.
3217 * @param $contextlevel
3219 function get_component_string($component, $contextlevel) {
3221 switch ($contextlevel) {
3223 case CONTEXT_SYSTEM
:
3224 if (preg_match('|^enrol/|', $component)) {
3225 $langname = str_replace('/', '_', $component);
3226 $string = get_string('enrolname', $langname);
3227 } else if (preg_match('|^block/|', $component)) {
3228 $langname = str_replace('/', '_', $component);
3229 $string = get_string('blockname', $langname);
3231 $string = get_string('coresystem');
3235 case CONTEXT_PERSONAL
:
3236 $string = get_string('personal');
3240 $string = get_string('users');
3243 case CONTEXT_COURSECAT
:
3244 $string = get_string('categories');
3247 case CONTEXT_COURSE
:
3248 $string = get_string('course');
3252 $string = get_string('group');
3255 case CONTEXT_MODULE
:
3256 $string = get_string('modulename', basename($component));
3260 $string = get_string('blockname', 'block_'.basename($component));
3264 error ('This is an unknown context $contextlevel (' . $contextlevel . ') in get_component_string!');
3272 * Gets the list of roles assigned to this context and up (parents)
3273 * @param object $context
3274 * @param view - set to true when roles are pulled for display only
3275 * this is so that we can filter roles with no visible
3276 * assignment, for example, you might want to "hide" all
3277 * course creators when browsing the course participants
3281 function get_roles_used_in_context($context, $view = false) {
3285 // filter for roles with all hidden assignments
3286 // no need to return when only pulling roles for reviewing
3287 // e.g. participants page.
3288 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))?
' AND ra.hidden = 0 ':'';
3289 $contextlist = get_related_contexts_string($context);
3291 $sql = "SELECT DISTINCT r.id,
3295 FROM {$CFG->prefix}role_assignments ra,
3296 {$CFG->prefix}role r
3297 WHERE r.id = ra.roleid
3298 AND ra.contextid $contextlist
3300 ORDER BY r.sortorder ASC";
3302 return get_records_sql($sql);
3305 /** this function is used to print roles column in user profile page.
3307 * @param int contextid
3310 function get_user_roles_in_context($userid, $contextid){
3314 $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';
3315 if ($roles = get_records_sql($SQL)) {
3316 foreach ($roles as $userrole) {
3317 $rolestring .= '<a href="'.$CFG->wwwroot
.'/user/index.php?contextid='.$userrole->contextid
.'&roleid='.$userrole->roleid
.'">'.$userrole->name
.'</a>, ';
3321 return rtrim($rolestring, ', ');
3326 * Checks if a user can override capabilities of a particular role in this context
3327 * @param object $context
3328 * @param int targetroleid - the id of the role you want to override
3331 function user_can_override($context, $targetroleid) {
3332 // first check if user has override capability
3333 // if not return false;
3334 if (!has_capability('moodle/role:override', $context)) {
3337 // pull out all active roles of this user from this context(or above)
3338 if ($userroles = get_user_roles($context)) {
3339 foreach ($userroles as $userrole) {
3340 // if any in the role_allow_override table, then it's ok
3341 if (get_record('role_allow_override', 'roleid', $userrole->roleid
, 'allowoverride', $targetroleid)) {
3352 * Checks if a user can assign users to a particular role in this context
3353 * @param object $context
3354 * @param int targetroleid - the id of the role you want to assign users to
3357 function user_can_assign($context, $targetroleid) {
3359 // first check if user has override capability
3360 // if not return false;
3361 if (!has_capability('moodle/role:assign', $context)) {
3364 // pull out all active roles of this user from this context(or above)
3365 if ($userroles = get_user_roles($context)) {
3366 foreach ($userroles as $userrole) {
3367 // if any in the role_allow_override table, then it's ok
3368 if (get_record('role_allow_assign', 'roleid', $userrole->roleid
, 'allowassign', $targetroleid)) {
3377 /** Returns all site roles in correct sort order.
3380 function get_all_roles() {
3381 return get_records('role', '', '', 'sortorder ASC');
3385 * gets all the user roles assigned in this context, or higher contexts
3386 * this is mainly used when checking if a user can assign a role, or overriding a role
3387 * i.e. we need to know what this user holds, in order to verify against allow_assign and
3388 * allow_override tables
3389 * @param object $context
3390 * @param int $userid
3391 * @param view - set to true when roles are pulled for display only
3392 * this is so that we can filter roles with no visible
3393 * assignment, for example, you might want to "hide" all
3394 * course creators when browsing the course participants
3398 function get_user_roles($context, $userid=0, $checkparentcontexts=true, $order='c.contextlevel DESC, r.sortorder ASC', $view=false) {
3400 global $USER, $CFG, $db;
3402 if (empty($userid)) {
3403 if (empty($USER->id
)) {
3406 $userid = $USER->id
;
3408 // set up hidden sql
3409 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))?
' AND ra.hidden = 0 ':'';
3411 if ($checkparentcontexts && ($parents = get_parent_contexts($context))) {
3412 $contexts = ' ra.contextid IN ('.implode(',' , $parents).','.$context->id
.')';
3414 $contexts = ' ra.contextid = \''.$context->id
.'\'';
3417 return get_records_sql('SELECT ra.*, r.name, r.shortname
3418 FROM '.$CFG->prefix
.'role_assignments ra,
3419 '.$CFG->prefix
.'role r,
3420 '.$CFG->prefix
.'context c
3421 WHERE ra.userid = '.$userid.
3422 ' AND ra.roleid = r.id
3423 AND ra.contextid = c.id
3424 AND '.$contexts . $hiddensql .
3425 ' ORDER BY '.$order);
3429 * Creates a record in the allow_override table
3430 * @param int sroleid - source roleid
3431 * @param int troleid - target roleid
3432 * @return int - id or false
3434 function allow_override($sroleid, $troleid) {
3435 $record = new object();
3436 $record->roleid
= $sroleid;
3437 $record->allowoverride
= $troleid;
3438 return insert_record('role_allow_override', $record);
3442 * Creates a record in the allow_assign table
3443 * @param int sroleid - source roleid
3444 * @param int troleid - target roleid
3445 * @return int - id or false
3447 function allow_assign($sroleid, $troleid) {
3448 $record = new object;
3449 $record->roleid
= $sroleid;
3450 $record->allowassign
= $troleid;
3451 return insert_record('role_allow_assign', $record);
3455 * Gets a list of roles that this user can assign in this context
3456 * @param object $context
3459 function get_assignable_roles ($context, $field="name") {
3463 if ($roles = get_all_roles()) {
3464 foreach ($roles as $role) {
3465 if (user_can_assign($context, $role->id
)) {
3466 $options[$role->id
] = strip_tags(format_string($role->{$field}, true));
3474 * Gets a list of roles that this user can override in this context
3475 * @param object $context
3478 function get_overridable_roles($context) {
3482 if ($roles = get_all_roles()) {
3483 foreach ($roles as $role) {
3484 if (user_can_override($context, $role->id
)) {
3485 $options[$role->id
] = strip_tags(format_string($role->name
, true));
3494 * Returns a role object that is the default role for new enrolments
3497 * @param object $course
3498 * @return object $role
3500 function get_default_course_role($course) {
3503 /// First let's take the default role the course may have
3504 if (!empty($course->defaultrole
)) {
3505 if ($role = get_record('role', 'id', $course->defaultrole
)) {
3510 /// Otherwise the site setting should tell us
3511 if ($CFG->defaultcourseroleid
) {
3512 if ($role = get_record('role', 'id', $CFG->defaultcourseroleid
)) {
3517 /// It's unlikely we'll get here, but just in case, try and find a student role
3518 if ($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW
)) {
3519 return array_shift($studentroles); /// Take the first one
3527 * who has this capability in this context
3528 * does not handling user level resolving!!!
3529 * (!)pleaes note if $fields is empty this function attempts to get u.*
3530 * which can get rather large.
3531 * i.e 1 person has 2 roles 1 allow, 1 prevent, this will not work properly
3532 * @param $context - object
3533 * @param $capability - string capability
3534 * @param $fields - fields to be pulled
3535 * @param $sort - the sort order
3536 * @param $limitfrom - number of records to skip (offset)
3537 * @param $limitnum - number of records to fetch
3538 * @param $groups - single group or array of groups - group(s) user is in
3539 * @param $exceptions - list of users to exclude
3540 * @param view - set to true when roles are pulled for display only
3541 * this is so that we can filter roles with no visible
3542 * assignment, for example, you might want to "hide" all
3543 * course creators when browsing the course participants
3546 function get_users_by_capability($context, $capability, $fields='', $sort='',
3547 $limitfrom='', $limitnum='', $groups='', $exceptions='', $doanything=true, $view=false) {
3550 /// Sorting out groups
3552 $groupjoin = 'INNER JOIN '.$CFG->prefix
.'groups_members gm ON gm.userid = ra.userid';
3554 if (is_array($groups)) {
3555 $groupsql = 'AND gm.groupid IN ('.implode(',', $groups).')';
3557 $groupsql = 'AND gm.groupid = '.$groups;
3564 /// Sorting out exceptions
3565 $exceptionsql = $exceptions ?
"AND u.id NOT IN ($exceptions)" : '';
3567 /// Set up default fields
3568 if (empty($fields)) {
3569 $fields = 'u.*, ul.timeaccess as lastaccess, ra.hidden';
3572 /// Set up default sort
3574 $sort = 'ul.timeaccess';
3577 $sortby = $sort ?
" ORDER BY $sort " : '';
3578 /// Set up hidden sql
3579 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))?
' AND ra.hidden = 0 ':'';
3581 /// If context is a course, then construct sql for ul
3582 if ($context->contextlevel
== CONTEXT_COURSE
) {
3583 $courseid = $context->instanceid
;
3584 $coursesql1 = "AND ul.courseid = $courseid";
3589 /// Sorting out roles with this capability set
3590 if ($possibleroles = get_roles_with_capability($capability, CAP_ALLOW
, $context)) {
3592 if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM
)) {
3593 return false; // Something is seriously wrong
3595 $doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW
, $sitecontext);
3598 $validroleids = array();
3599 foreach ($possibleroles as $possiblerole) {
3601 if (isset($doanythingroles[$possiblerole->id
])) { // We don't want these included
3605 if ($caps = role_context_capabilities($possiblerole->id
, $context, $capability)) { // resolved list
3606 if (isset($caps[$capability]) && $caps[$capability] > 0) { // resolved capability > 0
3607 $validroleids[] = $possiblerole->id
;
3611 if (empty($validroleids)) {
3614 $roleids = '('.implode(',', $validroleids).')';
3616 return false; // No need to continue, since no roles have this capability set
3619 /// Construct the main SQL
3620 $select = " SELECT $fields";
3621 $from = " FROM {$CFG->prefix}user u
3622 INNER JOIN {$CFG->prefix}role_assignments ra ON ra.userid = u.id
3623 INNER JOIN {$CFG->prefix}role r ON r.id = ra.roleid
3624 LEFT OUTER JOIN {$CFG->prefix}user_lastaccess ul ON (ul.userid = u.id $coursesql1)
3626 $where = " WHERE ra.contextid ".get_related_contexts_string($context)."
3628 AND ra.roleid in $roleids
3633 return get_records_sql($select.$from.$where.$sortby, $limitfrom, $limitnum);
3637 * gets all the users assigned this role in this context or higher
3639 * @param int contextid
3640 * @param bool parent if true, get list of users assigned in higher context too
3643 function get_role_users($roleid, $context, $parent=false, $fields='', $sort='u.lastname ASC', $view=false) {
3646 if (empty($fields)) {
3647 $fields = 'u.id, u.confirmed, u.username, u.firstname, u.lastname, '.
3648 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.city, '.
3649 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
3650 'u.emailstop, u.lang, u.timezone';
3653 // whether this assignment is hidden
3654 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))?
' AND r.hidden = 0 ':'';
3656 if ($contexts = get_parent_contexts($context)) {
3657 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
3659 $parentcontexts = '';
3662 $parentcontexts = '';
3666 $roleselect = "AND r.roleid = $roleid";
3671 $SQL = "SELECT $fields
3672 FROM {$CFG->prefix}role_assignments r,
3673 {$CFG->prefix}user u
3674 WHERE (r.contextid = $context->id $parentcontexts)
3675 AND u.id = r.userid $roleselect
3678 "; // join now so that we can just use fullname() later
3680 return get_records_sql($SQL);
3684 * Counts all the users assigned this role in this context or higher
3686 * @param int contextid
3687 * @param bool parent if true, get list of users assigned in higher context too
3690 function count_role_users($roleid, $context, $parent=false) {
3694 if ($contexts = get_parent_contexts($context)) {
3695 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
3697 $parentcontexts = '';
3700 $parentcontexts = '';
3703 $SQL = "SELECT count(*)
3704 FROM {$CFG->prefix}role_assignments r
3705 WHERE (r.contextid = $context->id $parentcontexts)
3706 AND r.roleid = $roleid";
3708 return count_records_sql($SQL);
3712 * This function gets the list of courses that this user has a particular capability in.
3713 * It is still not very efficient.
3714 * @param string $capability Capability in question
3715 * @param int $userid User ID or null for current user
3716 * @param bool $doanything True if 'doanything' is permitted (default)
3717 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
3718 * otherwise use a comma-separated list of the fields you require, not including id
3719 * @param string $orderby If set, use a comma-separated list of fields from course
3720 * table with sql modifiers (DESC) if needed
3721 * @return array Array of courses, may have zero entries. Or false if query failed.
3723 function get_user_capability_course($capability, $userid=NULL,$doanything=true,$fieldsexceptid='',$orderby='') {
3724 // Convert fields list and ordering
3726 if($fieldsexceptid) {
3727 $fields=explode(',',$fieldsexceptid);
3728 foreach($fields as $field) {
3729 $fieldlist.=',c.'.$field;
3733 $fields=explode(',',$orderby);
3735 foreach($fields as $field) {
3739 $orderby.='c.'.$field;
3741 $orderby='ORDER BY '.$orderby;
3744 // Obtain a list of everything relevant about all courses including context.
3745 // Note the result can be used directly as a context (we are going to), the course
3746 // fields are just appended.
3748 $rs=get_recordset_sql("
3750 x.*,c.id AS courseid$fieldlist
3752 {$CFG->prefix}course c
3753 INNER JOIN {$CFG->prefix}context x ON c.id=x.instanceid AND x.contextlevel=".CONTEXT_COURSE
."
3760 // Check capability for each course in turn
3762 while($coursecontext=rs_fetch_next_record($rs)) {
3763 if(has_capability($capability,$coursecontext,$userid,$doanything)) {
3764 // We've got the capability. Make the record look like a course record
3766 $coursecontext->id
=$coursecontext->courseid
;
3767 unset($coursecontext->courseid
);
3768 unset($coursecontext->contextlevel
);
3769 unset($coursecontext->instanceid
);
3770 $courses[]=$coursecontext;
3776 /** This function finds the roles assigned directly to this context only
3777 * i.e. no parents role
3778 * @param object $context
3781 function get_roles_on_exact_context($context) {
3785 return get_records_sql("SELECT r.*
3786 FROM {$CFG->prefix}role_assignments ra,
3787 {$CFG->prefix}role r
3788 WHERE ra.roleid = r.id
3789 AND ra.contextid = $context->id");
3794 * Switches the current user to another role for the current session and only
3795 * in the given context. If roleid is not valid (eg 0) or the current user
3796 * doesn't have permissions to be switching roles then the user's session
3797 * is compltely reset to have their normal roles.
3798 * @param integer $roleid
3799 * @param object $context
3802 function role_switch($roleid, $context) {
3805 /// If we can't use this or are already using it or no role was specified then bail completely and reset
3806 if (empty($roleid) ||
!has_capability('moodle/role:switchroles', $context)
3807 ||
!empty($USER->switchrole
[$context->id
]) ||
!confirm_sesskey()) {
3809 unset($USER->switchrole
[$context->id
]); // Delete old capabilities
3810 load_all_capabilities(); //reload user caps
3814 /// We're allowed to switch but can we switch to the specified role? Use assignable roles to check.
3815 if (!$roles = get_assignable_roles($context)) {
3819 /// unset default user role - it would not work anyway
3820 unset($roles[$CFG->defaultuserroleid
]);
3822 if (empty($roles[$roleid])) { /// We can't switch to this particular role
3826 /// We have a valid roleid that this user can switch to, so let's set up the session
3828 $USER->switchrole
[$context->id
] = $roleid; // So we know later what state we are in
3830 load_all_capabilities(); //reload switched role caps
3832 /// Add some permissions we are really going to always need, even if the role doesn't have them!
3834 $USER->capabilities
[$context->id
]['moodle/course:view'] = CAP_ALLOW
;
3841 // get any role that has an override on exact context
3842 function get_roles_with_override_on_context($context) {
3846 return get_records_sql("SELECT r.*
3847 FROM {$CFG->prefix}role_capabilities rc,
3848 {$CFG->prefix}role r
3849 WHERE rc.roleid = r.id
3850 AND rc.contextid = $context->id");
3853 // get all capabilities for this role on this context (overrids)
3854 function get_capabilities_from_role_on_context($role, $context) {
3858 return get_records_sql("SELECT *
3859 FROM {$CFG->prefix}role_capabilities
3860 WHERE contextid = $context->id
3861 AND roleid = $role->id");
3864 // find out which roles has assignment on this context
3865 function get_roles_with_assignment_on_context($context) {
3869 return get_records_sql("SELECT r.*
3870 FROM {$CFG->prefix}role_assignments ra,
3871 {$CFG->prefix}role r
3872 WHERE ra.roleid = r.id
3873 AND ra.contextid = $context->id");
3879 * Find all user assignemnt of users for this role, on this context
3881 function get_users_from_role_on_context($role, $context) {
3885 return get_records_sql("SELECT *
3886 FROM {$CFG->prefix}role_assignments
3887 WHERE contextid = $context->id
3888 AND roleid = $role->id");
3892 * Simple function returning a boolean true if roles exist, otherwise false
3894 function user_has_role_assignment($userid, $roleid, $contextid=0) {
3897 return record_exists('role_assignments', 'userid', $userid, 'roleid', $roleid, 'contextid', $contextid);
3899 return record_exists('role_assignments', 'userid', $userid, 'roleid', $roleid);
3904 * Inserts all parental context and self into context_rel table
3906 * @param object $context-context to be deleted
3907 * @param bool deletechild - deltes child contexts dependencies
3909 function insert_context_rel($context, $deletechild=true, $deleteparent=true) {
3911 // first check validity
3913 if (!validate_context($context->contextlevel
, $context->instanceid
)) {
3914 debugging('Error: Invalid context creation request for level "'.s($contextlevel).'", instance "'.s($instanceid).'".');
3918 // removes all parents
3920 delete_records('context_rel', 'c2', $context->id
);
3923 if ($deleteparent) {
3924 delete_records('context_rel', 'c1', $context->id
);
3926 // insert all parents
3927 if ($parents = get_parent_contexts($context)) {
3928 $parents[] = $context->id
;
3929 foreach ($parents as $parent) {
3931 $rec ->c1
= $context->id
;
3932 $rec ->c2
= $parent;
3933 insert_record('context_rel', $rec);
3939 * rebuild context_rel table without deleting
3941 function build_context_rel() {
3944 $savedb = $db->debug
;
3946 // total number of records
3947 $total = count_records('context');
3948 // processed records
3950 print_progress($done, $total, 10, 0, 'Processing context relations');
3952 if ($contexts = get_records('context')) {
3953 foreach ($contexts as $context) {
3954 // no need to delete because it's all empty
3955 insert_context_rel($context, false, false);
3957 print_progress(++
$done, $total, 10, 0, 'Processing context relations');
3962 $db->debug
= $savedb;
3966 // gets the custom name of the role in course
3967 // TODO: proper documentation
3968 function role_get_name($role, $context) {
3970 if ($r = get_record('role_names','roleid', $role->id
,'contextid', $context->id
)) {
3971 return format_string($r->text
);
3973 return format_string($role->name
);