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',$context) in forum
360 * This is a recursive function.
362 * @param string $capability - name of the capability (or debugcache or clearcache)
363 * @param object $context - a context object (record from context table)
364 * @param integer $userid - a userid number
365 * @param bool $doanything - if false, ignore do anything
368 function has_capability($capability, $context=NULL, $userid=NULL, $doanything=true) {
370 global $USER, $CONTEXT, $CFG;
372 static $capcache = array(); // Cache of capabilities
377 if ($capability == 'clearcache') {
378 $capcache = array(); // Clear ALL the capability cache
382 /// Some sanity checks
383 if (debugging('',DEBUG_DEVELOPER
)) {
384 if ($capability == 'debugcache') {
385 print_object($capcache);
388 if (!record_exists('capabilities', 'name', $capability)) {
389 debugging('Capability "'.$capability.'" was not found! This should be fixed in code.');
391 if ($doanything != true and $doanything != false) {
392 debugging('Capability parameter "doanything" is wierd ("'.$doanything.'"). This should be fixed in code.');
394 if (!is_object($context) && $context !== NULL) {
395 debugging('Incorrect context parameter "'.$context.'" for has_capability(), object expected! This should be fixed in code.');
399 /// Make sure we know the current context
400 if (empty($context)) { // Use default CONTEXT if none specified
401 if (empty($CONTEXT)) {
406 } else { // A context was given to us
407 if (empty($CONTEXT)) {
408 $CONTEXT = $context; // Store FIRST used context in this global as future default
412 /// Check and return cache in case we've processed this one before.
413 $requsteduser = empty($userid) ?
$USER->id
: $userid; // find out the requested user id, $USER->id might have been changed
414 $cachekey = $capability.'_'.$context->id
.'_'.intval($requsteduser).'_'.intval($doanything);
416 if (isset($capcache[$cachekey])) {
417 return $capcache[$cachekey];
421 /// Load up the capabilities list or item as necessary
423 if (empty($USER->id
) or ($userid != $USER->id
) or empty($USER->capabilities
)) {
425 //caching - helps user switching in cron
426 static $guestuserid = false; // guest user id
427 static $guestcaps = false; // guest caps
428 static $defcaps = false; // default user caps - this might help cron
430 if ($guestuserid === false) {
431 $guestuserid = get_field('user', 'id', 'username', 'guest');
434 if ($userid == $guestuserid) {
435 if ($guestcaps === false) {
436 $guestcaps = load_guest_role(true);
438 $capabilities = $guestcaps;
441 // This big SQL is expensive! We reduce it a little by avoiding checking for changed enrolments (false)
442 $capabilities = load_user_capability($capability, $context, $userid, false);
443 if ($defcaps === false) {
444 $defcaps = load_defaultuser_role(true);
446 $capabilities = merge_role_caps($capabilities, $defcaps);
449 } else { //$USER->id == $userid and needed capabilities already present
450 $capabilities = $USER->capabilities
;
453 } else { // no userid
454 if (empty($USER->capabilities
)) {
455 load_all_capabilities(); // expensive - but we have to do it once anyway
457 $capabilities = $USER->capabilities
;
461 /// We act a little differently when switchroles is active
463 $switchroleactive = false; // Assume it isn't active in this context
466 /// First deal with the "doanything" capability
470 /// First make sure that we aren't in a "switched role"
472 if (!empty($USER->switchrole
)) { // Switchrole is active somewhere!
473 if (!empty($USER->switchrole
[$context->id
])) { // Because of current context
474 $switchroleactive = true;
475 } else { // Check parent contexts
476 if ($parentcontextids = get_parent_contexts($context)) {
477 foreach ($parentcontextids as $parentcontextid) {
478 if (!empty($USER->switchrole
[$parentcontextid])) { // Yep, switchroles active here
479 $switchroleactive = true;
487 /// Check the site context for doanything (most common) first
489 if (empty($switchroleactive)) { // Ignore site setting if switchrole is active
490 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
491 if (isset($capabilities[$sitecontext->id
]['moodle/site:doanything'])) {
492 $result = (0 < $capabilities[$sitecontext->id
]['moodle/site:doanything']);
493 $capcache[$cachekey] = $result;
497 /// If it's not set at site level, it is possible to be set on other levels
498 /// Though this usage is not common and can cause risks
499 switch ($context->contextlevel
) {
501 case CONTEXT_COURSECAT
:
502 // Check parent cats.
503 $parentcats = get_parent_cats($context, CONTEXT_COURSECAT
);
504 foreach ($parentcats as $parentcat) {
505 if (isset($capabilities[$parentcat]['moodle/site:doanything'])) {
506 $result = (0 < $capabilities[$parentcat]['moodle/site:doanything']);
507 $capcache[$cachekey] = $result;
515 $parentcats = get_parent_cats($context, CONTEXT_COURSE
);
517 foreach ($parentcats as $parentcat) {
518 if (isset($capabilities[$parentcat]['do_anything'])) {
519 $result = (0 < $capabilities[$parentcat]['do_anything']);
520 $capcache[$cachekey] = $result;
528 $courseid = groups_get_course($context->instanceid
);
529 $courseinstance = get_context_instance(CONTEXT_COURSE
, $courseid);
531 $parentcats = get_parent_cats($courseinstance, CONTEXT_COURSE
);
532 foreach ($parentcats as $parentcat) {
533 if (isset($capabilities[$parentcat]['do_anything'])) {
534 $result = (0 < $capabilities[$parentcat]['do_anything']);
535 $capcache[$cachekey] = $result;
541 if (isset($capabilities[$courseinstance->id
]['do_anything'])) {
542 $result = (0 < $capabilities[$courseinstance->id
]['do_anything']);
543 $capcache[$cachekey] = $result;
551 $cm = get_record('course_modules', 'id', $context->instanceid
);
552 $courseinstance = get_context_instance(CONTEXT_COURSE
, $cm->course
);
554 if ($parentcats = get_parent_cats($courseinstance, CONTEXT_COURSE
)) {
555 foreach ($parentcats as $parentcat) {
556 if (isset($capabilities[$parentcat]['do_anything'])) {
557 $result = (0 < $capabilities[$parentcat]['do_anything']);
558 $capcache[$cachekey] = $result;
564 if (isset($capabilities[$courseinstance->id
]['do_anything'])) {
565 $result = (0 < $capabilities[$courseinstance->id
]['do_anything']);
566 $capcache[$cachekey] = $result;
573 // not necessarily 1 to 1 to course.
574 $block = get_record('block_instance','id',$context->instanceid
);
575 if ($block->pagetype
== 'course-view') {
576 $courseinstance = get_context_instance(CONTEXT_COURSE
, $block->pageid
); // needs check
577 $parentcats = get_parent_cats($courseinstance, CONTEXT_COURSE
);
579 foreach ($parentcats as $parentcat) {
580 if (isset($capabilities[$parentcat]['do_anything'])) {
581 $result = (0 < $capabilities[$parentcat]['do_anything']);
582 $capcache[$cachekey] = $result;
587 if (isset($capabilities[$courseinstance->id
]['do_anything'])) {
588 $result = (0 < $capabilities[$courseinstance->id
]['do_anything']);
589 $capcache[$cachekey] = $result;
592 } else { // if not course-view type of blocks, check site
593 if (isset($capabilities[$sitecontext->id
]['do_anything'])) {
594 $result = (0 < $capabilities[$sitecontext->id
]['do_anything']);
595 $capcache[$cachekey] = $result;
602 // CONTEXT_SYSTEM: CONTEXT_PERSONAL: CONTEXT_USER:
603 // Do nothing, because the parents are site context
604 // which has been checked already
609 if (isset($capabilities[$context->id
]['do_anything'])) {
610 $result = (0 < $capabilities[$context->id
]['do_anything']);
611 $capcache[$cachekey] = $result;
615 // do_anything has not been set, we now look for it the normal way.
616 $result = (0 < capability_search($capability, $context, $capabilities, $switchroleactive));
617 $capcache[$cachekey] = $result;
624 * In a separate function so that we won't have to deal with do_anything.
625 * again. Used by function has_capability().
626 * @param $capability - capability string
627 * @param $context - the context object
628 * @param $capabilities - either $USER->capability or loaded array (for other users)
629 * @return permission (int)
631 function capability_search($capability, $context, $capabilities, $switchroleactive=false) {
635 if (!isset($context->id
)) {
638 // if already set in the array explicitly, no need to look for it in parent
639 // context any longer
640 if (isset($capabilities[$context->id
][$capability])) {
641 return ($capabilities[$context->id
][$capability]);
644 /* Then, we check the cache recursively */
647 switch ($context->contextlevel
) {
649 case CONTEXT_SYSTEM
: // by now it's a definite an inherit
653 case CONTEXT_PERSONAL
:
654 $parentcontext = get_context_instance(CONTEXT_SYSTEM
);
655 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
659 $parentcontext = get_context_instance(CONTEXT_SYSTEM
);
660 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
663 case CONTEXT_COURSECAT
: // Coursecat -> coursecat or site
664 $coursecat = get_record('course_categories','id',$context->instanceid
);
665 if (!empty($coursecat->parent
)) { // return parent value if it exists
666 $parentcontext = get_context_instance(CONTEXT_COURSECAT
, $coursecat->parent
);
667 } else { // else return site value
668 $parentcontext = get_context_instance(CONTEXT_SYSTEM
);
670 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
673 case CONTEXT_COURSE
: // 1 to 1 to course cat
674 if (empty($switchroleactive)) {
675 // find the course cat, and return its value
676 $course = get_record('course','id',$context->instanceid
);
677 if ($course->id
== SITEID
) { // In 1.8 we've separated site course and system
678 $parentcontext = get_context_instance(CONTEXT_SYSTEM
);
680 $parentcontext = get_context_instance(CONTEXT_COURSECAT
, $course->category
);
682 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
686 case CONTEXT_GROUP
: // 1 to 1 to course
687 $courseid = groups_get_course($context->instanceid
);
688 $parentcontext = get_context_instance(CONTEXT_COURSE
, $courseid);
689 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
692 case CONTEXT_MODULE
: // 1 to 1 to course
693 $cm = get_record('course_modules','id',$context->instanceid
);
694 $parentcontext = get_context_instance(CONTEXT_COURSE
, $cm->course
);
695 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
698 case CONTEXT_BLOCK
: // not necessarily 1 to 1 to course
699 $block = get_record('block_instance','id',$context->instanceid
);
700 if ($block->pagetype
== 'course-view') {
701 $parentcontext = get_context_instance(CONTEXT_COURSE
, $block->pageid
); // needs check
703 $parentcontext = get_context_instance(CONTEXT_SYSTEM
);
705 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
709 error ('This is an unknown context (' . $context->contextlevel
. ') in capability_search!');
717 * auxillary function for load_user_capabilities()
718 * checks if context c1 is a parent (or itself) of context c2
719 * @param int $c1 - context id of context 1
720 * @param int $c2 - context id of context 2
723 function is_parent_context($c1, $c2) {
724 static $parentsarray;
726 // context can be itself and this is ok
731 if (isset($parentsarray[$c1][$c2])) {
732 return $parentsarray[$c1][$c2];
735 if (!$co2 = get_record('context', 'id', $c2)) {
739 if (!$parents = get_parent_contexts($co2)) {
743 foreach ($parents as $parent) {
744 $parentsarray[$parent][$c2] = true;
747 if (in_array($c1, $parents)) {
749 } else { // else not a parent, set the cache anyway
750 $parentsarray[$c1][$c2] = false;
757 * auxillary function for load_user_capabilities()
758 * handler in usort() to sort contexts according to level
759 * @param object contexta
760 * @param object contextb
763 function roles_context_cmp($contexta, $contextb) {
764 if ($contexta->contextlevel
== $contextb->contextlevel
) {
767 return ($contexta->contextlevel
< $contextb->contextlevel
) ?
-1 : 1;
771 * It will build an array of all the capabilities at each level
772 * i.e. site/metacourse/course_category/course/moduleinstance
773 * Note we should only load capabilities if they are explicitly assigned already,
774 * we should not load all module's capability!
776 * [Capabilities] => [26][forum_post] = 1
777 * [26][forum_start] = -8990
778 * [26][forum_edit] = -1
779 * [273][blah blah] = 1
780 * [273][blah blah blah] = 2
782 * @param $capability string - Only get a specific capability (string)
783 * @param $context object - Only get capabilities for a specific context object
784 * @param $userid integer - the id of the user whose capabilities we want to load
785 * @param $checkenrolments boolean - Should we check enrolment plugins (potentially expensive)
786 * @return array of permissions (or nothing if they get assigned to $USER)
788 function load_user_capability($capability='', $context=NULL, $userid=NULL, $checkenrolments=true) {
792 // this flag has not been set!
793 // (not clean install, or upgraded successfully to 1.7 and up)
794 if (empty($CFG->rolesactive
)) {
798 if (empty($userid)) {
799 if (empty($USER->id
)) { // We have no user to get capabilities for
800 debugging('User not logged in for load_user_capability!');
803 unset($USER->capabilities
); // We don't want possible older capabilites hanging around
805 if ($checkenrolments) { // Call "enrol" system to ensure that we have the correct picture
806 check_enrolment_plugins($USER);
810 $otheruserid = false;
812 if (!$user = get_record('user', 'id', $userid)) {
813 debugging('Non-existent userid in load_user_capability!');
817 if ($checkenrolments) { // Call "enrol" system to ensure that we have the correct picture
818 check_enrolment_plugins($user);
821 $otheruserid = $userid;
825 /// First we generate a list of all relevant contexts of the user
827 $usercontexts = array();
829 if ($context) { // if context is specified
830 $usercontexts = get_parent_contexts($context);
831 $usercontexts[] = $context->id
; // Add the current context as well
832 } else { // else, we load everything
833 if ($userroles = get_records('role_assignments','userid',$userid)) {
834 foreach ($userroles as $userrole) {
835 if (!in_array($userrole->contextid
, $usercontexts)) {
836 $usercontexts[] = $userrole->contextid
;
842 /// Set up SQL fragments for searching contexts
845 $listofcontexts = '('.implode(',', $usercontexts).')';
846 $searchcontexts1 = "c1.id IN $listofcontexts AND";
848 $searchcontexts1 = '';
852 // the doanything may override the requested capability
853 $capsearch = " AND (rc.capability = '$capability' OR rc.capability = 'moodle/site:doanything') ";
858 /// Then we use 1 giant SQL to bring out all relevant capabilities.
859 /// The first part gets the capabilities of orginal role.
860 /// The second part gets the capabilities of overriden roles.
862 $siteinstance = get_context_instance(CONTEXT_SYSTEM
);
863 $capabilities = array(); // Reinitialize.
865 // SQL for normal capabilities
866 $SQL1 = "SELECT rc.capability, c1.id as id1, c1.id as id2, (c1.contextlevel * 100) AS aggrlevel,
867 SUM(rc.permission) AS sum
869 {$CFG->prefix}role_assignments ra,
870 {$CFG->prefix}role_capabilities rc,
871 {$CFG->prefix}context c1
873 ra.contextid=c1.id AND
874 ra.roleid=rc.roleid AND
875 ra.userid=$userid AND
877 rc.contextid=$siteinstance->id
880 rc.capability, c1.id, c1.contextlevel * 100
882 SUM(rc.permission) != 0
886 SELECT rc.capability, c1.id as id1, c2.id as id2, (c1.contextlevel * 100 + c2.contextlevel) AS aggrlevel,
887 SUM(rc.permission) AS sum
889 {$CFG->prefix}role_assignments ra LEFT JOIN
890 {$CFG->prefix}role_capabilities rc on ra.roleid = rc.roleid LEFT JOIN
891 {$CFG->prefix}context c1 on ra.contextid = c1.id LEFT JOIN
892 {$CFG->prefix}context c2 on rc.contextid = c2.id LEFT JOIN
893 {$CFG->prefix}context_rel cr on cr.c1 = c2.id
895 ra.userid=$userid AND
897 rc.contextid != $siteinstance->id
901 rc.capability, c1.id, c2.id, c1.contextlevel * 100 + c2.contextlevel
903 SUM(rc.permission) != 0
907 if (!$rs = get_recordset_sql($SQL1)) {
908 error("Query failed in load_user_capability.");
911 if ($rs && $rs->RecordCount() > 0) {
912 while ($caprec = rs_fetch_next_record($rs)) {
913 $array = (array)$caprec;
914 $temprecord = new object;
916 foreach ($array as $key=>$val) {
917 if ($key == 'aggrlevel') {
918 $temprecord->contextlevel
= $val;
920 $temprecord->{$key} = $val;
923 $capabilities[] = $temprecord;
929 // this is take out because we have no way of making sure c1 is indeed related to c2 (parent)
930 // if we do not group by sum, it is possible to have multiple records of rc.capability, c1.id, c2.id, tuple having
931 // different values, we can maually sum it when we go through the list
935 $SQL2 = "SELECT rc.capability, c1.id as id1, c2.id as id2, (c1.contextlevel * 100 + c2.contextlevel) AS aggrlevel,
938 {$CFG->prefix}role_assignments ra,
939 {$CFG->prefix}role_capabilities rc,
940 {$CFG->prefix}context c1,
941 {$CFG->prefix}context c2
943 ra.contextid=c1.id AND
944 ra.roleid=rc.roleid AND
945 ra.userid=$userid AND
946 rc.contextid=c2.id AND
948 rc.contextid != $siteinstance->id
952 rc.capability, (c1.contextlevel * 100 + c2.contextlevel), c1.id, c2.id, rc.permission
958 if (!$rs = get_recordset_sql($SQL2)) {
959 error("Query failed in load_user_capability.");
962 if ($rs && $rs->RecordCount() > 0) {
963 while ($caprec = rs_fetch_next_record($rs)) {
964 $array = (array)$caprec;
965 $temprecord = new object;
967 foreach ($array as $key=>$val) {
968 if ($key == 'aggrlevel') {
969 $temprecord->contextlevel = $val;
971 $temprecord->{$key} = $val;
974 // for overrides, we have to make sure that context2 is a child of context1
975 // otherwise the combination makes no sense
976 //if (is_parent_context($temprecord->id1, $temprecord->id2)) {
977 $capabilities[] = $temprecord;
978 //} // only write if relevant
983 // this step sorts capabilities according to the contextlevel
984 // it is very important because the order matters when we
985 // go through each capabilities later. (i.e. higher level contextlevel
986 // will override lower contextlevel settings
987 usort($capabilities, 'roles_context_cmp');
989 /* so up to this point we should have somethign like this
990 * $capabilities[1] ->contextlevel = 1000
991 ->module = 0 // changed from SITEID in 1.8 (??)
992 ->capability = do_anything
993 ->id = 1 (id is the context id)
996 * $capabilities[2] ->contextlevel = 1000
997 ->module = 0 // changed from SITEID in 1.8 (??)
998 ->capability = post_messages
1002 * $capabilittes[3] ->contextlevel = 3000
1004 ->capability = view_course_activities
1008 * $capabilittes[4] ->contextlevel = 3000
1010 ->capability = view_course_activities
1012 ->sum = 0 (this is another course)
1014 * $capabilities[5] ->contextlevel = 3050
1016 ->capability = view_course_activities
1017 ->id = 25 (override in course 25)
1020 * now we proceed to write the session array, going from top to bottom
1021 * at anypoint, we need to go up and check parent to look for prohibit
1023 // print_object($capabilities);
1025 /* This is where we write to the actualy capabilities array
1026 * what we need to do from here on is
1027 * going down the array from lowest level to highest level
1028 * 1) recursively check for prohibit,
1029 * if any, we write prohibit
1030 * else, we write the value
1031 * 2) at an override level, we overwrite current level
1032 * if it's not set to prohibit already, and if different
1033 * ........ that should be it ........
1036 // This is the flag used for detecting the current context level. Since we are going through
1037 // the array in ascending order of context level. For normal capabilities, there should only
1038 // be 1 value per (capability, contextlevel, context), because they are already summed. But,
1039 // for overrides, since we are processing them separate, we need to sum the relevcant entries.
1040 // We set this flag when we hit a new level.
1041 // If the flag is already set, we keep adding (summing), otherwise, we just override previous
1042 // settings (from lower level contexts)
1043 $capflags = array(); // (contextid, contextlevel, capability)
1044 $usercap = array(); // for other user's capabilities
1045 foreach ($capabilities as $capability) {
1047 if (!$context = get_context_instance_by_id($capability->id2
)) {
1048 continue; // incorrect stale context
1051 if (!empty($otheruserid)) { // we are pulling out other user's capabilities, do not write to session
1053 if (capability_prohibits($capability->capability
, $context, $capability->sum
, $usercap)) {
1054 $usercap[$capability->id2
][$capability->capability
] = CAP_PROHIBIT
;
1057 if (isset($usercap[$capability->id2
][$capability->capability
])) { // use isset because it can be sum 0
1058 if (!empty($capflags[$capability->id2
][$capability->contextlevel
][$capability->capability
])) {
1059 $usercap[$capability->id2
][$capability->capability
] +
= $capability->sum
;
1060 } else { // else we override, and update flag
1061 $usercap[$capability->id2
][$capability->capability
] = $capability->sum
;
1062 $capflags[$capability->id2
][$capability->contextlevel
][$capability->capability
] = true;
1065 $usercap[$capability->id2
][$capability->capability
] = $capability->sum
;
1066 $capflags[$capability->id2
][$capability->contextlevel
][$capability->capability
] = true;
1071 if (capability_prohibits($capability->capability
, $context, $capability->sum
)) { // if any parent or parent's parent is set to prohibit
1072 $USER->capabilities
[$capability->id2
][$capability->capability
] = CAP_PROHIBIT
;
1076 // if no parental prohibit set
1077 // just write to session, i am not sure this is correct yet
1078 // since 3050 shows up after 3000, and 3070 shows up after 3050,
1079 // it should be ok just to overwrite like this, provided that there's no
1080 // parental prohibits
1081 // we need to write even if it's 0, because it could be an inherit override
1082 if (isset($USER->capabilities
[$capability->id2
][$capability->capability
])) {
1083 if (!empty($capflags[$capability->id2
][$capability->contextlevel
][$capability->capability
])) {
1084 $USER->capabilities
[$capability->id2
][$capability->capability
] +
= $capability->sum
;
1085 } else { // else we override, and update flag
1086 $USER->capabilities
[$capability->id2
][$capability->capability
] = $capability->sum
;
1087 $capflags[$capability->id2
][$capability->contextlevel
][$capability->capability
] = true;
1090 $USER->capabilities
[$capability->id2
][$capability->capability
] = $capability->sum
;
1091 $capflags[$capability->id2
][$capability->contextlevel
][$capability->capability
] = true;
1096 // now we don't care about the huge array anymore, we can dispose it.
1097 unset($capabilities);
1100 if (!empty($otheruserid)) {
1101 return $usercap; // return the array
1107 * A convenience function to completely load all the capabilities
1108 * for the current user. This is what gets called from login, for example.
1110 function load_all_capabilities() {
1113 //caching - helps user switching in cron
1114 static $defcaps = false;
1116 unset($USER->mycourses
); // Reset a cache used by get_my_courses
1118 if (isguestuser()) {
1119 load_guest_role(); // All non-guest users get this by default
1121 } else if (isloggedin()) {
1122 if ($defcaps === false) {
1123 $defcaps = load_defaultuser_role(true);
1126 load_user_capability();
1128 // when in "course login as" - load only course caqpabilitites (it may not always work as expected)
1129 if (!empty($USER->realuser
) and $USER->loginascontext
->contextlevel
!= CONTEXT_SYSTEM
) {
1130 $children = get_child_contexts($USER->loginascontext
);
1131 $children[] = $USER->loginascontext
->id
;
1132 foreach ($USER->capabilities
as $conid => $caps) {
1133 if (!in_array($conid, $children)) {
1134 unset($USER->capabilities
[$conid]);
1139 // handle role switching in courses
1140 if (!empty($USER->switchrole
)) {
1141 foreach ($USER->switchrole
as $contextid => $roleid) {
1142 $context = get_context_instance_by_id($contextid);
1144 // first prune context and any child contexts
1145 $children = get_child_contexts($context);
1146 foreach ($children as $childid) {
1147 unset($USER->capabilities
[$childid]);
1149 unset($USER->capabilities
[$contextid]);
1151 // now merge all switched role caps in context and bellow
1152 $swithccaps = get_role_context_caps($roleid, $context);
1153 $USER->capabilities
= merge_role_caps($USER->capabilities
, $swithccaps);
1157 if (isset($USER->capabilities
)) {
1158 $USER->capabilities
= merge_role_caps($USER->capabilities
, $defcaps);
1160 $USER->capabilities
= $defcaps;
1164 load_notloggedin_role();
1170 * Check all the login enrolment information for the given user object
1171 * by querying the enrolment plugins
1173 function check_enrolment_plugins(&$user) {
1176 static $inprogress; // To prevent this function being called more than once in an invocation
1178 if (!empty($inprogress[$user->id
])) {
1182 $inprogress[$user->id
] = true; // Set the flag
1184 require_once($CFG->dirroot
.'/enrol/enrol.class.php');
1186 if (!($plugins = explode(',', $CFG->enrol_plugins_enabled
))) {
1187 $plugins = array($CFG->enrol
);
1190 foreach ($plugins as $plugin) {
1191 $enrol = enrolment_factory
::factory($plugin);
1192 if (method_exists($enrol, 'setup_enrolments')) { /// Plugin supports Roles (Moodle 1.7 and later)
1193 $enrol->setup_enrolments($user);
1194 } else { /// Run legacy enrolment methods
1195 if (method_exists($enrol, 'get_student_courses')) {
1196 $enrol->get_student_courses($user);
1198 if (method_exists($enrol, 'get_teacher_courses')) {
1199 $enrol->get_teacher_courses($user);
1202 /// deal with $user->students and $user->teachers stuff
1203 unset($user->student
);
1204 unset($user->teacher
);
1209 unset($inprogress[$user->id
]); // Unset the flag
1214 * This is a recursive function that checks whether the capability in this
1215 * context, or the parent capabilities are set to prohibit.
1217 * At this point, we can probably just use the values already set in the
1218 * session variable, since we are going down the level. Any prohit set in
1219 * parents would already reflect in the session.
1221 * @param $capability - capability name
1222 * @param $sum - sum of all capabilities values
1223 * @param $context - the context object
1224 * @param $array - when loading another user caps, their caps are not stored in session but an array
1226 function capability_prohibits($capability, $context, $sum='', $array='') {
1229 // caching, mainly to save unnecessary sqls
1230 static $prohibits; //[capability][contextid]
1231 if (isset($prohibits[$capability][$context->id
])) {
1232 return $prohibits[$capability][$context->id
];
1235 if (empty($context->id
)) {
1236 $prohibits[$capability][$context->id
] = false;
1240 if (empty($capability)) {
1241 $prohibits[$capability][$context->id
] = false;
1245 if ($sum < (CAP_PROHIBIT
/2)) {
1246 // If this capability is set to prohibit.
1247 $prohibits[$capability][$context->id
] = true;
1251 if (!empty($array)) {
1252 if (isset($array[$context->id
][$capability])
1253 && $array[$context->id
][$capability] < (CAP_PROHIBIT
/2)) {
1254 $prohibits[$capability][$context->id
] = true;
1258 // Else if set in session.
1259 if (isset($USER->capabilities
[$context->id
][$capability])
1260 && $USER->capabilities
[$context->id
][$capability] < (CAP_PROHIBIT
/2)) {
1261 $prohibits[$capability][$context->id
] = true;
1265 switch ($context->contextlevel
) {
1267 case CONTEXT_SYSTEM
:
1268 // By now it's a definite an inherit.
1272 case CONTEXT_PERSONAL
:
1273 $parent = get_context_instance(CONTEXT_SYSTEM
);
1274 $prohibits[$capability][$context->id
] = capability_prohibits($capability, $parent);
1275 return $prohibits[$capability][$context->id
];
1279 $parent = get_context_instance(CONTEXT_SYSTEM
);
1280 $prohibits[$capability][$context->id
] = capability_prohibits($capability, $parent);
1281 return $prohibits[$capability][$context->id
];
1284 case CONTEXT_COURSECAT
:
1285 // Coursecat -> coursecat or site.
1286 if (!$coursecat = get_record('course_categories','id',$context->instanceid
)) {
1287 $prohibits[$capability][$context->id
] = false;
1290 if (!empty($coursecat->parent
)) {
1291 // return parent value if exist.
1292 $parent = get_context_instance(CONTEXT_COURSECAT
, $coursecat->parent
);
1294 // Return site value.
1295 $parent = get_context_instance(CONTEXT_SYSTEM
);
1297 $prohibits[$capability][$context->id
] = capability_prohibits($capability, $parent);
1298 return $prohibits[$capability][$context->id
];
1301 case CONTEXT_COURSE
:
1302 // 1 to 1 to course cat.
1303 // Find the course cat, and return its value.
1304 if (!$course = get_record('course','id',$context->instanceid
)) {
1305 $prohibits[$capability][$context->id
] = false;
1308 // Yu: Separating site and site course context
1309 if ($course->id
== SITEID
) {
1310 $parent = get_context_instance(CONTEXT_SYSTEM
);
1312 $parent = get_context_instance(CONTEXT_COURSECAT
, $course->category
);
1314 $prohibits[$capability][$context->id
] = capability_prohibits($capability, $parent);
1315 return $prohibits[$capability][$context->id
];
1319 // 1 to 1 to course.
1320 if (!$courseid = groups_get_course($context->instanceid
)) {
1321 $prohibits[$capability][$context->id
] = false;
1324 $parent = get_context_instance(CONTEXT_COURSE
, $courseid);
1325 $prohibits[$capability][$context->id
] = capability_prohibits($capability, $parent);
1326 return $prohibits[$capability][$context->id
];
1329 case CONTEXT_MODULE
:
1330 // 1 to 1 to course.
1331 if (!$cm = get_record('course_modules','id',$context->instanceid
)) {
1332 $prohibits[$capability][$context->id
] = false;
1335 $parent = get_context_instance(CONTEXT_COURSE
, $cm->course
);
1336 $prohibits[$capability][$context->id
] = capability_prohibits($capability, $parent);
1337 return $prohibits[$capability][$context->id
];
1341 // 1 to 1 to course.
1342 if (!$block = get_record('block_instance','id',$context->instanceid
)) {
1343 $prohibits[$capability][$context->id
] = false;
1346 if ($block->pagetype
== 'course-view') {
1347 $parent = get_context_instance(CONTEXT_COURSE
, $block->pageid
); // needs check
1349 $parent = get_context_instance(CONTEXT_SYSTEM
);
1351 $prohibits[$capability][$context->id
] = capability_prohibits($capability, $parent);
1352 return $prohibits[$capability][$context->id
];
1356 print_error('unknowncontext');
1363 * A print form function. This should either grab all the capabilities from
1364 * files or a central table for that particular module instance, then present
1365 * them in check boxes. Only relevant capabilities should print for known
1367 * @param $mod - module id of the mod
1369 function print_capabilities($modid=0) {
1372 $capabilities = array();
1375 // We are in a module specific context.
1377 // Get the mod's name.
1378 // Call the function that grabs the file and parse.
1379 $cm = get_record('course_modules', 'id', $modid);
1380 $module = get_record('modules', 'id', $cm->module
);
1383 // Print all capabilities.
1384 foreach ($capabilities as $capability) {
1385 // Prints the check box component.
1392 * Installs the roles system.
1393 * This function runs on a fresh install as well as on an upgrade from the old
1394 * hard-coded student/teacher/admin etc. roles to the new roles system.
1396 function moodle_install_roles() {
1400 /// Create a system wide context for assignemnt.
1401 $systemcontext = $context = get_context_instance(CONTEXT_SYSTEM
);
1404 /// Create default/legacy roles and capabilities.
1405 /// (1 legacy capability per legacy role at system level).
1407 $adminrole = create_role(addslashes(get_string('administrator')), 'admin',
1408 addslashes(get_string('administratordescription')), 'moodle/legacy:admin');
1409 $coursecreatorrole = create_role(addslashes(get_string('coursecreators')), 'coursecreator',
1410 addslashes(get_string('coursecreatorsdescription')), 'moodle/legacy:coursecreator');
1411 $editteacherrole = create_role(addslashes(get_string('defaultcourseteacher')), 'editingteacher',
1412 addslashes(get_string('defaultcourseteacherdescription')), 'moodle/legacy:editingteacher');
1413 $noneditteacherrole = create_role(addslashes(get_string('noneditingteacher')), 'teacher',
1414 addslashes(get_string('noneditingteacherdescription')), 'moodle/legacy:teacher');
1415 $studentrole = create_role(addslashes(get_string('defaultcoursestudent')), 'student',
1416 addslashes(get_string('defaultcoursestudentdescription')), 'moodle/legacy:student');
1417 $guestrole = create_role(addslashes(get_string('guest')), 'guest',
1418 addslashes(get_string('guestdescription')), 'moodle/legacy:guest');
1419 $userrole = create_role(addslashes(get_string('authenticateduser')), 'user',
1420 addslashes(get_string('authenticateduserdescription')), 'moodle/legacy:user');
1422 /// Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles
1424 if (!assign_capability('moodle/site:doanything', CAP_ALLOW
, $adminrole, $systemcontext->id
)) {
1425 error('Could not assign moodle/site:doanything to the admin role');
1427 if (!update_capabilities()) {
1428 error('Had trouble upgrading the core capabilities for the Roles System');
1431 /// Look inside user_admin, user_creator, user_teachers, user_students and
1432 /// assign above new roles. If a user has both teacher and student role,
1433 /// only teacher role is assigned. The assignment should be system level.
1435 $dbtables = $db->MetaTables('TABLES');
1437 /// Set up the progress bar
1439 $usertables = array('user_admins', 'user_coursecreators', 'user_teachers', 'user_students');
1441 $totalcount = $progresscount = 0;
1442 foreach ($usertables as $usertable) {
1443 if (in_array($CFG->prefix
.$usertable, $dbtables)) {
1444 $totalcount +
= count_records($usertable);
1448 print_progress(0, $totalcount, 5, 1, 'Processing role assignments');
1450 /// Upgrade the admins.
1451 /// Sort using id ASC, first one is primary admin.
1453 if (in_array($CFG->prefix
.'user_admins', $dbtables)) {
1454 if ($rs = get_recordset_sql('SELECT * from '.$CFG->prefix
.'user_admins ORDER BY ID ASC')) {
1455 while ($admin = rs_fetch_next_record($rs)) {
1456 role_assign($adminrole, $admin->userid
, 0, $systemcontext->id
);
1458 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1463 // This is a fresh install.
1467 /// Upgrade course creators.
1468 if (in_array($CFG->prefix
.'user_coursecreators', $dbtables)) {
1469 if ($rs = get_recordset('user_coursecreators')) {
1470 while ($coursecreator = rs_fetch_next_record($rs)) {
1471 role_assign($coursecreatorrole, $coursecreator->userid
, 0, $systemcontext->id
);
1473 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1480 /// Upgrade editting teachers and non-editting teachers.
1481 if (in_array($CFG->prefix
.'user_teachers', $dbtables)) {
1482 if ($rs = get_recordset('user_teachers')) {
1483 while ($teacher = rs_fetch_next_record($rs)) {
1485 // removed code here to ignore site level assignments
1486 // since the contexts are separated now
1488 // populate the user_lastaccess table
1489 $access = new object();
1490 $access->timeaccess
= $teacher->timeaccess
;
1491 $access->userid
= $teacher->userid
;
1492 $access->courseid
= $teacher->course
;
1493 insert_record('user_lastaccess', $access);
1495 // assign the default student role
1496 $coursecontext = get_context_instance(CONTEXT_COURSE
, $teacher->course
); // needs cache
1498 if ($teacher->authority
== 0) {
1504 if ($teacher->editall
) { // editting teacher
1505 role_assign($editteacherrole, $teacher->userid
, 0, $coursecontext->id
, 0, 0, $hiddenteacher);
1507 role_assign($noneditteacherrole, $teacher->userid
, 0, $coursecontext->id
, 0, 0, $hiddenteacher);
1510 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1517 /// Upgrade students.
1518 if (in_array($CFG->prefix
.'user_students', $dbtables)) {
1519 if ($rs = get_recordset('user_students')) {
1520 while ($student = rs_fetch_next_record($rs)) {
1522 // populate the user_lastaccess table
1523 $access = new object;
1524 $access->timeaccess
= $student->timeaccess
;
1525 $access->userid
= $student->userid
;
1526 $access->courseid
= $student->course
;
1527 insert_record('user_lastaccess', $access);
1529 // assign the default student role
1530 $coursecontext = get_context_instance(CONTEXT_COURSE
, $student->course
);
1531 role_assign($studentrole, $student->userid
, 0, $coursecontext->id
);
1533 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1540 /// Upgrade guest (only 1 entry).
1541 if ($guestuser = get_record('user', 'username', 'guest')) {
1542 role_assign($guestrole, $guestuser->id
, 0, $systemcontext->id
);
1544 print_progress($totalcount, $totalcount, 5, 1, 'Processing role assignments');
1547 /// Insert the correct records for legacy roles
1548 allow_assign($adminrole, $adminrole);
1549 allow_assign($adminrole, $coursecreatorrole);
1550 allow_assign($adminrole, $noneditteacherrole);
1551 allow_assign($adminrole, $editteacherrole);
1552 allow_assign($adminrole, $studentrole);
1553 allow_assign($adminrole, $guestrole);
1555 allow_assign($coursecreatorrole, $noneditteacherrole);
1556 allow_assign($coursecreatorrole, $editteacherrole);
1557 allow_assign($coursecreatorrole, $studentrole);
1558 allow_assign($coursecreatorrole, $guestrole);
1560 allow_assign($editteacherrole, $noneditteacherrole);
1561 allow_assign($editteacherrole, $studentrole);
1562 allow_assign($editteacherrole, $guestrole);
1564 /// Set up default permissions for overrides
1565 allow_override($adminrole, $adminrole);
1566 allow_override($adminrole, $coursecreatorrole);
1567 allow_override($adminrole, $noneditteacherrole);
1568 allow_override($adminrole, $editteacherrole);
1569 allow_override($adminrole, $studentrole);
1570 allow_override($adminrole, $guestrole);
1571 allow_override($adminrole, $userrole);
1574 /// Delete the old user tables when we are done
1576 drop_table(new XMLDBTable('user_students'));
1577 drop_table(new XMLDBTable('user_teachers'));
1578 drop_table(new XMLDBTable('user_coursecreators'));
1579 drop_table(new XMLDBTable('user_admins'));
1584 * Returns array of all legacy roles.
1586 function get_legacy_roles() {
1588 'admin' => 'moodle/legacy:admin',
1589 'coursecreator' => 'moodle/legacy:coursecreator',
1590 'editingteacher' => 'moodle/legacy:editingteacher',
1591 'teacher' => 'moodle/legacy:teacher',
1592 'student' => 'moodle/legacy:student',
1593 'guest' => 'moodle/legacy:guest',
1594 'user' => 'moodle/legacy:user'
1598 function get_legacy_type($roleid) {
1599 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
1600 $legacyroles = get_legacy_roles();
1603 foreach($legacyroles as $ltype=>$lcap) {
1604 $localoverride = get_local_override($roleid, $sitecontext->id
, $lcap);
1605 if (!empty($localoverride->permission
) and $localoverride->permission
== CAP_ALLOW
) {
1606 //choose first selected legacy capability - reset the rest
1607 if (empty($result)) {
1610 unassign_capability($lcap, $roleid);
1619 * Assign the defaults found in this capabality definition to roles that have
1620 * the corresponding legacy capabilities assigned to them.
1621 * @param $legacyperms - an array in the format (example):
1622 * 'guest' => CAP_PREVENT,
1623 * 'student' => CAP_ALLOW,
1624 * 'teacher' => CAP_ALLOW,
1625 * 'editingteacher' => CAP_ALLOW,
1626 * 'coursecreator' => CAP_ALLOW,
1627 * 'admin' => CAP_ALLOW
1628 * @return boolean - success or failure.
1630 function assign_legacy_capabilities($capability, $legacyperms) {
1632 $legacyroles = get_legacy_roles();
1634 foreach ($legacyperms as $type => $perm) {
1636 $systemcontext = get_context_instance(CONTEXT_SYSTEM
);
1638 if (!array_key_exists($type, $legacyroles)) {
1639 error('Incorrect legacy role definition for type: '.$type);
1642 if ($roles = get_roles_with_capability($legacyroles[$type], CAP_ALLOW
)) {
1643 foreach ($roles as $role) {
1644 // Assign a site level capability.
1645 if (!assign_capability($capability, $perm, $role->id
, $systemcontext->id
)) {
1656 * Checks to see if a capability is a legacy capability.
1657 * @param $capabilityname
1660 function islegacy($capabilityname) {
1661 if (strpos($capabilityname, 'moodle/legacy') === 0) {
1670 /**********************************
1671 * Context Manipulation functions *
1672 **********************************/
1675 * Create a new context record for use by all roles-related stuff
1677 * @param $instanceid
1679 * @return object newly created context (or existing one with a debug warning)
1681 function create_context($contextlevel, $instanceid) {
1682 if (!$context = get_record('context','contextlevel',$contextlevel,'instanceid',$instanceid)) {
1683 if (!validate_context($contextlevel, $instanceid)) {
1684 debugging('Error: Invalid context creation request for level "'.s($contextlevel).'", instance "'.s($instanceid).'".');
1687 if ($contextlevel == CONTEXT_SYSTEM
) {
1688 return create_system_context();
1691 $context = new object();
1692 $context->contextlevel
= $contextlevel;
1693 $context->instanceid
= $instanceid;
1694 if ($id = insert_record('context',$context)) {
1695 // we need to populate context_rel for every new context inserted
1696 $c = get_record('context','id',$id);
1697 insert_context_rel ($c);
1700 debugging('Error: could not insert new context level "'.s($contextlevel).'", instance "'.s($instanceid).'".');
1704 debugging('Warning: Context id "'.s($context->id
).'" not created, because it already exists.');
1710 * This hacky function is needed because we can not change system context instanceid using normal upgrade routine.
1712 function create_system_context() {
1713 if ($context = get_record('context', 'contextlevel', CONTEXT_SYSTEM
, 'instanceid', SITEID
)) {
1714 // we are going to change instanceid of system context to 0 now
1715 $context->instanceid
= 0;
1716 update_record('context', $context);
1717 //context rel not affected
1721 $context = new object();
1722 $context->contextlevel
= CONTEXT_SYSTEM
;
1723 $context->instanceid
= 0;
1724 if ($context->id
= insert_record('context',$context)) {
1725 // we need not to populate context_rel for system context
1728 debugging('Can not create system context');
1734 * Create a new context record for use by all roles-related stuff
1736 * @param $instanceid
1738 * @return true if properly deleted
1740 function delete_context($contextlevel, $instanceid) {
1741 if ($context = get_context_instance($contextlevel, $instanceid)) {
1742 delete_records('context_rel', 'c2', $context->id
); // might not be a parent
1743 return delete_records('context', 'id', $context->id
) &&
1744 delete_records('role_assignments', 'contextid', $context->id
) &&
1745 delete_records('role_capabilities', 'contextid', $context->id
) &&
1746 delete_records('context_rel', 'c1', $context->id
);
1752 * Validate that object with instanceid really exists in given context level.
1754 * return if instanceid object exists
1756 function validate_context($contextlevel, $instanceid) {
1757 switch ($contextlevel) {
1759 case CONTEXT_SYSTEM
:
1760 return ($instanceid == 0);
1762 case CONTEXT_PERSONAL
:
1763 return (boolean
)count_records('user', 'id', $instanceid);
1766 return (boolean
)count_records('user', 'id', $instanceid);
1768 case CONTEXT_COURSECAT
:
1769 if ($instanceid == 0) {
1770 return true; // site course category
1772 return (boolean
)count_records('course_categories', 'id', $instanceid);
1774 case CONTEXT_COURSE
:
1775 return (boolean
)count_records('course', 'id', $instanceid);
1778 return groups_group_exists($instanceid);
1780 case CONTEXT_MODULE
:
1781 return (boolean
)count_records('course_modules', 'id', $instanceid);
1784 return (boolean
)count_records('block_instance', 'id', $instanceid);
1792 * Get the context instance as an object. This function will create the
1793 * context instance if it does not exist yet.
1794 * @param integer $level The context level, for example CONTEXT_COURSE, or CONTEXT_MODULE.
1795 * @param integer $instance The instance id. For $level = CONTEXT_COURSE, this would be $course->id,
1796 * for $level = CONTEXT_MODULE, this would be $cm->id. And so on.
1797 * @return object The context object.
1799 function get_context_instance($contextlevel=NULL, $instance=0) {
1801 global $context_cache, $context_cache_id, $CONTEXT;
1802 static $allowed_contexts = array(CONTEXT_SYSTEM
, CONTEXT_PERSONAL
, CONTEXT_USER
, CONTEXT_COURSECAT
, CONTEXT_COURSE
, CONTEXT_GROUP
, CONTEXT_MODULE
, CONTEXT_BLOCK
);
1804 // Yu: Separating site and site course context - removed CONTEXT_COURSE override when SITEID
1807 if ($contextlevel == 'clearcache') {
1809 $context_cache = array();
1810 $context_cache_id = array();
1815 /// If no level is supplied then return the current global context if there is one
1816 if (empty($contextlevel)) {
1817 if (empty($CONTEXT)) {
1818 //fatal error, code must be fixed
1819 error("Error: get_context_instance() called without a context");
1825 /// Backwards compatibility with obsoleted (CONTEXT_SYSTEM, SITEID)
1826 if ($contextlevel == CONTEXT_SYSTEM
) {
1830 /// check allowed context levels
1831 if (!in_array($contextlevel, $allowed_contexts)) {
1832 // fatal error, code must be fixed - probably typo or switched parameters
1833 error('Error: get_context_instance() called with incorrect context level "'.s($contextlevel).'"');
1837 if (isset($context_cache[$contextlevel][$instance])) { // Already cached
1838 return $context_cache[$contextlevel][$instance];
1841 /// Get it from the database, or create it
1842 if (!$context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance)) {
1843 create_context($contextlevel, $instance);
1844 $context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance);
1847 /// Only add to cache if context isn't empty.
1848 if (!empty($context)) {
1849 $context_cache[$contextlevel][$instance] = $context; // Cache it for later
1850 $context_cache_id[$context->id
] = $context; // Cache it for later
1858 * Get a context instance as an object, from a given context id.
1859 * @param $id a context id.
1860 * @return object The context object.
1862 function get_context_instance_by_id($id) {
1864 global $context_cache, $context_cache_id;
1866 if (isset($context_cache_id[$id])) { // Already cached
1867 return $context_cache_id[$id];
1870 if ($context = get_record('context', 'id', $id)) { // Update the cache and return
1871 $context_cache[$context->contextlevel
][$context->instanceid
] = $context;
1872 $context_cache_id[$context->id
] = $context;
1881 * Get the local override (if any) for a given capability in a role in a context
1884 * @param $capability
1886 function get_local_override($roleid, $contextid, $capability) {
1887 return get_record('role_capabilities', 'roleid', $roleid, 'capability', $capability, 'contextid', $contextid);
1892 /************************************
1893 * DB TABLE RELATED FUNCTIONS *
1894 ************************************/
1897 * function that creates a role
1898 * @param name - role name
1899 * @param shortname - role short name
1900 * @param description - role description
1901 * @param legacy - optional legacy capability
1902 * @return id or false
1904 function create_role($name, $shortname, $description, $legacy='') {
1906 // check for duplicate role name
1908 if ($role = get_record('role','name', $name)) {
1909 error('there is already a role with this name!');
1912 if ($role = get_record('role','shortname', $shortname)) {
1913 error('there is already a role with this shortname!');
1916 $role = new object();
1917 $role->name
= $name;
1918 $role->shortname
= $shortname;
1919 $role->description
= $description;
1921 //find free sortorder number
1922 $role->sortorder
= count_records('role');
1923 while (get_record('role','sortorder', $role->sortorder
)) {
1924 $role->sortorder +
= 1;
1927 if (!$context = get_context_instance(CONTEXT_SYSTEM
)) {
1931 if ($id = insert_record('role', $role)) {
1933 assign_capability($legacy, CAP_ALLOW
, $id, $context->id
);
1936 /// By default, users with role:manage at site level
1937 /// should be able to assign users to this new role, and override this new role's capabilities
1939 // find all admin roles
1940 if ($adminroles = get_roles_with_capability('moodle/role:manage', CAP_ALLOW
, $context)) {
1941 // foreach admin role
1942 foreach ($adminroles as $arole) {
1943 // write allow_assign and allow_overrid
1944 allow_assign($arole->id
, $id);
1945 allow_override($arole->id
, $id);
1957 * function that deletes a role and cleanups up after it
1958 * @param roleid - id of role to delete
1961 function delete_role($roleid) {
1964 // first unssign all users
1965 if (!role_unassign($roleid)) {
1966 debugging("Error while unassigning all users from role with ID $roleid!");
1970 // cleanup all references to this role, ignore errors
1972 delete_records('role_capabilities', 'roleid', $roleid);
1973 delete_records('role_allow_assign', 'roleid', $roleid);
1974 delete_records('role_allow_assign', 'allowassign', $roleid);
1975 delete_records('role_allow_override', 'roleid', $roleid);
1976 delete_records('role_allow_override', 'allowoverride', $roleid);
1977 delete_records('role_names', 'roleid', $roleid);
1980 // finally delete the role itself
1981 if ($success and !delete_records('role', 'id', $roleid)) {
1982 debugging("Could not delete role record with ID $roleid!");
1990 * Function to write context specific overrides, or default capabilities.
1991 * @param module - string name
1992 * @param capability - string name
1993 * @param contextid - context id
1994 * @param roleid - role id
1995 * @param permission - int 1,-1 or -1000
1996 * should not be writing if permission is 0
1998 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite=false) {
2002 if (empty($permission) ||
$permission == CAP_INHERIT
) { // if permission is not set
2003 unassign_capability($capability, $roleid, $contextid);
2007 $existing = get_record('role_capabilities', 'contextid', $contextid, 'roleid', $roleid, 'capability', $capability);
2009 if ($existing and !$overwrite) { // We want to keep whatever is there already
2014 $cap->contextid
= $contextid;
2015 $cap->roleid
= $roleid;
2016 $cap->capability
= $capability;
2017 $cap->permission
= $permission;
2018 $cap->timemodified
= time();
2019 $cap->modifierid
= empty($USER->id
) ?
0 : $USER->id
;
2022 $cap->id
= $existing->id
;
2023 return update_record('role_capabilities', $cap);
2025 return insert_record('role_capabilities', $cap);
2031 * Unassign a capability from a role.
2032 * @param $roleid - the role id
2033 * @param $capability - the name of the capability
2034 * @return boolean - success or failure
2036 function unassign_capability($capability, $roleid, $contextid=NULL) {
2038 if (isset($contextid)) {
2039 $status = delete_records('role_capabilities', 'capability', $capability,
2040 'roleid', $roleid, 'contextid', $contextid);
2042 $status = delete_records('role_capabilities', 'capability', $capability,
2050 * Get the roles that have a given capability assigned to it. This function
2051 * does not resolve the actual permission of the capability. It just checks
2052 * for assignment only.
2053 * @param $capability - capability name (string)
2054 * @param $permission - optional, the permission defined for this capability
2055 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT
2056 * @return array or role objects
2058 function get_roles_with_capability($capability, $permission=NULL, $context='') {
2063 if ($contexts = get_parent_contexts($context)) {
2064 $listofcontexts = '('.implode(',', $contexts).')';
2066 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
2067 $listofcontexts = '('.$sitecontext->id
.')'; // must be site
2069 $contextstr = "AND (rc.contextid = '$context->id' OR rc.contextid IN $listofcontexts)";
2074 $selectroles = "SELECT r.*
2075 FROM {$CFG->prefix}role r,
2076 {$CFG->prefix}role_capabilities rc
2077 WHERE rc.capability = '$capability'
2078 AND rc.roleid = r.id $contextstr";
2080 if (isset($permission)) {
2081 $selectroles .= " AND rc.permission = '$permission'";
2083 return get_records_sql($selectroles);
2088 * This function makes a role-assignment (a role for a user or group in a particular context)
2089 * @param $roleid - the role of the id
2090 * @param $userid - userid
2091 * @param $groupid - group id
2092 * @param $contextid - id of the context
2093 * @param $timestart - time this assignment becomes effective
2094 * @param $timeend - time this assignemnt ceases to be effective
2096 * @return id - new id of the assigment
2098 function role_assign($roleid, $userid, $groupid, $contextid, $timestart=0, $timeend=0, $hidden=0, $enrol='manual') {
2101 debugging("Assign roleid $roleid userid $userid contextid $contextid", DEBUG_DEVELOPER
);
2103 /// Do some data validation
2105 if (empty($roleid)) {
2106 debugging('Role ID not provided');
2110 if (empty($userid) && empty($groupid)) {
2111 debugging('Either userid or groupid must be provided');
2115 if ($userid && !record_exists('user', 'id', $userid)) {
2116 debugging('User ID '.intval($userid).' does not exist!');
2120 if ($groupid && !groups_group_exists($groupid)) {
2121 debugging('Group ID '.intval($groupid).' does not exist!');
2125 if (!$context = get_context_instance_by_id($contextid)) {
2126 debugging('Context ID '.intval($contextid).' does not exist!');
2130 if (($timestart and $timeend) and ($timestart > $timeend)) {
2131 debugging('The end time can not be earlier than the start time');
2136 /// Check for existing entry
2138 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id
, 'userid', $userid);
2140 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id
, 'groupid', $groupid);
2144 $newra = new object;
2146 if (empty($ra)) { // Create a new entry
2147 $newra->roleid
= $roleid;
2148 $newra->contextid
= $context->id
;
2149 $newra->userid
= $userid;
2150 $newra->hidden
= $hidden;
2151 $newra->enrol
= $enrol;
2152 /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
2153 /// by repeating queries with the same exact parameters in a 100 secs time window
2154 $newra->timestart
= round($timestart, -2);
2155 $newra->timeend
= $timeend;
2156 $newra->timemodified
= time();
2157 $newra->modifierid
= empty($USER->id
) ?
0 : $USER->id
;
2159 $success = insert_record('role_assignments', $newra);
2161 } else { // We already have one, just update it
2163 $newra->id
= $ra->id
;
2164 $newra->hidden
= $hidden;
2165 $newra->enrol
= $enrol;
2166 /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
2167 /// by repeating queries with the same exact parameters in a 100 secs time window
2168 $newra->timestart
= round($timestart, -2);
2169 $newra->timeend
= $timeend;
2170 $newra->timemodified
= time();
2171 $newra->modifierid
= empty($USER->id
) ?
0 : $USER->id
;
2173 $success = update_record('role_assignments', $newra);
2176 if ($success) { /// Role was assigned, so do some other things
2178 /// If the user is the current user, then reload the capabilities too.
2179 if (!empty($USER->id
) && $USER->id
== $userid) {
2180 load_all_capabilities();
2183 /// Ask all the modules if anything needs to be done for this user
2184 if ($mods = get_list_of_plugins('mod')) {
2185 foreach ($mods as $mod) {
2186 include_once($CFG->dirroot
.'/mod/'.$mod.'/lib.php');
2187 $functionname = $mod.'_role_assign';
2188 if (function_exists($functionname)) {
2189 $functionname($userid, $context, $roleid);
2194 /// Make sure they have an entry in user_lastaccess for courses they can access
2195 // role_add_lastaccess_entries($userid, $context);
2198 /// now handle metacourse role assignments if in course context
2199 if ($success and $context->contextlevel
== CONTEXT_COURSE
) {
2200 if ($parents = get_records('course_meta', 'child_course', $context->instanceid
)) {
2201 foreach ($parents as $parent) {
2202 sync_metacourse($parent->parent_course
);
2212 * Deletes one or more role assignments. You must specify at least one parameter.
2217 * @param $enrol unassign only if enrolment type matches, NULL means anything
2218 * @return boolean - success or failure
2220 function role_unassign($roleid=0, $userid=0, $groupid=0, $contextid=0, $enrol=NULL) {
2226 $args = array('roleid', 'userid', 'groupid', 'contextid');
2228 foreach ($args as $arg) {
2230 $select[] = $arg.' = '.$
$arg;
2233 if (!empty($enrol)) {
2234 $select[] = "enrol='$enrol'";
2238 if ($ras = get_records_select('role_assignments', implode(' AND ', $select))) {
2239 $mods = get_list_of_plugins('mod');
2240 foreach($ras as $ra) {
2241 /// infinite loop protection when deleting recursively
2242 if (!$ra = get_record('role_assignments', 'id', $ra->id
)) {
2245 $success = delete_records('role_assignments', 'id', $ra->id
) and $success;
2247 /// If the user is the current user, then reload the capabilities too.
2248 if (!empty($USER->id
) && $USER->id
== $ra->userid
) {
2249 load_all_capabilities();
2251 $context = get_record('context', 'id', $ra->contextid
);
2253 /// Ask all the modules if anything needs to be done for this user
2254 foreach ($mods as $mod) {
2255 include_once($CFG->dirroot
.'/mod/'.$mod.'/lib.php');
2256 $functionname = $mod.'_role_unassign';
2257 if (function_exists($functionname)) {
2258 $functionname($ra->userid
, $context); // watch out, $context might be NULL if something goes wrong
2262 /// now handle metacourse role unassigment and removing from goups if in course context
2263 if (!empty($context) and $context->contextlevel
== CONTEXT_COURSE
) {
2264 //remove from groups when user has no role
2265 $roles = get_user_roles($context, $ra->userid
, true);
2266 if (empty($roles)) {
2267 if ($groups = get_groups($context->instanceid
, $ra->userid
)) {
2268 foreach ($groups as $group) {
2269 delete_records('groups_members', 'groupid', $group->id
, 'userid', $ra->userid
);
2273 //unassign roles in metacourses if needed
2274 if ($parents = get_records('course_meta', 'child_course', $context->instanceid
)) {
2275 foreach ($parents as $parent) {
2276 sync_metacourse($parent->parent_course
);
2288 * A convenience function to take care of the common case where you
2289 * just want to enrol someone using the default role into a course
2291 * @param object $course
2292 * @param object $user
2293 * @param string $enrol - the plugin used to do this enrolment
2295 function enrol_into_course($course, $user, $enrol) {
2297 $timestart = time();
2298 if ($course->enrolperiod
) {
2299 $timeend = time() +
$course->enrolperiod
;
2304 if ($role = get_default_course_role($course)) {
2306 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
2308 if (!role_assign($role->id
, $user->id
, 0, $context->id
, $timestart, $timeend, 0, $enrol)) {
2312 email_welcome_message_to_user($course, $user);
2314 add_to_log($course->id
, 'course', 'enrol', 'view.php?id='.$course->id
, $user->id
);
2323 * Add last access times to user_lastaccess as required
2326 * @return boolean - success or failure
2328 function role_add_lastaccess_entries($userid, $context) {
2332 if (empty($context->contextlevel
)) {
2336 $lastaccess = new object; // Reusable object below
2337 $lastaccess->userid
= $userid;
2338 $lastaccess->timeaccess
= 0;
2340 switch ($context->contextlevel
) {
2342 case CONTEXT_SYSTEM
: // For the whole site
2343 if ($courses = get_record('course')) {
2344 foreach ($courses as $course) {
2345 $lastaccess->courseid
= $course->id
;
2346 role_set_lastaccess($lastaccess);
2351 case CONTEXT_CATEGORY
: // For a whole category
2352 if ($courses = get_record('course', 'category', $context->instanceid
)) {
2353 foreach ($courses as $course) {
2354 $lastaccess->courseid
= $course->id
;
2355 role_set_lastaccess($lastaccess);
2358 if ($categories = get_record('course_categories', 'parent', $context->instanceid
)) {
2359 foreach ($categories as $category) {
2360 $subcontext = get_context_instance(CONTEXT_CATEGORY
, $category->id
);
2361 role_add_lastaccess_entries($userid, $subcontext);
2367 case CONTEXT_COURSE
: // For a whole course
2368 if ($course = get_record('course', 'id', $context->instanceid
)) {
2369 $lastaccess->courseid
= $course->id
;
2370 role_set_lastaccess($lastaccess);
2377 * Delete last access times from user_lastaccess as required
2380 * @return boolean - success or failure
2382 function role_remove_lastaccess_entries($userid, $context) {
2390 * Loads the capability definitions for the component (from file). If no
2391 * capabilities are defined for the component, we simply return an empty array.
2392 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2393 * @return array of capabilities
2395 function load_capability_def($component) {
2398 if ($component == 'moodle') {
2399 $defpath = $CFG->libdir
.'/db/access.php';
2400 $varprefix = 'moodle';
2402 $compparts = explode('/', $component);
2404 if ($compparts[0] == 'block') {
2405 // Blocks are an exception. Blocks directory is 'blocks', and not
2406 // 'block'. So we need to jump through hoops.
2407 $defpath = $CFG->dirroot
.'/'.$compparts[0].
2408 's/'.$compparts[1].'/db/access.php';
2409 $varprefix = $compparts[0].'_'.$compparts[1];
2410 } else if ($compparts[0] == 'format') {
2411 // Similar to the above, course formats are 'format' while they
2412 // are stored in 'course/format'.
2413 $defpath = $CFG->dirroot
.'/course/'.$component.'/db/access.php';
2414 $varprefix = $compparts[0].'_'.$compparts[1];
2415 } else if ($compparts[0] == 'gradeimport') {
2416 $defpath = $CFG->dirroot
.'/grade/import/'.$component.'/db/access.php';
2417 $varprefix = $component;
2418 } else if ($compparts[0] == 'gradeexport') {
2419 $defpath = $CFG->dirroot
.'/grade/export/'.$component.'/db/access.php';
2420 $varprefix = $component;
2421 } else if ($compparts[0] == 'gradereport') {
2422 $defpath = $CFG->dirroot
.'/grade/report/'.$component.'/db/access.php';
2423 $varprefix = $component;
2425 $defpath = $CFG->dirroot
.'/'.$component.'/db/access.php';
2426 $varprefix = str_replace('/', '_', $component);
2429 $capabilities = array();
2431 if (file_exists($defpath)) {
2433 $capabilities = $
{$varprefix.'_capabilities'};
2435 return $capabilities;
2440 * Gets the capabilities that have been cached in the database for this
2442 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2443 * @return array of capabilities
2445 function get_cached_capabilities($component='moodle') {
2446 if ($component == 'moodle') {
2447 $storedcaps = get_records_select('capabilities',
2448 "name LIKE 'moodle/%:%'");
2450 $storedcaps = get_records_select('capabilities',
2451 "name LIKE '$component:%'");
2457 * Returns default capabilities for given legacy role type.
2459 * @param string legacy role name
2462 function get_default_capabilities($legacyrole) {
2463 if (!$allcaps = get_records('capabilities')) {
2464 error('Error: no capabilitites defined!');
2467 $defaults = array();
2468 $components = array();
2469 foreach ($allcaps as $cap) {
2470 if (!in_array($cap->component
, $components)) {
2471 $components[] = $cap->component
;
2472 $alldefs = array_merge($alldefs, load_capability_def($cap->component
));
2475 foreach($alldefs as $name=>$def) {
2476 if (isset($def['legacy'][$legacyrole])) {
2477 $defaults[$name] = $def['legacy'][$legacyrole];
2482 $defaults['moodle/legacy:'.$legacyrole] = CAP_ALLOW
;
2483 if ($legacyrole == 'admin') {
2484 $defaults['moodle/site:doanything'] = CAP_ALLOW
;
2490 * Reset role capabilitites to default according to selected legacy capability.
2491 * If several legacy caps selected, use the first from get_default_capabilities.
2492 * If no legacy selected, removes all capabilities.
2494 * @param int @roleid
2496 function reset_role_capabilities($roleid) {
2497 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
2498 $legacyroles = get_legacy_roles();
2500 $defaultcaps = array();
2501 foreach($legacyroles as $ltype=>$lcap) {
2502 $localoverride = get_local_override($roleid, $sitecontext->id
, $lcap);
2503 if (!empty($localoverride->permission
) and $localoverride->permission
== CAP_ALLOW
) {
2504 //choose first selected legacy capability
2505 $defaultcaps = get_default_capabilities($ltype);
2510 delete_records('role_capabilities', 'roleid', $roleid);
2511 if (!empty($defaultcaps)) {
2512 foreach($defaultcaps as $cap=>$permission) {
2513 assign_capability($cap, $permission, $roleid, $sitecontext->id
);
2519 * Updates the capabilities table with the component capability definitions.
2520 * If no parameters are given, the function updates the core moodle
2523 * Note that the absence of the db/access.php capabilities definition file
2524 * will cause any stored capabilities for the component to be removed from
2527 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2530 function update_capabilities($component='moodle') {
2532 $storedcaps = array();
2534 $filecaps = load_capability_def($component);
2535 $cachedcaps = get_cached_capabilities($component);
2537 foreach ($cachedcaps as $cachedcap) {
2538 array_push($storedcaps, $cachedcap->name
);
2539 // update risk bitmasks and context levels in existing capabilities if needed
2540 if (array_key_exists($cachedcap->name
, $filecaps)) {
2541 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name
])) {
2542 $filecaps[$cachedcap->name
]['riskbitmask'] = 0; // no risk if not specified
2544 if ($cachedcap->riskbitmask
!= $filecaps[$cachedcap->name
]['riskbitmask']) {
2545 $updatecap = new object();
2546 $updatecap->id
= $cachedcap->id
;
2547 $updatecap->riskbitmask
= $filecaps[$cachedcap->name
]['riskbitmask'];
2548 if (!update_record('capabilities', $updatecap)) {
2553 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name
])) {
2554 $filecaps[$cachedcap->name
]['contextlevel'] = 0; // no context level defined
2556 if ($cachedcap->contextlevel
!= $filecaps[$cachedcap->name
]['contextlevel']) {
2557 $updatecap = new object();
2558 $updatecap->id
= $cachedcap->id
;
2559 $updatecap->contextlevel
= $filecaps[$cachedcap->name
]['contextlevel'];
2560 if (!update_record('capabilities', $updatecap)) {
2568 // Are there new capabilities in the file definition?
2571 foreach ($filecaps as $filecap => $def) {
2573 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2574 if (!array_key_exists('riskbitmask', $def)) {
2575 $def['riskbitmask'] = 0; // no risk if not specified
2577 $newcaps[$filecap] = $def;
2580 // Add new capabilities to the stored definition.
2581 foreach ($newcaps as $capname => $capdef) {
2582 $capability = new object;
2583 $capability->name
= $capname;
2584 $capability->captype
= $capdef['captype'];
2585 $capability->contextlevel
= $capdef['contextlevel'];
2586 $capability->component
= $component;
2587 $capability->riskbitmask
= $capdef['riskbitmask'];
2589 if (!insert_record('capabilities', $capability, false, 'id')) {
2594 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $storedcaps)){
2595 if ($rolecapabilities = get_records('role_capabilities', 'capability', $capdef['clonepermissionsfrom'])){
2596 foreach ($rolecapabilities as $rolecapability){
2597 //assign_capability will update rather than insert if capability exists
2598 if (!assign_capability($capname, $rolecapability->permission
,
2599 $rolecapability->roleid
, $rolecapability->contextid
, true)){
2600 notify('Could not clone capabilities for '.$capname);
2604 // Do we need to assign the new capabilities to roles that have the
2605 // legacy capabilities moodle/legacy:* as well?
2606 // we ignore legacy key if we have cloned permissions
2607 } else if (isset($capdef['legacy']) && is_array($capdef['legacy']) &&
2608 !assign_legacy_capabilities($capname, $capdef['legacy'])) {
2609 notify('Could not assign legacy capabilities for '.$capname);
2612 // Are there any capabilities that have been removed from the file
2613 // definition that we need to delete from the stored capabilities and
2614 // role assignments?
2615 capabilities_cleanup($component, $filecaps);
2622 * Deletes cached capabilities that are no longer needed by the component.
2623 * Also unassigns these capabilities from any roles that have them.
2624 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2625 * @param $newcapdef - array of the new capability definitions that will be
2626 * compared with the cached capabilities
2627 * @return int - number of deprecated capabilities that have been removed
2629 function capabilities_cleanup($component, $newcapdef=NULL) {
2633 if ($cachedcaps = get_cached_capabilities($component)) {
2634 foreach ($cachedcaps as $cachedcap) {
2635 if (empty($newcapdef) ||
2636 array_key_exists($cachedcap->name
, $newcapdef) === false) {
2638 // Remove from capabilities cache.
2639 if (!delete_records('capabilities', 'name', $cachedcap->name
)) {
2640 error('Could not delete deprecated capability '.$cachedcap->name
);
2644 // Delete from roles.
2645 if($roles = get_roles_with_capability($cachedcap->name
)) {
2646 foreach($roles as $role) {
2647 if (!unassign_capability($cachedcap->name
, $role->id
)) {
2648 error('Could not unassign deprecated capability '.
2649 $cachedcap->name
.' from role '.$role->name
);
2656 return $removedcount;
2667 * prints human readable context identifier.
2669 function print_context_name($context, $withprefix = true, $short = false) {
2672 switch ($context->contextlevel
) {
2674 case CONTEXT_SYSTEM
: // by now it's a definite an inherit
2675 $name = get_string('coresystem');
2678 case CONTEXT_PERSONAL
:
2679 $name = get_string('personal');
2683 if ($user = get_record('user', 'id', $context->instanceid
)) {
2685 $name = get_string('user').': ';
2687 $name .= fullname($user);
2691 case CONTEXT_COURSECAT
: // Coursecat -> coursecat or site
2692 if ($category = get_record('course_categories', 'id', $context->instanceid
)) {
2694 $name = get_string('category').': ';
2696 $name .=format_string($category->name
);
2700 case CONTEXT_COURSE
: // 1 to 1 to course cat
2701 if ($course = get_record('course', 'id', $context->instanceid
)) {
2703 if ($context->instanceid
== SITEID
) {
2704 $name = get_string('site').': ';
2706 $name = get_string('course').': ';
2710 $name .=format_string($course->shortname
);
2712 $name .=format_string($course->fullname
);
2718 case CONTEXT_GROUP
: // 1 to 1 to course
2719 if ($name = groups_get_group_name($context->instanceid
)) {
2721 $name = get_string('group').': '. $name;
2726 case CONTEXT_MODULE
: // 1 to 1 to course
2727 if ($cm = get_record('course_modules','id',$context->instanceid
)) {
2728 if ($module = get_record('modules','id',$cm->module
)) {
2729 if ($mod = get_record($module->name
, 'id', $cm->instance
)) {
2731 $name = get_string('activitymodule').': ';
2733 $name .= $mod->name
;
2739 case CONTEXT_BLOCK
: // 1 to 1 to course
2740 if ($blockinstance = get_record('block_instance','id',$context->instanceid
)) {
2741 if ($block = get_record('block','id',$blockinstance->blockid
)) {
2743 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
2744 require_once("$CFG->dirroot/blocks/$block->name/block_$block->name.php");
2745 $blockname = "block_$block->name";
2746 if ($blockobject = new $blockname()) {
2748 $name = get_string('block').': ';
2750 $name .= $blockobject->title
;
2757 error ('This is an unknown context (' . $context->contextlevel
. ') in print_context_name!');
2766 * Extracts the relevant capabilities given a contextid.
2767 * All case based, example an instance of forum context.
2768 * Will fetch all forum related capabilities, while course contexts
2769 * Will fetch all capabilities
2770 * @param object context
2774 * `name` varchar(150) NOT NULL,
2775 * `captype` varchar(50) NOT NULL,
2776 * `contextlevel` int(10) NOT NULL,
2777 * `component` varchar(100) NOT NULL,
2779 function fetch_context_capabilities($context) {
2783 $sort = 'ORDER BY contextlevel,component,id'; // To group them sensibly for display
2785 switch ($context->contextlevel
) {
2787 case CONTEXT_SYSTEM
: // all
2788 $SQL = "select * from {$CFG->prefix}capabilities";
2791 case CONTEXT_PERSONAL
:
2792 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_PERSONAL
;
2797 FROM {$CFG->prefix}capabilities
2798 WHERE contextlevel = ".CONTEXT_USER
;
2801 case CONTEXT_COURSECAT
: // all
2802 $SQL = "select * from {$CFG->prefix}capabilities";
2805 case CONTEXT_COURSE
: // all
2806 $SQL = "select * from {$CFG->prefix}capabilities";
2809 case CONTEXT_GROUP
: // group caps
2812 case CONTEXT_MODULE
: // mod caps
2813 $cm = get_record('course_modules', 'id', $context->instanceid
);
2814 $module = get_record('modules', 'id', $cm->module
);
2816 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_MODULE
."
2817 and component = 'mod/$module->name'";
2820 case CONTEXT_BLOCK
: // block caps
2821 $cb = get_record('block_instance', 'id', $context->instanceid
);
2822 $block = get_record('block', 'id', $cb->blockid
);
2824 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_BLOCK
."
2825 and component = 'block/$block->name'";
2832 if (!$records = get_records_sql($SQL.' '.$sort)) {
2836 /// the rest of code is a bit hacky, think twice before modifying it :-(
2838 // special sorting of core system capabiltites and enrollments
2839 if (in_array($context->contextlevel
, array(CONTEXT_SYSTEM
, CONTEXT_COURSECAT
, CONTEXT_COURSE
))) {
2841 foreach ($records as $key=>$record) {
2842 if (preg_match('|^moodle/|', $record->name
) and $record->contextlevel
== CONTEXT_SYSTEM
) {
2843 $first[$key] = $record;
2844 unset($records[$key]);
2845 } else if (count($first)){
2849 if (count($first)) {
2850 $records = $first +
$records; // merge the two arrays keeping the keys
2853 $contextindependentcaps = fetch_context_independent_capabilities();
2854 $records = array_merge($contextindependentcaps, $records);
2863 * Gets the context-independent capabilities that should be overrridable in
2865 * @return array of capability records from the capabilities table.
2867 function fetch_context_independent_capabilities() {
2869 //only CONTEXT_SYSTEM capabilities here or it will break the hack in fetch_context_capabilities()
2870 $contextindependentcaps = array(
2871 'moodle/site:accessallgroups'
2876 foreach ($contextindependentcaps as $capname) {
2877 $record = get_record('capabilities', 'name', $capname);
2878 array_push($records, $record);
2885 * This function pulls out all the resolved capabilities (overrides and
2886 * defaults) of a role used in capability overrides in contexts at a given
2888 * @param obj $context
2889 * @param int $roleid
2890 * @param bool self - if set to true, resolve till this level, else stop at immediate parent level
2893 function role_context_capabilities($roleid, $context, $cap='') {
2896 $contexts = get_parent_contexts($context);
2897 $contexts[] = $context->id
;
2898 $contexts = '('.implode(',', $contexts).')';
2901 $search = " AND rc.capability = '$cap' ";
2907 FROM {$CFG->prefix}role_capabilities rc,
2908 {$CFG->prefix}context c
2909 WHERE rc.contextid in $contexts
2910 AND rc.roleid = $roleid
2911 AND rc.contextid = c.id $search
2912 ORDER BY c.contextlevel DESC,
2913 rc.capability DESC";
2915 $capabilities = array();
2917 if ($records = get_records_sql($SQL)) {
2918 // We are traversing via reverse order.
2919 foreach ($records as $record) {
2920 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2921 if (!isset($capabilities[$record->capability
]) ||
$record->permission
<-500) {
2922 $capabilities[$record->capability
] = $record->permission
;
2926 return $capabilities;
2930 * Recursive function which, given a context, find all parent context ids,
2931 * and return the array in reverse order, i.e. parent first, then grand
2933 * @param object $context
2936 function get_parent_contexts($context) {
2938 static $pcontexts; // cache
2939 if (isset($pcontexts[$context->id
])) {
2940 return ($pcontexts[$context->id
]);
2943 switch ($context->contextlevel
) {
2945 case CONTEXT_SYSTEM
: // no parent
2949 case CONTEXT_PERSONAL
:
2950 if (!$parent = get_context_instance(CONTEXT_SYSTEM
)) {
2953 $res = array($parent->id
);
2954 $pcontexts[$context->id
] = $res;
2960 if (!$parent = get_context_instance(CONTEXT_SYSTEM
)) {
2963 $res = array($parent->id
);
2964 $pcontexts[$context->id
] = $res;
2969 case CONTEXT_COURSECAT
: // Coursecat -> coursecat or site
2970 if (!$coursecat = get_record('course_categories','id',$context->instanceid
)) {
2973 if (!empty($coursecat->parent
)) { // return parent value if exist
2974 $parent = get_context_instance(CONTEXT_COURSECAT
, $coursecat->parent
);
2975 $res = array_merge(array($parent->id
), get_parent_contexts($parent));
2976 $pcontexts[$context->id
] = $res;
2978 } else { // else return site value
2979 $parent = get_context_instance(CONTEXT_SYSTEM
);
2980 $res = array($parent->id
);
2981 $pcontexts[$context->id
] = $res;
2986 case CONTEXT_COURSE
: // 1 to 1 to course cat
2987 if (!$course = get_record('course','id',$context->instanceid
)) {
2990 if ($course->id
!= SITEID
) {
2991 $parent = get_context_instance(CONTEXT_COURSECAT
, $course->category
);
2992 $res = array_merge(array($parent->id
), get_parent_contexts($parent));
2995 // Yu: Separating site and site course context
2996 $parent = get_context_instance(CONTEXT_SYSTEM
);
2997 $res = array($parent->id
);
2998 $pcontexts[$context->id
] = $res;
3003 case CONTEXT_GROUP
: // 1 to 1 to course
3004 if (! $group = groups_get_group($context->instanceid
)) {
3007 if ($parent = get_context_instance(CONTEXT_COURSE
, $group->courseid
)) {
3008 $res = array_merge(array($parent->id
), get_parent_contexts($parent));
3009 $pcontexts[$context->id
] = $res;
3016 case CONTEXT_MODULE
: // 1 to 1 to course
3017 if (!$cm = get_record('course_modules','id',$context->instanceid
)) {
3020 if ($parent = get_context_instance(CONTEXT_COURSE
, $cm->course
)) {
3021 $res = array_merge(array($parent->id
), get_parent_contexts($parent));
3022 $pcontexts[$context->id
] = $res;
3029 case CONTEXT_BLOCK
: // 1 to 1 to course
3030 if (!$block = get_record('block_instance','id',$context->instanceid
)) {
3033 // fix for MDL-9656, block parents are not necessarily courses
3034 if ($block->pagetype
== 'course-view') {
3035 $parent = get_context_instance(CONTEXT_COURSE
, $block->pageid
);
3037 $parent = get_context_instance(CONTEXT_SYSTEM
);
3041 $res = array_merge(array($parent->id
), get_parent_contexts($parent));
3042 $pcontexts[$context->id
] = $res;
3050 error('This is an unknown context (' . $context->contextlevel
. ') in get_parent_contexts!');
3057 * Recursive function which, given a context, find all its children context ids.
3058 * @param object $context.
3059 * @return array of children context ids.
3061 function get_child_contexts($context) {
3064 $children = array();
3066 switch ($context->contextlevel
) {
3073 case CONTEXT_MODULE
:
3083 case CONTEXT_COURSE
:
3084 // Find all block instances for the course.
3085 $page = new page_course
;
3086 $page->id
= $context->instanceid
;
3087 $page->type
= 'course-view';
3088 if ($blocks = blocks_get_by_page_pinned($page)) {
3089 foreach ($blocks['l'] as $leftblock) {
3090 if ($child = get_context_instance(CONTEXT_BLOCK
, $leftblock->id
)) {
3091 array_push($children, $child->id
);
3094 foreach ($blocks['r'] as $rightblock) {
3095 if ($child = get_context_instance(CONTEXT_BLOCK
, $rightblock->id
)) {
3096 array_push($children, $child->id
);
3100 // Find all module instances for the course.
3101 if ($modules = get_records('course_modules', 'course', $context->instanceid
)) {
3102 foreach ($modules as $module) {
3103 if ($child = get_context_instance(CONTEXT_MODULE
, $module->id
)) {
3104 array_push($children, $child->id
);
3108 // Find all group instances for the course.
3109 if ($groupids = groups_get_groups($context->instanceid
)) {
3110 foreach ($groupids as $groupid) {
3111 if ($child = get_context_instance(CONTEXT_GROUP
, $groupid)) {
3112 array_push($children, $child->id
);
3119 case CONTEXT_COURSECAT
:
3120 // We need to get the contexts for:
3121 // 1) The subcategories of the given category
3122 // 2) The courses in the given category and all its subcategories
3123 // 3) All the child contexts for these courses
3125 $categories = get_all_subcategories($context->instanceid
);
3127 // Add the contexts for all the subcategories.
3128 foreach ($categories as $catid) {
3129 if ($catci = get_context_instance(CONTEXT_COURSECAT
, $catid)) {
3130 array_push($children, $catci->id
);
3134 // Add the parent category as well so we can find the contexts
3136 array_unshift($categories, $context->instanceid
);
3138 foreach ($categories as $catid) {
3139 // Find all courses for the category.
3140 if ($courses = get_records('course', 'category', $catid)) {
3141 foreach ($courses as $course) {
3142 if ($courseci = get_context_instance(CONTEXT_COURSE
, $course->id
)) {
3143 array_push($children, $courseci->id
);
3144 $children = array_merge($children, get_child_contexts($courseci));
3157 case CONTEXT_PERSONAL
:
3162 case CONTEXT_SYSTEM
:
3163 // Just get all the contexts except for CONTEXT_SYSTEM level.
3164 $sql = 'SELECT c.id '.
3165 'FROM '.$CFG->prefix
.'context AS c '.
3166 'WHERE contextlevel != '.CONTEXT_SYSTEM
;
3168 $contexts = get_records_sql($sql);
3169 foreach ($contexts as $cid) {
3170 array_push($children, $cid->id
);
3176 error('This is an unknown context (' . $context->contextlevel
. ') in get_child_contexts!');
3183 * Gets a string for sql calls, searching for stuff in this context or above
3184 * @param object $context
3187 function get_related_contexts_string($context) {
3188 if ($parents = get_parent_contexts($context)) {
3189 return (' IN ('.$context->id
.','.implode(',', $parents).')');
3191 return (' ='.$context->id
);
3197 * This function gets the capability of a role in a given context.
3198 * It is needed when printing override forms.
3199 * @param int $contextid
3200 * @param string $capability
3201 * @param array $capabilities - array loaded using role_context_capabilities
3202 * @return int (allow, prevent, prohibit, inherit)
3204 function get_role_context_capability($contextid, $capability, $capabilities) {
3205 if (isset($capabilities[$contextid][$capability])) {
3206 return $capabilities[$contextid][$capability];
3215 * Returns the human-readable, translated version of the capability.
3216 * Basically a big switch statement.
3217 * @param $capabilityname - e.g. mod/choice:readresponses
3219 function get_capability_string($capabilityname) {
3221 // Typical capabilityname is mod/choice:readresponses
3223 $names = split('/', $capabilityname);
3224 $stringname = $names[1]; // choice:readresponses
3225 $components = split(':', $stringname);
3226 $componentname = $components[0]; // choice
3228 switch ($names[0]) {
3230 $string = get_string($stringname, $componentname);
3234 $string = get_string($stringname, 'block_'.$componentname);
3238 $string = get_string($stringname, 'role');
3242 $string = get_string($stringname, 'enrol_'.$componentname);
3246 $string = get_string($stringname, 'format_'.$componentname);
3250 $string = get_string($stringname);
3259 * This gets the mod/block/course/core etc strings.
3261 * @param $contextlevel
3263 function get_component_string($component, $contextlevel) {
3265 switch ($contextlevel) {
3267 case CONTEXT_SYSTEM
:
3268 if (preg_match('|^enrol/|', $component)) {
3269 $langname = str_replace('/', '_', $component);
3270 $string = get_string('enrolname', $langname);
3271 } else if (preg_match('|^block/|', $component)) {
3272 $langname = str_replace('/', '_', $component);
3273 $string = get_string('blockname', $langname);
3275 $string = get_string('coresystem');
3279 case CONTEXT_PERSONAL
:
3280 $string = get_string('personal');
3284 $string = get_string('users');
3287 case CONTEXT_COURSECAT
:
3288 $string = get_string('categories');
3291 case CONTEXT_COURSE
:
3292 $string = get_string('course');
3296 $string = get_string('group');
3299 case CONTEXT_MODULE
:
3300 $string = get_string('modulename', basename($component));
3304 $string = get_string('blockname', 'block_'.basename($component));
3308 error ('This is an unknown context $contextlevel (' . $contextlevel . ') in get_component_string!');
3316 * Gets the list of roles assigned to this context and up (parents)
3317 * @param object $context
3318 * @param view - set to true when roles are pulled for display only
3319 * this is so that we can filter roles with no visible
3320 * assignment, for example, you might want to "hide" all
3321 * course creators when browsing the course participants
3325 function get_roles_used_in_context($context, $view = false) {
3329 // filter for roles with all hidden assignments
3330 // no need to return when only pulling roles for reviewing
3331 // e.g. participants page.
3332 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))?
' AND ra.hidden = 0 ':'';
3333 $contextlist = get_related_contexts_string($context);
3335 $sql = "SELECT DISTINCT r.id,
3339 FROM {$CFG->prefix}role_assignments ra,
3340 {$CFG->prefix}role r
3341 WHERE r.id = ra.roleid
3342 AND ra.contextid $contextlist
3344 ORDER BY r.sortorder ASC";
3346 return get_records_sql($sql);
3349 /** this function is used to print roles column in user profile page.
3351 * @param int contextid
3354 function get_user_roles_in_context($userid, $contextid){
3358 $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';
3359 if ($roles = get_records_sql($SQL)) {
3360 foreach ($roles as $userrole) {
3361 $rolestring .= '<a href="'.$CFG->wwwroot
.'/user/index.php?contextid='.$userrole->contextid
.'&roleid='.$userrole->roleid
.'">'.$userrole->name
.'</a>, ';
3365 return rtrim($rolestring, ', ');
3370 * Checks if a user can override capabilities of a particular role in this context
3371 * @param object $context
3372 * @param int targetroleid - the id of the role you want to override
3375 function user_can_override($context, $targetroleid) {
3376 // first check if user has override capability
3377 // if not return false;
3378 if (!has_capability('moodle/role:override', $context)) {
3381 // pull out all active roles of this user from this context(or above)
3382 if ($userroles = get_user_roles($context)) {
3383 foreach ($userroles as $userrole) {
3384 // if any in the role_allow_override table, then it's ok
3385 if (get_record('role_allow_override', 'roleid', $userrole->roleid
, 'allowoverride', $targetroleid)) {
3396 * Checks if a user can assign users to a particular role in this context
3397 * @param object $context
3398 * @param int targetroleid - the id of the role you want to assign users to
3401 function user_can_assign($context, $targetroleid) {
3403 // first check if user has override capability
3404 // if not return false;
3405 if (!has_capability('moodle/role:assign', $context)) {
3408 // pull out all active roles of this user from this context(or above)
3409 if ($userroles = get_user_roles($context)) {
3410 foreach ($userroles as $userrole) {
3411 // if any in the role_allow_override table, then it's ok
3412 if (get_record('role_allow_assign', 'roleid', $userrole->roleid
, 'allowassign', $targetroleid)) {
3421 /** Returns all site roles in correct sort order.
3424 function get_all_roles() {
3425 return get_records('role', '', '', 'sortorder ASC');
3429 * gets all the user roles assigned in this context, or higher contexts
3430 * this is mainly used when checking if a user can assign a role, or overriding a role
3431 * i.e. we need to know what this user holds, in order to verify against allow_assign and
3432 * allow_override tables
3433 * @param object $context
3434 * @param int $userid
3435 * @param view - set to true when roles are pulled for display only
3436 * this is so that we can filter roles with no visible
3437 * assignment, for example, you might want to "hide" all
3438 * course creators when browsing the course participants
3442 function get_user_roles($context, $userid=0, $checkparentcontexts=true, $order='c.contextlevel DESC, r.sortorder ASC', $view=false) {
3444 global $USER, $CFG, $db;
3446 if (empty($userid)) {
3447 if (empty($USER->id
)) {
3450 $userid = $USER->id
;
3452 // set up hidden sql
3453 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))?
' AND ra.hidden = 0 ':'';
3455 if ($checkparentcontexts && ($parents = get_parent_contexts($context))) {
3456 $contexts = ' ra.contextid IN ('.implode(',' , $parents).','.$context->id
.')';
3458 $contexts = ' ra.contextid = \''.$context->id
.'\'';
3461 return get_records_sql('SELECT ra.*, r.name, r.shortname
3462 FROM '.$CFG->prefix
.'role_assignments ra,
3463 '.$CFG->prefix
.'role r,
3464 '.$CFG->prefix
.'context c
3465 WHERE ra.userid = '.$userid.
3466 ' AND ra.roleid = r.id
3467 AND ra.contextid = c.id
3468 AND '.$contexts . $hiddensql .
3469 ' ORDER BY '.$order);
3473 * Creates a record in the allow_override table
3474 * @param int sroleid - source roleid
3475 * @param int troleid - target roleid
3476 * @return int - id or false
3478 function allow_override($sroleid, $troleid) {
3479 $record = new object();
3480 $record->roleid
= $sroleid;
3481 $record->allowoverride
= $troleid;
3482 return insert_record('role_allow_override', $record);
3486 * Creates a record in the allow_assign table
3487 * @param int sroleid - source roleid
3488 * @param int troleid - target roleid
3489 * @return int - id or false
3491 function allow_assign($sroleid, $troleid) {
3492 $record = new object;
3493 $record->roleid
= $sroleid;
3494 $record->allowassign
= $troleid;
3495 return insert_record('role_allow_assign', $record);
3499 * Gets a list of roles that this user can assign in this context
3500 * @param object $context
3503 function get_assignable_roles ($context, $field="name") {
3507 if ($roles = get_all_roles()) {
3508 foreach ($roles as $role) {
3509 if (user_can_assign($context, $role->id
)) {
3510 $options[$role->id
] = strip_tags(format_string($role->{$field}, true));
3518 * Gets a list of roles that this user can override in this context
3519 * @param object $context
3522 function get_overridable_roles($context) {
3526 if ($roles = get_all_roles()) {
3527 foreach ($roles as $role) {
3528 if (user_can_override($context, $role->id
)) {
3529 $options[$role->id
] = strip_tags(format_string($role->name
, true));
3538 * Returns a role object that is the default role for new enrolments
3541 * @param object $course
3542 * @return object $role
3544 function get_default_course_role($course) {
3547 /// First let's take the default role the course may have
3548 if (!empty($course->defaultrole
)) {
3549 if ($role = get_record('role', 'id', $course->defaultrole
)) {
3554 /// Otherwise the site setting should tell us
3555 if ($CFG->defaultcourseroleid
) {
3556 if ($role = get_record('role', 'id', $CFG->defaultcourseroleid
)) {
3561 /// It's unlikely we'll get here, but just in case, try and find a student role
3562 if ($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW
)) {
3563 return array_shift($studentroles); /// Take the first one
3571 * who has this capability in this context
3572 * does not handling user level resolving!!!
3573 * (!)pleaes note if $fields is empty this function attempts to get u.*
3574 * which can get rather large.
3575 * i.e 1 person has 2 roles 1 allow, 1 prevent, this will not work properly
3576 * @param $context - object
3577 * @param $capability - string capability
3578 * @param $fields - fields to be pulled
3579 * @param $sort - the sort order
3580 * @param $limitfrom - number of records to skip (offset)
3581 * @param $limitnum - number of records to fetch
3582 * @param $groups - single group or array of groups - only return
3583 * users who are in one of these group(s).
3584 * @param $exceptions - list of users to exclude
3585 * @param view - set to true when roles are pulled for display only
3586 * this is so that we can filter roles with no visible
3587 * assignment, for example, you might want to "hide" all
3588 * course creators when browsing the course participants
3590 * @param boolean $useviewallgroups if $groups is set the return users who
3591 * have capability both $capability and moodle/site:accessallgroups
3592 * in this context, as well as users who have $capability and who are
3595 function get_users_by_capability($context, $capability, $fields='', $sort='',
3596 $limitfrom='', $limitnum='', $groups='', $exceptions='', $doanything=true,
3597 $view=false, $useviewallgroups=false) {
3600 /// Sorting out groups
3602 if (is_array($groups)) {
3603 $grouptest = 'gm.groupid IN (' . implode(',', $groups) . ')';
3605 $grouptest = 'gm.groupid = ' . $groups;
3607 $grouptest = 'ra.userid IN (SELECT userid FROM ' .
3608 $CFG->prefix
. 'groups_members gm WHERE ' . $grouptest . ')';
3610 if ($useviewallgroups) {
3611 $viewallgroupsusers = get_users_by_capability($context,
3612 'moodle/site:accessallgroups', $fields='id, id', '', '', '', '', $exceptions);
3613 $groupsql = ' AND (' . $grouptest . ' OR ra.userid IN (' .
3614 implode(',', array_keys($viewallgroupsusers)) . '))';
3616 $groupsql = ' AND ' . $grouptest;
3622 /// Sorting out exceptions
3623 $exceptionsql = $exceptions ?
"AND u.id NOT IN ($exceptions)" : '';
3625 /// Set up default fields
3626 if (empty($fields)) {
3627 $fields = 'u.*, ul.timeaccess as lastaccess, ra.hidden';
3630 /// Set up default sort
3632 $sort = 'ul.timeaccess';
3635 $sortby = $sort ?
" ORDER BY $sort " : '';
3636 /// Set up hidden sql
3637 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))?
' AND ra.hidden = 0 ':'';
3639 /// If context is a course, then construct sql for ul
3640 if ($context->contextlevel
== CONTEXT_COURSE
) {
3641 $courseid = $context->instanceid
;
3642 $coursesql1 = "AND ul.courseid = $courseid";
3647 /// Sorting out roles with this capability set
3648 if ($possibleroles = get_roles_with_capability($capability, CAP_ALLOW
, $context)) {
3650 if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM
)) {
3651 return false; // Something is seriously wrong
3653 $doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW
, $sitecontext);
3656 $validroleids = array();
3657 foreach ($possibleroles as $possiblerole) {
3659 if (isset($doanythingroles[$possiblerole->id
])) { // We don't want these included
3663 if ($caps = role_context_capabilities($possiblerole->id
, $context, $capability)) { // resolved list
3664 if (isset($caps[$capability]) && $caps[$capability] > 0) { // resolved capability > 0
3665 $validroleids[] = $possiblerole->id
;
3669 if (empty($validroleids)) {
3672 $roleids = '('.implode(',', $validroleids).')';
3674 return false; // No need to continue, since no roles have this capability set
3677 /// Construct the main SQL
3678 $select = " SELECT $fields";
3679 $from = " FROM {$CFG->prefix}user u
3680 INNER JOIN {$CFG->prefix}role_assignments ra ON ra.userid = u.id
3681 INNER JOIN {$CFG->prefix}role r ON r.id = ra.roleid
3682 LEFT OUTER JOIN {$CFG->prefix}user_lastaccess ul ON (ul.userid = u.id $coursesql1)";
3683 $where = " WHERE ra.contextid ".get_related_contexts_string($context)."
3685 AND ra.roleid in $roleids
3690 return get_records_sql($select.$from.$where.$sortby, $limitfrom, $limitnum);
3694 * gets all the users assigned this role in this context or higher
3696 * @param int contextid
3697 * @param bool parent if true, get list of users assigned in higher context too
3700 function get_role_users($roleid, $context, $parent=false, $fields='', $sort='u.lastname ASC', $view=false, $limitfrom='', $limitnum='') {
3703 if (empty($fields)) {
3704 $fields = 'u.id, u.confirmed, u.username, u.firstname, u.lastname, '.
3705 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.city, '.
3706 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
3707 'u.emailstop, u.lang, u.timezone';
3710 // whether this assignment is hidden
3711 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))?
' AND r.hidden = 0 ':'';
3713 if ($contexts = get_parent_contexts($context)) {
3714 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
3716 $parentcontexts = '';
3719 $parentcontexts = '';
3723 $roleselect = "AND r.roleid = $roleid";
3728 $SQL = "SELECT $fields
3729 FROM {$CFG->prefix}role_assignments r,
3730 {$CFG->prefix}user u
3731 WHERE (r.contextid = $context->id $parentcontexts)
3732 AND u.id = r.userid $roleselect
3735 "; // join now so that we can just use fullname() later
3737 return get_records_sql($SQL, $limitfrom, $limitnum);
3741 * Counts all the users assigned this role in this context or higher
3743 * @param int contextid
3744 * @param bool parent if true, get list of users assigned in higher context too
3747 function count_role_users($roleid, $context, $parent=false) {
3751 if ($contexts = get_parent_contexts($context)) {
3752 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
3754 $parentcontexts = '';
3757 $parentcontexts = '';
3760 $SQL = "SELECT count(*)
3761 FROM {$CFG->prefix}role_assignments r
3762 WHERE (r.contextid = $context->id $parentcontexts)
3763 AND r.roleid = $roleid";
3765 return count_records_sql($SQL);
3769 * This function gets the list of courses that this user has a particular capability in.
3770 * It is still not very efficient.
3771 * @param string $capability Capability in question
3772 * @param int $userid User ID or null for current user
3773 * @param bool $doanything True if 'doanything' is permitted (default)
3774 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
3775 * otherwise use a comma-separated list of the fields you require, not including id
3776 * @param string $orderby If set, use a comma-separated list of fields from course
3777 * table with sql modifiers (DESC) if needed
3778 * @return array Array of courses, may have zero entries. Or false if query failed.
3780 function get_user_capability_course($capability, $userid=NULL,$doanything=true,$fieldsexceptid='',$orderby='') {
3781 // Convert fields list and ordering
3783 if($fieldsexceptid) {
3784 $fields=explode(',',$fieldsexceptid);
3785 foreach($fields as $field) {
3786 $fieldlist.=',c.'.$field;
3790 $fields=explode(',',$orderby);
3792 foreach($fields as $field) {
3796 $orderby.='c.'.$field;
3798 $orderby='ORDER BY '.$orderby;
3801 // Obtain a list of everything relevant about all courses including context.
3802 // Note the result can be used directly as a context (we are going to), the course
3803 // fields are just appended.
3805 $rs=get_recordset_sql("
3807 x.*,c.id AS courseid$fieldlist
3809 {$CFG->prefix}course c
3810 INNER JOIN {$CFG->prefix}context x ON c.id=x.instanceid AND x.contextlevel=".CONTEXT_COURSE
."
3817 // Check capability for each course in turn
3819 while($coursecontext=rs_fetch_next_record($rs)) {
3820 if(has_capability($capability,$coursecontext,$userid,$doanything)) {
3821 // We've got the capability. Make the record look like a course record
3823 $coursecontext->id
=$coursecontext->courseid
;
3824 unset($coursecontext->courseid
);
3825 unset($coursecontext->contextlevel
);
3826 unset($coursecontext->instanceid
);
3827 $courses[]=$coursecontext;
3833 /** This function finds the roles assigned directly to this context only
3834 * i.e. no parents role
3835 * @param object $context
3838 function get_roles_on_exact_context($context) {
3842 return get_records_sql("SELECT r.*
3843 FROM {$CFG->prefix}role_assignments ra,
3844 {$CFG->prefix}role r
3845 WHERE ra.roleid = r.id
3846 AND ra.contextid = $context->id");
3851 * Switches the current user to another role for the current session and only
3852 * in the given context. If roleid is not valid (eg 0) or the current user
3853 * doesn't have permissions to be switching roles then the user's session
3854 * is compltely reset to have their normal roles.
3855 * @param integer $roleid
3856 * @param object $context
3859 function role_switch($roleid, $context) {
3862 /// If we can't use this or are already using it or no role was specified then bail completely and reset
3863 if (empty($roleid) ||
!has_capability('moodle/role:switchroles', $context)
3864 ||
!empty($USER->switchrole
[$context->id
]) ||
!confirm_sesskey()) {
3866 unset($USER->switchrole
[$context->id
]); // Delete old capabilities
3867 load_all_capabilities(); //reload user caps
3871 /// We're allowed to switch but can we switch to the specified role? Use assignable roles to check.
3872 if (!$roles = get_assignable_roles($context)) {
3876 /// unset default user role - it would not work anyway
3877 unset($roles[$CFG->defaultuserroleid
]);
3879 if (empty($roles[$roleid])) { /// We can't switch to this particular role
3883 /// We have a valid roleid that this user can switch to, so let's set up the session
3885 $USER->switchrole
[$context->id
] = $roleid; // So we know later what state we are in
3887 load_all_capabilities(); //reload switched role caps
3889 /// Add some permissions we are really going to always need, even if the role doesn't have them!
3891 $USER->capabilities
[$context->id
]['moodle/course:view'] = CAP_ALLOW
;
3898 // get any role that has an override on exact context
3899 function get_roles_with_override_on_context($context) {
3903 return get_records_sql("SELECT r.*
3904 FROM {$CFG->prefix}role_capabilities rc,
3905 {$CFG->prefix}role r
3906 WHERE rc.roleid = r.id
3907 AND rc.contextid = $context->id");
3910 // get all capabilities for this role on this context (overrids)
3911 function get_capabilities_from_role_on_context($role, $context) {
3915 return get_records_sql("SELECT *
3916 FROM {$CFG->prefix}role_capabilities
3917 WHERE contextid = $context->id
3918 AND roleid = $role->id");
3921 // find out which roles has assignment on this context
3922 function get_roles_with_assignment_on_context($context) {
3926 return get_records_sql("SELECT r.*
3927 FROM {$CFG->prefix}role_assignments ra,
3928 {$CFG->prefix}role r
3929 WHERE ra.roleid = r.id
3930 AND ra.contextid = $context->id");
3936 * Find all user assignemnt of users for this role, on this context
3938 function get_users_from_role_on_context($role, $context) {
3942 return get_records_sql("SELECT *
3943 FROM {$CFG->prefix}role_assignments
3944 WHERE contextid = $context->id
3945 AND roleid = $role->id");
3949 * Simple function returning a boolean true if roles exist, otherwise false
3951 function user_has_role_assignment($userid, $roleid, $contextid=0) {
3954 return record_exists('role_assignments', 'userid', $userid, 'roleid', $roleid, 'contextid', $contextid);
3956 return record_exists('role_assignments', 'userid', $userid, 'roleid', $roleid);
3961 * Inserts all parental context and self into context_rel table
3963 * @param object $context-context to be deleted
3964 * @param bool deletechild - deltes child contexts dependencies
3966 function insert_context_rel($context, $deletechild=true, $deleteparent=true) {
3968 // first check validity
3970 if (!validate_context($context->contextlevel
, $context->instanceid
)) {
3971 debugging('Error: Invalid context creation request for level "' .
3972 s($context->contextlevel
) . '", instance "' . s($context->instanceid
) . '".');
3976 // removes all parents
3978 delete_records('context_rel', 'c2', $context->id
);
3981 if ($deleteparent) {
3982 delete_records('context_rel', 'c1', $context->id
);
3984 // insert all parents
3985 if ($parents = get_parent_contexts($context)) {
3986 $parents[] = $context->id
;
3987 foreach ($parents as $parent) {
3989 $rec ->c1
= $context->id
;
3990 $rec ->c2
= $parent;
3991 insert_record('context_rel', $rec);
3997 * rebuild context_rel table without deleting
3999 function build_context_rel() {
4002 $savedb = $db->debug
;
4004 // total number of records
4005 $total = count_records('context');
4006 // processed records
4008 print_progress($done, $total, 10, 0, 'Processing context relations');
4010 if ($contexts = get_records('context')) {
4011 foreach ($contexts as $context) {
4012 // no need to delete because it's all empty
4013 insert_context_rel($context, false, false);
4015 print_progress(++
$done, $total, 10, 0, 'Processing context relations');
4020 $db->debug
= $savedb;
4024 // gets the custom name of the role in course
4025 // TODO: proper documentation
4026 function role_get_name($role, $context) {
4028 if ($r = get_record('role_names','roleid', $role->id
,'contextid', $context->id
)) {
4029 return format_string($r->text
);
4031 return format_string($role->name
);