Dan's fix from MDL-7263
[moodle.git] / lib / accesslib.php
blob06d309dd7761a0c450b6cc0c4d21641a4e4e2d5b
1 <?php
2 /**
3 * Capability session information format
4 * 2 x 2 array
5 * [context][capability]
6 * where context is the context id of the table 'context'
7 * and capability is a string defining the capability
8 * e.g.
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 // permission definitions
18 define('CAP_INHERIT', 0);
19 define('CAP_ALLOW', 1);
20 define('CAP_PREVENT', -1);
21 define('CAP_PROHIBIT', -1000);
23 // context definitions
24 define('CONTEXT_SYSTEM', 10);
25 define('CONTEXT_PERSONAL', 20);
26 define('CONTEXT_USER', 30);
27 define('CONTEXT_COURSECAT', 40);
28 define('CONTEXT_COURSE', 50);
29 define('CONTEXT_GROUP', 60);
30 define('CONTEXT_MODULE', 70);
31 define('CONTEXT_BLOCK', 80);
33 // capability risks - see http://docs.moodle.org/en/Hardening_new_Roles_system
34 define('RISK_MANAGETRUST', 0x0001);
35 define('RISK_CONFIG', 0x0002);
36 define('RISK_XSS', 0x0004);
37 define('RISK_PERSONAL', 0x0008);
38 define('RISK_SPAM', 0x0010);
41 $context_cache = array(); // Cache of all used context objects for performance (by level and instance)
42 $context_cache_id = array(); // Index to above cache by id
45 /**
46 * Loads the capabilities for the default guest role to the current user in a specific context
47 * @return object
49 function load_guest_role($context=NULL) {
50 global $USER;
52 static $guestrole;
54 if (!isloggedin()) {
55 return false;
58 if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM)) {
59 return false;
62 if (empty($context)) {
63 $context = $sitecontext;
66 if (empty($guestrole)) {
67 if (!$guestrole = get_guest_role()) {
68 return false;
72 if ($capabilities = get_records_select('role_capabilities',
73 "roleid = $guestrole->id AND contextid = $sitecontext->id")) {
74 foreach ($capabilities as $capability) {
75 $USER->capabilities[$context->id][$capability->capability] = $capability->permission;
79 return true;
82 /**
83 * Load default not logged in role capabilities when user is not logged in
84 * @return bool
86 function load_notloggedin_role() {
87 global $CFG, $USER;
89 if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM)) {
90 return false;
93 if (empty($CFG->notloggedinroleid)) { // Let's set the default to the guest role
94 if ($role = get_guest_role()) {
95 set_config('notloggedinroleid', $role->id);
96 } else {
97 return false;
101 if ($capabilities = get_records_select('role_capabilities',
102 "roleid = $CFG->notloggedinroleid AND contextid = $sitecontext->id")) {
103 foreach ($capabilities as $capability) {
104 $USER->capabilities[$sitecontext->id][$capability->capability] = $capability->permission;
108 return true;
112 * Load default not logged in role capabilities when user is not logged in
113 * @return bool
115 function load_defaultuser_role() {
116 global $CFG, $USER;
118 if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM)) {
119 return false;
122 if (empty($CFG->defaultuserroleid)) { // Let's set the default to the guest role
123 if ($role = get_guest_role()) {
124 set_config('defaultuserroleid', $role->id);
125 } else {
126 return false;
130 if ($capabilities = get_records_select('role_capabilities',
131 "roleid = $CFG->defaultuserroleid AND contextid = $sitecontext->id AND permission <> 0")) {
132 foreach ($capabilities as $capability) {
133 if (!isset($USER->capabilities[$sitecontext->id][$capability->capability])) { // Don't overwrite
134 $USER->capabilities[$sitecontext->id][$capability->capability] = $capability->permission;
138 // SPECIAL EXCEPTION: If the default user role is actually a guest role, then
139 // remove some capabilities so this user doesn't get confused with a REAL guest
140 if (isset($USER->capabilities[$sitecontext->id]['moodle/legacy:guest']) and $USER->username != 'guest') {
141 unset($USER->capabilities[$sitecontext->id]['moodle/legacy:guest']);
142 unset($USER->capabilities[$sitecontext->id]['moodle/course:view']); // No access to courses by default
146 return true;
151 * Get the default guest role
152 * @return object role
154 function get_guest_role() {
155 if ($roles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW)) {
156 return array_shift($roles); // Pick the first one
157 } else {
158 return false;
164 * This functions get all the course categories in proper order
165 * @param int $context
166 * @param int $type
167 * @return array of contextids
169 function get_parent_cats($context, $type) {
171 $parents = array();
173 switch ($type) {
174 case CONTEXT_COURSECAT:
175 if (!$cat = get_record('course_categories','id',$context->instanceid)) {
176 break;
179 while (!empty($cat->parent)) {
180 if (!$context = get_context_instance(CONTEXT_COURSECAT, $cat->parent)) {
181 break;
183 $parents[] = $context->id;
184 $cat = get_record('course_categories','id',$cat->parent);
186 break;
188 case CONTEXT_COURSE:
189 if (!$course = get_record('course', 'id', $context->instanceid)) {
190 break;
192 if (!$catinstance = get_context_instance(CONTEXT_COURSECAT, $course->category)) {
193 break;
196 $parents[] = $catinstance->id;
198 if (!$cat = get_record('course_categories','id',$course->category)) {
199 break;
202 while (!empty($cat->parent)) {
203 if (!$context = get_context_instance(CONTEXT_COURSECAT, $cat->parent)) {
204 break;
206 $parents[] = $context->id;
207 $cat = get_record('course_categories','id',$cat->parent);
209 break;
211 default:
212 break;
214 return array_reverse($parents);
220 * This function checks for a capability assertion being true. If it isn't
221 * then the page is terminated neatly with a standard error message
222 * @param string $capability - name of the capability
223 * @param object $context - a context object (record from context table)
224 * @param integer $userid - a userid number
225 * @param bool $doanything - if false, ignore do anything
226 * @param string $errorstring - an errorstring
227 * @param string $stringfile - which stringfile to get it from
229 function require_capability($capability, $context=NULL, $userid=NULL, $doanything=true,
230 $errormessage='nopermissions', $stringfile='') {
232 global $USER, $CFG;
234 /// If the current user is not logged in, then make sure they are (if needed)
236 if (empty($userid) and empty($USER->capabilities)) {
237 if ($context && ($context->contextlevel == CONTEXT_COURSE)) {
238 require_login($context->instanceid);
239 } else if ($context && ($context->contextlevel == CONTEXT_MODULE)) {
240 if ($cm = get_record('course_modules','id',$context->instanceid)) {
241 if (!$course = get_record('course', 'id', $cm->course)) {
242 error('Incorrect course.');
244 require_course_login($course, true, $cm);
246 } else {
247 require_login();
249 } else if ($context && ($context->contextlevel == CONTEXT_SYSTEM)) {
250 if (!empty($CFG->forcelogin)) {
251 require_login();
254 } else {
255 require_login();
259 /// OK, if they still don't have the capability then print a nice error message
261 if (!has_capability($capability, $context, $userid, $doanything)) {
262 $capabilityname = get_capability_string($capability);
263 print_error($errormessage, $stringfile, '', $capabilityname);
269 * This function returns whether the current user has the capability of performing a function
270 * For example, we can do has_capability('mod/forum:replypost',$cm) in forum
271 * only one of the 4 (moduleinstance, courseid, site, userid) would be set at 1 time
272 * This is a recursive funciton.
273 * @uses $USER
274 * @param string $capability - name of the capability
275 * @param object $context - a context object (record from context table)
276 * @param integer $userid - a userid number
277 * @param bool $doanything - if false, ignore do anything
278 * @return bool
280 function has_capability($capability, $context=NULL, $userid=NULL, $doanything=true) {
282 global $USER, $CONTEXT, $CFG;
284 static $capcache = array(); // Cache of capabilities
287 /// Some sanity checks
288 if (debugging()) {
289 if ($capability == 'debugcache') {
290 print_object($capcache);
291 return true;
293 if (!record_exists('capabilities', 'name', $capability)) {
294 debugging('Capability "'.$capability.'" was not found! This should be fixed in code.');
296 if ($doanything != true and $doanything != false) {
297 debugging('Capability parameter "doanything" is wierd ("'.$doanything.'"). This should be fixed in code.');
299 if (!is_object($context) && $context !== NULL) {
300 debugging('Incorrect context parameter "'.$context.'" for has_capability(), object expected! This should be fixed in code.');
304 /// Make sure we know the current context
305 if (empty($context)) { // Use default CONTEXT if none specified
306 if (empty($CONTEXT)) {
307 return false;
308 } else {
309 $context = $CONTEXT;
311 } else { // A context was given to us
312 if (empty($CONTEXT)) {
313 $CONTEXT = $context; // Store FIRST used context in this global as future default
317 /// Check and return cache in case we've processed this one before.
319 $cachekey = $capability.'_'.$context->id.'_'.intval($userid).'_'.intval($doanything);
320 if (isset($capcache[$cachekey])) {
321 return $capcache[$cachekey];
324 /// Set up user's default roles
325 if (empty($userid) && empty($USER->capabilities)) { // Real user, first time here
326 if (isloggedin()) {
327 load_defaultuser_role(); // All users get this by default
328 } else {
329 load_notloggedin_role(); // others get this by default
333 /// Load up the capabilities list or item as necessary
334 if ($userid && (($USER === NULL) or ($userid != $USER->id))) {
335 if (empty($USER->id) or ($userid != $USER->id)) {
336 $capabilities = load_user_capability($capability, $context, $userid); // expensive
337 } else { //$USER->id == $userid
338 $capabilities = empty($USER->capabilities) ? NULL : $USER->capabilities;
340 } else { // no userid
341 $capabilities = empty($USER->capabilities) ? NULL : $USER->capabilities;
342 $userid = $USER->id;
346 /// First deal with the "doanything" capability
348 if ($doanything) {
350 /// First make sure that we aren't in a "switched role"
352 $switchroleactive = false; // Assume it isn't active in this context
354 if (!empty($USER->switchrole)) { // Switchrole is active somewhere!
355 if (!empty($USER->switchrole[$context->id])) { // Because of current context
356 $switchroleactive = true;
357 } else { // Check parent contexts
358 if ($parentcontextids = get_parent_contexts($context)) {
359 foreach ($parentcontextids as $parentcontextid) {
360 if (!empty($USER->switchrole[$parentcontextid])) { // Yep, switchroles active here
361 $switchroleactive = true;
362 break;
369 /// Check the site context for doanything (most common) first
371 if (empty($switchroleactive)) { // Ignore site setting if switchrole is active
372 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
373 if (isset($capabilities[$sitecontext->id]['moodle/site:doanything'])) {
374 $result = (0 < $capabilities[$sitecontext->id]['moodle/site:doanything']);
375 $capcache[$cachekey] = $result;
376 return $result;
380 switch ($context->contextlevel) {
382 case CONTEXT_COURSECAT:
383 // Check parent cats.
384 $parentcats = get_parent_cats($context, CONTEXT_COURSECAT);
385 foreach ($parentcats as $parentcat) {
386 if (isset($capabilities[$parentcat]['moodle/site:doanything'])) {
387 $result = (0 < $capabilities[$parentcat]['moodle/site:doanything']);
388 $capcache[$cachekey] = $result;
389 return $result;
392 break;
394 case CONTEXT_COURSE:
395 // Check parent cat.
396 $parentcats = get_parent_cats($context, CONTEXT_COURSE);
398 foreach ($parentcats as $parentcat) {
399 if (isset($capabilities[$parentcat]['do_anything'])) {
400 $result = (0 < $capabilities[$parentcat]['do_anything']);
401 $capcache[$cachekey] = $result;
402 return $result;
405 break;
407 case CONTEXT_GROUP:
408 // Find course.
409 $group = get_record('groups','id',$context->instanceid);
410 $courseinstance = get_context_instance(CONTEXT_COURSE, $group->courseid);
412 $parentcats = get_parent_cats($courseinstance, CONTEXT_COURSE);
413 foreach ($parentcats as $parentcat) {
414 if (isset($capabilities[$parentcat]['do_anything'])) {
415 $result = (0 < $capabilities[$parentcat]['do_anything']);
416 $capcache[$cachekey] = $result;
417 return $result;
421 $coursecontext = '';
422 if (isset($capabilities[$courseinstance->id]['do_anything'])) {
423 $result = (0 < $capabilities[$courseinstance->id]['do_anything']);
424 $capcache[$cachekey] = $result;
425 return $result;
428 break;
430 case CONTEXT_MODULE:
431 // Find course.
432 $cm = get_record('course_modules', 'id', $context->instanceid);
433 $courseinstance = get_context_instance(CONTEXT_COURSE, $cm->course);
435 if ($parentcats = get_parent_cats($courseinstance, CONTEXT_COURSE)) {
436 foreach ($parentcats as $parentcat) {
437 if (isset($capabilities[$parentcat]['do_anything'])) {
438 $result = (0 < $capabilities[$parentcat]['do_anything']);
439 $capcache[$cachekey] = $result;
440 return $result;
445 if (isset($capabilities[$courseinstance->id]['do_anything'])) {
446 $result = (0 < $capabilities[$courseinstance->id]['do_anything']);
447 $capcache[$cachekey] = $result;
448 return $result;
451 break;
453 case CONTEXT_BLOCK:
454 // 1 to 1 to course.
455 // Find course.
456 $block = get_record('block_instance','id',$context->instanceid);
457 $courseinstance = get_context_instance(CONTEXT_COURSE, $block->pageid); // needs check
459 $parentcats = get_parent_cats($courseinstance, CONTEXT_COURSE);
460 foreach ($parentcats as $parentcat) {
461 if (isset($capabilities[$parentcat]['do_anything'])) {
462 $result = (0 < $capabilities[$parentcat]['do_anything']);
463 $capcache[$cachekey] = $result;
464 return $result;
468 if (isset($capabilities[$courseinstance->id]['do_anything'])) {
469 $result = (0 < $capabilities[$courseinstance->id]['do_anything']);
470 $capcache[$cachekey] = $result;
471 return $result;
473 break;
475 default:
476 // CONTEXT_SYSTEM: CONTEXT_PERSONAL: CONTEXT_USER:
477 // Do nothing.
478 break;
481 // Last: check self.
482 if (isset($capabilities[$context->id]['do_anything'])) {
483 $result = (0 < $capabilities[$context->id]['do_anything']);
484 $capcache[$cachekey] = $result;
485 return $result;
488 // do_anything has not been set, we now look for it the normal way.
489 $result = (0 < capability_search($capability, $context, $capabilities));
490 $capcache[$cachekey] = $result;
491 return $result;
497 * In a separate function so that we won't have to deal with do_anything.
498 * again. Used by function has_capability.
499 * @param $capability - capability string
500 * @param $context - the context object
501 * @param $capabilities - either $USER->capability or loaded array
502 * @return permission (int)
504 function capability_search($capability, $context, $capabilities) {
506 global $USER, $CFG;
508 if (!isset($context->id)) {
509 return 0;
512 if (isset($capabilities[$context->id][$capability])) {
513 return ($capabilities[$context->id][$capability]);
516 /* Then, we check the cache recursively */
517 $permission = 0;
519 switch ($context->contextlevel) {
521 case CONTEXT_SYSTEM: // by now it's a definite an inherit
522 $permission = 0;
523 break;
525 case CONTEXT_PERSONAL:
526 $parentcontext = get_context_instance(CONTEXT_SYSTEM);
527 $permission = capability_search($capability, $parentcontext, $capabilities);
528 break;
530 case CONTEXT_USER:
531 $parentcontext = get_context_instance(CONTEXT_SYSTEM);
532 $permission = capability_search($capability, $parentcontext, $capabilities);
533 break;
535 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
536 $coursecat = get_record('course_categories','id',$context->instanceid);
537 if (!empty($coursecat->parent)) { // return parent value if it exists
538 $parentcontext = get_context_instance(CONTEXT_COURSECAT, $coursecat->parent);
539 } else { // else return site value
540 $parentcontext = get_context_instance(CONTEXT_SYSTEM);
542 $permission = capability_search($capability, $parentcontext, $capabilities);
543 break;
545 case CONTEXT_COURSE: // 1 to 1 to course cat
546 // find the course cat, and return its value
547 $course = get_record('course','id',$context->instanceid);
548 $parentcontext = get_context_instance(CONTEXT_COURSECAT, $course->category);
549 $permission = capability_search($capability, $parentcontext, $capabilities);
550 break;
552 case CONTEXT_GROUP: // 1 to 1 to course
553 $group = get_record('groups','id',$context->instanceid);
554 $parentcontext = get_context_instance(CONTEXT_COURSE, $group->courseid);
555 $permission = capability_search($capability, $parentcontext, $capabilities);
556 break;
558 case CONTEXT_MODULE: // 1 to 1 to course
559 $cm = get_record('course_modules','id',$context->instanceid);
560 $parentcontext = get_context_instance(CONTEXT_COURSE, $cm->course);
561 $permission = capability_search($capability, $parentcontext, $capabilities);
562 break;
564 case CONTEXT_BLOCK: // 1 to 1 to course
565 $block = get_record('block_instance','id',$context->instanceid);
566 $parentcontext = get_context_instance(CONTEXT_COURSE, $block->pageid); // needs check
567 $permission = capability_search($capability, $parentcontext, $capabilities);
568 break;
570 default:
571 error ('This is an unknown context!');
572 return false;
575 return $permission;
578 // auxillary function for load_user_capabilities()
579 // if context c1 is a parent (or itself) of context c2
580 // returns true
581 function is_parent_context($c1, $c2) {
582 static $parentsarray;
584 // context can be itself and this is ok
585 if ($c1 == $c2) {
586 return true;
588 // hit in cache?
589 if (isset($parentsarray[$c1][$c2])) {
590 return $parentsarray[$c1][$c2];
593 if (!$co2 = get_record('context', 'id', $c2)) {
594 return false;
597 if (!$parents = get_parent_contexts($co2)) {
598 return false;
601 foreach ($parents as $parent) {
602 $parentsarray[$parent][$c2] = true;
605 if (in_array($c1, $parents)) {
606 return true;
607 } else { // else not a parent, set the cache anyway
608 $parentsarray[$c1][$c2] = false;
609 return false;
615 * auxillary function for load_user_capabilities()
616 * handler in usort() to sort contexts according to level
618 function roles_context_cmp($contexta, $contextb) {
619 if ($contexta->contextlevel == $contextb->contextlevel) {
620 return 0;
622 return ($contexta->contextlevel < $contextb->contextlevel) ? -1 : 1;
627 * This function should be called immediately after a login, when $USER is set.
628 * It will build an array of all the capabilities at each level
629 * i.e. site/metacourse/course_category/course/moduleinstance
630 * Note we should only load capabilities if they are explicitly assigned already,
631 * we should not load all module's capability!
633 * [Capabilities] => [26][forum_post] = 1
634 * [26][forum_start] = -8990
635 * [26][forum_edit] = -1
636 * [273][blah blah] = 1
637 * [273][blah blah blah] = 2
639 * @param $capability string - Only get a specific capability (string)
640 * @param $context object - Only get capabilities for a specific context object
641 * @param $userid integer - the id of the user whose capabilities we want to load
642 * @return array of permissions (or nothing if they get assigned to $USER)
644 function load_user_capability($capability='', $context = NULL, $userid='') {
646 global $USER, $CFG;
648 if (empty($CFG->rolesactive)) {
649 return false;
652 if (empty($userid)) {
653 if (empty($USER->id)) { // We have no user to get capabilities for
654 debugging('User not logged in for load_user_capability!');
655 return false;
657 unset($USER->capabilities); // We don't want possible older capabilites hanging around
659 check_enrolment_plugins($USER); // Call "enrol" system to ensure that we have the correct picture
661 $userid = $USER->id;
662 $otheruserid = false;
663 } else {
664 if (!$user = get_record('user', 'id', $userid)) {
665 debugging('Non-existent userid in load_user_capability!');
666 return false;
669 check_enrolment_plugins($user); // Ensure that we have the correct picture
671 $otheruserid = $userid;
675 /// First we generate a list of all relevant contexts of the user
677 $usercontexts = array();
679 if ($context) { // if context is specified
680 $usercontexts = get_parent_contexts($context);
681 $usercontexts[] = $context->id; // Add the current context as well
682 } else { // else, we load everything
683 if ($userroles = get_records('role_assignments','userid',$userid)) {
684 foreach ($userroles as $userrole) {
685 $usercontexts[] = $userrole->contextid;
690 /// Set up SQL fragments for searching contexts
692 if ($usercontexts) {
693 $listofcontexts = '('.implode(',', $usercontexts).')';
694 $searchcontexts1 = "c1.id IN $listofcontexts AND";
695 } else {
696 $searchcontexts1 = '';
699 if ($capability) {
700 $capsearch = " AND rc.capability = '$capability' ";
701 } else {
702 $capsearch ="";
705 /// Set up SQL fragments for timestart, timeend etc
706 $now = time();
707 $timesql = "AND ((ra.timestart = 0 OR ra.timestart < $now) AND (ra.timeend = 0 OR ra.timeend > $now))";
709 /// Then we use 1 giant SQL to bring out all relevant capabilities.
710 /// The first part gets the capabilities of orginal role.
711 /// The second part gets the capabilities of overriden roles.
713 $siteinstance = get_context_instance(CONTEXT_SYSTEM);
714 $capabilities = array(); // Reinitialize.
716 // SQL for normal capabilities
717 $SQL1 = "SELECT rc.capability, c1.id as id1, c1.id as id2, (c1.contextlevel * 100) AS aggrlevel,
718 SUM(rc.permission) AS sum
719 FROM
720 {$CFG->prefix}role_assignments ra,
721 {$CFG->prefix}role_capabilities rc,
722 {$CFG->prefix}context c1
723 WHERE
724 ra.contextid=c1.id AND
725 ra.roleid=rc.roleid AND
726 ra.userid=$userid AND
727 $searchcontexts1
728 rc.contextid=$siteinstance->id
729 $capsearch
730 $timesql
731 GROUP BY
732 rc.capability, (c1.contextlevel * 100), c1.id
733 HAVING
734 SUM(rc.permission) != 0
735 ORDER BY
736 aggrlevel ASC";
738 if (!$rs = get_recordset_sql($SQL1)) {
739 error("Query failed in load_user_capability.");
742 if ($rs && $rs->RecordCount() > 0) {
743 while (!$rs->EOF) {
744 $array = $rs->fields;
745 $temprecord = new object;
747 foreach ($array as $key=>$val) {
748 if ($key == 'aggrlevel') {
749 $temprecord->contextlevel = $val;
750 } else {
751 $temprecord->{$key} = $val;
755 $capabilities[] = $temprecord;
756 $rs->MoveNext();
759 // SQL for overrides
760 // this is take out because we have no way of making sure c1 is indeed related to c2 (parent)
761 // if we do not group by sum, it is possible to have multiple records of rc.capability, c1.id, c2.id, tuple having
762 // different values, we can maually sum it when we go through the list
763 $SQL2 = "SELECT rc.capability, c1.id as id1, c2.id as id2, (c1.contextlevel * 100 + c2.contextlevel) AS aggrlevel,
764 rc.permission AS sum
765 FROM
766 {$CFG->prefix}role_assignments ra,
767 {$CFG->prefix}role_capabilities rc,
768 {$CFG->prefix}context c1,
769 {$CFG->prefix}context c2
770 WHERE
771 ra.contextid=c1.id AND
772 ra.roleid=rc.roleid AND
773 ra.userid=$userid AND
774 rc.contextid=c2.id AND
775 $searchcontexts1
776 rc.contextid != $siteinstance->id
777 $capsearch
778 $timesql
780 GROUP BY
781 rc.capability, (c1.contextlevel * 100 + c2.contextlevel), c1.id, c2.id, rc.permission
782 ORDER BY
783 aggrlevel ASC
787 if (!$rs = get_recordset_sql($SQL2)) {
788 error("Query failed in load_user_capability.");
791 if ($rs && $rs->RecordCount() > 0) {
792 while (!$rs->EOF) {
793 $array = $rs->fields;
794 $temprecord = new object;
796 foreach ($array as $key=>$val) {
797 if ($key == 'aggrlevel') {
798 $temprecord->contextlevel = $val;
799 } else {
800 $temprecord->{$key} = $val;
803 // for overrides, we have to make sure that context2 is a child of context1
804 // otherwise the combination makes no sense
805 if (is_parent_context($temprecord->id1, $temprecord->id2)) {
806 $capabilities[] = $temprecord;
807 } // only write if relevant
808 $rs->MoveNext();
812 // this step sorts capabilities according to the contextlevel
813 // it is very important because the order matters when we
814 // go through each capabilities later. (i.e. higher level contextlevel
815 // will override lower contextlevel settings
816 usort($capabilities, 'roles_context_cmp');
818 /* so up to this point we should have somethign like this
819 * $capabilities[1] ->contextlevel = 1000
820 ->module = SITEID
821 ->capability = do_anything
822 ->id = 1 (id is the context id)
823 ->sum = 0
825 * $capabilities[2] ->contextlevel = 1000
826 ->module = SITEID
827 ->capability = post_messages
828 ->id = 1
829 ->sum = -9000
831 * $capabilittes[3] ->contextlevel = 3000
832 ->module = course
833 ->capability = view_course_activities
834 ->id = 25
835 ->sum = 1
837 * $capabilittes[4] ->contextlevel = 3000
838 ->module = course
839 ->capability = view_course_activities
840 ->id = 26
841 ->sum = 0 (this is another course)
843 * $capabilities[5] ->contextlevel = 3050
844 ->module = course
845 ->capability = view_course_activities
846 ->id = 25 (override in course 25)
847 ->sum = -1
848 * ....
849 * now we proceed to write the session array, going from top to bottom
850 * at anypoint, we need to go up and check parent to look for prohibit
852 // print_object($capabilities);
854 /* This is where we write to the actualy capabilities array
855 * what we need to do from here on is
856 * going down the array from lowest level to highest level
857 * 1) recursively check for prohibit,
858 * if any, we write prohibit
859 * else, we write the value
860 * 2) at an override level, we overwrite current level
861 * if it's not set to prohibit already, and if different
862 * ........ that should be it ........
865 // This is the flag used for detecting the current context level. Since we are going through
866 // the array in ascending order of context level. For normal capabilities, there should only
867 // be 1 value per (capability, contextlevel, context), because they are already summed. But,
868 // for overrides, since we are processing them separate, we need to sum the relevcant entries.
869 // We set this flag when we hit a new level.
870 // If the flag is already set, we keep adding (summing), otherwise, we just override previous
871 // settings (from lower level contexts)
872 $capflags = array(); // (contextid, contextlevel, capability)
873 $usercap = array(); // for other user's capabilities
874 foreach ($capabilities as $capability) {
876 if (!$context = get_context_instance_by_id($capability->id2)) {
877 continue; // incorrect stale context
880 if (!empty($otheruserid)) { // we are pulling out other user's capabilities, do not write to session
882 if (capability_prohibits($capability->capability, $context, $capability->sum, $usercap)) {
883 $usercap[$capability->id2][$capability->capability] = CAP_PROHIBIT;
884 continue;
886 if (isset($usercap[$capability->id2][$capability->capability])) { // use isset because it can be sum 0
887 if (!empty($capflags[$capability->id2][$capability->contextlevel][$capability->capability])) {
888 $usercap[$capability->id2][$capability->capability] += $capability->sum;
889 } else { // else we override, and update flag
890 $usercap[$capability->id2][$capability->capability] = $capability->sum;
891 $capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
893 } else {
894 $usercap[$capability->id2][$capability->capability] = $capability->sum;
895 $capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
898 } else {
900 if (capability_prohibits($capability->capability, $context, $capability->sum)) { // if any parent or parent's parent is set to prohibit
901 $USER->capabilities[$capability->id2][$capability->capability] = CAP_PROHIBIT;
902 continue;
905 // if no parental prohibit set
906 // just write to session, i am not sure this is correct yet
907 // since 3050 shows up after 3000, and 3070 shows up after 3050,
908 // it should be ok just to overwrite like this, provided that there's no
909 // parental prohibits
910 // we need to write even if it's 0, because it could be an inherit override
911 if (isset($USER->capabilities[$capability->id2][$capability->capability])) {
912 if (!empty($capflags[$capability->id2][$capability->contextlevel][$capability->capability])) {
913 $USER->capabilities[$capability->id2][$capability->capability] += $capability->sum;
914 } else { // else we override, and update flag
915 $USER->capabilities[$capability->id2][$capability->capability] = $capability->sum;
916 $capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
918 } else {
919 $USER->capabilities[$capability->id2][$capability->capability] = $capability->sum;
920 $capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
925 // now we don't care about the huge array anymore, we can dispose it.
926 unset($capabilities);
927 unset($capflags);
929 if (!empty($otheruserid)) {
930 return $usercap; // return the array
936 * A convenience function to completely load all the capabilities
937 * for the current user. This is what gets called from login, for example.
939 function load_all_capabilities() {
940 global $USER;
942 if (empty($USER->username)) {
943 return;
946 load_user_capability(); // Load basic capabilities assigned to this user
948 if ($USER->username == 'guest') {
949 load_guest_role(); // All non-guest users get this by default
950 } else {
951 load_defaultuser_role(); // All non-guest users get this by default
957 * Check all the login enrolment information for the given user object
958 * by querying the enrolment plugins
960 function check_enrolment_plugins(&$user) {
961 global $CFG;
963 static $inprogress; // To prevent this function being called more than once in an invocation
965 if (!empty($inprogress[$user->id])) {
966 return;
969 $inprogress[$user->id] = true; // Set the flag
971 require_once($CFG->dirroot .'/enrol/enrol.class.php');
973 if (!($plugins = explode(',', $CFG->enrol_plugins_enabled))) {
974 $plugins = array($CFG->enrol);
977 foreach ($plugins as $plugin) {
978 $enrol = enrolment_factory::factory($plugin);
979 if (method_exists($enrol, 'setup_enrolments')) { /// Plugin supports Roles (Moodle 1.7 and later)
980 $enrol->setup_enrolments($user);
981 } else { /// Run legacy enrolment methods
982 if (method_exists($enrol, 'get_student_courses')) {
983 $enrol->get_student_courses($user);
985 if (method_exists($enrol, 'get_teacher_courses')) {
986 $enrol->get_teacher_courses($user);
989 /// deal with $user->students and $user->teachers stuff
990 unset($user->student);
991 unset($user->teacher);
993 unset($enrol);
996 unset($inprogress[$user->id]); // Unset the flag
1001 * This is a recursive function that checks whether the capability in this
1002 * context, or the parent capabilities are set to prohibit.
1004 * At this point, we can probably just use the values already set in the
1005 * session variable, since we are going down the level. Any prohit set in
1006 * parents would already reflect in the session.
1008 * @param $capability - capability name
1009 * @param $sum - sum of all capabilities values
1010 * @param $context - the context object
1011 * @param $array - when loading another user caps, their caps are not stored in session but an array
1013 function capability_prohibits($capability, $context, $sum='', $array='') {
1014 global $USER;
1016 if (empty($context->id)) {
1017 return false;
1020 if (empty($capability)) {
1021 return false;
1024 if ($sum < (CAP_PROHIBIT/2)) {
1025 // If this capability is set to prohibit.
1026 return true;
1029 if (!empty($array)) {
1030 if (isset($array[$context->id][$capability])
1031 && $array[$context->id][$capability] < (CAP_PROHIBIT/2)) {
1032 return true;
1034 } else {
1035 // Else if set in session.
1036 if (isset($USER->capabilities[$context->id][$capability])
1037 && $USER->capabilities[$context->id][$capability] < (CAP_PROHIBIT/2)) {
1038 return true;
1041 switch ($context->contextlevel) {
1043 case CONTEXT_SYSTEM:
1044 // By now it's a definite an inherit.
1045 return 0;
1046 break;
1048 case CONTEXT_PERSONAL:
1049 $parent = get_context_instance(CONTEXT_SYSTEM);
1050 return capability_prohibits($capability, $parent);
1051 break;
1053 case CONTEXT_USER:
1054 $parent = get_context_instance(CONTEXT_SYSTEM);
1055 return capability_prohibits($capability, $parent);
1056 break;
1058 case CONTEXT_COURSECAT:
1059 // Coursecat -> coursecat or site.
1060 if (!$coursecat = get_record('course_categories','id',$context->instanceid)) {
1061 return false;
1063 if (!empty($coursecat->parent)) {
1064 // return parent value if exist.
1065 $parent = get_context_instance(CONTEXT_COURSECAT, $coursecat->parent);
1066 } else {
1067 // Return site value.
1068 $parent = get_context_instance(CONTEXT_SYSTEM);
1070 return capability_prohibits($capability, $parent);
1071 break;
1073 case CONTEXT_COURSE:
1074 // 1 to 1 to course cat.
1075 // Find the course cat, and return its value.
1076 if (!$course = get_record('course','id',$context->instanceid)) {
1077 return false;
1079 $parent = get_context_instance(CONTEXT_COURSECAT, $course->category);
1080 return capability_prohibits($capability, $parent);
1081 break;
1083 case CONTEXT_GROUP:
1084 // 1 to 1 to course.
1085 if (!$group = get_record('groups','id',$context->instanceid)) {
1086 return false;
1088 $parent = get_context_instance(CONTEXT_COURSE, $group->courseid);
1089 return capability_prohibits($capability, $parent);
1090 break;
1092 case CONTEXT_MODULE:
1093 // 1 to 1 to course.
1094 if (!$cm = get_record('course_modules','id',$context->instanceid)) {
1095 return false;
1097 $parent = get_context_instance(CONTEXT_COURSE, $cm->course);
1098 return capability_prohibits($capability, $parent);
1099 break;
1101 case CONTEXT_BLOCK:
1102 // 1 to 1 to course.
1103 if (!$block = get_record('block_instance','id',$context->instanceid)) {
1104 return false;
1106 $parent = get_context_instance(CONTEXT_COURSE, $block->pageid); // needs check
1107 return capability_prohibits($capability, $parent);
1108 break;
1110 default:
1111 print_error('unknowncontext');
1112 return false;
1118 * A print form function. This should either grab all the capabilities from
1119 * files or a central table for that particular module instance, then present
1120 * them in check boxes. Only relevant capabilities should print for known
1121 * context.
1122 * @param $mod - module id of the mod
1124 function print_capabilities($modid=0) {
1125 global $CFG;
1127 $capabilities = array();
1129 if ($modid) {
1130 // We are in a module specific context.
1132 // Get the mod's name.
1133 // Call the function that grabs the file and parse.
1134 $cm = get_record('course_modules', 'id', $modid);
1135 $module = get_record('modules', 'id', $cm->module);
1137 } else {
1138 // Print all capabilities.
1139 foreach ($capabilities as $capability) {
1140 // Prints the check box component.
1147 * Installs the roles system.
1148 * This function runs on a fresh install as well as on an upgrade from the old
1149 * hard-coded student/teacher/admin etc. roles to the new roles system.
1151 function moodle_install_roles() {
1153 global $CFG, $db;
1155 /// Create a system wide context for assignemnt.
1156 $systemcontext = $context = get_context_instance(CONTEXT_SYSTEM);
1159 /// Create default/legacy roles and capabilities.
1160 /// (1 legacy capability per legacy role at system level).
1162 $adminrole = create_role(get_string('administrator'), 'admin',
1163 get_string('administratordescription'), 'moodle/legacy:admin');
1164 $coursecreatorrole = create_role(get_string('coursecreators'), 'coursecreator',
1165 get_string('coursecreatorsdescription'), 'moodle/legacy:coursecreator');
1166 $editteacherrole = create_role(get_string('defaultcourseteacher'), 'editingteacher',
1167 get_string('defaultcourseteacherdescription'), 'moodle/legacy:editingteacher');
1168 $noneditteacherrole = create_role(get_string('noneditingteacher'), 'teacher',
1169 get_string('noneditingteacherdescription'), 'moodle/legacy:teacher');
1170 $studentrole = create_role(get_string('defaultcoursestudent'), 'student',
1171 get_string('defaultcoursestudentdescription'), 'moodle/legacy:student');
1172 $guestrole = create_role(get_string('guest'), 'guest',
1173 get_string('guestdescription'), 'moodle/legacy:guest');
1175 /// Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles
1177 if (!assign_capability('moodle/site:doanything', CAP_ALLOW, $adminrole, $systemcontext->id)) {
1178 error('Could not assign moodle/site:doanything to the admin role');
1180 if (!update_capabilities()) {
1181 error('Had trouble upgrading the core capabilities for the Roles System');
1184 /// Look inside user_admin, user_creator, user_teachers, user_students and
1185 /// assign above new roles. If a user has both teacher and student role,
1186 /// only teacher role is assigned. The assignment should be system level.
1188 $dbtables = $db->MetaTables('TABLES');
1190 /// Set up the progress bar
1192 $usertables = array('user_admins', 'user_coursecreators', 'user_teachers', 'user_students');
1194 $totalcount = $progresscount = 0;
1195 foreach ($usertables as $usertable) {
1196 if (in_array($CFG->prefix.$usertable, $dbtables)) {
1197 $totalcount += count_records($usertable);
1201 print_progress(0, $totalcount, 5, 1, 'Processing role assignments');
1203 /// Upgrade the admins.
1204 /// Sort using id ASC, first one is primary admin.
1206 if (in_array($CFG->prefix.'user_admins', $dbtables)) {
1207 if ($rs = get_recordset_sql('SELECT * from '.$CFG->prefix.'user_admins ORDER BY ID ASC')) {
1208 while (! $rs->EOF) {
1209 $admin = $rs->FetchObj();
1210 role_assign($adminrole, $admin->userid, 0, $systemcontext->id);
1211 $progresscount++;
1212 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1213 $rs->MoveNext();
1216 } else {
1217 // This is a fresh install.
1221 /// Upgrade course creators.
1222 if (in_array($CFG->prefix.'user_coursecreators', $dbtables)) {
1223 if ($rs = get_recordset('user_coursecreators')) {
1224 while (! $rs->EOF) {
1225 $coursecreator = $rs->FetchObj();
1226 role_assign($coursecreatorrole, $coursecreator->userid, 0, $systemcontext->id);
1227 $progresscount++;
1228 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1229 $rs->MoveNext();
1235 /// Upgrade editting teachers and non-editting teachers.
1236 if (in_array($CFG->prefix.'user_teachers', $dbtables)) {
1237 if ($rs = get_recordset('user_teachers')) {
1238 while (! $rs->EOF) {
1239 $teacher = $rs->FetchObj();
1240 // ignore site level teacher assignments
1241 if ($teacher->course == SITEID) {
1242 $progresscount++;
1243 $rs->MoveNext();
1244 continue;
1246 // populate the user_lastaccess table
1247 $access = new object();
1248 $access->timeaccess = $teacher->timeaccess;
1249 $access->userid = $teacher->userid;
1250 $access->courseid = $teacher->course;
1251 insert_record('user_lastaccess', $access);
1253 // assign the default student role
1254 $coursecontext = get_context_instance(CONTEXT_COURSE, $teacher->course); // needs cache
1255 if ($teacher->editall) { // editting teacher
1256 role_assign($editteacherrole, $teacher->userid, 0, $coursecontext->id);
1257 } else {
1258 role_assign($noneditteacherrole, $teacher->userid, 0, $coursecontext->id);
1260 $progresscount++;
1261 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1263 $rs->MoveNext();
1269 /// Upgrade students.
1270 if (in_array($CFG->prefix.'user_students', $dbtables)) {
1271 if ($rs = get_recordset('user_students')) {
1272 while (! $rs->EOF) {
1273 $student = $rs->FetchObj();
1275 // populate the user_lastaccess table
1276 $access = new object;
1277 $access->timeaccess = $student->timeaccess;
1278 $access->userid = $student->userid;
1279 $access->courseid = $student->course;
1280 insert_record('user_lastaccess', $access);
1282 // assign the default student role
1283 $coursecontext = get_context_instance(CONTEXT_COURSE, $student->course);
1284 role_assign($studentrole, $student->userid, 0, $coursecontext->id);
1285 $progresscount++;
1286 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1288 $rs->MoveNext();
1294 /// Upgrade guest (only 1 entry).
1295 if ($guestuser = get_record('user', 'username', 'guest')) {
1296 role_assign($guestrole, $guestuser->id, 0, $systemcontext->id);
1298 print_progress($totalcount, $totalcount, 5, 1, 'Processing role assignments');
1301 /// Insert the correct records for legacy roles
1302 allow_assign($adminrole, $adminrole);
1303 allow_assign($adminrole, $coursecreatorrole);
1304 allow_assign($adminrole, $noneditteacherrole);
1305 allow_assign($adminrole, $editteacherrole);
1306 allow_assign($adminrole, $studentrole);
1307 allow_assign($adminrole, $guestrole);
1309 allow_assign($coursecreatorrole, $noneditteacherrole);
1310 allow_assign($coursecreatorrole, $editteacherrole);
1311 allow_assign($coursecreatorrole, $studentrole);
1312 allow_assign($coursecreatorrole, $guestrole);
1314 allow_assign($editteacherrole, $noneditteacherrole);
1315 allow_assign($editteacherrole, $studentrole);
1316 allow_assign($editteacherrole, $guestrole);
1318 /// Set up default permissions for overrides
1319 allow_override($adminrole, $adminrole);
1320 allow_override($adminrole, $coursecreatorrole);
1321 allow_override($adminrole, $noneditteacherrole);
1322 allow_override($adminrole, $editteacherrole);
1323 allow_override($adminrole, $studentrole);
1324 allow_override($adminrole, $guestrole);
1327 /// Delete the old user tables when we are done
1329 drop_table(new XMLDBTable('user_students'));
1330 drop_table(new XMLDBTable('user_teachers'));
1331 drop_table(new XMLDBTable('user_coursecreators'));
1332 drop_table(new XMLDBTable('user_admins'));
1337 * Assign the defaults found in this capabality definition to roles that have
1338 * the corresponding legacy capabilities assigned to them.
1339 * @param $legacyperms - an array in the format (example):
1340 * 'guest' => CAP_PREVENT,
1341 * 'student' => CAP_ALLOW,
1342 * 'teacher' => CAP_ALLOW,
1343 * 'editingteacher' => CAP_ALLOW,
1344 * 'coursecreator' => CAP_ALLOW,
1345 * 'admin' => CAP_ALLOW
1346 * @return boolean - success or failure.
1348 function assign_legacy_capabilities($capability, $legacyperms) {
1350 foreach ($legacyperms as $type => $perm) {
1352 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
1354 // The legacy capabilities are:
1355 // 'moodle/legacy:guest'
1356 // 'moodle/legacy:student'
1357 // 'moodle/legacy:teacher'
1358 // 'moodle/legacy:editingteacher'
1359 // 'moodle/legacy:coursecreator'
1360 // 'moodle/legacy:admin'
1362 if ($roles = get_roles_with_capability('moodle/legacy:'.$type, CAP_ALLOW)) {
1363 foreach ($roles as $role) {
1364 // Assign a site level capability.
1365 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1366 return false;
1371 return true;
1376 * Checks to see if a capability is a legacy capability.
1377 * @param $capabilityname
1378 * @return boolean
1380 function islegacy($capabilityname) {
1381 if (strstr($capabilityname, 'legacy') === false) {
1382 return false;
1383 } else {
1384 return true;
1390 /**********************************
1391 * Context Manipulation functions *
1392 **********************************/
1395 * Create a new context record for use by all roles-related stuff
1396 * @param $level
1397 * @param $instanceid
1399 * @return object newly created context (or existing one with a debug warning)
1401 function create_context($contextlevel, $instanceid) {
1402 if (!$context = get_record('context','contextlevel',$contextlevel,'instanceid',$instanceid)) {
1403 if (!validate_context($contextlevel, $instanceid)) {
1404 debugging('Error: Invalid context creation request for level "'.s($contextlevel).'", instance "'.s($instanceid).'".');
1405 return NULL;
1407 $context = new object();
1408 $context->contextlevel = $contextlevel;
1409 $context->instanceid = $instanceid;
1410 if ($id = insert_record('context',$context)) {
1411 return get_record('context','id',$id);
1412 } else {
1413 debugging('Error: could not insert new context level "'.s($contextlevel).'", instance "'.s($instanceid).'".');
1414 return NULL;
1416 } else {
1417 debugging('Warning: Context id "'.s($context->id).'" not created, because it already exists.');
1418 return $context;
1423 * Create a new context record for use by all roles-related stuff
1424 * @param $level
1425 * @param $instanceid
1427 * @return true if properly deleted
1429 function delete_context($contextlevel, $instanceid) {
1430 if ($context = get_context_instance($contextlevel, $instanceid)) {
1431 return delete_records('context', 'id', $context->id) &&
1432 delete_records('role_assignments', 'contextid', $context->id) &&
1433 delete_records('role_capabilities', 'contextid', $context->id);
1435 return true;
1439 * Validate that object with instanceid really exists in given context level.
1441 * return if instanceid object exists
1443 function validate_context($contextlevel, $instanceid) {
1444 switch ($contextlevel) {
1446 case CONTEXT_SYSTEM:
1447 return ($instanceid == SITEID);
1449 case CONTEXT_PERSONAL:
1450 return (boolean)count_records('user', 'id', $instanceid);
1452 case CONTEXT_USER:
1453 return (boolean)count_records('user', 'id', $instanceid);
1455 case CONTEXT_COURSECAT:
1456 if ($instanceid == 0) {
1457 return true; // site course category
1459 return (boolean)count_records('course_categories', 'id', $instanceid);
1461 case CONTEXT_COURSE:
1462 return (boolean)count_records('course', 'id', $instanceid);
1464 case CONTEXT_GROUP:
1465 return (boolean)count_records('groups', 'id', $instanceid);
1467 case CONTEXT_MODULE:
1468 return (boolean)count_records('course_modules', 'id', $instanceid);
1470 case CONTEXT_BLOCK:
1471 return (boolean)count_records('block_instance', 'id', $instanceid);
1473 default:
1474 return false;
1479 * Get the context instance as an object. This function will create the
1480 * context instance if it does not exist yet.
1481 * @param $level
1482 * @param $instance
1484 function get_context_instance($contextlevel=NULL, $instance=SITEID) {
1486 global $context_cache, $context_cache_id, $CONTEXT;
1487 static $allowed_contexts = array(CONTEXT_SYSTEM, CONTEXT_PERSONAL, CONTEXT_USER, CONTEXT_COURSECAT, CONTEXT_COURSE, CONTEXT_GROUP, CONTEXT_MODULE, CONTEXT_BLOCK);
1489 // This is really a systen context
1490 if ($contextlevel == CONTEXT_COURSE && $instance == SITEID) {
1491 $contextlevel = CONTEXT_SYSTEM;
1494 /// If no level is supplied then return the current global context if there is one
1495 if (empty($contextlevel)) {
1496 if (empty($CONTEXT)) {
1497 //fatal error, code must be fixed
1498 error("Error: get_context_instance() called without a context");
1499 } else {
1500 return $CONTEXT;
1504 /// check allowed context levels
1505 if (!in_array($contextlevel, $allowed_contexts)) {
1506 // fatal error, code must be fixed - probably typo or switched parameters
1507 error('Error: get_context_instance() called with incorrect context level "'.s($contextlevel).'"');
1510 /// Check the cache
1511 if (isset($context_cache[$contextlevel][$instance])) { // Already cached
1512 return $context_cache[$contextlevel][$instance];
1515 /// Get it from the database, or create it
1516 if (!$context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance)) {
1517 create_context($contextlevel, $instance);
1518 $context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance);
1521 /// Only add to cache if context isn't empty.
1522 if (!empty($context)) {
1523 $context_cache[$contextlevel][$instance] = $context; // Cache it for later
1524 $context_cache_id[$context->id] = $context; // Cache it for later
1527 return $context;
1532 * Get a context instance as an object, from a given id.
1533 * @param $id
1535 function get_context_instance_by_id($id) {
1537 global $context_cache, $context_cache_id;
1539 if (isset($context_cache_id[$id])) { // Already cached
1540 return $context_cache_id[$id];
1543 if ($context = get_record('context', 'id', $id)) { // Update the cache and return
1544 $context_cache[$context->contextlevel][$context->instanceid] = $context;
1545 $context_cache_id[$context->id] = $context;
1546 return $context;
1549 return false;
1554 * Get the local override (if any) for a given capability in a role in a context
1555 * @param $roleid
1556 * @param $contextid
1557 * @param $capability
1559 function get_local_override($roleid, $contextid, $capability) {
1560 return get_record('role_capabilities', 'roleid', $roleid, 'capability', $capability, 'contextid', $contextid);
1565 /************************************
1566 * DB TABLE RELATED FUNCTIONS *
1567 ************************************/
1570 * function that creates a role
1571 * @param name - role name
1572 * @param shortname - role short name
1573 * @param description - role description
1574 * @param legacy - optional legacy capability
1575 * @return id or false
1577 function create_role($name, $shortname, $description, $legacy='') {
1579 // check for duplicate role name
1581 if ($role = get_record('role','name', $name)) {
1582 error('there is already a role with this name!');
1585 if ($role = get_record('role','shortname', $shortname)) {
1586 error('there is already a role with this shortname!');
1589 $role = new object();
1590 $role->name = $name;
1591 $role->shortname = $shortname;
1592 $role->description = $description;
1594 //find free sortorder number
1595 $role->sortorder = count_records('role');
1596 while (get_record('role','sortorder', $role->sortorder)) {
1597 $role->sortorder += 1;
1600 if (!$context = get_context_instance(CONTEXT_SYSTEM)) {
1601 return false;
1604 if ($id = insert_record('role', $role)) {
1605 if ($legacy) {
1606 assign_capability($legacy, CAP_ALLOW, $id, $context->id);
1609 /// By default, users with role:manage at site level
1610 /// should be able to assign users to this new role, and override this new role's capabilities
1612 // find all admin roles
1613 if ($adminroles = get_roles_with_capability('moodle/role:manage', CAP_ALLOW, $context)) {
1614 // foreach admin role
1615 foreach ($adminroles as $arole) {
1616 // write allow_assign and allow_overrid
1617 allow_assign($arole->id, $id);
1618 allow_override($arole->id, $id);
1622 return $id;
1623 } else {
1624 return false;
1630 * function that deletes a role and cleanups up after it
1631 * @param roleid - id of role to delete
1632 * @return success
1634 function delete_role($roleid) {
1635 $success = true;
1637 // first unssign all users
1638 if (!role_unassign($roleid)) {
1639 debugging("Error while unassigning all users from role with ID $roleid!");
1640 $success = false;
1643 // cleanup all references to this role, ignore errors
1644 if ($success) {
1645 delete_records('role_capabilities', 'roleid', $roleid);
1646 delete_records('role_allow_assign', 'roleid', $roleid);
1647 delete_records('role_allow_assign', 'allowassign', $roleid);
1648 delete_records('role_allow_override', 'roleid', $roleid);
1649 delete_records('role_allow_override', 'allowoverride', $roleid);
1650 delete_records('role_names', 'roleid', $roleid);
1653 // finally delete the role itself
1654 if ($success and !delete_records('role', 'id', $roleid)) {
1655 debugging("Could not delete role record with ID $roleid!");
1656 $success = false;
1659 return $success;
1663 * Function to write context specific overrides, or default capabilities.
1664 * @param module - string name
1665 * @param capability - string name
1666 * @param contextid - context id
1667 * @param roleid - role id
1668 * @param permission - int 1,-1 or -1000
1669 * should not be writing if permission is 0
1671 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite=false) {
1673 global $USER;
1675 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
1676 unassign_capability($capability, $roleid, $contextid);
1677 return true;
1680 $existing = get_record('role_capabilities', 'contextid', $contextid, 'roleid', $roleid, 'capability', $capability);
1682 if ($existing and !$overwrite) { // We want to keep whatever is there already
1683 return true;
1686 $cap = new object;
1687 $cap->contextid = $contextid;
1688 $cap->roleid = $roleid;
1689 $cap->capability = $capability;
1690 $cap->permission = $permission;
1691 $cap->timemodified = time();
1692 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
1694 if ($existing) {
1695 $cap->id = $existing->id;
1696 return update_record('role_capabilities', $cap);
1697 } else {
1698 return insert_record('role_capabilities', $cap);
1704 * Unassign a capability from a role.
1705 * @param $roleid - the role id
1706 * @param $capability - the name of the capability
1707 * @return boolean - success or failure
1709 function unassign_capability($capability, $roleid, $contextid=NULL) {
1711 if (isset($contextid)) {
1712 $status = delete_records('role_capabilities', 'capability', $capability,
1713 'roleid', $roleid, 'contextid', $contextid);
1714 } else {
1715 $status = delete_records('role_capabilities', 'capability', $capability,
1716 'roleid', $roleid);
1718 return $status;
1723 * Get the roles that have a given capability assigned to it. This function
1724 * does not resolve the actual permission of the capability. It just checks
1725 * for assignment only.
1726 * @param $capability - capability name (string)
1727 * @param $permission - optional, the permission defined for this capability
1728 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT
1729 * @return array or role objects
1731 function get_roles_with_capability($capability, $permission=NULL, $context='') {
1733 global $CFG;
1735 if ($context) {
1736 if ($contexts = get_parent_contexts($context)) {
1737 $listofcontexts = '('.implode(',', $contexts).')';
1738 } else {
1739 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
1740 $listofcontexts = '('.$sitecontext->id.')'; // must be site
1742 $contextstr = "AND (rc.contextid = '$context->id' OR rc.contextid IN $listofcontexts)";
1743 } else {
1744 $contextstr = '';
1747 $selectroles = "SELECT r.*
1748 FROM {$CFG->prefix}role r,
1749 {$CFG->prefix}role_capabilities rc
1750 WHERE rc.capability = '$capability'
1751 AND rc.roleid = r.id $contextstr";
1753 if (isset($permission)) {
1754 $selectroles .= " AND rc.permission = '$permission'";
1756 return get_records_sql($selectroles);
1761 * This function makes a role-assignment (a role for a user or group in a particular context)
1762 * @param $roleid - the role of the id
1763 * @param $userid - userid
1764 * @param $groupid - group id
1765 * @param $contextid - id of the context
1766 * @param $timestart - time this assignment becomes effective
1767 * @param $timeend - time this assignemnt ceases to be effective
1768 * @uses $USER
1769 * @return id - new id of the assigment
1771 function role_assign($roleid, $userid, $groupid, $contextid, $timestart=0, $timeend=0, $hidden=0, $enrol='manual') {
1772 global $USER, $CFG;
1774 debugging("Assign roleid $roleid userid $userid contextid $contextid", DEBUG_DEVELOPER);
1776 /// Do some data validation
1778 if (empty($roleid)) {
1779 debugging('Role ID not provided');
1780 return false;
1783 if (empty($userid) && empty($groupid)) {
1784 debugging('Either userid or groupid must be provided');
1785 return false;
1788 if ($userid && !record_exists('user', 'id', $userid)) {
1789 debugging('User ID '.intval($userid).' does not exist!');
1790 return false;
1793 if ($groupid && !record_exists('groups', 'id', $groupid)) {
1794 debugging('Group ID '.intval($groupid).' does not exist!');
1795 return false;
1798 if (!$context = get_context_instance_by_id($contextid)) {
1799 debugging('Context ID '.intval($contextid).' does not exist!');
1800 return false;
1803 if (($timestart and $timeend) and ($timestart > $timeend)) {
1804 debugging('The end time can not be earlier than the start time');
1805 return false;
1809 /// Check for existing entry
1810 if ($userid) {
1811 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id, 'userid', $userid);
1812 } else {
1813 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id, 'groupid', $groupid);
1817 $newra = new object;
1819 if (empty($ra)) { // Create a new entry
1820 $newra->roleid = $roleid;
1821 $newra->contextid = $context->id;
1822 $newra->userid = $userid;
1823 $newra->groupid = $groupid;
1825 $newra->hidden = $hidden;
1826 $newra->enrol = $enrol;
1827 $newra->timestart = $timestart;
1828 $newra->timeend = $timeend;
1829 $newra->timemodified = time();
1830 $newra->modifier = empty($USER->id) ? 0 : $USER->id;
1832 $success = insert_record('role_assignments', $newra);
1834 } else { // We already have one, just update it
1836 $newra->id = $ra->id;
1837 $newra->hidden = $hidden;
1838 $newra->enrol = $enrol;
1839 $newra->timestart = $timestart;
1840 $newra->timeend = $timeend;
1841 $newra->timemodified = time();
1842 $newra->modifier = empty($USER->id) ? 0 : $USER->id;
1844 $success = update_record('role_assignments', $newra);
1847 if ($success) { /// Role was assigned, so do some other things
1849 /// If the user is the current user, then reload the capabilities too.
1850 if (!empty($USER->id) && $USER->id == $userid) {
1851 load_all_capabilities();
1854 /// Ask all the modules if anything needs to be done for this user
1855 if ($mods = get_list_of_plugins('mod')) {
1856 foreach ($mods as $mod) {
1857 include_once($CFG->dirroot.'/mod/'.$mod.'/lib.php');
1858 $functionname = $mod.'_role_assign';
1859 if (function_exists($functionname)) {
1860 $functionname($userid, $context);
1865 /// Make sure they have an entry in user_lastaccess for courses they can access
1866 // role_add_lastaccess_entries($userid, $context);
1869 /// now handle metacourse role assignments if in course context
1870 if ($success and $context->contextlevel == CONTEXT_COURSE) {
1871 if ($parents = get_records('course_meta', 'child_course', $context->instanceid)) {
1872 foreach ($parents as $parent) {
1873 sync_metacourse($parent->parent_course);
1878 return $success;
1883 * Deletes one or more role assignments. You must specify at least one parameter.
1884 * @param $roleid
1885 * @param $userid
1886 * @param $groupid
1887 * @param $contextid
1888 * @return boolean - success or failure
1890 function role_unassign($roleid=0, $userid=0, $groupid=0, $contextid=0) {
1892 global $USER, $CFG;
1894 $success = true;
1896 $args = array('roleid', 'userid', 'groupid', 'contextid');
1897 $select = array();
1898 foreach ($args as $arg) {
1899 if ($$arg) {
1900 $select[] = $arg.' = '.$$arg;
1904 if ($select) {
1905 if ($ras = get_records_select('role_assignments', implode(' AND ', $select))) {
1906 $mods = get_list_of_plugins('mod');
1907 foreach($ras as $ra) {
1908 /// infinite loop protection when deleting recursively
1909 if (!$ra = get_record('role_assignments', 'id', $ra->id)) {
1910 continue;
1912 $success = delete_records('role_assignments', 'id', $ra->id) and $success;
1914 /// If the user is the current user, then reload the capabilities too.
1915 if (!empty($USER->id) && $USER->id == $ra->userid) {
1916 load_all_capabilities();
1918 $context = get_record('context', 'id', $ra->contextid);
1920 /// Ask all the modules if anything needs to be done for this user
1921 foreach ($mods as $mod) {
1922 include_once($CFG->dirroot.'/mod/'.$mod.'/lib.php');
1923 $functionname = $mod.'_role_unassign';
1924 if (function_exists($functionname)) {
1925 $functionname($ra->userid, $context); // watch out, $context might be NULL if something goes wrong
1929 /// now handle metacourse role unassigment and removing from goups if in course context
1930 if (!empty($context) and $context->contextlevel == CONTEXT_COURSE) {
1931 //remove from groups when user has no role
1932 $roles = get_user_roles($context, $ra->userid, true);
1933 if (empty($roles)) {
1934 if ($groups = get_groups($context->instanceid, $ra->userid)) {
1935 foreach ($groups as $group) {
1936 delete_records('groups_members', 'groupid', $group->id, 'userid', $ra->userid);
1940 //unassign roles in metacourses if needed
1941 if ($parents = get_records('course_meta', 'child_course', $context->instanceid)) {
1942 foreach ($parents as $parent) {
1943 sync_metacourse($parent->parent_course);
1951 return $success;
1955 * A convenience function to take care of the common case where you
1956 * just want to enrol someone using the default role into a course
1958 * @param object $course
1959 * @param object $user
1960 * @param string $enrol - the plugin used to do this enrolment
1962 function enrol_into_course($course, $user, $enrol) {
1964 if ($course->enrolperiod) {
1965 $timestart = time();
1966 $timeend = time() + $course->enrolperiod;
1967 } else {
1968 $timestart = $timeend = 0;
1971 if ($role = get_default_course_role($course)) {
1973 $context = get_context_instance(CONTEXT_COURSE, $course->id);
1975 if (!role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, $enrol)) {
1976 return false;
1979 email_welcome_message_to_user($course, $user);
1981 add_to_log($course->id, 'course', 'enrol', 'view.php?id='.$course->id, $user->id);
1983 return true;
1986 return false;
1990 * Add last access times to user_lastaccess as required
1991 * @param $userid
1992 * @param $context
1993 * @return boolean - success or failure
1995 function role_add_lastaccess_entries($userid, $context) {
1997 global $USER, $CFG;
1999 if (empty($context->contextlevel)) {
2000 return false;
2003 $lastaccess = new object; // Reusable object below
2004 $lastaccess->userid = $userid;
2005 $lastaccess->timeaccess = 0;
2007 switch ($context->contextlevel) {
2009 case CONTEXT_SYSTEM: // For the whole site
2010 if ($courses = get_record('course')) {
2011 foreach ($courses as $course) {
2012 $lastaccess->courseid = $course->id;
2013 role_set_lastaccess($lastaccess);
2016 break;
2018 case CONTEXT_CATEGORY: // For a whole category
2019 if ($courses = get_record('course', 'category', $context->instanceid)) {
2020 foreach ($courses as $course) {
2021 $lastaccess->courseid = $course->id;
2022 role_set_lastaccess($lastaccess);
2025 if ($categories = get_record('course_categories', 'parent', $context->instanceid)) {
2026 foreach ($categories as $category) {
2027 $subcontext = get_context_instance(CONTEXT_CATEGORY, $category->id);
2028 role_add_lastaccess_entries($userid, $subcontext);
2031 break;
2034 case CONTEXT_COURSE: // For a whole course
2035 if ($course = get_record('course', 'id', $context->instanceid)) {
2036 $lastaccess->courseid = $course->id;
2037 role_set_lastaccess($lastaccess);
2039 break;
2044 * Delete last access times from user_lastaccess as required
2045 * @param $userid
2046 * @param $context
2047 * @return boolean - success or failure
2049 function role_remove_lastaccess_entries($userid, $context) {
2051 global $USER, $CFG;
2057 * Loads the capability definitions for the component (from file). If no
2058 * capabilities are defined for the component, we simply return an empty array.
2059 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2060 * @return array of capabilities
2062 function load_capability_def($component) {
2063 global $CFG;
2065 if ($component == 'moodle') {
2066 $defpath = $CFG->libdir.'/db/access.php';
2067 $varprefix = 'moodle';
2068 } else {
2069 $compparts = explode('/', $component);
2071 if ($compparts[0] == 'block') {
2072 // Blocks are an exception. Blocks directory is 'blocks', and not
2073 // 'block'. So we need to jump through hoops.
2074 $defpath = $CFG->dirroot.'/'.$compparts[0].
2075 's/'.$compparts[1].'/db/access.php';
2076 $varprefix = $compparts[0].'_'.$compparts[1];
2077 } else {
2078 $defpath = $CFG->dirroot.'/'.$component.'/db/access.php';
2079 $varprefix = str_replace('/', '_', $component);
2082 $capabilities = array();
2084 if (file_exists($defpath)) {
2085 require_once($defpath);
2086 $capabilities = ${$varprefix.'_capabilities'};
2088 return $capabilities;
2093 * Gets the capabilities that have been cached in the database for this
2094 * component.
2095 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2096 * @return array of capabilities
2098 function get_cached_capabilities($component='moodle') {
2099 if ($component == 'moodle') {
2100 $storedcaps = get_records_select('capabilities',
2101 "name LIKE 'moodle/%:%'");
2102 } else {
2103 $storedcaps = get_records_select('capabilities',
2104 "name LIKE '$component:%'");
2106 return $storedcaps;
2111 * Updates the capabilities table with the component capability definitions.
2112 * If no parameters are given, the function updates the core moodle
2113 * capabilities.
2115 * Note that the absence of the db/access.php capabilities definition file
2116 * will cause any stored capabilities for the component to be removed from
2117 * the database.
2119 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2120 * @return boolean
2122 function update_capabilities($component='moodle') {
2124 $storedcaps = array();
2126 $filecaps = load_capability_def($component);
2127 $cachedcaps = get_cached_capabilities($component);
2128 if ($cachedcaps) {
2129 foreach ($cachedcaps as $cachedcap) {
2130 array_push($storedcaps, $cachedcap->name);
2131 // update risk bitmasks in existing capabilities if needed
2132 if (array_key_exists($cachedcap->name, $filecaps)) {
2133 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2134 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
2136 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
2137 $updatecap = new object;
2138 $updatecap->id = $cachedcap->id;
2139 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2140 if (!update_record('capabilities', $updatecap)) {
2141 return false;
2148 // Are there new capabilities in the file definition?
2149 $newcaps = array();
2151 foreach ($filecaps as $filecap => $def) {
2152 if (!$storedcaps ||
2153 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2154 if (!array_key_exists('riskbitmask', $def)) {
2155 $def['riskbitmask'] = 0; // no risk if not specified
2157 $newcaps[$filecap] = $def;
2160 // Add new capabilities to the stored definition.
2161 foreach ($newcaps as $capname => $capdef) {
2162 $capability = new object;
2163 $capability->name = $capname;
2164 $capability->captype = $capdef['captype'];
2165 $capability->contextlevel = $capdef['contextlevel'];
2166 $capability->component = $component;
2167 $capability->riskbitmask = $capdef['riskbitmask'];
2169 if (!insert_record('capabilities', $capability, false, 'id')) {
2170 return false;
2173 // Do we need to assign the new capabilities to roles that have the
2174 // legacy capabilities moodle/legacy:* as well?
2175 if (isset($capdef['legacy']) && is_array($capdef['legacy']) &&
2176 !assign_legacy_capabilities($capname, $capdef['legacy'])) {
2177 notify('Could not assign legacy capabilities for '.$capname);
2180 // Are there any capabilities that have been removed from the file
2181 // definition that we need to delete from the stored capabilities and
2182 // role assignments?
2183 capabilities_cleanup($component, $filecaps);
2185 return true;
2190 * Deletes cached capabilities that are no longer needed by the component.
2191 * Also unassigns these capabilities from any roles that have them.
2192 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2193 * @param $newcapdef - array of the new capability definitions that will be
2194 * compared with the cached capabilities
2195 * @return int - number of deprecated capabilities that have been removed
2197 function capabilities_cleanup($component, $newcapdef=NULL) {
2199 $removedcount = 0;
2201 if ($cachedcaps = get_cached_capabilities($component)) {
2202 foreach ($cachedcaps as $cachedcap) {
2203 if (empty($newcapdef) ||
2204 array_key_exists($cachedcap->name, $newcapdef) === false) {
2206 // Remove from capabilities cache.
2207 if (!delete_records('capabilities', 'name', $cachedcap->name)) {
2208 error('Could not delete deprecated capability '.$cachedcap->name);
2209 } else {
2210 $removedcount++;
2212 // Delete from roles.
2213 if($roles = get_roles_with_capability($cachedcap->name)) {
2214 foreach($roles as $role) {
2215 if (!unassign_capability($cachedcap->name, $role->id)) {
2216 error('Could not unassign deprecated capability '.
2217 $cachedcap->name.' from role '.$role->name);
2221 } // End if.
2224 return $removedcount;
2229 /****************
2230 * UI FUNCTIONS *
2231 ****************/
2235 * prints human readable context identifier.
2237 function print_context_name($context) {
2239 $name = '';
2240 switch ($context->contextlevel) {
2242 case CONTEXT_SYSTEM: // by now it's a definite an inherit
2243 $name = get_string('site');
2244 break;
2246 case CONTEXT_PERSONAL:
2247 $name = get_string('personal');
2248 break;
2250 case CONTEXT_USER:
2251 if ($user = get_record('user', 'id', $context->instanceid)) {
2252 $name = get_string('user').': '.fullname($user);
2254 break;
2256 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
2257 if ($category = get_record('course_categories', 'id', $context->instanceid)) {
2258 $name = get_string('category').': '.$category->name;
2260 break;
2262 case CONTEXT_COURSE: // 1 to 1 to course cat
2263 if ($course = get_record('course', 'id', $context->instanceid)) {
2264 $name = get_string('course').': '.$course->fullname;
2266 break;
2268 case CONTEXT_GROUP: // 1 to 1 to course
2269 if ($group = get_record('groups', 'id', $context->instanceid)) {
2270 $name = get_string('group').': '.$group->name;
2272 break;
2274 case CONTEXT_MODULE: // 1 to 1 to course
2275 if ($cm = get_record('course_modules','id',$context->instanceid)) {
2276 if ($module = get_record('modules','id',$cm->module)) {
2277 if ($mod = get_record($module->name, 'id', $cm->instance)) {
2278 $name = get_string('activitymodule').': '.$mod->name;
2282 break;
2284 case CONTEXT_BLOCK: // 1 to 1 to course
2285 if ($blockinstance = get_record('block_instance','id',$context->instanceid)) {
2286 if ($block = get_record('block','id',$blockinstance->blockid)) {
2287 global $CFG;
2288 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
2289 require_once("$CFG->dirroot/blocks/$block->name/block_$block->name.php");
2290 $blockname = "block_$block->name";
2291 if ($blockobject = new $blockname()) {
2292 $name = $blockobject->title.' ('.get_string('block').')';
2296 break;
2298 default:
2299 error ('This is an unknown context!');
2300 return false;
2303 return $name;
2308 * Extracts the relevant capabilities given a contextid.
2309 * All case based, example an instance of forum context.
2310 * Will fetch all forum related capabilities, while course contexts
2311 * Will fetch all capabilities
2312 * @param object context
2313 * @return array();
2315 * capabilities
2316 * `name` varchar(150) NOT NULL,
2317 * `captype` varchar(50) NOT NULL,
2318 * `contextlevel` int(10) NOT NULL,
2319 * `component` varchar(100) NOT NULL,
2321 function fetch_context_capabilities($context) {
2323 global $CFG;
2325 $sort = 'ORDER BY contextlevel,component,id'; // To group them sensibly for display
2327 switch ($context->contextlevel) {
2329 case CONTEXT_SYSTEM: // all
2330 $SQL = "select * from {$CFG->prefix}capabilities";
2331 break;
2333 case CONTEXT_PERSONAL:
2334 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_PERSONAL;
2335 break;
2337 case CONTEXT_USER:
2338 $SQL = "SELECT *
2339 FROM {$CFG->prefix}capabilities
2340 WHERE contextlevel = ".CONTEXT_USER;
2341 break;
2343 case CONTEXT_COURSECAT: // all
2344 $SQL = "select * from {$CFG->prefix}capabilities";
2345 break;
2347 case CONTEXT_COURSE: // all
2348 $SQL = "select * from {$CFG->prefix}capabilities";
2349 break;
2351 case CONTEXT_GROUP: // group caps
2352 break;
2354 case CONTEXT_MODULE: // mod caps
2355 $cm = get_record('course_modules', 'id', $context->instanceid);
2356 $module = get_record('modules', 'id', $cm->module);
2358 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_MODULE."
2359 and component = 'mod/$module->name'";
2360 break;
2362 case CONTEXT_BLOCK: // block caps
2363 $cb = get_record('block_instance', 'id', $context->instanceid);
2364 $block = get_record('block', 'id', $cb->blockid);
2366 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_BLOCK."
2367 and component = 'block/$block->name'";
2368 break;
2370 default:
2371 return false;
2374 if (!$records = get_records_sql($SQL.' '.$sort)) {
2375 $records = array();
2378 /// the rest of code is a bit hacky, think twice before modifying it :-(
2380 // special sorting of core system capabiltites and enrollments
2381 if (in_array($context->contextlevel, array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE))) {
2382 $first = array();
2383 foreach ($records as $key=>$record) {
2384 if (preg_match('|^moodle/|', $record->name) and $record->contextlevel == CONTEXT_SYSTEM) {
2385 $first[$key] = $record;
2386 unset($records[$key]);
2387 } else if (count($first)){
2388 break;
2391 if (count($first)) {
2392 $records = $first + $records; // merge the two arrays keeping the keys
2394 } else {
2395 $contextindependentcaps = fetch_context_independent_capabilities();
2396 $records = array_merge($contextindependentcaps, $records);
2399 return $records;
2405 * Gets the context-independent capabilities that should be overrridable in
2406 * any context.
2407 * @return array of capability records from the capabilities table.
2409 function fetch_context_independent_capabilities() {
2411 //only CONTEXT_SYSTEM capabilities here or it will break the hack in fetch_context_capabilities()
2412 $contextindependentcaps = array(
2413 'moodle/site:accessallgroups'
2416 $records = array();
2418 foreach ($contextindependentcaps as $capname) {
2419 $record = get_record('capabilities', 'name', $capname);
2420 array_push($records, $record);
2422 return $records;
2427 * This function pulls out all the resolved capabilities (overrides and
2428 * defaults) of a role used in capability overrides in contexts at a given
2429 * context.
2430 * @param obj $context
2431 * @param int $roleid
2432 * @param bool self - if set to true, resolve till this level, else stop at immediate parent level
2433 * @return array
2435 function role_context_capabilities($roleid, $context, $cap='') {
2436 global $CFG;
2438 $contexts = get_parent_contexts($context);
2439 $contexts[] = $context->id;
2440 $contexts = '('.implode(',', $contexts).')';
2442 if ($cap) {
2443 $search = " AND rc.capability = '$cap' ";
2444 } else {
2445 $search = '';
2448 $SQL = "SELECT rc.*
2449 FROM {$CFG->prefix}role_capabilities rc,
2450 {$CFG->prefix}context c
2451 WHERE rc.contextid in $contexts
2452 AND rc.roleid = $roleid
2453 AND rc.contextid = c.id $search
2454 ORDER BY c.contextlevel DESC,
2455 rc.capability DESC";
2457 $capabilities = array();
2459 if ($records = get_records_sql($SQL)) {
2460 // We are traversing via reverse order.
2461 foreach ($records as $record) {
2462 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2463 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2464 $capabilities[$record->capability] = $record->permission;
2468 return $capabilities;
2472 * Recursive function which, given a context, find all parent context ids,
2473 * and return the array in reverse order, i.e. parent first, then grand
2474 * parent, etc.
2475 * @param object $context
2476 * @return array()
2478 function get_parent_contexts($context) {
2480 switch ($context->contextlevel) {
2482 case CONTEXT_SYSTEM: // no parent
2483 return array();
2484 break;
2486 case CONTEXT_PERSONAL:
2487 if (!$parent = get_context_instance(CONTEXT_SYSTEM)) {
2488 return array();
2489 } else {
2490 return array($parent->id);
2492 break;
2494 case CONTEXT_USER:
2495 if (!$parent = get_context_instance(CONTEXT_SYSTEM)) {
2496 return array();
2497 } else {
2498 return array($parent->id);
2500 break;
2502 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
2503 if (!$coursecat = get_record('course_categories','id',$context->instanceid)) {
2504 return array();
2506 if (!empty($coursecat->parent)) { // return parent value if exist
2507 $parent = get_context_instance(CONTEXT_COURSECAT, $coursecat->parent);
2508 return array_merge(array($parent->id), get_parent_contexts($parent));
2509 } else { // else return site value
2510 $parent = get_context_instance(CONTEXT_SYSTEM);
2511 return array($parent->id);
2513 break;
2515 case CONTEXT_COURSE: // 1 to 1 to course cat
2516 if (!$course = get_record('course','id',$context->instanceid)) {
2517 return array();
2519 if (!empty($course->category)) {
2520 $parent = get_context_instance(CONTEXT_COURSECAT, $course->category);
2521 return array_merge(array($parent->id), get_parent_contexts($parent));
2522 } else {
2523 return array();
2525 break;
2527 case CONTEXT_GROUP: // 1 to 1 to course
2528 if (!$group = get_record('groups','id',$context->instanceid)) {
2529 return array();
2531 if ($parent = get_context_instance(CONTEXT_COURSE, $group->courseid)) {
2532 return array_merge(array($parent->id), get_parent_contexts($parent));
2533 } else {
2534 return array();
2536 break;
2538 case CONTEXT_MODULE: // 1 to 1 to course
2539 if (!$cm = get_record('course_modules','id',$context->instanceid)) {
2540 return array();
2542 if ($parent = get_context_instance(CONTEXT_COURSE, $cm->course)) {
2543 return array_merge(array($parent->id), get_parent_contexts($parent));
2544 } else {
2545 return array();
2547 break;
2549 case CONTEXT_BLOCK: // 1 to 1 to course
2550 if (!$block = get_record('block_instance','id',$context->instanceid)) {
2551 return array();
2553 if ($parent = get_context_instance(CONTEXT_COURSE, $block->pageid)) {
2554 return array_merge(array($parent->id), get_parent_contexts($parent));
2555 } else {
2556 return array();
2558 break;
2560 default:
2561 error('This is an unknown context!');
2562 return false;
2568 * Gets a string for sql calls, searching for stuff in this context or above
2569 * @param object $context
2570 * @return string
2572 function get_related_contexts_string($context) {
2573 if ($parents = get_parent_contexts($context)) {
2574 return (' IN ('.$context->id.','.implode(',', $parents).')');
2575 } else {
2576 return (' ='.$context->id);
2582 * This function gets the capability of a role in a given context.
2583 * It is needed when printing override forms.
2584 * @param int $contextid
2585 * @param string $capability
2586 * @param array $capabilities - array loaded using role_context_capabilities
2587 * @return int (allow, prevent, prohibit, inherit)
2589 function get_role_context_capability($contextid, $capability, $capabilities) {
2590 if (isset($capabilities[$contextid][$capability])) {
2591 return $capabilities[$contextid][$capability];
2593 else {
2594 return false;
2600 * Returns the human-readable, translated version of the capability.
2601 * Basically a big switch statement.
2602 * @param $capabilityname - e.g. mod/choice:readresponses
2604 function get_capability_string($capabilityname) {
2606 // Typical capabilityname is mod/choice:readresponses
2608 $names = split('/', $capabilityname);
2609 $stringname = $names[1]; // choice:readresponses
2610 $components = split(':', $stringname);
2611 $componentname = $components[0]; // choice
2613 switch ($names[0]) {
2614 case 'mod':
2615 $string = get_string($stringname, $componentname);
2616 break;
2618 case 'block':
2619 $string = get_string($stringname, 'block_'.$componentname);
2620 break;
2622 case 'moodle':
2623 $string = get_string($stringname, 'role');
2624 break;
2626 case 'enrol':
2627 $string = get_string($stringname, 'enrol_'.$componentname);
2628 break;
2630 default:
2631 $string = get_string($stringname);
2632 break;
2635 return $string;
2640 * This gets the mod/block/course/core etc strings.
2641 * @param $component
2642 * @param $contextlevel
2644 function get_component_string($component, $contextlevel) {
2646 switch ($contextlevel) {
2648 case CONTEXT_SYSTEM:
2649 if (preg_match('|^enrol/|', $component)) {
2650 $langname = str_replace('/', '_', $component);
2651 $string = get_string('enrolname', $langname);
2652 } else if (preg_match('|^block/|', $component)) {
2653 $langname = str_replace('/', '_', $component);
2654 $string = get_string('blockname', $langname);
2655 } else {
2656 $string = get_string('coresystem');
2658 break;
2660 case CONTEXT_PERSONAL:
2661 $string = get_string('personal');
2662 break;
2664 case CONTEXT_USER:
2665 $string = get_string('users');
2666 break;
2668 case CONTEXT_COURSECAT:
2669 $string = get_string('categories');
2670 break;
2672 case CONTEXT_COURSE:
2673 $string = get_string('course');
2674 break;
2676 case CONTEXT_GROUP:
2677 $string = get_string('group');
2678 break;
2680 case CONTEXT_MODULE:
2681 $string = get_string('modulename', basename($component));
2682 break;
2684 case CONTEXT_BLOCK:
2685 $string = get_string('blockname', 'block_'.$component.'.php');
2686 break;
2688 default:
2689 error ('This is an unknown context!');
2690 return false;
2693 return $string;
2697 * Gets the list of roles assigned to this context and up (parents)
2698 * @param object $context
2699 * @return array
2701 function get_roles_used_in_context($context) {
2703 global $CFG;
2704 $contextlist = get_related_contexts_string($context);
2706 $sql = "SELECT DISTINCT r.id,
2707 r.name,
2708 r.shortname,
2709 r.sortorder
2710 FROM {$CFG->prefix}role_assignments ra,
2711 {$CFG->prefix}role r
2712 WHERE r.id = ra.roleid
2713 AND ra.contextid $contextlist
2714 ORDER BY r.sortorder ASC";
2716 return get_records_sql($sql);
2719 /** this function is used to print roles column in user profile page.
2720 * @param int userid
2721 * @param int contextid
2722 * @return string
2724 function get_user_roles_in_context($userid, $contextid){
2725 global $CFG;
2727 $rolestring = '';
2728 $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';
2729 if ($roles = get_records_sql($SQL)) {
2730 foreach ($roles as $userrole) {
2731 $rolestring .= '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$userrole->contextid.'&amp;roleid='.$userrole->roleid.'">'.$userrole->name.'</a>, ';
2735 return rtrim($rolestring, ', ');
2740 * Checks if a user can override capabilities of a particular role in this context
2741 * @param object $context
2742 * @param int targetroleid - the id of the role you want to override
2743 * @return boolean
2745 function user_can_override($context, $targetroleid) {
2746 // first check if user has override capability
2747 // if not return false;
2748 if (!has_capability('moodle/role:override', $context)) {
2749 return false;
2751 // pull out all active roles of this user from this context(or above)
2752 if ($userroles = get_user_roles($context)) {
2753 foreach ($userroles as $userrole) {
2754 // if any in the role_allow_override table, then it's ok
2755 if (get_record('role_allow_override', 'roleid', $userrole->roleid, 'allowoverride', $targetroleid)) {
2756 return true;
2761 return false;
2766 * Checks if a user can assign users to a particular role in this context
2767 * @param object $context
2768 * @param int targetroleid - the id of the role you want to assign users to
2769 * @return boolean
2771 function user_can_assign($context, $targetroleid) {
2773 // first check if user has override capability
2774 // if not return false;
2775 if (!has_capability('moodle/role:assign', $context)) {
2776 return false;
2778 // pull out all active roles of this user from this context(or above)
2779 if ($userroles = get_user_roles($context)) {
2780 foreach ($userroles as $userrole) {
2781 // if any in the role_allow_override table, then it's ok
2782 if (get_record('role_allow_assign', 'roleid', $userrole->roleid, 'allowassign', $targetroleid)) {
2783 return true;
2788 return false;
2791 /** Returns all site roles in correct sort order.
2794 function get_all_roles() {
2795 return get_records('role', '', '', 'sortorder ASC');
2799 * gets all the user roles assigned in this context, or higher contexts
2800 * this is mainly used when checking if a user can assign a role, or overriding a role
2801 * i.e. we need to know what this user holds, in order to verify against allow_assign and
2802 * allow_override tables
2803 * @param object $context
2804 * @param int $userid
2805 * @return array
2807 function get_user_roles($context, $userid=0, $checkparentcontexts=true) {
2809 global $USER, $CFG, $db;
2811 if (empty($userid)) {
2812 if (empty($USER->id)) {
2813 return array();
2815 $userid = $USER->id;
2818 if ($checkparentcontexts && ($parents = get_parent_contexts($context))) {
2819 $contexts = ' ra.contextid IN ('.implode(',' , $parents).','.$context->id.')';
2820 } else {
2821 $contexts = ' ra.contextid = \''.$context->id.'\'';
2824 return get_records_sql('SELECT ra.*, r.name, r.shortname
2825 FROM '.$CFG->prefix.'role_assignments ra,
2826 '.$CFG->prefix.'role r,
2827 '.$CFG->prefix.'context c
2828 WHERE ra.userid = '.$userid.
2829 ' AND ra.roleid = r.id
2830 AND ra.contextid = c.id
2831 AND '.$contexts.
2832 ' ORDER BY c.contextlevel DESC, r.sortorder ASC');
2836 * Creates a record in the allow_override table
2837 * @param int sroleid - source roleid
2838 * @param int troleid - target roleid
2839 * @return int - id or false
2841 function allow_override($sroleid, $troleid) {
2842 $record = new object();
2843 $record->roleid = $sroleid;
2844 $record->allowoverride = $troleid;
2845 return insert_record('role_allow_override', $record);
2849 * Creates a record in the allow_assign table
2850 * @param int sroleid - source roleid
2851 * @param int troleid - target roleid
2852 * @return int - id or false
2854 function allow_assign($sroleid, $troleid) {
2855 $record = new object;
2856 $record->roleid = $sroleid;
2857 $record->allowassign = $troleid;
2858 return insert_record('role_allow_assign', $record);
2862 * Gets a list of roles that this user can assign in this context
2863 * @param object $context
2864 * @return array
2866 function get_assignable_roles ($context, $field="name") {
2868 $options = array();
2870 if ($roles = get_all_roles()) {
2871 foreach ($roles as $role) {
2872 if (user_can_assign($context, $role->id)) {
2873 $options[$role->id] = strip_tags(format_string($role->{$field}, true));
2877 return $options;
2881 * Gets a list of roles that this user can override in this context
2882 * @param object $context
2883 * @return array
2885 function get_overridable_roles ($context) {
2887 $options = array();
2889 if ($roles = get_all_roles()) {
2890 foreach ($roles as $role) {
2891 if (user_can_override($context, $role->id)) {
2892 $options[$role->id] = strip_tags(format_string($role->name, true));
2897 return $options;
2901 * Returns a role object that is the default role for new enrolments
2902 * in a given course
2904 * @param object $course
2905 * @return object $role
2907 function get_default_course_role($course) {
2908 global $CFG;
2910 /// First let's take the default role the course may have
2911 if (!empty($course->defaultrole)) {
2912 if ($role = get_record('role', 'id', $course->defaultrole)) {
2913 return $role;
2917 /// Otherwise the site setting should tell us
2918 if ($CFG->defaultcourseroleid) {
2919 if ($role = get_record('role', 'id', $CFG->defaultcourseroleid)) {
2920 return $role;
2924 /// It's unlikely we'll get here, but just in case, try and find a student role
2925 if ($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW)) {
2926 return array_shift($studentroles); /// Take the first one
2929 return NULL;
2934 * who has this capability in this context
2935 * does not handling user level resolving!!!
2936 * i.e 1 person has 2 roles 1 allow, 1 prevent, this will not work properly
2937 * @param $context - object
2938 * @param $capability - string capability
2939 * @param $fields - fields to be pulled
2940 * @param $sort - the sort order
2941 * @param $limitfrom - number of records to skip (offset)
2942 * @param $limitnum - number of records to fetch
2943 * @param $groups - single group or array of groups - group(s) user is in
2944 * @param $exceptions - list of users to exclude
2946 function get_users_by_capability($context, $capability, $fields='', $sort='',
2947 $limitfrom='', $limitnum='', $groups='', $exceptions='', $doanything=true) {
2948 global $CFG;
2950 /// Sorting out groups
2951 if ($groups) {
2952 $groupjoin = 'INNER JOIN '.$CFG->prefix.'groups_members gm ON gm.userid = ra.userid';
2954 if (is_array($groups)) {
2955 $groupsql = 'AND gm.groupid IN ('.implode(',', $groups).')';
2956 } else {
2957 $groupsql = 'AND gm.groupid = '.$groups;
2959 } else {
2960 $groupjoin = '';
2961 $groupsql = '';
2964 /// Sorting out exceptions
2965 $exceptionsql = $exceptions ? "AND u.id NOT IN ($exceptions)" : '';
2967 /// Set up default fields
2968 if (empty($fields)) {
2969 $fields = 'u.*, ul.timeaccess as lastaccess, ra.hidden';
2972 /// Set up default sort
2973 if (empty($sort)) {
2974 $sort = 'ul.timeaccess';
2977 $sortby = $sort ? " ORDER BY $sort " : '';
2979 /// If context is a course, then construct sql for ul
2980 if ($context->contextlevel == CONTEXT_COURSE) {
2981 $courseid = $context->instanceid;
2982 $coursesql = "AND (ul.courseid = $courseid OR ul.courseid IS NULL)";
2983 } else {
2984 $coursesql = '';
2987 /// Sorting out roles with this capability set
2988 if ($possibleroles = get_roles_with_capability($capability, CAP_ALLOW, $context)) {
2989 if (!$doanything) {
2990 if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM)) {
2991 return false; // Something is seriously wrong
2993 $doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, $sitecontext);
2996 $validroleids = array();
2997 foreach ($possibleroles as $possiblerole) {
2998 if (!$doanything) {
2999 if (isset($doanythingroles[$possiblerole->id])) { // We don't want these included
3000 continue;
3003 if ($caps = role_context_capabilities($possiblerole->id, $context, $capability)) { // resolved list
3004 if (isset($caps[$capability]) && $caps[$capability] > 0) { // resolved capability > 0
3005 $validroleids[] = $possiblerole->id;
3009 if (empty($validroleids)) {
3010 return false;
3012 $roleids = '('.implode(',', $validroleids).')';
3013 } else {
3014 return false; // No need to continue, since no roles have this capability set
3017 /// Construct the main SQL
3018 $select = " SELECT $fields";
3019 $from = " FROM {$CFG->prefix}user u
3020 INNER JOIN {$CFG->prefix}role_assignments ra ON ra.userid = u.id
3021 INNER JOIN {$CFG->prefix}role r ON r.id = ra.roleid
3022 LEFT OUTER JOIN {$CFG->prefix}user_lastaccess ul ON ul.userid = u.id
3023 $groupjoin";
3024 $where = " WHERE ra.contextid ".get_related_contexts_string($context)."
3025 AND u.deleted = 0
3026 AND ra.roleid in $roleids
3027 $exceptionsql
3028 $coursesql
3029 $groupsql";
3031 return get_records_sql($select.$from.$where.$sortby, $limitfrom, $limitnum);
3035 * gets all the users assigned this role in this context or higher
3036 * @param int roleid
3037 * @param int contextid
3038 * @param bool parent if true, get list of users assigned in higher context too
3039 * @return array()
3041 function get_role_users($roleid, $context, $parent=false, $fields='', $sort='u.lastname ASC') {
3042 global $CFG;
3044 if (empty($fields)) {
3045 $fields = 'u.id, u.confirmed, u.username, u.firstname, u.lastname, '.
3046 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.city, '.
3047 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
3048 'u.emailstop, u.lang, u.timezone';
3051 if ($parent) {
3052 if ($contexts = get_parent_contexts($context)) {
3053 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
3054 } else {
3055 $parentcontexts = '';
3057 } else {
3058 $parentcontexts = '';
3061 if ($roleid) {
3062 $roleselect = "AND r.roleid = $roleid";
3063 } else {
3064 $roleselect = '';
3067 $SQL = "SELECT $fields
3068 FROM {$CFG->prefix}role_assignments r,
3069 {$CFG->prefix}user u
3070 WHERE (r.contextid = $context->id $parentcontexts)
3071 AND u.id = r.userid $roleselect
3072 ORDER BY $sort
3073 "; // join now so that we can just use fullname() later
3075 return get_records_sql($SQL);
3079 * Counts all the users assigned this role in this context or higher
3080 * @param int roleid
3081 * @param int contextid
3082 * @param bool parent if true, get list of users assigned in higher context too
3083 * @return array()
3085 function count_role_users($roleid, $context, $parent=false) {
3086 global $CFG;
3088 if ($parent) {
3089 if ($contexts = get_parent_contexts($context)) {
3090 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
3091 } else {
3092 $parentcontexts = '';
3094 } else {
3095 $parentcontexts = '';
3098 $SQL = "SELECT count(*)
3099 FROM {$CFG->prefix}role_assignments r
3100 WHERE (r.contextid = $context->id $parentcontexts)
3101 AND r.roleid = $roleid";
3103 return count_records_sql($SQL);
3107 * This function gets the list of courses that this user has a particular capability in
3108 * This is not the most efficient way of doing this
3109 * @param string capability
3110 * @param int $userid
3111 * @return array
3113 function get_user_capability_course($capability, $userid='') {
3115 global $USER;
3116 if (!$userid) {
3117 $userid = $USER->id;
3120 $usercourses = array();
3121 $courses = get_records_select('course', '', '', 'id, id');
3123 foreach ($courses as $course) {
3124 if (has_capability($capability, get_context_instance(CONTEXT_COURSE, $course->id))) {
3125 $usercourses[] = $course;
3128 return $usercourses;
3132 /** This function finds the roles assigned directly to this context only
3133 * i.e. no parents role
3134 * @param object $context
3135 * @return array
3137 function get_roles_on_exact_context($context) {
3139 global $CFG;
3141 return get_records_sql("SELECT r.*
3142 FROM {$CFG->prefix}role_assignments ra,
3143 {$CFG->prefix}role r
3144 WHERE ra.roleid = r.id
3145 AND ra.contextid = $context->id");
3150 * Switches the current user to another role for the current session and only
3151 * in the given context. If roleid is not valid (eg 0) or the current user
3152 * doesn't have permissions to be switching roles then the user's session
3153 * is compltely reset to have their normal roles.
3154 * @param integer $roleid
3155 * @param object $context
3156 * @return bool
3158 function role_switch($roleid, $context) {
3159 global $USER;
3161 global $db;
3163 /// If we can't use this or are already using it or no role was specified then bail completely and reset
3164 if (empty($roleid) || !has_capability('moodle/role:switchroles', $context)
3165 || !empty($USER->switchrole[$context->id]) || !confirm_sesskey()) {
3166 load_user_capability('', $context); // Reset all permissions for this context to normal
3167 unset($USER->switchrole[$context->id]); // Delete old capabilities
3168 return true;
3171 /// We're allowed to switch but can we switch to the specified role? Use assignable roles to check.
3172 if (!$roles = get_assignable_roles($context)) {
3173 return false;
3176 if (empty($roles[$roleid])) { /// We can't switch to this particular role
3177 return false;
3180 if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM)) {
3181 return false;
3184 /// We have a valid roleid that this user can switch to, so let's set up the session
3186 $USER->switchrole[$context->id] = $roleid; // So we know later what state we are in
3188 unset($USER->capabilities[$context->id]); // Delete old capabilities
3190 if ($capabilities = get_records_select('role_capabilities', "roleid = $roleid AND contextid = $sitecontext->id")) {
3191 foreach ($capabilities as $capability) {
3192 $USER->capabilities[$context->id][$capability->capability] = $capability->permission;
3196 /// Add some permissions we are really going to always need, even if the role doesn't have them!
3198 $USER->capabilities[$context->id]['moodle/course:view'] = CAP_ALLOW;
3200 return true;
3205 // get any role that has an override on exact context
3206 function get_roles_with_override_on_context($context) {
3208 global $CFG;
3210 return get_records_sql("SELECT r.*
3211 FROM {$CFG->prefix}role_capabilities rc,
3212 {$CFG->prefix}role r
3213 WHERE rc.roleid = r.id
3214 AND rc.contextid = $context->id");
3217 // get all capabilities for this role on this context (overrids)
3218 function get_capabilities_from_role_on_context($role, $context) {
3220 global $CFG;
3222 return get_records_sql("SELECT *
3223 FROM {$CFG->prefix}role_capabilities
3224 WHERE contextid = $context->id
3225 AND roleid = $role->id");
3228 // find out which roles has assignment on this context
3229 function get_roles_with_assignment_on_context($context) {
3231 global $CFG;
3233 return get_records_sql("SELECT r.*
3234 FROM {$CFG->prefix}role_assignments ra,
3235 {$CFG->prefix}role r
3236 WHERE ra.roleid = r.id
3237 AND ra.contextid = $context->id");
3242 /* find all user assignemnt of users for this role, on this context
3244 function get_users_from_role_on_context($role, $context) {
3246 global $CFG;
3248 return get_records_sql("SELECT *
3249 FROM {$CFG->prefix}role_assignments
3250 WHERE contextid = $context->id
3251 AND roleid = $role->id");
3255 * Simple function returning a boolean true if roles exist, otherwise false
3257 function user_has_role_assignment($userid, $roleid, $contextid=0) {
3259 if ($contextid) {
3260 return record_exists('role_assignments', 'userid', $userid, 'roleid', $roleid, 'contextid', $contextid);
3261 } else {
3262 return record_exists('role_assignments', 'userid', $userid, 'roleid', $roleid);