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 INNER JOIN
890 {$CFG->prefix}role_capabilities rc on ra.roleid = rc.roleid INNER JOIN
891 {$CFG->prefix}context c1 on ra.contextid = c1.id INNER JOIN
892 {$CFG->prefix}context c2 on rc.contextid = c2.id INNER JOIN
893 {$CFG->prefix}context_rel cr on cr.c1 = c2.id AND cr.c2 = c1.id
895 ra.userid=$userid AND
897 rc.contextid != $siteinstance->id
900 rc.capability, c1.id, c2.id, c1.contextlevel * 100 + c2.contextlevel
902 SUM(rc.permission) != 0
906 if (!$rs = get_recordset_sql($SQL1)) {
907 error("Query failed in load_user_capability.");
910 if ($rs && $rs->RecordCount() > 0) {
911 while ($caprec = rs_fetch_next_record($rs)) {
912 $array = (array)$caprec;
913 $temprecord = new object;
915 foreach ($array as $key=>$val) {
916 if ($key == 'aggrlevel') {
917 $temprecord->contextlevel
= $val;
919 $temprecord->{$key} = $val;
922 $capabilities[] = $temprecord;
928 // this is take out because we have no way of making sure c1 is indeed related to c2 (parent)
929 // if we do not group by sum, it is possible to have multiple records of rc.capability, c1.id, c2.id, tuple having
930 // different values, we can maually sum it when we go through the list
934 $SQL2 = "SELECT rc.capability, c1.id as id1, c2.id as id2, (c1.contextlevel * 100 + c2.contextlevel) AS aggrlevel,
937 {$CFG->prefix}role_assignments ra,
938 {$CFG->prefix}role_capabilities rc,
939 {$CFG->prefix}context c1,
940 {$CFG->prefix}context c2
942 ra.contextid=c1.id AND
943 ra.roleid=rc.roleid AND
944 ra.userid=$userid AND
945 rc.contextid=c2.id AND
947 rc.contextid != $siteinstance->id
951 rc.capability, (c1.contextlevel * 100 + c2.contextlevel), c1.id, c2.id, rc.permission
957 if (!$rs = get_recordset_sql($SQL2)) {
958 error("Query failed in load_user_capability.");
961 if ($rs && $rs->RecordCount() > 0) {
962 while ($caprec = rs_fetch_next_record($rs)) {
963 $array = (array)$caprec;
964 $temprecord = new object;
966 foreach ($array as $key=>$val) {
967 if ($key == 'aggrlevel') {
968 $temprecord->contextlevel = $val;
970 $temprecord->{$key} = $val;
973 // for overrides, we have to make sure that context2 is a child of context1
974 // otherwise the combination makes no sense
975 //if (is_parent_context($temprecord->id1, $temprecord->id2)) {
976 $capabilities[] = $temprecord;
977 //} // only write if relevant
982 // this step sorts capabilities according to the contextlevel
983 // it is very important because the order matters when we
984 // go through each capabilities later. (i.e. higher level contextlevel
985 // will override lower contextlevel settings
986 usort($capabilities, 'roles_context_cmp');
988 /* so up to this point we should have somethign like this
989 * $capabilities[1] ->contextlevel = 1000
990 ->module = 0 // changed from SITEID in 1.8 (??)
991 ->capability = do_anything
992 ->id = 1 (id is the context id)
995 * $capabilities[2] ->contextlevel = 1000
996 ->module = 0 // changed from SITEID in 1.8 (??)
997 ->capability = post_messages
1001 * $capabilittes[3] ->contextlevel = 3000
1003 ->capability = view_course_activities
1007 * $capabilittes[4] ->contextlevel = 3000
1009 ->capability = view_course_activities
1011 ->sum = 0 (this is another course)
1013 * $capabilities[5] ->contextlevel = 3050
1015 ->capability = view_course_activities
1016 ->id = 25 (override in course 25)
1019 * now we proceed to write the session array, going from top to bottom
1020 * at anypoint, we need to go up and check parent to look for prohibit
1022 // print_object($capabilities);
1024 /* This is where we write to the actualy capabilities array
1025 * what we need to do from here on is
1026 * going down the array from lowest level to highest level
1027 * 1) recursively check for prohibit,
1028 * if any, we write prohibit
1029 * else, we write the value
1030 * 2) at an override level, we overwrite current level
1031 * if it's not set to prohibit already, and if different
1032 * ........ that should be it ........
1035 // This is the flag used for detecting the current context level. Since we are going through
1036 // the array in ascending order of context level. For normal capabilities, there should only
1037 // be 1 value per (capability, contextlevel, context), because they are already summed. But,
1038 // for overrides, since we are processing them separate, we need to sum the relevcant entries.
1039 // We set this flag when we hit a new level.
1040 // If the flag is already set, we keep adding (summing), otherwise, we just override previous
1041 // settings (from lower level contexts)
1042 $capflags = array(); // (contextid, contextlevel, capability)
1043 $usercap = array(); // for other user's capabilities
1044 foreach ($capabilities as $capability) {
1046 if (!$context = get_context_instance_by_id($capability->id2
)) {
1047 continue; // incorrect stale context
1050 if (!empty($otheruserid)) { // we are pulling out other user's capabilities, do not write to session
1052 if (capability_prohibits($capability->capability
, $context, $capability->sum
, $usercap)) {
1053 $usercap[$capability->id2
][$capability->capability
] = CAP_PROHIBIT
;
1056 if (isset($usercap[$capability->id2
][$capability->capability
])) { // use isset because it can be sum 0
1057 if (!empty($capflags[$capability->id2
][$capability->contextlevel
][$capability->capability
])) {
1058 $usercap[$capability->id2
][$capability->capability
] +
= $capability->sum
;
1059 } else { // else we override, and update flag
1060 $usercap[$capability->id2
][$capability->capability
] = $capability->sum
;
1061 $capflags[$capability->id2
][$capability->contextlevel
][$capability->capability
] = true;
1064 $usercap[$capability->id2
][$capability->capability
] = $capability->sum
;
1065 $capflags[$capability->id2
][$capability->contextlevel
][$capability->capability
] = true;
1070 if (capability_prohibits($capability->capability
, $context, $capability->sum
)) { // if any parent or parent's parent is set to prohibit
1071 $USER->capabilities
[$capability->id2
][$capability->capability
] = CAP_PROHIBIT
;
1075 // if no parental prohibit set
1076 // just write to session, i am not sure this is correct yet
1077 // since 3050 shows up after 3000, and 3070 shows up after 3050,
1078 // it should be ok just to overwrite like this, provided that there's no
1079 // parental prohibits
1080 // we need to write even if it's 0, because it could be an inherit override
1081 if (isset($USER->capabilities
[$capability->id2
][$capability->capability
])) {
1082 if (!empty($capflags[$capability->id2
][$capability->contextlevel
][$capability->capability
])) {
1083 $USER->capabilities
[$capability->id2
][$capability->capability
] +
= $capability->sum
;
1084 } else { // else we override, and update flag
1085 $USER->capabilities
[$capability->id2
][$capability->capability
] = $capability->sum
;
1086 $capflags[$capability->id2
][$capability->contextlevel
][$capability->capability
] = true;
1089 $USER->capabilities
[$capability->id2
][$capability->capability
] = $capability->sum
;
1090 $capflags[$capability->id2
][$capability->contextlevel
][$capability->capability
] = true;
1095 // now we don't care about the huge array anymore, we can dispose it.
1096 unset($capabilities);
1099 if (!empty($otheruserid)) {
1100 return $usercap; // return the array
1106 * A convenience function to completely load all the capabilities
1107 * for the current user. This is what gets called from login, for example.
1109 function load_all_capabilities() {
1112 //caching - helps user switching in cron
1113 static $defcaps = false;
1115 unset($USER->mycourses
); // Reset a cache used by get_my_courses
1117 if (isguestuser()) {
1118 load_guest_role(); // All non-guest users get this by default
1120 } else if (isloggedin()) {
1121 if ($defcaps === false) {
1122 $defcaps = load_defaultuser_role(true);
1125 load_user_capability();
1127 // when in "course login as" - load only course caqpabilitites (it may not always work as expected)
1128 if (!empty($USER->realuser
) and $USER->loginascontext
->contextlevel
!= CONTEXT_SYSTEM
) {
1129 $children = get_child_contexts($USER->loginascontext
);
1130 $children[] = $USER->loginascontext
->id
;
1131 foreach ($USER->capabilities
as $conid => $caps) {
1132 if (!in_array($conid, $children)) {
1133 unset($USER->capabilities
[$conid]);
1138 // handle role switching in courses
1139 if (!empty($USER->switchrole
)) {
1140 foreach ($USER->switchrole
as $contextid => $roleid) {
1141 $context = get_context_instance_by_id($contextid);
1143 // first prune context and any child contexts
1144 $children = get_child_contexts($context);
1145 foreach ($children as $childid) {
1146 unset($USER->capabilities
[$childid]);
1148 unset($USER->capabilities
[$contextid]);
1150 // now merge all switched role caps in context and bellow
1151 $swithccaps = get_role_context_caps($roleid, $context);
1152 $USER->capabilities
= merge_role_caps($USER->capabilities
, $swithccaps);
1156 if (isset($USER->capabilities
)) {
1157 $USER->capabilities
= merge_role_caps($USER->capabilities
, $defcaps);
1159 $USER->capabilities
= $defcaps;
1163 load_notloggedin_role();
1169 * Check all the login enrolment information for the given user object
1170 * by querying the enrolment plugins
1172 function check_enrolment_plugins(&$user) {
1175 static $inprogress; // To prevent this function being called more than once in an invocation
1177 if (!empty($inprogress[$user->id
])) {
1181 $inprogress[$user->id
] = true; // Set the flag
1183 require_once($CFG->dirroot
.'/enrol/enrol.class.php');
1185 if (!($plugins = explode(',', $CFG->enrol_plugins_enabled
))) {
1186 $plugins = array($CFG->enrol
);
1189 foreach ($plugins as $plugin) {
1190 $enrol = enrolment_factory
::factory($plugin);
1191 if (method_exists($enrol, 'setup_enrolments')) { /// Plugin supports Roles (Moodle 1.7 and later)
1192 $enrol->setup_enrolments($user);
1193 } else { /// Run legacy enrolment methods
1194 if (method_exists($enrol, 'get_student_courses')) {
1195 $enrol->get_student_courses($user);
1197 if (method_exists($enrol, 'get_teacher_courses')) {
1198 $enrol->get_teacher_courses($user);
1201 /// deal with $user->students and $user->teachers stuff
1202 unset($user->student
);
1203 unset($user->teacher
);
1208 unset($inprogress[$user->id
]); // Unset the flag
1213 * This is a recursive function that checks whether the capability in this
1214 * context, or the parent capabilities are set to prohibit.
1216 * At this point, we can probably just use the values already set in the
1217 * session variable, since we are going down the level. Any prohit set in
1218 * parents would already reflect in the session.
1220 * @param $capability - capability name
1221 * @param $sum - sum of all capabilities values
1222 * @param $context - the context object
1223 * @param $array - when loading another user caps, their caps are not stored in session but an array
1225 function capability_prohibits($capability, $context, $sum='', $array='') {
1228 // caching, mainly to save unnecessary sqls
1229 static $prohibits; //[capability][contextid]
1230 if (isset($prohibits[$capability][$context->id
])) {
1231 return $prohibits[$capability][$context->id
];
1234 if (empty($context->id
)) {
1235 $prohibits[$capability][$context->id
] = false;
1239 if (empty($capability)) {
1240 $prohibits[$capability][$context->id
] = false;
1244 if ($sum < (CAP_PROHIBIT
/2)) {
1245 // If this capability is set to prohibit.
1246 $prohibits[$capability][$context->id
] = true;
1250 if (!empty($array)) {
1251 if (isset($array[$context->id
][$capability])
1252 && $array[$context->id
][$capability] < (CAP_PROHIBIT
/2)) {
1253 $prohibits[$capability][$context->id
] = true;
1257 // Else if set in session.
1258 if (isset($USER->capabilities
[$context->id
][$capability])
1259 && $USER->capabilities
[$context->id
][$capability] < (CAP_PROHIBIT
/2)) {
1260 $prohibits[$capability][$context->id
] = true;
1264 switch ($context->contextlevel
) {
1266 case CONTEXT_SYSTEM
:
1267 // By now it's a definite an inherit.
1271 case CONTEXT_PERSONAL
:
1272 $parent = get_context_instance(CONTEXT_SYSTEM
);
1273 $prohibits[$capability][$context->id
] = capability_prohibits($capability, $parent);
1274 return $prohibits[$capability][$context->id
];
1278 $parent = get_context_instance(CONTEXT_SYSTEM
);
1279 $prohibits[$capability][$context->id
] = capability_prohibits($capability, $parent);
1280 return $prohibits[$capability][$context->id
];
1283 case CONTEXT_COURSECAT
:
1284 // Coursecat -> coursecat or site.
1285 if (!$coursecat = get_record('course_categories','id',$context->instanceid
)) {
1286 $prohibits[$capability][$context->id
] = false;
1289 if (!empty($coursecat->parent
)) {
1290 // return parent value if exist.
1291 $parent = get_context_instance(CONTEXT_COURSECAT
, $coursecat->parent
);
1293 // Return site value.
1294 $parent = get_context_instance(CONTEXT_SYSTEM
);
1296 $prohibits[$capability][$context->id
] = capability_prohibits($capability, $parent);
1297 return $prohibits[$capability][$context->id
];
1300 case CONTEXT_COURSE
:
1301 // 1 to 1 to course cat.
1302 // Find the course cat, and return its value.
1303 if (!$course = get_record('course','id',$context->instanceid
)) {
1304 $prohibits[$capability][$context->id
] = false;
1307 // Yu: Separating site and site course context
1308 if ($course->id
== SITEID
) {
1309 $parent = get_context_instance(CONTEXT_SYSTEM
);
1311 $parent = get_context_instance(CONTEXT_COURSECAT
, $course->category
);
1313 $prohibits[$capability][$context->id
] = capability_prohibits($capability, $parent);
1314 return $prohibits[$capability][$context->id
];
1318 // 1 to 1 to course.
1319 if (!$courseid = groups_get_course($context->instanceid
)) {
1320 $prohibits[$capability][$context->id
] = false;
1323 $parent = get_context_instance(CONTEXT_COURSE
, $courseid);
1324 $prohibits[$capability][$context->id
] = capability_prohibits($capability, $parent);
1325 return $prohibits[$capability][$context->id
];
1328 case CONTEXT_MODULE
:
1329 // 1 to 1 to course.
1330 if (!$cm = get_record('course_modules','id',$context->instanceid
)) {
1331 $prohibits[$capability][$context->id
] = false;
1334 $parent = get_context_instance(CONTEXT_COURSE
, $cm->course
);
1335 $prohibits[$capability][$context->id
] = capability_prohibits($capability, $parent);
1336 return $prohibits[$capability][$context->id
];
1340 // 1 to 1 to course.
1341 if (!$block = get_record('block_instance','id',$context->instanceid
)) {
1342 $prohibits[$capability][$context->id
] = false;
1345 if ($block->pagetype
== 'course-view') {
1346 $parent = get_context_instance(CONTEXT_COURSE
, $block->pageid
); // needs check
1348 $parent = get_context_instance(CONTEXT_SYSTEM
);
1350 $prohibits[$capability][$context->id
] = capability_prohibits($capability, $parent);
1351 return $prohibits[$capability][$context->id
];
1355 print_error('unknowncontext');
1362 * A print form function. This should either grab all the capabilities from
1363 * files or a central table for that particular module instance, then present
1364 * them in check boxes. Only relevant capabilities should print for known
1366 * @param $mod - module id of the mod
1368 function print_capabilities($modid=0) {
1371 $capabilities = array();
1374 // We are in a module specific context.
1376 // Get the mod's name.
1377 // Call the function that grabs the file and parse.
1378 $cm = get_record('course_modules', 'id', $modid);
1379 $module = get_record('modules', 'id', $cm->module
);
1382 // Print all capabilities.
1383 foreach ($capabilities as $capability) {
1384 // Prints the check box component.
1391 * Installs the roles system.
1392 * This function runs on a fresh install as well as on an upgrade from the old
1393 * hard-coded student/teacher/admin etc. roles to the new roles system.
1395 function moodle_install_roles() {
1399 /// Create a system wide context for assignemnt.
1400 $systemcontext = $context = get_context_instance(CONTEXT_SYSTEM
);
1403 /// Create default/legacy roles and capabilities.
1404 /// (1 legacy capability per legacy role at system level).
1406 $adminrole = create_role(addslashes(get_string('administrator')), 'admin',
1407 addslashes(get_string('administratordescription')), 'moodle/legacy:admin');
1408 $coursecreatorrole = create_role(addslashes(get_string('coursecreators')), 'coursecreator',
1409 addslashes(get_string('coursecreatorsdescription')), 'moodle/legacy:coursecreator');
1410 $editteacherrole = create_role(addslashes(get_string('defaultcourseteacher')), 'editingteacher',
1411 addslashes(get_string('defaultcourseteacherdescription')), 'moodle/legacy:editingteacher');
1412 $noneditteacherrole = create_role(addslashes(get_string('noneditingteacher')), 'teacher',
1413 addslashes(get_string('noneditingteacherdescription')), 'moodle/legacy:teacher');
1414 $studentrole = create_role(addslashes(get_string('defaultcoursestudent')), 'student',
1415 addslashes(get_string('defaultcoursestudentdescription')), 'moodle/legacy:student');
1416 $guestrole = create_role(addslashes(get_string('guest')), 'guest',
1417 addslashes(get_string('guestdescription')), 'moodle/legacy:guest');
1418 $userrole = create_role(addslashes(get_string('authenticateduser')), 'user',
1419 addslashes(get_string('authenticateduserdescription')), 'moodle/legacy:user');
1421 /// Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles
1423 if (!assign_capability('moodle/site:doanything', CAP_ALLOW
, $adminrole, $systemcontext->id
)) {
1424 error('Could not assign moodle/site:doanything to the admin role');
1426 if (!update_capabilities()) {
1427 error('Had trouble upgrading the core capabilities for the Roles System');
1430 /// Look inside user_admin, user_creator, user_teachers, user_students and
1431 /// assign above new roles. If a user has both teacher and student role,
1432 /// only teacher role is assigned. The assignment should be system level.
1434 $dbtables = $db->MetaTables('TABLES');
1436 /// Set up the progress bar
1438 $usertables = array('user_admins', 'user_coursecreators', 'user_teachers', 'user_students');
1440 $totalcount = $progresscount = 0;
1441 foreach ($usertables as $usertable) {
1442 if (in_array($CFG->prefix
.$usertable, $dbtables)) {
1443 $totalcount +
= count_records($usertable);
1447 print_progress(0, $totalcount, 5, 1, 'Processing role assignments');
1449 /// Upgrade the admins.
1450 /// Sort using id ASC, first one is primary admin.
1452 if (in_array($CFG->prefix
.'user_admins', $dbtables)) {
1453 if ($rs = get_recordset_sql('SELECT * from '.$CFG->prefix
.'user_admins ORDER BY ID ASC')) {
1454 while ($admin = rs_fetch_next_record($rs)) {
1455 role_assign($adminrole, $admin->userid
, 0, $systemcontext->id
);
1457 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1462 // This is a fresh install.
1466 /// Upgrade course creators.
1467 if (in_array($CFG->prefix
.'user_coursecreators', $dbtables)) {
1468 if ($rs = get_recordset('user_coursecreators')) {
1469 while ($coursecreator = rs_fetch_next_record($rs)) {
1470 role_assign($coursecreatorrole, $coursecreator->userid
, 0, $systemcontext->id
);
1472 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1479 /// Upgrade editting teachers and non-editting teachers.
1480 if (in_array($CFG->prefix
.'user_teachers', $dbtables)) {
1481 if ($rs = get_recordset('user_teachers')) {
1482 while ($teacher = rs_fetch_next_record($rs)) {
1484 // removed code here to ignore site level assignments
1485 // since the contexts are separated now
1487 // populate the user_lastaccess table
1488 $access = new object();
1489 $access->timeaccess
= $teacher->timeaccess
;
1490 $access->userid
= $teacher->userid
;
1491 $access->courseid
= $teacher->course
;
1492 insert_record('user_lastaccess', $access);
1494 // assign the default student role
1495 $coursecontext = get_context_instance(CONTEXT_COURSE
, $teacher->course
); // needs cache
1497 if ($teacher->authority
== 0) {
1503 if ($teacher->editall
) { // editting teacher
1504 role_assign($editteacherrole, $teacher->userid
, 0, $coursecontext->id
, 0, 0, $hiddenteacher);
1506 role_assign($noneditteacherrole, $teacher->userid
, 0, $coursecontext->id
, 0, 0, $hiddenteacher);
1509 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1516 /// Upgrade students.
1517 if (in_array($CFG->prefix
.'user_students', $dbtables)) {
1518 if ($rs = get_recordset('user_students')) {
1519 while ($student = rs_fetch_next_record($rs)) {
1521 // populate the user_lastaccess table
1522 $access = new object;
1523 $access->timeaccess
= $student->timeaccess
;
1524 $access->userid
= $student->userid
;
1525 $access->courseid
= $student->course
;
1526 insert_record('user_lastaccess', $access);
1528 // assign the default student role
1529 $coursecontext = get_context_instance(CONTEXT_COURSE
, $student->course
);
1530 role_assign($studentrole, $student->userid
, 0, $coursecontext->id
);
1532 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1539 /// Upgrade guest (only 1 entry).
1540 if ($guestuser = get_record('user', 'username', 'guest')) {
1541 role_assign($guestrole, $guestuser->id
, 0, $systemcontext->id
);
1543 print_progress($totalcount, $totalcount, 5, 1, 'Processing role assignments');
1546 /// Insert the correct records for legacy roles
1547 allow_assign($adminrole, $adminrole);
1548 allow_assign($adminrole, $coursecreatorrole);
1549 allow_assign($adminrole, $noneditteacherrole);
1550 allow_assign($adminrole, $editteacherrole);
1551 allow_assign($adminrole, $studentrole);
1552 allow_assign($adminrole, $guestrole);
1554 allow_assign($coursecreatorrole, $noneditteacherrole);
1555 allow_assign($coursecreatorrole, $editteacherrole);
1556 allow_assign($coursecreatorrole, $studentrole);
1557 allow_assign($coursecreatorrole, $guestrole);
1559 allow_assign($editteacherrole, $noneditteacherrole);
1560 allow_assign($editteacherrole, $studentrole);
1561 allow_assign($editteacherrole, $guestrole);
1563 /// Set up default permissions for overrides
1564 allow_override($adminrole, $adminrole);
1565 allow_override($adminrole, $coursecreatorrole);
1566 allow_override($adminrole, $noneditteacherrole);
1567 allow_override($adminrole, $editteacherrole);
1568 allow_override($adminrole, $studentrole);
1569 allow_override($adminrole, $guestrole);
1570 allow_override($adminrole, $userrole);
1573 /// Delete the old user tables when we are done
1575 drop_table(new XMLDBTable('user_students'));
1576 drop_table(new XMLDBTable('user_teachers'));
1577 drop_table(new XMLDBTable('user_coursecreators'));
1578 drop_table(new XMLDBTable('user_admins'));
1583 * Returns array of all legacy roles.
1585 function get_legacy_roles() {
1587 'admin' => 'moodle/legacy:admin',
1588 'coursecreator' => 'moodle/legacy:coursecreator',
1589 'editingteacher' => 'moodle/legacy:editingteacher',
1590 'teacher' => 'moodle/legacy:teacher',
1591 'student' => 'moodle/legacy:student',
1592 'guest' => 'moodle/legacy:guest',
1593 'user' => 'moodle/legacy:user'
1597 function get_legacy_type($roleid) {
1598 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
1599 $legacyroles = get_legacy_roles();
1602 foreach($legacyroles as $ltype=>$lcap) {
1603 $localoverride = get_local_override($roleid, $sitecontext->id
, $lcap);
1604 if (!empty($localoverride->permission
) and $localoverride->permission
== CAP_ALLOW
) {
1605 //choose first selected legacy capability - reset the rest
1606 if (empty($result)) {
1609 unassign_capability($lcap, $roleid);
1618 * Assign the defaults found in this capabality definition to roles that have
1619 * the corresponding legacy capabilities assigned to them.
1620 * @param $legacyperms - an array in the format (example):
1621 * 'guest' => CAP_PREVENT,
1622 * 'student' => CAP_ALLOW,
1623 * 'teacher' => CAP_ALLOW,
1624 * 'editingteacher' => CAP_ALLOW,
1625 * 'coursecreator' => CAP_ALLOW,
1626 * 'admin' => CAP_ALLOW
1627 * @return boolean - success or failure.
1629 function assign_legacy_capabilities($capability, $legacyperms) {
1631 $legacyroles = get_legacy_roles();
1633 foreach ($legacyperms as $type => $perm) {
1635 $systemcontext = get_context_instance(CONTEXT_SYSTEM
);
1637 if (!array_key_exists($type, $legacyroles)) {
1638 error('Incorrect legacy role definition for type: '.$type);
1641 if ($roles = get_roles_with_capability($legacyroles[$type], CAP_ALLOW
)) {
1642 foreach ($roles as $role) {
1643 // Assign a site level capability.
1644 if (!assign_capability($capability, $perm, $role->id
, $systemcontext->id
)) {
1655 * Checks to see if a capability is a legacy capability.
1656 * @param $capabilityname
1659 function islegacy($capabilityname) {
1660 if (strpos($capabilityname, 'moodle/legacy') === 0) {
1669 /**********************************
1670 * Context Manipulation functions *
1671 **********************************/
1674 * Create a new context record for use by all roles-related stuff
1676 * @param $instanceid
1678 * @return object newly created context (or existing one with a debug warning)
1680 function create_context($contextlevel, $instanceid) {
1681 if (!$context = get_record('context','contextlevel',$contextlevel,'instanceid',$instanceid)) {
1682 if (!validate_context($contextlevel, $instanceid)) {
1683 debugging('Error: Invalid context creation request for level "'.s($contextlevel).'", instance "'.s($instanceid).'".');
1686 if ($contextlevel == CONTEXT_SYSTEM
) {
1687 return create_system_context();
1690 $context = new object();
1691 $context->contextlevel
= $contextlevel;
1692 $context->instanceid
= $instanceid;
1693 if ($id = insert_record('context',$context)) {
1694 // we need to populate context_rel for every new context inserted
1695 $c = get_record('context','id',$id);
1696 insert_context_rel ($c);
1699 debugging('Error: could not insert new context level "'.s($contextlevel).'", instance "'.s($instanceid).'".');
1703 debugging('Warning: Context id "'.s($context->id
).'" not created, because it already exists.');
1709 * This hacky function is needed because we can not change system context instanceid using normal upgrade routine.
1711 function create_system_context() {
1712 if ($context = get_record('context', 'contextlevel', CONTEXT_SYSTEM
, 'instanceid', SITEID
)) {
1713 // we are going to change instanceid of system context to 0 now
1714 $context->instanceid
= 0;
1715 update_record('context', $context);
1716 //context rel not affected
1720 $context = new object();
1721 $context->contextlevel
= CONTEXT_SYSTEM
;
1722 $context->instanceid
= 0;
1723 if ($context->id
= insert_record('context',$context)) {
1724 // we need not to populate context_rel for system context
1727 debugging('Can not create system context');
1733 * Create a new context record for use by all roles-related stuff
1735 * @param $instanceid
1737 * @return true if properly deleted
1739 function delete_context($contextlevel, $instanceid) {
1740 if ($context = get_context_instance($contextlevel, $instanceid)) {
1741 delete_records('context_rel', 'c2', $context->id
); // might not be a parent
1742 return delete_records('context', 'id', $context->id
) &&
1743 delete_records('role_assignments', 'contextid', $context->id
) &&
1744 delete_records('role_capabilities', 'contextid', $context->id
) &&
1745 delete_records('context_rel', 'c1', $context->id
);
1751 * Validate that object with instanceid really exists in given context level.
1753 * return if instanceid object exists
1755 function validate_context($contextlevel, $instanceid) {
1756 switch ($contextlevel) {
1758 case CONTEXT_SYSTEM
:
1759 return ($instanceid == 0);
1761 case CONTEXT_PERSONAL
:
1762 return (boolean
)count_records('user', 'id', $instanceid);
1765 return (boolean
)count_records('user', 'id', $instanceid);
1767 case CONTEXT_COURSECAT
:
1768 if ($instanceid == 0) {
1769 return true; // site course category
1771 return (boolean
)count_records('course_categories', 'id', $instanceid);
1773 case CONTEXT_COURSE
:
1774 return (boolean
)count_records('course', 'id', $instanceid);
1777 return groups_group_exists($instanceid);
1779 case CONTEXT_MODULE
:
1780 return (boolean
)count_records('course_modules', 'id', $instanceid);
1783 return (boolean
)count_records('block_instance', 'id', $instanceid);
1791 * Get the context instance as an object. This function will create the
1792 * context instance if it does not exist yet.
1793 * @param integer $level The context level, for example CONTEXT_COURSE, or CONTEXT_MODULE.
1794 * @param integer $instance The instance id. For $level = CONTEXT_COURSE, this would be $course->id,
1795 * for $level = CONTEXT_MODULE, this would be $cm->id. And so on.
1796 * @return object The context object.
1798 function get_context_instance($contextlevel=NULL, $instance=0) {
1800 global $context_cache, $context_cache_id, $CONTEXT;
1801 static $allowed_contexts = array(CONTEXT_SYSTEM
, CONTEXT_PERSONAL
, CONTEXT_USER
, CONTEXT_COURSECAT
, CONTEXT_COURSE
, CONTEXT_GROUP
, CONTEXT_MODULE
, CONTEXT_BLOCK
);
1803 // Yu: Separating site and site course context - removed CONTEXT_COURSE override when SITEID
1806 if ($contextlevel == 'clearcache') {
1808 $context_cache = array();
1809 $context_cache_id = array();
1814 /// If no level is supplied then return the current global context if there is one
1815 if (empty($contextlevel)) {
1816 if (empty($CONTEXT)) {
1817 //fatal error, code must be fixed
1818 error("Error: get_context_instance() called without a context");
1824 /// Backwards compatibility with obsoleted (CONTEXT_SYSTEM, SITEID)
1825 if ($contextlevel == CONTEXT_SYSTEM
) {
1829 /// check allowed context levels
1830 if (!in_array($contextlevel, $allowed_contexts)) {
1831 // fatal error, code must be fixed - probably typo or switched parameters
1832 error('Error: get_context_instance() called with incorrect context level "'.s($contextlevel).'"');
1836 if (isset($context_cache[$contextlevel][$instance])) { // Already cached
1837 return $context_cache[$contextlevel][$instance];
1840 /// Get it from the database, or create it
1841 if (!$context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance)) {
1842 create_context($contextlevel, $instance);
1843 $context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance);
1846 /// Only add to cache if context isn't empty.
1847 if (!empty($context)) {
1848 $context_cache[$contextlevel][$instance] = $context; // Cache it for later
1849 $context_cache_id[$context->id
] = $context; // Cache it for later
1857 * Get a context instance as an object, from a given context id.
1858 * @param $id a context id.
1859 * @return object The context object.
1861 function get_context_instance_by_id($id) {
1863 global $context_cache, $context_cache_id;
1865 if (isset($context_cache_id[$id])) { // Already cached
1866 return $context_cache_id[$id];
1869 if ($context = get_record('context', 'id', $id)) { // Update the cache and return
1870 $context_cache[$context->contextlevel
][$context->instanceid
] = $context;
1871 $context_cache_id[$context->id
] = $context;
1880 * Get the local override (if any) for a given capability in a role in a context
1883 * @param $capability
1885 function get_local_override($roleid, $contextid, $capability) {
1886 return get_record('role_capabilities', 'roleid', $roleid, 'capability', $capability, 'contextid', $contextid);
1891 /************************************
1892 * DB TABLE RELATED FUNCTIONS *
1893 ************************************/
1896 * function that creates a role
1897 * @param name - role name
1898 * @param shortname - role short name
1899 * @param description - role description
1900 * @param legacy - optional legacy capability
1901 * @return id or false
1903 function create_role($name, $shortname, $description, $legacy='') {
1905 // check for duplicate role name
1907 if ($role = get_record('role','name', $name)) {
1908 error('there is already a role with this name!');
1911 if ($role = get_record('role','shortname', $shortname)) {
1912 error('there is already a role with this shortname!');
1915 $role = new object();
1916 $role->name
= $name;
1917 $role->shortname
= $shortname;
1918 $role->description
= $description;
1920 //find free sortorder number
1921 $role->sortorder
= count_records('role');
1922 while (get_record('role','sortorder', $role->sortorder
)) {
1923 $role->sortorder +
= 1;
1926 if (!$context = get_context_instance(CONTEXT_SYSTEM
)) {
1930 if ($id = insert_record('role', $role)) {
1932 assign_capability($legacy, CAP_ALLOW
, $id, $context->id
);
1935 /// By default, users with role:manage at site level
1936 /// should be able to assign users to this new role, and override this new role's capabilities
1938 // find all admin roles
1939 if ($adminroles = get_roles_with_capability('moodle/role:manage', CAP_ALLOW
, $context)) {
1940 // foreach admin role
1941 foreach ($adminroles as $arole) {
1942 // write allow_assign and allow_overrid
1943 allow_assign($arole->id
, $id);
1944 allow_override($arole->id
, $id);
1956 * function that deletes a role and cleanups up after it
1957 * @param roleid - id of role to delete
1960 function delete_role($roleid) {
1963 // mdl 10149, check if this is the last active admin role
1964 // if we make the admin role not deletable then this part can go
1966 $systemcontext = get_context_instance(CONTEXT_SYSTEM
);
1968 if ($role = get_record('role', 'id', $roleid)) {
1969 if (record_exists('role_capabilities', 'contextid', $systemcontext->id
, 'roleid', $roleid, 'capability', 'moodle/site:doanything')) {
1970 // deleting an admin role
1972 if ($adminroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW
, $systemcontext)) {
1973 foreach ($adminroles as $adminrole) {
1974 if ($adminrole->id
!= $roleid) {
1975 // some other admin role
1976 if (record_exists('role_assignments', 'roleid', $adminrole->id
, 'contextid', $systemcontext->id
)) {
1977 // found another admin role with at least 1 user assigned
1984 if ($status !== true) {
1985 error ('You can not delete this role because there is no other admin roles with users assigned');
1990 // first unssign all users
1991 if (!role_unassign($roleid)) {
1992 debugging("Error while unassigning all users from role with ID $roleid!");
1996 // cleanup all references to this role, ignore errors
1998 delete_records('role_capabilities', 'roleid', $roleid);
1999 delete_records('role_allow_assign', 'roleid', $roleid);
2000 delete_records('role_allow_assign', 'allowassign', $roleid);
2001 delete_records('role_allow_override', 'roleid', $roleid);
2002 delete_records('role_allow_override', 'allowoverride', $roleid);
2003 delete_records('role_names', 'roleid', $roleid);
2006 // finally delete the role itself
2007 if ($success and !delete_records('role', 'id', $roleid)) {
2008 debugging("Could not delete role record with ID $roleid!");
2016 * Function to write context specific overrides, or default capabilities.
2017 * @param module - string name
2018 * @param capability - string name
2019 * @param contextid - context id
2020 * @param roleid - role id
2021 * @param permission - int 1,-1 or -1000
2022 * should not be writing if permission is 0
2024 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite=false) {
2028 if (empty($permission) ||
$permission == CAP_INHERIT
) { // if permission is not set
2029 unassign_capability($capability, $roleid, $contextid);
2033 $existing = get_record('role_capabilities', 'contextid', $contextid, 'roleid', $roleid, 'capability', $capability);
2035 if ($existing and !$overwrite) { // We want to keep whatever is there already
2040 $cap->contextid
= $contextid;
2041 $cap->roleid
= $roleid;
2042 $cap->capability
= $capability;
2043 $cap->permission
= $permission;
2044 $cap->timemodified
= time();
2045 $cap->modifierid
= empty($USER->id
) ?
0 : $USER->id
;
2048 $cap->id
= $existing->id
;
2049 return update_record('role_capabilities', $cap);
2051 return insert_record('role_capabilities', $cap);
2057 * Unassign a capability from a role.
2058 * @param $roleid - the role id
2059 * @param $capability - the name of the capability
2060 * @return boolean - success or failure
2062 function unassign_capability($capability, $roleid, $contextid=NULL) {
2064 if (isset($contextid)) {
2065 $status = delete_records('role_capabilities', 'capability', $capability,
2066 'roleid', $roleid, 'contextid', $contextid);
2068 $status = delete_records('role_capabilities', 'capability', $capability,
2076 * Get the roles that have a given capability assigned to it. This function
2077 * does not resolve the actual permission of the capability. It just checks
2078 * for assignment only.
2079 * @param $capability - capability name (string)
2080 * @param $permission - optional, the permission defined for this capability
2081 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT
2082 * @return array or role objects
2084 function get_roles_with_capability($capability, $permission=NULL, $context='') {
2089 if ($contexts = get_parent_contexts($context)) {
2090 $listofcontexts = '('.implode(',', $contexts).')';
2092 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
2093 $listofcontexts = '('.$sitecontext->id
.')'; // must be site
2095 $contextstr = "AND (rc.contextid = '$context->id' OR rc.contextid IN $listofcontexts)";
2100 $selectroles = "SELECT r.*
2101 FROM {$CFG->prefix}role r,
2102 {$CFG->prefix}role_capabilities rc
2103 WHERE rc.capability = '$capability'
2104 AND rc.roleid = r.id $contextstr";
2106 if (isset($permission)) {
2107 $selectroles .= " AND rc.permission = '$permission'";
2109 return get_records_sql($selectroles);
2114 * This function makes a role-assignment (a role for a user or group in a particular context)
2115 * @param $roleid - the role of the id
2116 * @param $userid - userid
2117 * @param $groupid - group id
2118 * @param $contextid - id of the context
2119 * @param $timestart - time this assignment becomes effective
2120 * @param $timeend - time this assignemnt ceases to be effective
2122 * @return id - new id of the assigment
2124 function role_assign($roleid, $userid, $groupid, $contextid, $timestart=0, $timeend=0, $hidden=0, $enrol='manual',$timemodified='') {
2127 debugging("Assign roleid $roleid userid $userid contextid $contextid", DEBUG_DEVELOPER
);
2129 /// Do some data validation
2131 if (empty($roleid)) {
2132 debugging('Role ID not provided');
2136 if (empty($userid) && empty($groupid)) {
2137 debugging('Either userid or groupid must be provided');
2141 if ($userid && !record_exists('user', 'id', $userid)) {
2142 debugging('User ID '.intval($userid).' does not exist!');
2146 if ($groupid && !groups_group_exists($groupid)) {
2147 debugging('Group ID '.intval($groupid).' does not exist!');
2151 if (!$context = get_context_instance_by_id($contextid)) {
2152 debugging('Context ID '.intval($contextid).' does not exist!');
2156 if (($timestart and $timeend) and ($timestart > $timeend)) {
2157 debugging('The end time can not be earlier than the start time');
2161 if (!$timemodified) {
2162 $timemodified = time();
2165 /// Check for existing entry
2167 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id
, 'userid', $userid);
2169 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id
, 'groupid', $groupid);
2173 $newra = new object;
2175 if (empty($ra)) { // Create a new entry
2176 $newra->roleid
= $roleid;
2177 $newra->contextid
= $context->id
;
2178 $newra->userid
= $userid;
2179 $newra->hidden
= $hidden;
2180 $newra->enrol
= $enrol;
2181 /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
2182 /// by repeating queries with the same exact parameters in a 100 secs time window
2183 $newra->timestart
= round($timestart, -2);
2184 $newra->timeend
= $timeend;
2185 $newra->timemodified
= $timemodified;
2186 $newra->modifierid
= empty($USER->id
) ?
0 : $USER->id
;
2188 $success = insert_record('role_assignments', $newra);
2190 } else { // We already have one, just update it
2192 $newra->id
= $ra->id
;
2193 $newra->hidden
= $hidden;
2194 $newra->enrol
= $enrol;
2195 /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
2196 /// by repeating queries with the same exact parameters in a 100 secs time window
2197 $newra->timestart
= round($timestart, -2);
2198 $newra->timeend
= $timeend;
2199 $newra->timemodified
= $timemodified;
2200 $newra->modifierid
= empty($USER->id
) ?
0 : $USER->id
;
2202 $success = update_record('role_assignments', $newra);
2205 if ($success) { /// Role was assigned, so do some other things
2207 /// If the user is the current user, then reload the capabilities too.
2208 if (!empty($USER->id
) && $USER->id
== $userid) {
2209 load_all_capabilities();
2212 /// Ask all the modules if anything needs to be done for this user
2213 if ($mods = get_list_of_plugins('mod')) {
2214 foreach ($mods as $mod) {
2215 include_once($CFG->dirroot
.'/mod/'.$mod.'/lib.php');
2216 $functionname = $mod.'_role_assign';
2217 if (function_exists($functionname)) {
2218 $functionname($userid, $context, $roleid);
2223 /// Make sure they have an entry in user_lastaccess for courses they can access
2224 // role_add_lastaccess_entries($userid, $context);
2227 /// now handle metacourse role assignments if in course context
2228 if ($success and $context->contextlevel
== CONTEXT_COURSE
) {
2229 if ($parents = get_records('course_meta', 'child_course', $context->instanceid
)) {
2230 foreach ($parents as $parent) {
2231 sync_metacourse($parent->parent_course
);
2241 * Deletes one or more role assignments. You must specify at least one parameter.
2246 * @param $enrol unassign only if enrolment type matches, NULL means anything
2247 * @return boolean - success or failure
2249 function role_unassign($roleid=0, $userid=0, $groupid=0, $contextid=0, $enrol=NULL) {
2255 $args = array('roleid', 'userid', 'groupid', 'contextid');
2257 foreach ($args as $arg) {
2259 $select[] = $arg.' = '.$
$arg;
2262 if (!empty($enrol)) {
2263 $select[] = "enrol='$enrol'";
2267 if ($ras = get_records_select('role_assignments', implode(' AND ', $select))) {
2268 $mods = get_list_of_plugins('mod');
2269 foreach($ras as $ra) {
2270 /// infinite loop protection when deleting recursively
2271 if (!$ra = get_record('role_assignments', 'id', $ra->id
)) {
2274 $success = delete_records('role_assignments', 'id', $ra->id
) and $success;
2276 /// If the user is the current user, then reload the capabilities too.
2277 if (!empty($USER->id
) && $USER->id
== $ra->userid
) {
2278 load_all_capabilities();
2280 $context = get_record('context', 'id', $ra->contextid
);
2282 /// Ask all the modules if anything needs to be done for this user
2283 foreach ($mods as $mod) {
2284 include_once($CFG->dirroot
.'/mod/'.$mod.'/lib.php');
2285 $functionname = $mod.'_role_unassign';
2286 if (function_exists($functionname)) {
2287 $functionname($ra->userid
, $context); // watch out, $context might be NULL if something goes wrong
2291 /// now handle metacourse role unassigment and removing from goups if in course context
2292 if (!empty($context) and $context->contextlevel
== CONTEXT_COURSE
) {
2293 //remove from groups when user has no role
2294 $roles = get_user_roles($context, $ra->userid
, true);
2295 if (empty($roles)) {
2296 if ($groups = get_groups($context->instanceid
, $ra->userid
)) {
2297 foreach ($groups as $group) {
2298 delete_records('groups_members', 'groupid', $group->id
, 'userid', $ra->userid
);
2302 //unassign roles in metacourses if needed
2303 if ($parents = get_records('course_meta', 'child_course', $context->instanceid
)) {
2304 foreach ($parents as $parent) {
2305 sync_metacourse($parent->parent_course
);
2317 * A convenience function to take care of the common case where you
2318 * just want to enrol someone using the default role into a course
2320 * @param object $course
2321 * @param object $user
2322 * @param string $enrol - the plugin used to do this enrolment
2324 function enrol_into_course($course, $user, $enrol) {
2326 $timestart = time();
2327 // remove time part from the timestamp and keep only the date part
2328 $timestart = make_timestamp(date('Y', $timestart), date('m', $timestart), date('d', $timestart), 0, 0, 0);
2329 if ($course->enrolperiod
) {
2330 $timeend = $timestart +
$course->enrolperiod
;
2335 if ($role = get_default_course_role($course)) {
2337 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
2339 if (!role_assign($role->id
, $user->id
, 0, $context->id
, $timestart, $timeend, 0, $enrol)) {
2343 email_welcome_message_to_user($course, $user);
2345 add_to_log($course->id
, 'course', 'enrol', 'view.php?id='.$course->id
, $user->id
);
2354 * Add last access times to user_lastaccess as required
2357 * @return boolean - success or failure
2359 function role_add_lastaccess_entries($userid, $context) {
2363 if (empty($context->contextlevel
)) {
2367 $lastaccess = new object; // Reusable object below
2368 $lastaccess->userid
= $userid;
2369 $lastaccess->timeaccess
= 0;
2371 switch ($context->contextlevel
) {
2373 case CONTEXT_SYSTEM
: // For the whole site
2374 if ($courses = get_record('course')) {
2375 foreach ($courses as $course) {
2376 $lastaccess->courseid
= $course->id
;
2377 role_set_lastaccess($lastaccess);
2382 case CONTEXT_CATEGORY
: // For a whole category
2383 if ($courses = get_record('course', 'category', $context->instanceid
)) {
2384 foreach ($courses as $course) {
2385 $lastaccess->courseid
= $course->id
;
2386 role_set_lastaccess($lastaccess);
2389 if ($categories = get_record('course_categories', 'parent', $context->instanceid
)) {
2390 foreach ($categories as $category) {
2391 $subcontext = get_context_instance(CONTEXT_CATEGORY
, $category->id
);
2392 role_add_lastaccess_entries($userid, $subcontext);
2398 case CONTEXT_COURSE
: // For a whole course
2399 if ($course = get_record('course', 'id', $context->instanceid
)) {
2400 $lastaccess->courseid
= $course->id
;
2401 role_set_lastaccess($lastaccess);
2408 * Delete last access times from user_lastaccess as required
2411 * @return boolean - success or failure
2413 function role_remove_lastaccess_entries($userid, $context) {
2421 * Loads the capability definitions for the component (from file). If no
2422 * capabilities are defined for the component, we simply return an empty array.
2423 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2424 * @return array of capabilities
2426 function load_capability_def($component) {
2429 if ($component == 'moodle') {
2430 $defpath = $CFG->libdir
.'/db/access.php';
2431 $varprefix = 'moodle';
2433 $compparts = explode('/', $component);
2435 if ($compparts[0] == 'block') {
2436 // Blocks are an exception. Blocks directory is 'blocks', and not
2437 // 'block'. So we need to jump through hoops.
2438 $defpath = $CFG->dirroot
.'/'.$compparts[0].
2439 's/'.$compparts[1].'/db/access.php';
2440 $varprefix = $compparts[0].'_'.$compparts[1];
2442 } else if ($compparts[0] == 'format') {
2443 // Similar to the above, course formats are 'format' while they
2444 // are stored in 'course/format'.
2445 $defpath = $CFG->dirroot
.'/course/'.$component.'/db/access.php';
2446 $varprefix = $compparts[0].'_'.$compparts[1];
2448 } else if ($compparts[0] == 'gradeimport') {
2449 $defpath = $CFG->dirroot
.'/grade/import/'.$compparts[1].'/db/access.php';
2450 $varprefix = $compparts[0].'_'.$compparts[1];
2452 } else if ($compparts[0] == 'gradeexport') {
2453 $defpath = $CFG->dirroot
.'/grade/export/'.$compparts[1].'/db/access.php';
2454 $varprefix = $compparts[0].'_'.$compparts[1];
2456 } else if ($compparts[0] == 'gradereport') {
2457 $defpath = $CFG->dirroot
.'/grade/report/'.$compparts[1].'/db/access.php';
2458 $varprefix = $compparts[0].'_'.$compparts[1];
2461 $defpath = $CFG->dirroot
.'/'.$component.'/db/access.php';
2462 $varprefix = str_replace('/', '_', $component);
2465 $capabilities = array();
2467 if (file_exists($defpath)) {
2469 $capabilities = $
{$varprefix.'_capabilities'};
2471 return $capabilities;
2476 * Gets the capabilities that have been cached in the database for this
2478 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2479 * @return array of capabilities
2481 function get_cached_capabilities($component='moodle') {
2482 if ($component == 'moodle') {
2483 $storedcaps = get_records_select('capabilities',
2484 "name LIKE 'moodle/%:%'");
2486 $storedcaps = get_records_select('capabilities',
2487 "name LIKE '$component:%'");
2493 * Returns default capabilities for given legacy role type.
2495 * @param string legacy role name
2498 function get_default_capabilities($legacyrole) {
2499 if (!$allcaps = get_records('capabilities')) {
2500 error('Error: no capabilitites defined!');
2503 $defaults = array();
2504 $components = array();
2505 foreach ($allcaps as $cap) {
2506 if (!in_array($cap->component
, $components)) {
2507 $components[] = $cap->component
;
2508 $alldefs = array_merge($alldefs, load_capability_def($cap->component
));
2511 foreach($alldefs as $name=>$def) {
2512 if (isset($def['legacy'][$legacyrole])) {
2513 $defaults[$name] = $def['legacy'][$legacyrole];
2518 $defaults['moodle/legacy:'.$legacyrole] = CAP_ALLOW
;
2519 if ($legacyrole == 'admin') {
2520 $defaults['moodle/site:doanything'] = CAP_ALLOW
;
2526 * Reset role capabilitites to default according to selected legacy capability.
2527 * If several legacy caps selected, use the first from get_default_capabilities.
2528 * If no legacy selected, removes all capabilities.
2530 * @param int @roleid
2532 function reset_role_capabilities($roleid) {
2533 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
2534 $legacyroles = get_legacy_roles();
2536 $defaultcaps = array();
2537 foreach($legacyroles as $ltype=>$lcap) {
2538 $localoverride = get_local_override($roleid, $sitecontext->id
, $lcap);
2539 if (!empty($localoverride->permission
) and $localoverride->permission
== CAP_ALLOW
) {
2540 //choose first selected legacy capability
2541 $defaultcaps = get_default_capabilities($ltype);
2546 delete_records('role_capabilities', 'roleid', $roleid);
2547 if (!empty($defaultcaps)) {
2548 foreach($defaultcaps as $cap=>$permission) {
2549 assign_capability($cap, $permission, $roleid, $sitecontext->id
);
2555 * Updates the capabilities table with the component capability definitions.
2556 * If no parameters are given, the function updates the core moodle
2559 * Note that the absence of the db/access.php capabilities definition file
2560 * will cause any stored capabilities for the component to be removed from
2563 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2566 function update_capabilities($component='moodle') {
2568 $storedcaps = array();
2570 $filecaps = load_capability_def($component);
2571 $cachedcaps = get_cached_capabilities($component);
2573 foreach ($cachedcaps as $cachedcap) {
2574 array_push($storedcaps, $cachedcap->name
);
2575 // update risk bitmasks and context levels in existing capabilities if needed
2576 if (array_key_exists($cachedcap->name
, $filecaps)) {
2577 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name
])) {
2578 $filecaps[$cachedcap->name
]['riskbitmask'] = 0; // no risk if not specified
2580 if ($cachedcap->riskbitmask
!= $filecaps[$cachedcap->name
]['riskbitmask']) {
2581 $updatecap = new object();
2582 $updatecap->id
= $cachedcap->id
;
2583 $updatecap->riskbitmask
= $filecaps[$cachedcap->name
]['riskbitmask'];
2584 if (!update_record('capabilities', $updatecap)) {
2589 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name
])) {
2590 $filecaps[$cachedcap->name
]['contextlevel'] = 0; // no context level defined
2592 if ($cachedcap->contextlevel
!= $filecaps[$cachedcap->name
]['contextlevel']) {
2593 $updatecap = new object();
2594 $updatecap->id
= $cachedcap->id
;
2595 $updatecap->contextlevel
= $filecaps[$cachedcap->name
]['contextlevel'];
2596 if (!update_record('capabilities', $updatecap)) {
2604 // Are there new capabilities in the file definition?
2607 foreach ($filecaps as $filecap => $def) {
2609 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2610 if (!array_key_exists('riskbitmask', $def)) {
2611 $def['riskbitmask'] = 0; // no risk if not specified
2613 $newcaps[$filecap] = $def;
2616 // Add new capabilities to the stored definition.
2617 foreach ($newcaps as $capname => $capdef) {
2618 $capability = new object;
2619 $capability->name
= $capname;
2620 $capability->captype
= $capdef['captype'];
2621 $capability->contextlevel
= $capdef['contextlevel'];
2622 $capability->component
= $component;
2623 $capability->riskbitmask
= $capdef['riskbitmask'];
2625 if (!insert_record('capabilities', $capability, false, 'id')) {
2630 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $storedcaps)){
2631 if ($rolecapabilities = get_records('role_capabilities', 'capability', $capdef['clonepermissionsfrom'])){
2632 foreach ($rolecapabilities as $rolecapability){
2633 //assign_capability will update rather than insert if capability exists
2634 if (!assign_capability($capname, $rolecapability->permission
,
2635 $rolecapability->roleid
, $rolecapability->contextid
, true)){
2636 notify('Could not clone capabilities for '.$capname);
2640 // Do we need to assign the new capabilities to roles that have the
2641 // legacy capabilities moodle/legacy:* as well?
2642 // we ignore legacy key if we have cloned permissions
2643 } else if (isset($capdef['legacy']) && is_array($capdef['legacy']) &&
2644 !assign_legacy_capabilities($capname, $capdef['legacy'])) {
2645 notify('Could not assign legacy capabilities for '.$capname);
2648 // Are there any capabilities that have been removed from the file
2649 // definition that we need to delete from the stored capabilities and
2650 // role assignments?
2651 capabilities_cleanup($component, $filecaps);
2658 * Deletes cached capabilities that are no longer needed by the component.
2659 * Also unassigns these capabilities from any roles that have them.
2660 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2661 * @param $newcapdef - array of the new capability definitions that will be
2662 * compared with the cached capabilities
2663 * @return int - number of deprecated capabilities that have been removed
2665 function capabilities_cleanup($component, $newcapdef=NULL) {
2669 if ($cachedcaps = get_cached_capabilities($component)) {
2670 foreach ($cachedcaps as $cachedcap) {
2671 if (empty($newcapdef) ||
2672 array_key_exists($cachedcap->name
, $newcapdef) === false) {
2674 // Remove from capabilities cache.
2675 if (!delete_records('capabilities', 'name', $cachedcap->name
)) {
2676 error('Could not delete deprecated capability '.$cachedcap->name
);
2680 // Delete from roles.
2681 if($roles = get_roles_with_capability($cachedcap->name
)) {
2682 foreach($roles as $role) {
2683 if (!unassign_capability($cachedcap->name
, $role->id
)) {
2684 error('Could not unassign deprecated capability '.
2685 $cachedcap->name
.' from role '.$role->name
);
2692 return $removedcount;
2703 * prints human readable context identifier.
2705 function print_context_name($context, $withprefix = true, $short = false) {
2708 switch ($context->contextlevel
) {
2710 case CONTEXT_SYSTEM
: // by now it's a definite an inherit
2711 $name = get_string('coresystem');
2714 case CONTEXT_PERSONAL
:
2715 $name = get_string('personal');
2719 if ($user = get_record('user', 'id', $context->instanceid
)) {
2721 $name = get_string('user').': ';
2723 $name .= fullname($user);
2727 case CONTEXT_COURSECAT
: // Coursecat -> coursecat or site
2728 if ($category = get_record('course_categories', 'id', $context->instanceid
)) {
2730 $name = get_string('category').': ';
2732 $name .=format_string($category->name
);
2736 case CONTEXT_COURSE
: // 1 to 1 to course cat
2737 if ($course = get_record('course', 'id', $context->instanceid
)) {
2739 if ($context->instanceid
== SITEID
) {
2740 $name = get_string('site').': ';
2742 $name = get_string('course').': ';
2746 $name .=format_string($course->shortname
);
2748 $name .=format_string($course->fullname
);
2754 case CONTEXT_GROUP
: // 1 to 1 to course
2755 if ($name = groups_get_group_name($context->instanceid
)) {
2757 $name = get_string('group').': '. $name;
2762 case CONTEXT_MODULE
: // 1 to 1 to course
2763 if ($cm = get_record('course_modules','id',$context->instanceid
)) {
2764 if ($module = get_record('modules','id',$cm->module
)) {
2765 if ($mod = get_record($module->name
, 'id', $cm->instance
)) {
2767 $name = get_string('activitymodule').': ';
2769 $name .= $mod->name
;
2775 case CONTEXT_BLOCK
: // 1 to 1 to course
2776 if ($blockinstance = get_record('block_instance','id',$context->instanceid
)) {
2777 if ($block = get_record('block','id',$blockinstance->blockid
)) {
2779 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
2780 require_once("$CFG->dirroot/blocks/$block->name/block_$block->name.php");
2781 $blockname = "block_$block->name";
2782 if ($blockobject = new $blockname()) {
2784 $name = get_string('block').': ';
2786 $name .= $blockobject->title
;
2793 error ('This is an unknown context (' . $context->contextlevel
. ') in print_context_name!');
2802 * Extracts the relevant capabilities given a contextid.
2803 * All case based, example an instance of forum context.
2804 * Will fetch all forum related capabilities, while course contexts
2805 * Will fetch all capabilities
2806 * @param object context
2810 * `name` varchar(150) NOT NULL,
2811 * `captype` varchar(50) NOT NULL,
2812 * `contextlevel` int(10) NOT NULL,
2813 * `component` varchar(100) NOT NULL,
2815 function fetch_context_capabilities($context) {
2819 $sort = 'ORDER BY contextlevel,component,id'; // To group them sensibly for display
2821 switch ($context->contextlevel
) {
2823 case CONTEXT_SYSTEM
: // all
2824 $SQL = "select * from {$CFG->prefix}capabilities";
2827 case CONTEXT_PERSONAL
:
2828 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_PERSONAL
;
2833 FROM {$CFG->prefix}capabilities
2834 WHERE contextlevel = ".CONTEXT_USER
;
2837 case CONTEXT_COURSECAT
: // all
2838 $SQL = "select * from {$CFG->prefix}capabilities";
2841 case CONTEXT_COURSE
: // all
2842 $SQL = "select * from {$CFG->prefix}capabilities";
2845 case CONTEXT_GROUP
: // group caps
2848 case CONTEXT_MODULE
: // mod caps
2849 $cm = get_record('course_modules', 'id', $context->instanceid
);
2850 $module = get_record('modules', 'id', $cm->module
);
2852 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_MODULE
."
2853 and component = 'mod/$module->name'";
2856 case CONTEXT_BLOCK
: // block caps
2857 $cb = get_record('block_instance', 'id', $context->instanceid
);
2858 $block = get_record('block', 'id', $cb->blockid
);
2860 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_BLOCK
."
2861 and component = 'block/$block->name'";
2868 if (!$records = get_records_sql($SQL.' '.$sort)) {
2872 /// the rest of code is a bit hacky, think twice before modifying it :-(
2874 // special sorting of core system capabiltites and enrollments
2875 if (in_array($context->contextlevel
, array(CONTEXT_SYSTEM
, CONTEXT_COURSECAT
, CONTEXT_COURSE
))) {
2877 foreach ($records as $key=>$record) {
2878 if (preg_match('|^moodle/|', $record->name
) and $record->contextlevel
== CONTEXT_SYSTEM
) {
2879 $first[$key] = $record;
2880 unset($records[$key]);
2881 } else if (count($first)){
2885 if (count($first)) {
2886 $records = $first +
$records; // merge the two arrays keeping the keys
2889 $contextindependentcaps = fetch_context_independent_capabilities();
2890 $records = array_merge($contextindependentcaps, $records);
2899 * Gets the context-independent capabilities that should be overrridable in
2901 * @return array of capability records from the capabilities table.
2903 function fetch_context_independent_capabilities() {
2905 //only CONTEXT_SYSTEM capabilities here or it will break the hack in fetch_context_capabilities()
2906 $contextindependentcaps = array(
2907 'moodle/site:accessallgroups'
2912 foreach ($contextindependentcaps as $capname) {
2913 $record = get_record('capabilities', 'name', $capname);
2914 array_push($records, $record);
2921 * This function pulls out all the resolved capabilities (overrides and
2922 * defaults) of a role used in capability overrides in contexts at a given
2924 * @param obj $context
2925 * @param int $roleid
2926 * @param bool self - if set to true, resolve till this level, else stop at immediate parent level
2929 function role_context_capabilities($roleid, $context, $cap='') {
2932 $contexts = get_parent_contexts($context);
2933 $contexts[] = $context->id
;
2934 $contexts = '('.implode(',', $contexts).')';
2937 $search = " AND rc.capability = '$cap' ";
2943 FROM {$CFG->prefix}role_capabilities rc,
2944 {$CFG->prefix}context c
2945 WHERE rc.contextid in $contexts
2946 AND rc.roleid = $roleid
2947 AND rc.contextid = c.id $search
2948 ORDER BY c.contextlevel DESC,
2949 rc.capability DESC";
2951 $capabilities = array();
2953 if ($records = get_records_sql($SQL)) {
2954 // We are traversing via reverse order.
2955 foreach ($records as $record) {
2956 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2957 if (!isset($capabilities[$record->capability
]) ||
$record->permission
<-500) {
2958 $capabilities[$record->capability
] = $record->permission
;
2962 return $capabilities;
2966 * Recursive function which, given a context, find all parent context ids,
2967 * and return the array in reverse order, i.e. parent first, then grand
2969 * @param object $context
2972 function get_parent_contexts($context) {
2974 static $pcontexts; // cache
2975 if (isset($pcontexts[$context->id
])) {
2976 return ($pcontexts[$context->id
]);
2979 switch ($context->contextlevel
) {
2981 case CONTEXT_SYSTEM
: // no parent
2985 case CONTEXT_PERSONAL
:
2986 if (!$parent = get_context_instance(CONTEXT_SYSTEM
)) {
2989 $res = array($parent->id
);
2990 $pcontexts[$context->id
] = $res;
2996 if (!$parent = get_context_instance(CONTEXT_SYSTEM
)) {
2999 $res = array($parent->id
);
3000 $pcontexts[$context->id
] = $res;
3005 case CONTEXT_COURSECAT
: // Coursecat -> coursecat or site
3006 if (!$coursecat = get_record('course_categories','id',$context->instanceid
)) {
3009 if (!empty($coursecat->parent
)) { // return parent value if exist
3010 $parent = get_context_instance(CONTEXT_COURSECAT
, $coursecat->parent
);
3011 $res = array_merge(array($parent->id
), get_parent_contexts($parent));
3012 $pcontexts[$context->id
] = $res;
3014 } else { // else return site value
3015 $parent = get_context_instance(CONTEXT_SYSTEM
);
3016 $res = array($parent->id
);
3017 $pcontexts[$context->id
] = $res;
3022 case CONTEXT_COURSE
: // 1 to 1 to course cat
3023 if (!$course = get_record('course','id',$context->instanceid
)) {
3026 if ($course->id
!= SITEID
) {
3027 $parent = get_context_instance(CONTEXT_COURSECAT
, $course->category
);
3028 $res = array_merge(array($parent->id
), get_parent_contexts($parent));
3031 // Yu: Separating site and site course context
3032 $parent = get_context_instance(CONTEXT_SYSTEM
);
3033 $res = array($parent->id
);
3034 $pcontexts[$context->id
] = $res;
3039 case CONTEXT_GROUP
: // 1 to 1 to course
3040 if (! $group = groups_get_group($context->instanceid
)) {
3043 if ($parent = get_context_instance(CONTEXT_COURSE
, $group->courseid
)) {
3044 $res = array_merge(array($parent->id
), get_parent_contexts($parent));
3045 $pcontexts[$context->id
] = $res;
3052 case CONTEXT_MODULE
: // 1 to 1 to course
3053 if (!$cm = get_record('course_modules','id',$context->instanceid
)) {
3056 if ($parent = get_context_instance(CONTEXT_COURSE
, $cm->course
)) {
3057 $res = array_merge(array($parent->id
), get_parent_contexts($parent));
3058 $pcontexts[$context->id
] = $res;
3065 case CONTEXT_BLOCK
: // 1 to 1 to course
3066 if (!$block = get_record('block_instance','id',$context->instanceid
)) {
3069 // fix for MDL-9656, block parents are not necessarily courses
3070 if ($block->pagetype
== 'course-view') {
3071 $parent = get_context_instance(CONTEXT_COURSE
, $block->pageid
);
3073 $parent = get_context_instance(CONTEXT_SYSTEM
);
3077 $res = array_merge(array($parent->id
), get_parent_contexts($parent));
3078 $pcontexts[$context->id
] = $res;
3086 error('This is an unknown context (' . $context->contextlevel
. ') in get_parent_contexts!');
3093 * Recursive function which, given a context, find all its children context ids.
3094 * @param object $context.
3095 * @return array of children context ids.
3097 function get_child_contexts($context) {
3100 $children = array();
3102 switch ($context->contextlevel
) {
3109 case CONTEXT_MODULE
:
3119 case CONTEXT_COURSE
:
3120 // Find all block instances for the course.
3121 $page = new page_course
;
3122 $page->id
= $context->instanceid
;
3123 $page->type
= 'course-view';
3124 if ($blocks = blocks_get_by_page_pinned($page)) {
3125 foreach ($blocks['l'] as $leftblock) {
3126 if ($child = get_context_instance(CONTEXT_BLOCK
, $leftblock->id
)) {
3127 array_push($children, $child->id
);
3130 foreach ($blocks['r'] as $rightblock) {
3131 if ($child = get_context_instance(CONTEXT_BLOCK
, $rightblock->id
)) {
3132 array_push($children, $child->id
);
3136 // Find all module instances for the course.
3137 if ($modules = get_records('course_modules', 'course', $context->instanceid
)) {
3138 foreach ($modules as $module) {
3139 if ($child = get_context_instance(CONTEXT_MODULE
, $module->id
)) {
3140 array_push($children, $child->id
);
3144 // Find all group instances for the course.
3145 if ($groupids = groups_get_groups($context->instanceid
)) {
3146 foreach ($groupids as $groupid) {
3147 if ($child = get_context_instance(CONTEXT_GROUP
, $groupid)) {
3148 array_push($children, $child->id
);
3155 case CONTEXT_COURSECAT
:
3156 // We need to get the contexts for:
3157 // 1) The subcategories of the given category
3158 // 2) The courses in the given category and all its subcategories
3159 // 3) All the child contexts for these courses
3161 $categories = get_all_subcategories($context->instanceid
);
3163 // Add the contexts for all the subcategories.
3164 foreach ($categories as $catid) {
3165 if ($catci = get_context_instance(CONTEXT_COURSECAT
, $catid)) {
3166 array_push($children, $catci->id
);
3170 // Add the parent category as well so we can find the contexts
3172 array_unshift($categories, $context->instanceid
);
3174 foreach ($categories as $catid) {
3175 // Find all courses for the category.
3176 if ($courses = get_records('course', 'category', $catid)) {
3177 foreach ($courses as $course) {
3178 if ($courseci = get_context_instance(CONTEXT_COURSE
, $course->id
)) {
3179 array_push($children, $courseci->id
);
3180 $children = array_merge($children, get_child_contexts($courseci));
3193 case CONTEXT_PERSONAL
:
3198 case CONTEXT_SYSTEM
:
3199 // Just get all the contexts except for CONTEXT_SYSTEM level.
3200 $sql = 'SELECT c.id '.
3201 'FROM '.$CFG->prefix
.'context AS c '.
3202 'WHERE contextlevel != '.CONTEXT_SYSTEM
;
3204 $contexts = get_records_sql($sql);
3205 foreach ($contexts as $cid) {
3206 array_push($children, $cid->id
);
3212 error('This is an unknown context (' . $context->contextlevel
. ') in get_child_contexts!');
3219 * Gets a string for sql calls, searching for stuff in this context or above
3220 * @param object $context
3223 function get_related_contexts_string($context) {
3224 if ($parents = get_parent_contexts($context)) {
3225 return (' IN ('.$context->id
.','.implode(',', $parents).')');
3227 return (' ='.$context->id
);
3233 * This function gets the capability of a role in a given context.
3234 * It is needed when printing override forms.
3235 * @param int $contextid
3236 * @param string $capability
3237 * @param array $capabilities - array loaded using role_context_capabilities
3238 * @return int (allow, prevent, prohibit, inherit)
3240 function get_role_context_capability($contextid, $capability, $capabilities) {
3241 if (isset($capabilities[$contextid][$capability])) {
3242 return $capabilities[$contextid][$capability];
3251 * Returns the human-readable, translated version of the capability.
3252 * Basically a big switch statement.
3253 * @param $capabilityname - e.g. mod/choice:readresponses
3255 function get_capability_string($capabilityname) {
3257 // Typical capabilityname is mod/choice:readresponses
3259 $names = split('/', $capabilityname);
3260 $stringname = $names[1]; // choice:readresponses
3261 $components = split(':', $stringname);
3262 $componentname = $components[0]; // choice
3264 switch ($names[0]) {
3266 $string = get_string($stringname, $componentname);
3270 $string = get_string($stringname, 'block_'.$componentname);
3274 $string = get_string($stringname, 'role');
3278 $string = get_string($stringname, 'enrol_'.$componentname);
3282 $string = get_string($stringname, 'format_'.$componentname);
3286 $string = get_string($stringname);
3295 * This gets the mod/block/course/core etc strings.
3297 * @param $contextlevel
3299 function get_component_string($component, $contextlevel) {
3301 switch ($contextlevel) {
3303 case CONTEXT_SYSTEM
:
3304 if (preg_match('|^enrol/|', $component)) {
3305 $langname = str_replace('/', '_', $component);
3306 $string = get_string('enrolname', $langname);
3307 } else if (preg_match('|^block/|', $component)) {
3308 $langname = str_replace('/', '_', $component);
3309 $string = get_string('blockname', $langname);
3311 $string = get_string('coresystem');
3315 case CONTEXT_PERSONAL
:
3316 $string = get_string('personal');
3320 $string = get_string('users');
3323 case CONTEXT_COURSECAT
:
3324 $string = get_string('categories');
3327 case CONTEXT_COURSE
:
3328 $string = get_string('course');
3332 $string = get_string('group');
3335 case CONTEXT_MODULE
:
3336 $string = get_string('modulename', basename($component));
3340 $string = get_string('blockname', 'block_'.basename($component));
3344 error ('This is an unknown context $contextlevel (' . $contextlevel . ') in get_component_string!');
3352 * Gets the list of roles assigned to this context and up (parents)
3353 * @param object $context
3354 * @param view - set to true when roles are pulled for display only
3355 * this is so that we can filter roles with no visible
3356 * assignment, for example, you might want to "hide" all
3357 * course creators when browsing the course participants
3361 function get_roles_used_in_context($context, $view = false) {
3365 // filter for roles with all hidden assignments
3366 // no need to return when only pulling roles for reviewing
3367 // e.g. participants page.
3368 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))?
' AND ra.hidden = 0 ':'';
3369 $contextlist = get_related_contexts_string($context);
3371 $sql = "SELECT DISTINCT r.id,
3375 FROM {$CFG->prefix}role_assignments ra,
3376 {$CFG->prefix}role r
3377 WHERE r.id = ra.roleid
3378 AND ra.contextid $contextlist
3380 ORDER BY r.sortorder ASC";
3382 return get_records_sql($sql);
3385 /** this function is used to print roles column in user profile page.
3387 * @param int contextid
3390 function get_user_roles_in_context($userid, $contextid){
3394 $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';
3395 if ($roles = get_records_sql($SQL)) {
3396 foreach ($roles as $userrole) {
3397 $rolestring .= '<a href="'.$CFG->wwwroot
.'/user/index.php?contextid='.$userrole->contextid
.'&roleid='.$userrole->roleid
.'">'.$userrole->name
.'</a>, ';
3401 return rtrim($rolestring, ', ');
3406 * Checks if a user can override capabilities of a particular role in this context
3407 * @param object $context
3408 * @param int targetroleid - the id of the role you want to override
3411 function user_can_override($context, $targetroleid) {
3412 // first check if user has override capability
3413 // if not return false;
3414 if (!has_capability('moodle/role:override', $context)) {
3417 // pull out all active roles of this user from this context(or above)
3418 if ($userroles = get_user_roles($context)) {
3419 foreach ($userroles as $userrole) {
3420 // if any in the role_allow_override table, then it's ok
3421 if (get_record('role_allow_override', 'roleid', $userrole->roleid
, 'allowoverride', $targetroleid)) {
3432 * Checks if a user can assign users to a particular role in this context
3433 * @param object $context
3434 * @param int targetroleid - the id of the role you want to assign users to
3437 function user_can_assign($context, $targetroleid) {
3439 // first check if user has override capability
3440 // if not return false;
3441 if (!has_capability('moodle/role:assign', $context)) {
3444 // pull out all active roles of this user from this context(or above)
3445 if ($userroles = get_user_roles($context)) {
3446 foreach ($userroles as $userrole) {
3447 // if any in the role_allow_override table, then it's ok
3448 if (get_record('role_allow_assign', 'roleid', $userrole->roleid
, 'allowassign', $targetroleid)) {
3457 /** Returns all site roles in correct sort order.
3460 function get_all_roles() {
3461 return get_records('role', '', '', 'sortorder ASC');
3465 * gets all the user roles assigned in this context, or higher contexts
3466 * this is mainly used when checking if a user can assign a role, or overriding a role
3467 * i.e. we need to know what this user holds, in order to verify against allow_assign and
3468 * allow_override tables
3469 * @param object $context
3470 * @param int $userid
3471 * @param view - set to true when roles are pulled for display only
3472 * this is so that we can filter roles with no visible
3473 * assignment, for example, you might want to "hide" all
3474 * course creators when browsing the course participants
3478 function get_user_roles($context, $userid=0, $checkparentcontexts=true, $order='c.contextlevel DESC, r.sortorder ASC', $view=false) {
3480 global $USER, $CFG, $db;
3482 if (empty($userid)) {
3483 if (empty($USER->id
)) {
3486 $userid = $USER->id
;
3488 // set up hidden sql
3489 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))?
' AND ra.hidden = 0 ':'';
3491 if ($checkparentcontexts && ($parents = get_parent_contexts($context))) {
3492 $contexts = ' ra.contextid IN ('.implode(',' , $parents).','.$context->id
.')';
3494 $contexts = ' ra.contextid = \''.$context->id
.'\'';
3497 return get_records_sql('SELECT ra.*, r.name, r.shortname
3498 FROM '.$CFG->prefix
.'role_assignments ra,
3499 '.$CFG->prefix
.'role r,
3500 '.$CFG->prefix
.'context c
3501 WHERE ra.userid = '.$userid.
3502 ' AND ra.roleid = r.id
3503 AND ra.contextid = c.id
3504 AND '.$contexts . $hiddensql .
3505 ' ORDER BY '.$order);
3509 * Creates a record in the allow_override table
3510 * @param int sroleid - source roleid
3511 * @param int troleid - target roleid
3512 * @return int - id or false
3514 function allow_override($sroleid, $troleid) {
3515 $record = new object();
3516 $record->roleid
= $sroleid;
3517 $record->allowoverride
= $troleid;
3518 return insert_record('role_allow_override', $record);
3522 * Creates a record in the allow_assign table
3523 * @param int sroleid - source roleid
3524 * @param int troleid - target roleid
3525 * @return int - id or false
3527 function allow_assign($sroleid, $troleid) {
3528 $record = new object;
3529 $record->roleid
= $sroleid;
3530 $record->allowassign
= $troleid;
3531 return insert_record('role_allow_assign', $record);
3535 * Gets a list of roles that this user can assign in this context
3536 * @param object $context
3539 function get_assignable_roles ($context, $field="name") {
3543 if ($roles = get_all_roles()) {
3544 foreach ($roles as $role) {
3545 if (user_can_assign($context, $role->id
)) {
3546 $options[$role->id
] = strip_tags(format_string($role->{$field}, true));
3554 * Gets a list of roles that this user can override in this context
3555 * @param object $context
3558 function get_overridable_roles($context) {
3562 if ($roles = get_all_roles()) {
3563 foreach ($roles as $role) {
3564 if (user_can_override($context, $role->id
)) {
3565 $options[$role->id
] = strip_tags(format_string($role->name
, true));
3574 * Returns a role object that is the default role for new enrolments
3577 * @param object $course
3578 * @return object $role
3580 function get_default_course_role($course) {
3583 /// First let's take the default role the course may have
3584 if (!empty($course->defaultrole
)) {
3585 if ($role = get_record('role', 'id', $course->defaultrole
)) {
3590 /// Otherwise the site setting should tell us
3591 if ($CFG->defaultcourseroleid
) {
3592 if ($role = get_record('role', 'id', $CFG->defaultcourseroleid
)) {
3597 /// It's unlikely we'll get here, but just in case, try and find a student role
3598 if ($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW
)) {
3599 return array_shift($studentroles); /// Take the first one
3607 * who has this capability in this context
3608 * does not handling user level resolving!!!
3609 * (!)pleaes note if $fields is empty this function attempts to get u.*
3610 * which can get rather large.
3611 * i.e 1 person has 2 roles 1 allow, 1 prevent, this will not work properly
3612 * @param $context - object
3613 * @param $capability - string capability
3614 * @param $fields - fields to be pulled
3615 * @param $sort - the sort order
3616 * @param $limitfrom - number of records to skip (offset)
3617 * @param $limitnum - number of records to fetch
3618 * @param $groups - single group or array of groups - only return
3619 * users who are in one of these group(s).
3620 * @param $exceptions - list of users to exclude
3621 * @param view - set to true when roles are pulled for display only
3622 * this is so that we can filter roles with no visible
3623 * assignment, for example, you might want to "hide" all
3624 * course creators when browsing the course participants
3626 * @param boolean $useviewallgroups if $groups is set the return users who
3627 * have capability both $capability and moodle/site:accessallgroups
3628 * in this context, as well as users who have $capability and who are
3631 function get_users_by_capability($context, $capability, $fields='', $sort='',
3632 $limitfrom='', $limitnum='', $groups='', $exceptions='', $doanything=true,
3633 $view=false, $useviewallgroups=false) {
3636 /// Sorting out groups
3638 if (is_array($groups)) {
3639 $grouptest = 'gm.groupid IN (' . implode(',', $groups) . ')';
3641 $grouptest = 'gm.groupid = ' . $groups;
3643 $grouptest = 'ra.userid IN (SELECT userid FROM ' .
3644 $CFG->prefix
. 'groups_members gm WHERE ' . $grouptest . ')';
3646 if ($useviewallgroups) {
3647 $viewallgroupsusers = get_users_by_capability($context,
3648 'moodle/site:accessallgroups', 'u.id, u,id', '', '', '', '', $exceptions);
3649 $groupsql = ' AND (' . $grouptest . ' OR ra.userid IN (' .
3650 implode(',', array_keys($viewallgroupsusers)) . '))';
3652 $groupsql = ' AND ' . $grouptest;
3658 /// Sorting out exceptions
3659 $exceptionsql = $exceptions ?
"AND u.id NOT IN ($exceptions)" : '';
3661 /// Set up default fields
3662 if (empty($fields)) {
3663 $fields = 'u.*, ul.timeaccess as lastaccess, ra.hidden';
3666 /// Set up default sort
3668 $sort = 'ul.timeaccess';
3671 $sortby = $sort ?
" ORDER BY $sort " : '';
3672 /// Set up hidden sql
3673 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))?
' AND ra.hidden = 0 ':'';
3675 /// If context is a course, then construct sql for ul
3676 if ($context->contextlevel
== CONTEXT_COURSE
) {
3677 $courseid = $context->instanceid
;
3678 $coursesql1 = "AND ul.courseid = $courseid";
3683 /// Sorting out roles with this capability set
3684 if ($possibleroles = get_roles_with_capability($capability, CAP_ALLOW
, $context)) {
3686 if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM
)) {
3687 return false; // Something is seriously wrong
3689 $doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW
, $sitecontext);
3692 $validroleids = array();
3693 foreach ($possibleroles as $possiblerole) {
3695 if (isset($doanythingroles[$possiblerole->id
])) { // We don't want these included
3699 if ($caps = role_context_capabilities($possiblerole->id
, $context, $capability)) { // resolved list
3700 if (isset($caps[$capability]) && $caps[$capability] > 0) { // resolved capability > 0
3701 $validroleids[] = $possiblerole->id
;
3705 if (empty($validroleids)) {
3708 $roleids = '('.implode(',', $validroleids).')';
3710 return false; // No need to continue, since no roles have this capability set
3713 /// Construct the main SQL
3714 $select = " SELECT $fields";
3715 $from = " FROM {$CFG->prefix}user u
3716 INNER JOIN {$CFG->prefix}role_assignments ra ON ra.userid = u.id
3717 INNER JOIN {$CFG->prefix}role r ON r.id = ra.roleid
3718 LEFT OUTER JOIN {$CFG->prefix}user_lastaccess ul ON (ul.userid = u.id $coursesql1)";
3719 $where = " WHERE ra.contextid ".get_related_contexts_string($context)."
3721 AND ra.roleid in $roleids
3726 return get_records_sql($select.$from.$where.$sortby, $limitfrom, $limitnum);
3730 * gets all the users assigned this role in this context or higher
3732 * @param int contextid
3733 * @param bool parent if true, get list of users assigned in higher context too
3736 function get_role_users($roleid, $context, $parent=false, $fields='', $sort='u.lastname ASC', $view=false, $limitfrom='', $limitnum='', $group='') {
3739 if (empty($fields)) {
3740 $fields = 'u.id, u.confirmed, u.username, u.firstname, u.lastname, '.
3741 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.city, '.
3742 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
3743 'u.emailstop, u.lang, u.timezone';
3746 // whether this assignment is hidden
3747 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))?
' AND r.hidden = 0 ':'';
3749 if ($contexts = get_parent_contexts($context)) {
3750 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
3752 $parentcontexts = '';
3755 $parentcontexts = '';
3759 $roleselect = "AND r.roleid = $roleid";
3765 $groupsql = "{$CFG->prefix}groups_members gm, ";
3766 $groupwheresql = " AND gm.userid = u.id AND gm.groupid = $group ";
3769 $groupwheresql = '';
3772 $SQL = "SELECT $fields
3773 FROM {$CFG->prefix}role_assignments r,
3775 {$CFG->prefix}user u
3776 WHERE (r.contextid = $context->id $parentcontexts)
3778 AND u.id = r.userid $roleselect
3781 "; // join now so that we can just use fullname() later
3783 return get_records_sql($SQL, $limitfrom, $limitnum);
3787 * Counts all the users assigned this role in this context or higher
3789 * @param int contextid
3790 * @param bool parent if true, get list of users assigned in higher context too
3793 function count_role_users($roleid, $context, $parent=false) {
3797 if ($contexts = get_parent_contexts($context)) {
3798 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
3800 $parentcontexts = '';
3803 $parentcontexts = '';
3806 $SQL = "SELECT count(*)
3807 FROM {$CFG->prefix}role_assignments r
3808 WHERE (r.contextid = $context->id $parentcontexts)
3809 AND r.roleid = $roleid";
3811 return count_records_sql($SQL);
3815 * This function gets the list of courses that this user has a particular capability in.
3816 * It is still not very efficient.
3817 * @param string $capability Capability in question
3818 * @param int $userid User ID or null for current user
3819 * @param bool $doanything True if 'doanything' is permitted (default)
3820 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
3821 * otherwise use a comma-separated list of the fields you require, not including id
3822 * @param string $orderby If set, use a comma-separated list of fields from course
3823 * table with sql modifiers (DESC) if needed
3824 * @return array Array of courses, may have zero entries. Or false if query failed.
3826 function get_user_capability_course($capability, $userid=NULL,$doanything=true,$fieldsexceptid='',$orderby='') {
3827 // Convert fields list and ordering
3829 if($fieldsexceptid) {
3830 $fields=explode(',',$fieldsexceptid);
3831 foreach($fields as $field) {
3832 $fieldlist.=',c.'.$field;
3836 $fields=explode(',',$orderby);
3838 foreach($fields as $field) {
3842 $orderby.='c.'.$field;
3844 $orderby='ORDER BY '.$orderby;
3847 // Obtain a list of everything relevant about all courses including context.
3848 // Note the result can be used directly as a context (we are going to), the course
3849 // fields are just appended.
3851 $rs=get_recordset_sql("
3853 x.*,c.id AS courseid$fieldlist
3855 {$CFG->prefix}course c
3856 INNER JOIN {$CFG->prefix}context x ON c.id=x.instanceid AND x.contextlevel=".CONTEXT_COURSE
."
3863 // Check capability for each course in turn
3865 while($coursecontext=rs_fetch_next_record($rs)) {
3866 if(has_capability($capability,$coursecontext,$userid,$doanything)) {
3867 // We've got the capability. Make the record look like a course record
3869 $coursecontext->id
=$coursecontext->courseid
;
3870 unset($coursecontext->courseid
);
3871 unset($coursecontext->contextlevel
);
3872 unset($coursecontext->instanceid
);
3873 $courses[]=$coursecontext;
3879 /** This function finds the roles assigned directly to this context only
3880 * i.e. no parents role
3881 * @param object $context
3884 function get_roles_on_exact_context($context) {
3888 return get_records_sql("SELECT r.*
3889 FROM {$CFG->prefix}role_assignments ra,
3890 {$CFG->prefix}role r
3891 WHERE ra.roleid = r.id
3892 AND ra.contextid = $context->id");
3897 * Switches the current user to another role for the current session and only
3898 * in the given context. If roleid is not valid (eg 0) or the current user
3899 * doesn't have permissions to be switching roles then the user's session
3900 * is compltely reset to have their normal roles.
3901 * @param integer $roleid
3902 * @param object $context
3905 function role_switch($roleid, $context) {
3908 /// If we can't use this or are already using it or no role was specified then bail completely and reset
3909 if (empty($roleid) ||
!has_capability('moodle/role:switchroles', $context)
3910 ||
!empty($USER->switchrole
[$context->id
]) ||
!confirm_sesskey()) {
3912 unset($USER->switchrole
[$context->id
]); // Delete old capabilities
3913 load_all_capabilities(); //reload user caps
3917 /// We're allowed to switch but can we switch to the specified role? Use assignable roles to check.
3918 if (!$roles = get_assignable_roles($context)) {
3922 /// unset default user role - it would not work anyway
3923 unset($roles[$CFG->defaultuserroleid
]);
3925 if (empty($roles[$roleid])) { /// We can't switch to this particular role
3929 /// We have a valid roleid that this user can switch to, so let's set up the session
3931 $USER->switchrole
[$context->id
] = $roleid; // So we know later what state we are in
3933 load_all_capabilities(); //reload switched role caps
3935 /// Add some permissions we are really going to always need, even if the role doesn't have them!
3937 $USER->capabilities
[$context->id
]['moodle/course:view'] = CAP_ALLOW
;
3944 // get any role that has an override on exact context
3945 function get_roles_with_override_on_context($context) {
3949 return get_records_sql("SELECT r.*
3950 FROM {$CFG->prefix}role_capabilities rc,
3951 {$CFG->prefix}role r
3952 WHERE rc.roleid = r.id
3953 AND rc.contextid = $context->id");
3956 // get all capabilities for this role on this context (overrids)
3957 function get_capabilities_from_role_on_context($role, $context) {
3961 return get_records_sql("SELECT *
3962 FROM {$CFG->prefix}role_capabilities
3963 WHERE contextid = $context->id
3964 AND roleid = $role->id");
3967 // find out which roles has assignment on this context
3968 function get_roles_with_assignment_on_context($context) {
3972 return get_records_sql("SELECT r.*
3973 FROM {$CFG->prefix}role_assignments ra,
3974 {$CFG->prefix}role r
3975 WHERE ra.roleid = r.id
3976 AND ra.contextid = $context->id");
3982 * Find all user assignemnt of users for this role, on this context
3984 function get_users_from_role_on_context($role, $context) {
3988 return get_records_sql("SELECT *
3989 FROM {$CFG->prefix}role_assignments
3990 WHERE contextid = $context->id
3991 AND roleid = $role->id");
3995 * Simple function returning a boolean true if roles exist, otherwise false
3997 function user_has_role_assignment($userid, $roleid, $contextid=0) {
4000 return record_exists('role_assignments', 'userid', $userid, 'roleid', $roleid, 'contextid', $contextid);
4002 return record_exists('role_assignments', 'userid', $userid, 'roleid', $roleid);
4007 * Inserts all parental context and self into context_rel table
4009 * @param object $context-context to be deleted
4010 * @param bool deletechild - deltes child contexts dependencies
4012 function insert_context_rel($context, $deletechild=true, $deleteparent=true) {
4014 // first check validity
4016 if (!validate_context($context->contextlevel
, $context->instanceid
)) {
4017 debugging('Error: Invalid context creation request for level "' .
4018 s($context->contextlevel
) . '", instance "' . s($context->instanceid
) . '".');
4022 // removes all parents
4024 delete_records('context_rel', 'c2', $context->id
);
4027 if ($deleteparent) {
4028 delete_records('context_rel', 'c1', $context->id
);
4030 // insert all parents
4031 if ($parents = get_parent_contexts($context)) {
4032 $parents[] = $context->id
;
4033 foreach ($parents as $parent) {
4035 $rec ->c1
= $context->id
;
4036 $rec ->c2
= $parent;
4037 insert_record('context_rel', $rec);
4043 * rebuild context_rel table without deleting
4045 function build_context_rel() {
4048 $savedb = $db->debug
;
4050 // total number of records
4051 $total = count_records('context');
4052 // processed records
4054 print_progress($done, $total, 10, 0, 'Processing context relations');
4056 if ($contexts = get_records('context')) {
4057 foreach ($contexts as $context) {
4058 // no need to delete because it's all empty
4059 insert_context_rel($context, false, false);
4061 print_progress(++
$done, $total, 10, 0, 'Processing context relations');
4066 $db->debug
= $savedb;
4070 // gets the custom name of the role in course
4071 // TODO: proper documentation
4072 function role_get_name($role, $context) {
4074 if ($r = get_record('role_names','roleid', $role->id
,'contextid', $context->id
)) {
4075 return format_string($r->text
);
4077 return format_string($role->name
);