MDL-10689:
[moodle-linuxchix.git] / lib / accesslib.php
blob7bc3f9ad1d23f86da649a8e80f5ab7be168fbb30
1 <?php // $Id$
3 ///////////////////////////////////////////////////////////////////////////
4 // //
5 // NOTICE OF COPYRIGHT //
6 // //
7 // Moodle - Modular Object-Oriented Dynamic Learning Environment //
8 // http://moodle.org //
9 // //
10 // Copyright (C) 1999-2004 Martin Dougiamas http://dougiamas.com //
11 // //
12 // This program is free software; you can redistribute it and/or modify //
13 // it under the terms of the GNU General Public License as published by //
14 // the Free Software Foundation; either version 2 of the License, or //
15 // (at your option) any later version. //
16 // //
17 // This program is distributed in the hope that it will be useful, //
18 // but WITHOUT ANY WARRANTY; without even the implied warranty of //
19 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
20 // GNU General Public License for more details: //
21 // //
22 // http://www.gnu.org/copyleft/gpl.html //
23 // //
24 ///////////////////////////////////////////////////////////////////////////
26 /**
27 * Capability session information format
28 * 2 x 2 array
29 * [context][capability]
30 * where context is the context id of the table 'context'
31 * and capability is a string defining the capability
32 * e.g.
34 * [Capabilities] => [26][mod/forum:viewpost] = 1
35 * [26][mod/forum:startdiscussion] = -8990
36 * [26][mod/forum:editallpost] = -1
37 * [273][moodle:blahblah] = 1
38 * [273][moodle:blahblahblah] = 2
41 require_once $CFG->dirroot.'/lib/blocklib.php';
43 // permission definitions
44 define('CAP_INHERIT', 0);
45 define('CAP_ALLOW', 1);
46 define('CAP_PREVENT', -1);
47 define('CAP_PROHIBIT', -1000);
49 // context definitions
50 define('CONTEXT_SYSTEM', 10);
51 define('CONTEXT_PERSONAL', 20);
52 define('CONTEXT_USER', 30);
53 define('CONTEXT_COURSECAT', 40);
54 define('CONTEXT_COURSE', 50);
55 define('CONTEXT_GROUP', 60);
56 define('CONTEXT_MODULE', 70);
57 define('CONTEXT_BLOCK', 80);
59 // capability risks - see http://docs.moodle.org/en/Hardening_new_Roles_system
60 define('RISK_MANAGETRUST', 0x0001);
61 define('RISK_CONFIG', 0x0002);
62 define('RISK_XSS', 0x0004);
63 define('RISK_PERSONAL', 0x0008);
64 define('RISK_SPAM', 0x0010);
66 require_once($CFG->dirroot.'/group/lib.php');
68 $context_cache = array(); // Cache of all used context objects for performance (by level and instance)
69 $context_cache_id = array(); // Index to above cache by id
72 function get_role_context_caps($roleid, $context) {
73 //this is really slow!!!! - do not use above course context level!
74 $result = array();
75 $result[$context->id] = array();
77 // first emulate the parent context capabilities merging into context
78 $searchcontexts = array_reverse(get_parent_contexts($context));
79 array_push($searchcontexts, $context->id);
80 foreach ($searchcontexts as $cid) {
81 if ($capabilities = get_records_select('role_capabilities', "roleid = $roleid AND contextid = $cid")) {
82 foreach ($capabilities as $cap) {
83 if (!array_key_exists($cap->capability, $result[$context->id])) {
84 $result[$context->id][$cap->capability] = 0;
86 $result[$context->id][$cap->capability] += $cap->permission;
91 // now go through the contexts bellow given context
92 $searchcontexts = get_child_contexts($context);
93 foreach ($searchcontexts as $cid) {
94 if ($capabilities = get_records_select('role_capabilities', "roleid = $roleid AND contextid = $cid")) {
95 foreach ($capabilities as $cap) {
96 if (!array_key_exists($cap->contextid, $result)) {
97 $result[$cap->contextid] = array();
99 $result[$cap->contextid][$cap->capability] = $cap->permission;
104 return $result;
107 function get_role_caps($roleid) {
108 $result = array();
109 if ($capabilities = get_records_select('role_capabilities',"roleid = $roleid")) {
110 foreach ($capabilities as $cap) {
111 if (!array_key_exists($cap->contextid, $result)) {
112 $result[$cap->contextid] = array();
114 $result[$cap->contextid][$cap->capability] = $cap->permission;
117 return $result;
120 function merge_role_caps($caps, $mergecaps) {
121 if (empty($mergecaps)) {
122 return $caps;
125 if (empty($caps)) {
126 return $mergecaps;
129 foreach ($mergecaps as $contextid=>$capabilities) {
130 if (!array_key_exists($contextid, $caps)) {
131 $caps[$contextid] = array();
133 foreach ($capabilities as $capability=>$permission) {
134 if (!array_key_exists($capability, $caps[$contextid])) {
135 $caps[$contextid][$capability] = 0;
137 $caps[$contextid][$capability] += $permission;
140 return $caps;
144 * Loads the capabilities for the default guest role to the current user in a
145 * specific context.
146 * @return object
148 function load_guest_role($return=false) {
149 global $USER;
151 static $guestrole = false;
153 if ($guestrole === false) {
154 if (!$guestrole = get_guest_role()) {
155 return false;
159 if ($return) {
160 return get_role_caps($guestrole->id);
161 } else {
162 has_capability('clearcache');
163 $USER->capabilities = get_role_caps($guestrole->id);
164 return true;
169 * Load default not logged in role capabilities when user is not logged in
170 * @return bool
172 function load_notloggedin_role($return=false) {
173 global $CFG, $USER;
175 if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM)) {
176 return false;
179 if (empty($CFG->notloggedinroleid)) { // Let's set the default to the guest role
180 if ($role = get_guest_role()) {
181 set_config('notloggedinroleid', $role->id);
182 } else {
183 return false;
187 if ($return) {
188 return get_role_caps($CFG->notloggedinroleid);
189 } else {
190 has_capability('clearcache');
191 $USER->capabilities = get_role_caps($CFG->notloggedinroleid);
192 return true;
197 * Load default logged in role capabilities for all logged in users
198 * @return bool
200 function load_defaultuser_role($return=false) {
201 global $CFG, $USER;
203 if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM)) {
204 return false;
207 if (empty($CFG->defaultuserroleid)) { // Let's set the default to the guest role
208 if ($role = get_guest_role()) {
209 set_config('defaultuserroleid', $role->id);
210 } else {
211 return false;
215 $capabilities = get_role_caps($CFG->defaultuserroleid);
217 // fix the guest user heritage:
218 // If the default role is a guest role, then don't copy legacy:guest,
219 // otherwise this user could get confused with a REAL guest. Also don't copy
220 // course:view, which is a hack that's necessary because guest roles are
221 // not really handled properly (see MDL-7513)
222 if (!empty($capabilities[$sitecontext->id]['moodle/legacy:guest'])) {
223 unset($capabilities[$sitecontext->id]['moodle/legacy:guest']);
224 unset($capabilities[$sitecontext->id]['moodle/course:view']);
227 if ($return) {
228 return $capabilities;
229 } else {
230 has_capability('clearcache');
231 $USER->capabilities = $capabilities;
232 return true;
238 * Get the default guest role
239 * @return object role
241 function get_guest_role() {
242 global $CFG;
244 if (empty($CFG->guestroleid)) {
245 if ($roles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW)) {
246 $guestrole = array_shift($roles); // Pick the first one
247 set_config('guestroleid', $guestrole->id);
248 return $guestrole;
249 } else {
250 debugging('Can not find any guest role!');
251 return false;
253 } else {
254 if ($guestrole = get_record('role','id', $CFG->guestroleid)) {
255 return $guestrole;
256 } else {
257 //somebody is messing with guest roles, remove incorrect setting and try to find a new one
258 set_config('guestroleid', '');
259 return get_guest_role();
266 * This functions get all the course categories in proper order
267 * (!)note this only gets course category contexts, and not the site
268 * context
269 * @param object $context
270 * @param int $type
271 * @return array of contextids
273 function get_parent_cats($context, $type) {
275 $parents = array();
277 switch ($type) {
278 // a category can be the parent of another category
279 // there is no limit of depth in this case
280 case CONTEXT_COURSECAT:
281 if (!$cat = get_record('course_categories','id',$context->instanceid)) {
282 break;
285 while (!empty($cat->parent)) {
286 if (!$context = get_context_instance(CONTEXT_COURSECAT, $cat->parent)) {
287 break;
289 $parents[] = $context->id;
290 $cat = get_record('course_categories','id',$cat->parent);
292 break;
294 // a course always fall into a category, unless it's a site course
295 // this happens when SITEID == $course->id
296 // in this case the parent of the course is site context
297 case CONTEXT_COURSE:
298 if (!$course = get_record('course', 'id', $context->instanceid)) {
299 break;
301 if (!$catinstance = get_context_instance(CONTEXT_COURSECAT, $course->category)) {
302 break;
305 $parents[] = $catinstance->id;
307 if (!$cat = get_record('course_categories','id',$course->category)) {
308 break;
310 // Yu: Separating site and site course context
311 if ($course->id == SITEID) {
312 break;
315 while (!empty($cat->parent)) {
316 if (!$context = get_context_instance(CONTEXT_COURSECAT, $cat->parent)) {
317 break;
319 $parents[] = $context->id;
320 $cat = get_record('course_categories','id',$cat->parent);
322 break;
324 default:
325 break;
327 return array_reverse($parents);
333 * This function checks for a capability assertion being true. If it isn't
334 * then the page is terminated neatly with a standard error message
335 * @param string $capability - name of the capability
336 * @param object $context - a context object (record from context table)
337 * @param integer $userid - a userid number
338 * @param bool $doanything - if false, ignore do anything
339 * @param string $errorstring - an errorstring
340 * @param string $stringfile - which stringfile to get it from
342 function require_capability($capability, $context=NULL, $userid=NULL, $doanything=true,
343 $errormessage='nopermissions', $stringfile='') {
345 global $USER, $CFG;
347 /// If the current user is not logged in, then make sure they are (if needed)
349 if (empty($userid) and empty($USER->capabilities)) {
350 if ($context && ($context->contextlevel == CONTEXT_COURSE)) {
351 require_login($context->instanceid);
352 } else if ($context && ($context->contextlevel == CONTEXT_MODULE)) {
353 if ($cm = get_record('course_modules','id',$context->instanceid)) {
354 if (!$course = get_record('course', 'id', $cm->course)) {
355 error('Incorrect course.');
357 require_course_login($course, true, $cm);
359 } else {
360 require_login();
362 } else if ($context && ($context->contextlevel == CONTEXT_SYSTEM)) {
363 if (!empty($CFG->forcelogin)) {
364 require_login();
367 } else {
368 require_login();
372 /// OK, if they still don't have the capability then print a nice error message
374 if (!has_capability($capability, $context, $userid, $doanything)) {
375 $capabilityname = get_capability_string($capability);
376 print_error($errormessage, $stringfile, '', $capabilityname);
382 * This function returns whether the current user has the capability of performing a function
383 * For example, we can do has_capability('mod/forum:replypost',$context) in forum
384 * This is a recursive function.
385 * @uses $USER
386 * @param string $capability - name of the capability (or debugcache or clearcache)
387 * @param object $context - a context object (record from context table)
388 * @param integer $userid - a userid number
389 * @param bool $doanything - if false, ignore do anything
390 * @return bool
392 function has_capability($capability, $context=NULL, $userid=NULL, $doanything=true) {
394 global $USER, $CONTEXT, $CFG;
396 static $capcache = array(); // Cache of capabilities
399 /// Cache management
401 if ($capability == 'clearcache') {
402 $capcache = array(); // Clear ALL the capability cache
403 return false;
406 /// Some sanity checks
407 if (debugging('',DEBUG_DEVELOPER)) {
408 if ($capability == 'debugcache') {
409 print_object($capcache);
410 return true;
412 if (!record_exists('capabilities', 'name', $capability)) {
413 debugging('Capability "'.$capability.'" was not found! This should be fixed in code.');
415 if ($doanything != true and $doanything != false) {
416 debugging('Capability parameter "doanything" is wierd ("'.$doanything.'"). This should be fixed in code.');
418 if (!is_object($context) && $context !== NULL) {
419 debugging('Incorrect context parameter "'.$context.'" for has_capability(), object expected! This should be fixed in code.');
423 /// Make sure we know the current context
424 if (empty($context)) { // Use default CONTEXT if none specified
425 if (empty($CONTEXT)) {
426 return false;
427 } else {
428 $context = $CONTEXT;
430 } else { // A context was given to us
431 if (empty($CONTEXT)) {
432 $CONTEXT = $context; // Store FIRST used context in this global as future default
436 /// Check and return cache in case we've processed this one before.
437 $requsteduser = empty($userid) ? $USER->id : $userid; // find out the requested user id, $USER->id might have been changed
438 $cachekey = $capability.'_'.$context->id.'_'.intval($requsteduser).'_'.intval($doanything);
440 if (isset($capcache[$cachekey])) {
441 return $capcache[$cachekey];
445 /// Load up the capabilities list or item as necessary
446 if ($userid) {
447 if (empty($USER->id) or ($userid != $USER->id) or empty($USER->capabilities)) {
449 //caching - helps user switching in cron
450 static $guestuserid = false; // guest user id
451 static $guestcaps = false; // guest caps
452 static $defcaps = false; // default user caps - this might help cron
454 if ($guestuserid === false) {
455 $guestuserid = get_field('user', 'id', 'username', 'guest');
458 if ($userid == $guestuserid) {
459 if ($guestcaps === false) {
460 $guestcaps = load_guest_role(true);
462 $capabilities = $guestcaps;
464 } else {
465 // This big SQL is expensive! We reduce it a little by avoiding checking for changed enrolments (false)
466 $capabilities = load_user_capability($capability, $context, $userid, false);
467 if ($defcaps === false) {
468 $defcaps = load_defaultuser_role(true);
470 $capabilities = merge_role_caps($capabilities, $defcaps);
473 } else { //$USER->id == $userid and needed capabilities already present
474 $capabilities = $USER->capabilities;
477 } else { // no userid
478 if (empty($USER->capabilities)) {
479 load_all_capabilities(); // expensive - but we have to do it once anyway
481 $capabilities = $USER->capabilities;
482 $userid = $USER->id;
485 /// We act a little differently when switchroles is active
487 $switchroleactive = false; // Assume it isn't active in this context
490 /// First deal with the "doanything" capability
492 if ($doanything) {
494 /// First make sure that we aren't in a "switched role"
496 if (!empty($USER->switchrole)) { // Switchrole is active somewhere!
497 if (!empty($USER->switchrole[$context->id])) { // Because of current context
498 $switchroleactive = true;
499 } else { // Check parent contexts
500 if ($parentcontextids = get_parent_contexts($context)) {
501 foreach ($parentcontextids as $parentcontextid) {
502 if (!empty($USER->switchrole[$parentcontextid])) { // Yep, switchroles active here
503 $switchroleactive = true;
504 break;
511 /// Check the site context for doanything (most common) first
513 if (empty($switchroleactive)) { // Ignore site setting if switchrole is active
514 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
515 if (isset($capabilities[$sitecontext->id]['moodle/site:doanything'])) {
516 $result = (0 < $capabilities[$sitecontext->id]['moodle/site:doanything']);
517 $capcache[$cachekey] = $result;
518 return $result;
521 /// If it's not set at site level, it is possible to be set on other levels
522 /// Though this usage is not common and can cause risks
523 switch ($context->contextlevel) {
525 case CONTEXT_COURSECAT:
526 // Check parent cats.
527 $parentcats = get_parent_cats($context, CONTEXT_COURSECAT);
528 foreach ($parentcats as $parentcat) {
529 if (isset($capabilities[$parentcat]['moodle/site:doanything'])) {
530 $result = (0 < $capabilities[$parentcat]['moodle/site:doanything']);
531 $capcache[$cachekey] = $result;
532 return $result;
535 break;
537 case CONTEXT_COURSE:
538 // Check parent cat.
539 $parentcats = get_parent_cats($context, CONTEXT_COURSE);
541 foreach ($parentcats as $parentcat) {
542 if (isset($capabilities[$parentcat]['do_anything'])) {
543 $result = (0 < $capabilities[$parentcat]['do_anything']);
544 $capcache[$cachekey] = $result;
545 return $result;
548 break;
550 case CONTEXT_GROUP:
551 // Find course.
552 $courseid = get_field('groups', 'courseid', 'id', $context->instanceid);
553 $courseinstance = get_context_instance(CONTEXT_COURSE, $courseid);
555 $parentcats = get_parent_cats($courseinstance, CONTEXT_COURSE);
556 foreach ($parentcats as $parentcat) {
557 if (isset($capabilities[$parentcat]['do_anything'])) {
558 $result = (0 < $capabilities[$parentcat]['do_anything']);
559 $capcache[$cachekey] = $result;
560 return $result;
564 $coursecontext = '';
565 if (isset($capabilities[$courseinstance->id]['do_anything'])) {
566 $result = (0 < $capabilities[$courseinstance->id]['do_anything']);
567 $capcache[$cachekey] = $result;
568 return $result;
571 break;
573 case CONTEXT_MODULE:
574 // Find course.
575 $cm = get_record('course_modules', 'id', $context->instanceid);
576 $courseinstance = get_context_instance(CONTEXT_COURSE, $cm->course);
578 if ($parentcats = get_parent_cats($courseinstance, CONTEXT_COURSE)) {
579 foreach ($parentcats as $parentcat) {
580 if (isset($capabilities[$parentcat]['do_anything'])) {
581 $result = (0 < $capabilities[$parentcat]['do_anything']);
582 $capcache[$cachekey] = $result;
583 return $result;
588 if (isset($capabilities[$courseinstance->id]['do_anything'])) {
589 $result = (0 < $capabilities[$courseinstance->id]['do_anything']);
590 $capcache[$cachekey] = $result;
591 return $result;
594 break;
596 case CONTEXT_BLOCK:
597 // not necessarily 1 to 1 to course.
598 $block = get_record('block_instance','id',$context->instanceid);
599 if ($block->pagetype == 'course-view') {
600 $courseinstance = get_context_instance(CONTEXT_COURSE, $block->pageid); // needs check
601 $parentcats = get_parent_cats($courseinstance, CONTEXT_COURSE);
603 foreach ($parentcats as $parentcat) {
604 if (isset($capabilities[$parentcat]['do_anything'])) {
605 $result = (0 < $capabilities[$parentcat]['do_anything']);
606 $capcache[$cachekey] = $result;
607 return $result;
611 if (isset($capabilities[$courseinstance->id]['do_anything'])) {
612 $result = (0 < $capabilities[$courseinstance->id]['do_anything']);
613 $capcache[$cachekey] = $result;
614 return $result;
616 } else { // if not course-view type of blocks, check site
617 if (isset($capabilities[$sitecontext->id]['do_anything'])) {
618 $result = (0 < $capabilities[$sitecontext->id]['do_anything']);
619 $capcache[$cachekey] = $result;
620 return $result;
623 break;
625 default:
626 // CONTEXT_SYSTEM: CONTEXT_PERSONAL: CONTEXT_USER:
627 // Do nothing, because the parents are site context
628 // which has been checked already
629 break;
632 // Last: check self.
633 if (isset($capabilities[$context->id]['do_anything'])) {
634 $result = (0 < $capabilities[$context->id]['do_anything']);
635 $capcache[$cachekey] = $result;
636 return $result;
639 // do_anything has not been set, we now look for it the normal way.
640 $result = (0 < capability_search($capability, $context, $capabilities, $switchroleactive));
641 $capcache[$cachekey] = $result;
642 return $result;
648 * In a separate function so that we won't have to deal with do_anything.
649 * again. Used by function has_capability().
650 * @param $capability - capability string
651 * @param $context - the context object
652 * @param $capabilities - either $USER->capability or loaded array (for other users)
653 * @return permission (int)
655 function capability_search($capability, $context, $capabilities, $switchroleactive=false) {
657 global $USER, $CFG;
659 if (!isset($context->id)) {
660 return 0;
662 // if already set in the array explicitly, no need to look for it in parent
663 // context any longer
664 if (isset($capabilities[$context->id][$capability])) {
665 return ($capabilities[$context->id][$capability]);
668 /* Then, we check the cache recursively */
669 $permission = 0;
671 switch ($context->contextlevel) {
673 case CONTEXT_SYSTEM: // by now it's a definite an inherit
674 $permission = 0;
675 break;
677 case CONTEXT_PERSONAL:
678 $parentcontext = get_context_instance(CONTEXT_SYSTEM);
679 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
680 break;
682 case CONTEXT_USER:
683 $parentcontext = get_context_instance(CONTEXT_SYSTEM);
684 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
685 break;
687 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
688 $coursecat = get_record('course_categories','id',$context->instanceid);
689 if (!empty($coursecat->parent)) { // return parent value if it exists
690 $parentcontext = get_context_instance(CONTEXT_COURSECAT, $coursecat->parent);
691 } else { // else return site value
692 $parentcontext = get_context_instance(CONTEXT_SYSTEM);
694 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
695 break;
697 case CONTEXT_COURSE: // 1 to 1 to course cat
698 if (empty($switchroleactive)) {
699 // find the course cat, and return its value
700 $course = get_record('course','id',$context->instanceid);
701 if ($course->id == SITEID) { // In 1.8 we've separated site course and system
702 $parentcontext = get_context_instance(CONTEXT_SYSTEM);
703 } else {
704 $parentcontext = get_context_instance(CONTEXT_COURSECAT, $course->category);
706 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
708 break;
710 case CONTEXT_GROUP: // 1 to 1 to course
711 $courseid = get_field('groups', 'courseid', 'id', $context->instanceid);
712 $parentcontext = get_context_instance(CONTEXT_COURSE, $courseid);
713 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
714 break;
716 case CONTEXT_MODULE: // 1 to 1 to course
717 $cm = get_record('course_modules','id',$context->instanceid);
718 $parentcontext = get_context_instance(CONTEXT_COURSE, $cm->course);
719 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
720 break;
722 case CONTEXT_BLOCK: // not necessarily 1 to 1 to course
723 $block = get_record('block_instance','id',$context->instanceid);
724 if ($block->pagetype == 'course-view') {
725 $parentcontext = get_context_instance(CONTEXT_COURSE, $block->pageid); // needs check
726 } else {
727 $parentcontext = get_context_instance(CONTEXT_SYSTEM);
729 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
730 break;
732 default:
733 error ('This is an unknown context (' . $context->contextlevel . ') in capability_search!');
734 return false;
737 return $permission;
741 * auxillary function for load_user_capabilities()
742 * checks if context c1 is a parent (or itself) of context c2
743 * @param int $c1 - context id of context 1
744 * @param int $c2 - context id of context 2
745 * @return bool
747 function is_parent_context($c1, $c2) {
748 static $parentsarray;
750 // context can be itself and this is ok
751 if ($c1 == $c2) {
752 return true;
754 // hit in cache?
755 if (isset($parentsarray[$c1][$c2])) {
756 return $parentsarray[$c1][$c2];
759 if (!$co2 = get_record('context', 'id', $c2)) {
760 return false;
763 if (!$parents = get_parent_contexts($co2)) {
764 return false;
767 foreach ($parents as $parent) {
768 $parentsarray[$parent][$c2] = true;
771 if (in_array($c1, $parents)) {
772 return true;
773 } else { // else not a parent, set the cache anyway
774 $parentsarray[$c1][$c2] = false;
775 return false;
781 * auxillary function for load_user_capabilities()
782 * handler in usort() to sort contexts according to level
783 * @param object contexta
784 * @param object contextb
785 * @return int
787 function roles_context_cmp($contexta, $contextb) {
788 if ($contexta->contextlevel == $contextb->contextlevel) {
789 return 0;
791 return ($contexta->contextlevel < $contextb->contextlevel) ? -1 : 1;
795 * It will build an array of all the capabilities at each level
796 * i.e. site/metacourse/course_category/course/moduleinstance
797 * Note we should only load capabilities if they are explicitly assigned already,
798 * we should not load all module's capability!
800 * [Capabilities] => [26][forum_post] = 1
801 * [26][forum_start] = -8990
802 * [26][forum_edit] = -1
803 * [273][blah blah] = 1
804 * [273][blah blah blah] = 2
806 * @param $capability string - Only get a specific capability (string)
807 * @param $context object - Only get capabilities for a specific context object
808 * @param $userid integer - the id of the user whose capabilities we want to load
809 * @param $checkenrolments boolean - Should we check enrolment plugins (potentially expensive)
810 * @return array of permissions (or nothing if they get assigned to $USER)
812 function load_user_capability($capability='', $context=NULL, $userid=NULL, $checkenrolments=true) {
814 global $USER, $CFG;
816 // this flag has not been set!
817 // (not clean install, or upgraded successfully to 1.7 and up)
818 if (empty($CFG->rolesactive)) {
819 return false;
822 if (empty($userid)) {
823 if (empty($USER->id)) { // We have no user to get capabilities for
824 debugging('User not logged in for load_user_capability!');
825 return false;
827 unset($USER->capabilities); // We don't want possible older capabilites hanging around
829 if ($checkenrolments) { // Call "enrol" system to ensure that we have the correct picture
830 check_enrolment_plugins($USER);
833 $userid = $USER->id;
834 $otheruserid = false;
835 } else {
836 if (!$user = get_record('user', 'id', $userid)) {
837 debugging('Non-existent userid in load_user_capability!');
838 return false;
841 if ($checkenrolments) { // Call "enrol" system to ensure that we have the correct picture
842 check_enrolment_plugins($user);
845 $otheruserid = $userid;
849 /// First we generate a list of all relevant contexts of the user
851 $usercontexts = array();
853 if ($context) { // if context is specified
854 $usercontexts = get_parent_contexts($context);
855 $usercontexts[] = $context->id; // Add the current context as well
856 } else { // else, we load everything
857 if ($userroles = get_records('role_assignments','userid',$userid)) {
858 foreach ($userroles as $userrole) {
859 if (!in_array($userrole->contextid, $usercontexts)) {
860 $usercontexts[] = $userrole->contextid;
866 /// Set up SQL fragments for searching contexts
868 if ($usercontexts) {
869 $listofcontexts = '('.implode(',', $usercontexts).')';
870 $searchcontexts1 = "c1.id IN $listofcontexts AND";
871 } else {
872 $searchcontexts1 = '';
875 if ($capability) {
876 // the doanything may override the requested capability
877 $capsearch = " AND (rc.capability = '$capability' OR rc.capability = 'moodle/site:doanything') ";
878 } else {
879 $capsearch ="";
882 /// Then we use 1 giant SQL to bring out all relevant capabilities.
883 /// The first part gets the capabilities of orginal role.
884 /// The second part gets the capabilities of overriden roles.
886 $siteinstance = get_context_instance(CONTEXT_SYSTEM);
887 $capabilities = array(); // Reinitialize.
889 // SQL for normal capabilities
890 $SQL1 = "SELECT rc.capability, c1.id as id1, c1.id as id2, (c1.contextlevel * 100) AS aggrlevel,
891 SUM(rc.permission) AS sum
892 FROM
893 {$CFG->prefix}role_assignments ra,
894 {$CFG->prefix}role_capabilities rc,
895 {$CFG->prefix}context c1
896 WHERE
897 ra.contextid=c1.id AND
898 ra.roleid=rc.roleid AND
899 ra.userid=$userid AND
900 $searchcontexts1
901 rc.contextid=$siteinstance->id
902 $capsearch
903 GROUP BY
904 rc.capability, c1.id, c1.contextlevel * 100
905 HAVING
906 SUM(rc.permission) != 0
908 UNION ALL
910 SELECT rc.capability, c1.id as id1, c2.id as id2, (c1.contextlevel * 100 + c2.contextlevel) AS aggrlevel,
911 SUM(rc.permission) AS sum
912 FROM
913 {$CFG->prefix}role_assignments ra INNER JOIN
914 {$CFG->prefix}role_capabilities rc on ra.roleid = rc.roleid INNER JOIN
915 {$CFG->prefix}context c1 on ra.contextid = c1.id INNER JOIN
916 {$CFG->prefix}context c2 on rc.contextid = c2.id INNER JOIN
917 {$CFG->prefix}context_rel cr on cr.c1 = c2.id AND cr.c2 = c1.id
918 WHERE
919 ra.userid=$userid AND
920 $searchcontexts1
921 rc.contextid != $siteinstance->id
922 $capsearch
923 GROUP BY
924 rc.capability, c1.id, c2.id, c1.contextlevel * 100 + c2.contextlevel
925 HAVING
926 SUM(rc.permission) != 0
927 ORDER BY
928 aggrlevel ASC";
930 if (!$rs = get_recordset_sql($SQL1)) {
931 error("Query failed in load_user_capability.");
934 if ($rs && $rs->RecordCount() > 0) {
935 while ($caprec = rs_fetch_next_record($rs)) {
936 $array = (array)$caprec;
937 $temprecord = new object;
939 foreach ($array as $key=>$val) {
940 if ($key == 'aggrlevel') {
941 $temprecord->contextlevel = $val;
942 } else {
943 $temprecord->{$key} = $val;
946 $capabilities[] = $temprecord;
948 rs_close($rs);
951 // SQL for overrides
952 // this is take out because we have no way of making sure c1 is indeed related to c2 (parent)
953 // if we do not group by sum, it is possible to have multiple records of rc.capability, c1.id, c2.id, tuple having
954 // different values, we can maually sum it when we go through the list
958 $SQL2 = "SELECT rc.capability, c1.id as id1, c2.id as id2, (c1.contextlevel * 100 + c2.contextlevel) AS aggrlevel,
959 rc.permission AS sum
960 FROM
961 {$CFG->prefix}role_assignments ra,
962 {$CFG->prefix}role_capabilities rc,
963 {$CFG->prefix}context c1,
964 {$CFG->prefix}context c2
965 WHERE
966 ra.contextid=c1.id AND
967 ra.roleid=rc.roleid AND
968 ra.userid=$userid AND
969 rc.contextid=c2.id AND
970 $searchcontexts1
971 rc.contextid != $siteinstance->id
972 $capsearch
974 GROUP BY
975 rc.capability, (c1.contextlevel * 100 + c2.contextlevel), c1.id, c2.id, rc.permission
976 ORDER BY
977 aggrlevel ASC
978 ";*/
981 if (!$rs = get_recordset_sql($SQL2)) {
982 error("Query failed in load_user_capability.");
985 if ($rs && $rs->RecordCount() > 0) {
986 while ($caprec = rs_fetch_next_record($rs)) {
987 $array = (array)$caprec;
988 $temprecord = new object;
990 foreach ($array as $key=>$val) {
991 if ($key == 'aggrlevel') {
992 $temprecord->contextlevel = $val;
993 } else {
994 $temprecord->{$key} = $val;
997 // for overrides, we have to make sure that context2 is a child of context1
998 // otherwise the combination makes no sense
999 //if (is_parent_context($temprecord->id1, $temprecord->id2)) {
1000 $capabilities[] = $temprecord;
1001 //} // only write if relevant
1003 rs_close($rs);
1006 // this step sorts capabilities according to the contextlevel
1007 // it is very important because the order matters when we
1008 // go through each capabilities later. (i.e. higher level contextlevel
1009 // will override lower contextlevel settings
1010 usort($capabilities, 'roles_context_cmp');
1012 /* so up to this point we should have somethign like this
1013 * $capabilities[1] ->contextlevel = 1000
1014 ->module = 0 // changed from SITEID in 1.8 (??)
1015 ->capability = do_anything
1016 ->id = 1 (id is the context id)
1017 ->sum = 0
1019 * $capabilities[2] ->contextlevel = 1000
1020 ->module = 0 // changed from SITEID in 1.8 (??)
1021 ->capability = post_messages
1022 ->id = 1
1023 ->sum = -9000
1025 * $capabilittes[3] ->contextlevel = 3000
1026 ->module = course
1027 ->capability = view_course_activities
1028 ->id = 25
1029 ->sum = 1
1031 * $capabilittes[4] ->contextlevel = 3000
1032 ->module = course
1033 ->capability = view_course_activities
1034 ->id = 26
1035 ->sum = 0 (this is another course)
1037 * $capabilities[5] ->contextlevel = 3050
1038 ->module = course
1039 ->capability = view_course_activities
1040 ->id = 25 (override in course 25)
1041 ->sum = -1
1042 * ....
1043 * now we proceed to write the session array, going from top to bottom
1044 * at anypoint, we need to go up and check parent to look for prohibit
1046 // print_object($capabilities);
1048 /* This is where we write to the actualy capabilities array
1049 * what we need to do from here on is
1050 * going down the array from lowest level to highest level
1051 * 1) recursively check for prohibit,
1052 * if any, we write prohibit
1053 * else, we write the value
1054 * 2) at an override level, we overwrite current level
1055 * if it's not set to prohibit already, and if different
1056 * ........ that should be it ........
1059 // This is the flag used for detecting the current context level. Since we are going through
1060 // the array in ascending order of context level. For normal capabilities, there should only
1061 // be 1 value per (capability, contextlevel, context), because they are already summed. But,
1062 // for overrides, since we are processing them separate, we need to sum the relevcant entries.
1063 // We set this flag when we hit a new level.
1064 // If the flag is already set, we keep adding (summing), otherwise, we just override previous
1065 // settings (from lower level contexts)
1066 $capflags = array(); // (contextid, contextlevel, capability)
1067 $usercap = array(); // for other user's capabilities
1068 foreach ($capabilities as $capability) {
1070 if (!$context = get_context_instance_by_id($capability->id2)) {
1071 continue; // incorrect stale context
1074 if (!empty($otheruserid)) { // we are pulling out other user's capabilities, do not write to session
1076 if (capability_prohibits($capability->capability, $context, $capability->sum, $usercap)) {
1077 $usercap[$capability->id2][$capability->capability] = CAP_PROHIBIT;
1078 continue;
1080 if (isset($usercap[$capability->id2][$capability->capability])) { // use isset because it can be sum 0
1081 if (!empty($capflags[$capability->id2][$capability->contextlevel][$capability->capability])) {
1082 $usercap[$capability->id2][$capability->capability] += $capability->sum;
1083 } else { // else we override, and update flag
1084 $usercap[$capability->id2][$capability->capability] = $capability->sum;
1085 $capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
1087 } else {
1088 $usercap[$capability->id2][$capability->capability] = $capability->sum;
1089 $capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
1092 } else {
1094 if (capability_prohibits($capability->capability, $context, $capability->sum)) { // if any parent or parent's parent is set to prohibit
1095 $USER->capabilities[$capability->id2][$capability->capability] = CAP_PROHIBIT;
1096 continue;
1099 // if no parental prohibit set
1100 // just write to session, i am not sure this is correct yet
1101 // since 3050 shows up after 3000, and 3070 shows up after 3050,
1102 // it should be ok just to overwrite like this, provided that there's no
1103 // parental prohibits
1104 // we need to write even if it's 0, because it could be an inherit override
1105 if (isset($USER->capabilities[$capability->id2][$capability->capability])) {
1106 if (!empty($capflags[$capability->id2][$capability->contextlevel][$capability->capability])) {
1107 $USER->capabilities[$capability->id2][$capability->capability] += $capability->sum;
1108 } else { // else we override, and update flag
1109 $USER->capabilities[$capability->id2][$capability->capability] = $capability->sum;
1110 $capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
1112 } else {
1113 $USER->capabilities[$capability->id2][$capability->capability] = $capability->sum;
1114 $capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
1119 // now we don't care about the huge array anymore, we can dispose it.
1120 unset($capabilities);
1121 unset($capflags);
1123 if (!empty($otheruserid)) {
1124 return $usercap; // return the array
1130 * A convenience function to completely load all the capabilities
1131 * for the current user. This is what gets called from login, for example.
1133 function load_all_capabilities() {
1134 global $USER;
1136 //caching - helps user switching in cron
1137 static $defcaps = false;
1139 unset($USER->mycourses); // Reset a cache used by get_my_courses
1141 if (isguestuser()) {
1142 load_guest_role(); // All non-guest users get this by default
1144 } else if (isloggedin()) {
1145 if ($defcaps === false) {
1146 $defcaps = load_defaultuser_role(true);
1149 load_user_capability();
1151 // when in "course login as" - load only course caqpabilitites (it may not always work as expected)
1152 if (!empty($USER->realuser) and $USER->loginascontext->contextlevel != CONTEXT_SYSTEM) {
1153 $children = get_child_contexts($USER->loginascontext);
1154 $children[] = $USER->loginascontext->id;
1155 foreach ($USER->capabilities as $conid => $caps) {
1156 if (!in_array($conid, $children)) {
1157 unset($USER->capabilities[$conid]);
1162 // handle role switching in courses
1163 if (!empty($USER->switchrole)) {
1164 foreach ($USER->switchrole as $contextid => $roleid) {
1165 $context = get_context_instance_by_id($contextid);
1167 // first prune context and any child contexts
1168 $children = get_child_contexts($context);
1169 foreach ($children as $childid) {
1170 unset($USER->capabilities[$childid]);
1172 unset($USER->capabilities[$contextid]);
1174 // now merge all switched role caps in context and bellow
1175 $swithccaps = get_role_context_caps($roleid, $context);
1176 $USER->capabilities = merge_role_caps($USER->capabilities, $swithccaps);
1180 if (isset($USER->capabilities)) {
1181 $USER->capabilities = merge_role_caps($USER->capabilities, $defcaps);
1182 } else {
1183 $USER->capabilities = $defcaps;
1186 } else {
1187 load_notloggedin_role();
1193 * Check all the login enrolment information for the given user object
1194 * by querying the enrolment plugins
1196 function check_enrolment_plugins(&$user) {
1197 global $CFG;
1199 static $inprogress; // To prevent this function being called more than once in an invocation
1201 if (!empty($inprogress[$user->id])) {
1202 return;
1205 $inprogress[$user->id] = true; // Set the flag
1207 require_once($CFG->dirroot .'/enrol/enrol.class.php');
1209 if (!($plugins = explode(',', $CFG->enrol_plugins_enabled))) {
1210 $plugins = array($CFG->enrol);
1213 foreach ($plugins as $plugin) {
1214 $enrol = enrolment_factory::factory($plugin);
1215 if (method_exists($enrol, 'setup_enrolments')) { /// Plugin supports Roles (Moodle 1.7 and later)
1216 $enrol->setup_enrolments($user);
1217 } else { /// Run legacy enrolment methods
1218 if (method_exists($enrol, 'get_student_courses')) {
1219 $enrol->get_student_courses($user);
1221 if (method_exists($enrol, 'get_teacher_courses')) {
1222 $enrol->get_teacher_courses($user);
1225 /// deal with $user->students and $user->teachers stuff
1226 unset($user->student);
1227 unset($user->teacher);
1229 unset($enrol);
1232 unset($inprogress[$user->id]); // Unset the flag
1237 * This is a recursive function that checks whether the capability in this
1238 * context, or the parent capabilities are set to prohibit.
1240 * At this point, we can probably just use the values already set in the
1241 * session variable, since we are going down the level. Any prohit set in
1242 * parents would already reflect in the session.
1244 * @param $capability - capability name
1245 * @param $sum - sum of all capabilities values
1246 * @param $context - the context object
1247 * @param $array - when loading another user caps, their caps are not stored in session but an array
1249 function capability_prohibits($capability, $context, $sum='', $array='') {
1250 global $USER;
1252 // caching, mainly to save unnecessary sqls
1253 static $prohibits; //[capability][contextid]
1254 if (isset($prohibits[$capability][$context->id])) {
1255 return $prohibits[$capability][$context->id];
1258 if (empty($context->id)) {
1259 $prohibits[$capability][$context->id] = false;
1260 return false;
1263 if (empty($capability)) {
1264 $prohibits[$capability][$context->id] = false;
1265 return false;
1268 if ($sum < (CAP_PROHIBIT/2)) {
1269 // If this capability is set to prohibit.
1270 $prohibits[$capability][$context->id] = true;
1271 return true;
1274 if (!empty($array)) {
1275 if (isset($array[$context->id][$capability])
1276 && $array[$context->id][$capability] < (CAP_PROHIBIT/2)) {
1277 $prohibits[$capability][$context->id] = true;
1278 return true;
1280 } else {
1281 // Else if set in session.
1282 if (isset($USER->capabilities[$context->id][$capability])
1283 && $USER->capabilities[$context->id][$capability] < (CAP_PROHIBIT/2)) {
1284 $prohibits[$capability][$context->id] = true;
1285 return true;
1288 switch ($context->contextlevel) {
1290 case CONTEXT_SYSTEM:
1291 // By now it's a definite an inherit.
1292 return 0;
1293 break;
1295 case CONTEXT_PERSONAL:
1296 $parent = get_context_instance(CONTEXT_SYSTEM);
1297 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1298 return $prohibits[$capability][$context->id];
1299 break;
1301 case CONTEXT_USER:
1302 $parent = get_context_instance(CONTEXT_SYSTEM);
1303 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1304 return $prohibits[$capability][$context->id];
1305 break;
1307 case CONTEXT_COURSECAT:
1308 // Coursecat -> coursecat or site.
1309 if (!$coursecat = get_record('course_categories','id',$context->instanceid)) {
1310 $prohibits[$capability][$context->id] = false;
1311 return false;
1313 if (!empty($coursecat->parent)) {
1314 // return parent value if exist.
1315 $parent = get_context_instance(CONTEXT_COURSECAT, $coursecat->parent);
1316 } else {
1317 // Return site value.
1318 $parent = get_context_instance(CONTEXT_SYSTEM);
1320 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1321 return $prohibits[$capability][$context->id];
1322 break;
1324 case CONTEXT_COURSE:
1325 // 1 to 1 to course cat.
1326 // Find the course cat, and return its value.
1327 if (!$course = get_record('course','id',$context->instanceid)) {
1328 $prohibits[$capability][$context->id] = false;
1329 return false;
1331 // Yu: Separating site and site course context
1332 if ($course->id == SITEID) {
1333 $parent = get_context_instance(CONTEXT_SYSTEM);
1334 } else {
1335 $parent = get_context_instance(CONTEXT_COURSECAT, $course->category);
1337 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1338 return $prohibits[$capability][$context->id];
1339 break;
1341 case CONTEXT_GROUP:
1342 // 1 to 1 to course.
1343 if (!$courseid = get_field('groups', 'courseid', 'id', $context->instanceid)) {
1344 $prohibits[$capability][$context->id] = false;
1345 return false;
1347 $parent = get_context_instance(CONTEXT_COURSE, $courseid);
1348 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1349 return $prohibits[$capability][$context->id];
1350 break;
1352 case CONTEXT_MODULE:
1353 // 1 to 1 to course.
1354 if (!$cm = get_record('course_modules','id',$context->instanceid)) {
1355 $prohibits[$capability][$context->id] = false;
1356 return false;
1358 $parent = get_context_instance(CONTEXT_COURSE, $cm->course);
1359 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1360 return $prohibits[$capability][$context->id];
1361 break;
1363 case CONTEXT_BLOCK:
1364 // 1 to 1 to course.
1365 if (!$block = get_record('block_instance','id',$context->instanceid)) {
1366 $prohibits[$capability][$context->id] = false;
1367 return false;
1369 if ($block->pagetype == 'course-view') {
1370 $parent = get_context_instance(CONTEXT_COURSE, $block->pageid); // needs check
1371 } else {
1372 $parent = get_context_instance(CONTEXT_SYSTEM);
1374 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1375 return $prohibits[$capability][$context->id];
1376 break;
1378 default:
1379 print_error('unknowncontext');
1380 return false;
1386 * A print form function. This should either grab all the capabilities from
1387 * files or a central table for that particular module instance, then present
1388 * them in check boxes. Only relevant capabilities should print for known
1389 * context.
1390 * @param $mod - module id of the mod
1392 function print_capabilities($modid=0) {
1393 global $CFG;
1395 $capabilities = array();
1397 if ($modid) {
1398 // We are in a module specific context.
1400 // Get the mod's name.
1401 // Call the function that grabs the file and parse.
1402 $cm = get_record('course_modules', 'id', $modid);
1403 $module = get_record('modules', 'id', $cm->module);
1405 } else {
1406 // Print all capabilities.
1407 foreach ($capabilities as $capability) {
1408 // Prints the check box component.
1415 * Installs the roles system.
1416 * This function runs on a fresh install as well as on an upgrade from the old
1417 * hard-coded student/teacher/admin etc. roles to the new roles system.
1419 function moodle_install_roles() {
1421 global $CFG, $db;
1423 /// Create a system wide context for assignemnt.
1424 $systemcontext = $context = get_context_instance(CONTEXT_SYSTEM);
1427 /// Create default/legacy roles and capabilities.
1428 /// (1 legacy capability per legacy role at system level).
1430 $adminrole = create_role(addslashes(get_string('administrator')), 'admin',
1431 addslashes(get_string('administratordescription')), 'moodle/legacy:admin');
1432 $coursecreatorrole = create_role(addslashes(get_string('coursecreators')), 'coursecreator',
1433 addslashes(get_string('coursecreatorsdescription')), 'moodle/legacy:coursecreator');
1434 $editteacherrole = create_role(addslashes(get_string('defaultcourseteacher')), 'editingteacher',
1435 addslashes(get_string('defaultcourseteacherdescription')), 'moodle/legacy:editingteacher');
1436 $noneditteacherrole = create_role(addslashes(get_string('noneditingteacher')), 'teacher',
1437 addslashes(get_string('noneditingteacherdescription')), 'moodle/legacy:teacher');
1438 $studentrole = create_role(addslashes(get_string('defaultcoursestudent')), 'student',
1439 addslashes(get_string('defaultcoursestudentdescription')), 'moodle/legacy:student');
1440 $guestrole = create_role(addslashes(get_string('guest')), 'guest',
1441 addslashes(get_string('guestdescription')), 'moodle/legacy:guest');
1442 $userrole = create_role(addslashes(get_string('authenticateduser')), 'user',
1443 addslashes(get_string('authenticateduserdescription')), 'moodle/legacy:user');
1445 /// Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles
1447 if (!assign_capability('moodle/site:doanything', CAP_ALLOW, $adminrole, $systemcontext->id)) {
1448 error('Could not assign moodle/site:doanything to the admin role');
1450 if (!update_capabilities()) {
1451 error('Had trouble upgrading the core capabilities for the Roles System');
1454 /// Look inside user_admin, user_creator, user_teachers, user_students and
1455 /// assign above new roles. If a user has both teacher and student role,
1456 /// only teacher role is assigned. The assignment should be system level.
1458 $dbtables = $db->MetaTables('TABLES');
1460 /// Set up the progress bar
1462 $usertables = array('user_admins', 'user_coursecreators', 'user_teachers', 'user_students');
1464 $totalcount = $progresscount = 0;
1465 foreach ($usertables as $usertable) {
1466 if (in_array($CFG->prefix.$usertable, $dbtables)) {
1467 $totalcount += count_records($usertable);
1471 print_progress(0, $totalcount, 5, 1, 'Processing role assignments');
1473 /// Upgrade the admins.
1474 /// Sort using id ASC, first one is primary admin.
1476 if (in_array($CFG->prefix.'user_admins', $dbtables)) {
1477 if ($rs = get_recordset_sql('SELECT * from '.$CFG->prefix.'user_admins ORDER BY ID ASC')) {
1478 while ($admin = rs_fetch_next_record($rs)) {
1479 role_assign($adminrole, $admin->userid, 0, $systemcontext->id);
1480 $progresscount++;
1481 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1483 rs_close($rs);
1485 } else {
1486 // This is a fresh install.
1490 /// Upgrade course creators.
1491 if (in_array($CFG->prefix.'user_coursecreators', $dbtables)) {
1492 if ($rs = get_recordset('user_coursecreators')) {
1493 while ($coursecreator = rs_fetch_next_record($rs)) {
1494 role_assign($coursecreatorrole, $coursecreator->userid, 0, $systemcontext->id);
1495 $progresscount++;
1496 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1498 rs_close($rs);
1503 /// Upgrade editting teachers and non-editting teachers.
1504 if (in_array($CFG->prefix.'user_teachers', $dbtables)) {
1505 if ($rs = get_recordset('user_teachers')) {
1506 while ($teacher = rs_fetch_next_record($rs)) {
1508 // removed code here to ignore site level assignments
1509 // since the contexts are separated now
1511 // populate the user_lastaccess table
1512 $access = new object();
1513 $access->timeaccess = $teacher->timeaccess;
1514 $access->userid = $teacher->userid;
1515 $access->courseid = $teacher->course;
1516 insert_record('user_lastaccess', $access);
1518 // assign the default student role
1519 $coursecontext = get_context_instance(CONTEXT_COURSE, $teacher->course); // needs cache
1520 // hidden teacher
1521 if ($teacher->authority == 0) {
1522 $hiddenteacher = 1;
1523 } else {
1524 $hiddenteacher = 0;
1527 if ($teacher->editall) { // editting teacher
1528 role_assign($editteacherrole, $teacher->userid, 0, $coursecontext->id, 0, 0, $hiddenteacher);
1529 } else {
1530 role_assign($noneditteacherrole, $teacher->userid, 0, $coursecontext->id, 0, 0, $hiddenteacher);
1532 $progresscount++;
1533 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1535 rs_close($rs);
1540 /// Upgrade students.
1541 if (in_array($CFG->prefix.'user_students', $dbtables)) {
1542 if ($rs = get_recordset('user_students')) {
1543 while ($student = rs_fetch_next_record($rs)) {
1545 // populate the user_lastaccess table
1546 $access = new object;
1547 $access->timeaccess = $student->timeaccess;
1548 $access->userid = $student->userid;
1549 $access->courseid = $student->course;
1550 insert_record('user_lastaccess', $access);
1552 // assign the default student role
1553 $coursecontext = get_context_instance(CONTEXT_COURSE, $student->course);
1554 role_assign($studentrole, $student->userid, 0, $coursecontext->id);
1555 $progresscount++;
1556 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1558 rs_close($rs);
1563 /// Upgrade guest (only 1 entry).
1564 if ($guestuser = get_record('user', 'username', 'guest')) {
1565 role_assign($guestrole, $guestuser->id, 0, $systemcontext->id);
1567 print_progress($totalcount, $totalcount, 5, 1, 'Processing role assignments');
1570 /// Insert the correct records for legacy roles
1571 allow_assign($adminrole, $adminrole);
1572 allow_assign($adminrole, $coursecreatorrole);
1573 allow_assign($adminrole, $noneditteacherrole);
1574 allow_assign($adminrole, $editteacherrole);
1575 allow_assign($adminrole, $studentrole);
1576 allow_assign($adminrole, $guestrole);
1578 allow_assign($coursecreatorrole, $noneditteacherrole);
1579 allow_assign($coursecreatorrole, $editteacherrole);
1580 allow_assign($coursecreatorrole, $studentrole);
1581 allow_assign($coursecreatorrole, $guestrole);
1583 allow_assign($editteacherrole, $noneditteacherrole);
1584 allow_assign($editteacherrole, $studentrole);
1585 allow_assign($editteacherrole, $guestrole);
1587 /// Set up default permissions for overrides
1588 allow_override($adminrole, $adminrole);
1589 allow_override($adminrole, $coursecreatorrole);
1590 allow_override($adminrole, $noneditteacherrole);
1591 allow_override($adminrole, $editteacherrole);
1592 allow_override($adminrole, $studentrole);
1593 allow_override($adminrole, $guestrole);
1594 allow_override($adminrole, $userrole);
1597 /// Delete the old user tables when we are done
1599 drop_table(new XMLDBTable('user_students'));
1600 drop_table(new XMLDBTable('user_teachers'));
1601 drop_table(new XMLDBTable('user_coursecreators'));
1602 drop_table(new XMLDBTable('user_admins'));
1607 * Returns array of all legacy roles.
1609 function get_legacy_roles() {
1610 return array(
1611 'admin' => 'moodle/legacy:admin',
1612 'coursecreator' => 'moodle/legacy:coursecreator',
1613 'editingteacher' => 'moodle/legacy:editingteacher',
1614 'teacher' => 'moodle/legacy:teacher',
1615 'student' => 'moodle/legacy:student',
1616 'guest' => 'moodle/legacy:guest',
1617 'user' => 'moodle/legacy:user'
1621 function get_legacy_type($roleid) {
1622 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
1623 $legacyroles = get_legacy_roles();
1625 $result = '';
1626 foreach($legacyroles as $ltype=>$lcap) {
1627 $localoverride = get_local_override($roleid, $sitecontext->id, $lcap);
1628 if (!empty($localoverride->permission) and $localoverride->permission == CAP_ALLOW) {
1629 //choose first selected legacy capability - reset the rest
1630 if (empty($result)) {
1631 $result = $ltype;
1632 } else {
1633 unassign_capability($lcap, $roleid);
1638 return $result;
1642 * Assign the defaults found in this capabality definition to roles that have
1643 * the corresponding legacy capabilities assigned to them.
1644 * @param $legacyperms - an array in the format (example):
1645 * 'guest' => CAP_PREVENT,
1646 * 'student' => CAP_ALLOW,
1647 * 'teacher' => CAP_ALLOW,
1648 * 'editingteacher' => CAP_ALLOW,
1649 * 'coursecreator' => CAP_ALLOW,
1650 * 'admin' => CAP_ALLOW
1651 * @return boolean - success or failure.
1653 function assign_legacy_capabilities($capability, $legacyperms) {
1655 $legacyroles = get_legacy_roles();
1657 foreach ($legacyperms as $type => $perm) {
1659 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
1661 if (!array_key_exists($type, $legacyroles)) {
1662 error('Incorrect legacy role definition for type: '.$type);
1665 if ($roles = get_roles_with_capability($legacyroles[$type], CAP_ALLOW)) {
1666 foreach ($roles as $role) {
1667 // Assign a site level capability.
1668 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1669 return false;
1674 return true;
1679 * Checks to see if a capability is a legacy capability.
1680 * @param $capabilityname
1681 * @return boolean
1683 function islegacy($capabilityname) {
1684 if (strpos($capabilityname, 'moodle/legacy') === 0) {
1685 return true;
1686 } else {
1687 return false;
1693 /**********************************
1694 * Context Manipulation functions *
1695 **********************************/
1698 * Create a new context record for use by all roles-related stuff
1699 * @param $level
1700 * @param $instanceid
1702 * @return object newly created context (or existing one with a debug warning)
1704 function create_context($contextlevel, $instanceid) {
1705 if (!$context = get_record('context','contextlevel',$contextlevel,'instanceid',$instanceid)) {
1706 if (!validate_context($contextlevel, $instanceid)) {
1707 debugging('Error: Invalid context creation request for level "'.s($contextlevel).'", instance "'.s($instanceid).'".');
1708 return NULL;
1710 if ($contextlevel == CONTEXT_SYSTEM) {
1711 return create_system_context();
1714 $context = new object();
1715 $context->contextlevel = $contextlevel;
1716 $context->instanceid = $instanceid;
1717 if ($id = insert_record('context',$context)) {
1718 $c = get_record('context','id',$id);
1719 return $c;
1720 } else {
1721 debugging('Error: could not insert new context level "'.s($contextlevel).'", instance "'.s($instanceid).'".');
1722 return NULL;
1724 } else {
1725 debugging('Warning: Context id "'.s($context->id).'" not created, because it already exists.');
1726 return $context;
1731 * This hacky function is needed because we can not change system context instanceid using normal upgrade routine.
1733 function create_system_context() {
1734 if ($context = get_record('context', 'contextlevel', CONTEXT_SYSTEM, 'instanceid', SITEID)) {
1735 // we are going to change instanceid of system context to 0 now
1736 $context->instanceid = 0;
1737 update_record('context', $context);
1738 //context rel not affected
1739 return $context;
1741 } else {
1742 $context = new object();
1743 $context->contextlevel = CONTEXT_SYSTEM;
1744 $context->instanceid = 0;
1745 if ($context->id = insert_record('context',$context)) {
1746 // we need not to populate context_rel for system context
1747 return $context;
1748 } else {
1749 debugging('Can not create system context');
1750 return NULL;
1755 * Create a new context record for use by all roles-related stuff
1756 * @param $level
1757 * @param $instanceid
1759 * @return true if properly deleted
1761 function delete_context($contextlevel, $instanceid) {
1762 if ($context = get_context_instance($contextlevel, $instanceid)) {
1763 delete_records('context_rel', 'c2', $context->id); // might not be a parent
1764 return delete_records('context', 'id', $context->id) &&
1765 delete_records('role_assignments', 'contextid', $context->id) &&
1766 delete_records('role_capabilities', 'contextid', $context->id) &&
1767 delete_records('context_rel', 'c1', $context->id);
1769 return true;
1773 * Validate that object with instanceid really exists in given context level.
1775 * return if instanceid object exists
1777 function validate_context($contextlevel, $instanceid) {
1778 switch ($contextlevel) {
1780 case CONTEXT_SYSTEM:
1781 return ($instanceid == 0);
1783 case CONTEXT_PERSONAL:
1784 return (boolean)count_records('user', 'id', $instanceid);
1786 case CONTEXT_USER:
1787 return (boolean)count_records('user', 'id', $instanceid);
1789 case CONTEXT_COURSECAT:
1790 if ($instanceid == 0) {
1791 return true; // site course category
1793 return (boolean)count_records('course_categories', 'id', $instanceid);
1795 case CONTEXT_COURSE:
1796 return (boolean)count_records('course', 'id', $instanceid);
1798 case CONTEXT_GROUP:
1799 return groups_group_exists($instanceid);
1801 case CONTEXT_MODULE:
1802 return (boolean)count_records('course_modules', 'id', $instanceid);
1804 case CONTEXT_BLOCK:
1805 return (boolean)count_records('block_instance', 'id', $instanceid);
1807 default:
1808 return false;
1813 * Get the context instance as an object. This function will create the
1814 * context instance if it does not exist yet.
1815 * @param integer $level The context level, for example CONTEXT_COURSE, or CONTEXT_MODULE.
1816 * @param integer $instance The instance id. For $level = CONTEXT_COURSE, this would be $course->id,
1817 * for $level = CONTEXT_MODULE, this would be $cm->id. And so on.
1818 * @return object The context object.
1820 function get_context_instance($contextlevel=NULL, $instance=0) {
1822 global $context_cache, $context_cache_id, $CONTEXT;
1823 static $allowed_contexts = array(CONTEXT_SYSTEM, CONTEXT_PERSONAL, CONTEXT_USER, CONTEXT_COURSECAT, CONTEXT_COURSE, CONTEXT_GROUP, CONTEXT_MODULE, CONTEXT_BLOCK);
1825 // Yu: Separating site and site course context - removed CONTEXT_COURSE override when SITEID
1827 // fix for MDL-9016
1828 if ($contextlevel == 'clearcache') {
1829 // Clear ALL cache
1830 $context_cache = array();
1831 $context_cache_id = array();
1832 $CONTEXT = '';
1833 return false;
1836 /// If no level is supplied then return the current global context if there is one
1837 if (empty($contextlevel)) {
1838 if (empty($CONTEXT)) {
1839 //fatal error, code must be fixed
1840 error("Error: get_context_instance() called without a context");
1841 } else {
1842 return $CONTEXT;
1846 /// Backwards compatibility with obsoleted (CONTEXT_SYSTEM, SITEID)
1847 if ($contextlevel == CONTEXT_SYSTEM) {
1848 $instance = 0;
1851 /// check allowed context levels
1852 if (!in_array($contextlevel, $allowed_contexts)) {
1853 // fatal error, code must be fixed - probably typo or switched parameters
1854 error('Error: get_context_instance() called with incorrect context level "'.s($contextlevel).'"');
1857 /// Check the cache
1858 if (isset($context_cache[$contextlevel][$instance])) { // Already cached
1859 return $context_cache[$contextlevel][$instance];
1862 /// Get it from the database, or create it
1863 if (!$context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance)) {
1864 create_context($contextlevel, $instance);
1865 $context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance);
1868 /// Only add to cache if context isn't empty.
1869 if (!empty($context)) {
1870 $context_cache[$contextlevel][$instance] = $context; // Cache it for later
1871 $context_cache_id[$context->id] = $context; // Cache it for later
1874 return $context;
1879 * Get a context instance as an object, from a given context id.
1880 * @param $id a context id.
1881 * @return object The context object.
1883 function get_context_instance_by_id($id) {
1885 global $context_cache, $context_cache_id;
1887 if (isset($context_cache_id[$id])) { // Already cached
1888 return $context_cache_id[$id];
1891 if ($context = get_record('context', 'id', $id)) { // Update the cache and return
1892 $context_cache[$context->contextlevel][$context->instanceid] = $context;
1893 $context_cache_id[$context->id] = $context;
1894 return $context;
1897 return false;
1902 * Get the local override (if any) for a given capability in a role in a context
1903 * @param $roleid
1904 * @param $contextid
1905 * @param $capability
1907 function get_local_override($roleid, $contextid, $capability) {
1908 return get_record('role_capabilities', 'roleid', $roleid, 'capability', $capability, 'contextid', $contextid);
1913 /************************************
1914 * DB TABLE RELATED FUNCTIONS *
1915 ************************************/
1918 * function that creates a role
1919 * @param name - role name
1920 * @param shortname - role short name
1921 * @param description - role description
1922 * @param legacy - optional legacy capability
1923 * @return id or false
1925 function create_role($name, $shortname, $description, $legacy='') {
1927 // check for duplicate role name
1929 if ($role = get_record('role','name', $name)) {
1930 error('there is already a role with this name!');
1933 if ($role = get_record('role','shortname', $shortname)) {
1934 error('there is already a role with this shortname!');
1937 $role = new object();
1938 $role->name = $name;
1939 $role->shortname = $shortname;
1940 $role->description = $description;
1942 //find free sortorder number
1943 $role->sortorder = count_records('role');
1944 while (get_record('role','sortorder', $role->sortorder)) {
1945 $role->sortorder += 1;
1948 if (!$context = get_context_instance(CONTEXT_SYSTEM)) {
1949 return false;
1952 if ($id = insert_record('role', $role)) {
1953 if ($legacy) {
1954 assign_capability($legacy, CAP_ALLOW, $id, $context->id);
1957 /// By default, users with role:manage at site level
1958 /// should be able to assign users to this new role, and override this new role's capabilities
1960 // find all admin roles
1961 if ($adminroles = get_roles_with_capability('moodle/role:manage', CAP_ALLOW, $context)) {
1962 // foreach admin role
1963 foreach ($adminroles as $arole) {
1964 // write allow_assign and allow_overrid
1965 allow_assign($arole->id, $id);
1966 allow_override($arole->id, $id);
1970 return $id;
1971 } else {
1972 return false;
1978 * function that deletes a role and cleanups up after it
1979 * @param roleid - id of role to delete
1980 * @return success
1982 function delete_role($roleid) {
1983 global $CFG;
1984 $success = true;
1986 // mdl 10149, check if this is the last active admin role
1987 // if we make the admin role not deletable then this part can go
1989 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
1991 if ($role = get_record('role', 'id', $roleid)) {
1992 if (record_exists('role_capabilities', 'contextid', $systemcontext->id, 'roleid', $roleid, 'capability', 'moodle/site:doanything')) {
1993 // deleting an admin role
1994 $status = false;
1995 if ($adminroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, $systemcontext)) {
1996 foreach ($adminroles as $adminrole) {
1997 if ($adminrole->id != $roleid) {
1998 // some other admin role
1999 if (record_exists('role_assignments', 'roleid', $adminrole->id, 'contextid', $systemcontext->id)) {
2000 // found another admin role with at least 1 user assigned
2001 $status = true;
2002 break;
2007 if ($status !== true) {
2008 error ('You can not delete this role because there is no other admin roles with users assigned');
2013 // first unssign all users
2014 if (!role_unassign($roleid)) {
2015 debugging("Error while unassigning all users from role with ID $roleid!");
2016 $success = false;
2019 // cleanup all references to this role, ignore errors
2020 if ($success) {
2022 // MDL-10679 find all contexts where this role has an override
2023 $contexts = get_records_sql("SELECT contextid, contextid
2024 FROM {$CFG->prefix}role_capabilities
2025 WHERE roleid = $roleid");
2027 delete_records('role_capabilities', 'roleid', $roleid);
2029 // MDL-10679, delete from context_rel if this role holds the last override in these contexts
2030 if ($contexts) {
2031 foreach ($contexts as $context) {
2032 if (!record_exists('role_capabilities', 'contextid', $context->contextid)) {
2033 delete_records('context_rel', 'c1', $context->contextid);
2038 delete_records('role_allow_assign', 'roleid', $roleid);
2039 delete_records('role_allow_assign', 'allowassign', $roleid);
2040 delete_records('role_allow_override', 'roleid', $roleid);
2041 delete_records('role_allow_override', 'allowoverride', $roleid);
2042 delete_records('role_names', 'roleid', $roleid);
2045 // finally delete the role itself
2046 if ($success and !delete_records('role', 'id', $roleid)) {
2047 debugging("Could not delete role record with ID $roleid!");
2048 $success = false;
2051 return $success;
2055 * Function to write context specific overrides, or default capabilities.
2056 * @param module - string name
2057 * @param capability - string name
2058 * @param contextid - context id
2059 * @param roleid - role id
2060 * @param permission - int 1,-1 or -1000
2061 * should not be writing if permission is 0
2063 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite=false) {
2065 global $USER;
2067 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
2068 unassign_capability($capability, $roleid, $contextid);
2069 return true;
2072 $existing = get_record('role_capabilities', 'contextid', $contextid, 'roleid', $roleid, 'capability', $capability);
2074 if ($existing and !$overwrite) { // We want to keep whatever is there already
2075 return true;
2078 $cap = new object;
2079 $cap->contextid = $contextid;
2080 $cap->roleid = $roleid;
2081 $cap->capability = $capability;
2082 $cap->permission = $permission;
2083 $cap->timemodified = time();
2084 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
2086 if ($existing) {
2087 $cap->id = $existing->id;
2088 return update_record('role_capabilities', $cap);
2089 } else {
2090 $c = get_record('context', 'id', $contextid);
2091 /// MDL-10679 insert context rel here
2092 insert_context_rel ($c);
2093 return insert_record('role_capabilities', $cap);
2099 * Unassign a capability from a role.
2100 * @param $roleid - the role id
2101 * @param $capability - the name of the capability
2102 * @return boolean - success or failure
2104 function unassign_capability($capability, $roleid, $contextid=NULL) {
2106 if (isset($contextid)) {
2107 // delete from context rel, if this is the last override in this context
2108 $status = delete_records('role_capabilities', 'capability', $capability,
2109 'roleid', $roleid, 'contextid', $contextid);
2111 // MDL-10679, if this is no more overrides for this context
2112 // delete entries from context where this context is a child
2113 if (!record_exists('role_capabilities', 'contextid', $contextid)) {
2114 delete_records('context_rel', 'c1', $contextid);
2117 } else {
2118 // There is no need to delete from context_rel here because
2119 // this is only used for legacy, for now
2120 $status = delete_records('role_capabilities', 'capability', $capability,
2121 'roleid', $roleid);
2123 return $status;
2128 * Get the roles that have a given capability assigned to it. This function
2129 * does not resolve the actual permission of the capability. It just checks
2130 * for assignment only.
2131 * @param $capability - capability name (string)
2132 * @param $permission - optional, the permission defined for this capability
2133 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT
2134 * @return array or role objects
2136 function get_roles_with_capability($capability, $permission=NULL, $context='') {
2138 global $CFG;
2140 if ($context) {
2141 if ($contexts = get_parent_contexts($context)) {
2142 $listofcontexts = '('.implode(',', $contexts).')';
2143 } else {
2144 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
2145 $listofcontexts = '('.$sitecontext->id.')'; // must be site
2147 $contextstr = "AND (rc.contextid = '$context->id' OR rc.contextid IN $listofcontexts)";
2148 } else {
2149 $contextstr = '';
2152 $selectroles = "SELECT r.*
2153 FROM {$CFG->prefix}role r,
2154 {$CFG->prefix}role_capabilities rc
2155 WHERE rc.capability = '$capability'
2156 AND rc.roleid = r.id $contextstr";
2158 if (isset($permission)) {
2159 $selectroles .= " AND rc.permission = '$permission'";
2161 return get_records_sql($selectroles);
2166 * This function makes a role-assignment (a role for a user or group in a particular context)
2167 * @param $roleid - the role of the id
2168 * @param $userid - userid
2169 * @param $groupid - group id
2170 * @param $contextid - id of the context
2171 * @param $timestart - time this assignment becomes effective
2172 * @param $timeend - time this assignemnt ceases to be effective
2173 * @uses $USER
2174 * @return id - new id of the assigment
2176 function role_assign($roleid, $userid, $groupid, $contextid, $timestart=0, $timeend=0, $hidden=0, $enrol='manual',$timemodified='') {
2177 global $USER, $CFG;
2179 debugging("Assign roleid $roleid userid $userid contextid $contextid", DEBUG_DEVELOPER);
2181 /// Do some data validation
2183 if (empty($roleid)) {
2184 debugging('Role ID not provided');
2185 return false;
2188 if (empty($userid) && empty($groupid)) {
2189 debugging('Either userid or groupid must be provided');
2190 return false;
2193 if ($userid && !record_exists('user', 'id', $userid)) {
2194 debugging('User ID '.intval($userid).' does not exist!');
2195 return false;
2198 if ($groupid && !groups_group_exists($groupid)) {
2199 debugging('Group ID '.intval($groupid).' does not exist!');
2200 return false;
2203 if (!$context = get_context_instance_by_id($contextid)) {
2204 debugging('Context ID '.intval($contextid).' does not exist!');
2205 return false;
2208 if (($timestart and $timeend) and ($timestart > $timeend)) {
2209 debugging('The end time can not be earlier than the start time');
2210 return false;
2213 if (!$timemodified) {
2214 $timemodified = time();
2217 /// Check for existing entry
2218 if ($userid) {
2219 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id, 'userid', $userid);
2220 } else {
2221 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id, 'groupid', $groupid);
2225 $newra = new object;
2227 if (empty($ra)) { // Create a new entry
2228 $newra->roleid = $roleid;
2229 $newra->contextid = $context->id;
2230 $newra->userid = $userid;
2231 $newra->hidden = $hidden;
2232 $newra->enrol = $enrol;
2233 /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
2234 /// by repeating queries with the same exact parameters in a 100 secs time window
2235 $newra->timestart = round($timestart, -2);
2236 $newra->timeend = $timeend;
2237 $newra->timemodified = $timemodified;
2238 $newra->modifierid = empty($USER->id) ? 0 : $USER->id;
2240 $success = insert_record('role_assignments', $newra);
2242 } else { // We already have one, just update it
2244 $newra->id = $ra->id;
2245 $newra->hidden = $hidden;
2246 $newra->enrol = $enrol;
2247 /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
2248 /// by repeating queries with the same exact parameters in a 100 secs time window
2249 $newra->timestart = round($timestart, -2);
2250 $newra->timeend = $timeend;
2251 $newra->timemodified = $timemodified;
2252 $newra->modifierid = empty($USER->id) ? 0 : $USER->id;
2254 $success = update_record('role_assignments', $newra);
2257 if ($success) { /// Role was assigned, so do some other things
2259 /// If the user is the current user, then reload the capabilities too.
2260 if (!empty($USER->id) && $USER->id == $userid) {
2261 load_all_capabilities();
2264 /// Ask all the modules if anything needs to be done for this user
2265 if ($mods = get_list_of_plugins('mod')) {
2266 foreach ($mods as $mod) {
2267 include_once($CFG->dirroot.'/mod/'.$mod.'/lib.php');
2268 $functionname = $mod.'_role_assign';
2269 if (function_exists($functionname)) {
2270 $functionname($userid, $context, $roleid);
2275 /// Make sure they have an entry in user_lastaccess for courses they can access
2276 // role_add_lastaccess_entries($userid, $context);
2279 /// now handle metacourse role assignments if in course context
2280 if ($success and $context->contextlevel == CONTEXT_COURSE) {
2281 if ($parents = get_records('course_meta', 'child_course', $context->instanceid)) {
2282 foreach ($parents as $parent) {
2283 sync_metacourse($parent->parent_course);
2288 return $success;
2293 * Deletes one or more role assignments. You must specify at least one parameter.
2294 * @param $roleid
2295 * @param $userid
2296 * @param $groupid
2297 * @param $contextid
2298 * @param $enrol unassign only if enrolment type matches, NULL means anything
2299 * @return boolean - success or failure
2301 function role_unassign($roleid=0, $userid=0, $groupid=0, $contextid=0, $enrol=NULL) {
2303 global $USER, $CFG;
2305 $success = true;
2307 $args = array('roleid', 'userid', 'groupid', 'contextid');
2308 $select = array();
2309 foreach ($args as $arg) {
2310 if ($$arg) {
2311 $select[] = $arg.' = '.$$arg;
2314 if (!empty($enrol)) {
2315 $select[] = "enrol='$enrol'";
2318 if ($select) {
2319 if ($ras = get_records_select('role_assignments', implode(' AND ', $select))) {
2320 $mods = get_list_of_plugins('mod');
2321 foreach($ras as $ra) {
2322 /// infinite loop protection when deleting recursively
2323 if (!$ra = get_record('role_assignments', 'id', $ra->id)) {
2324 continue;
2326 $success = delete_records('role_assignments', 'id', $ra->id) and $success;
2328 /// If the user is the current user, then reload the capabilities too.
2329 if (!empty($USER->id) && $USER->id == $ra->userid) {
2330 load_all_capabilities();
2332 $context = get_record('context', 'id', $ra->contextid);
2334 /// Ask all the modules if anything needs to be done for this user
2335 foreach ($mods as $mod) {
2336 include_once($CFG->dirroot.'/mod/'.$mod.'/lib.php');
2337 $functionname = $mod.'_role_unassign';
2338 if (function_exists($functionname)) {
2339 $functionname($ra->userid, $context); // watch out, $context might be NULL if something goes wrong
2343 /// now handle metacourse role unassigment and removing from goups if in course context
2344 if (!empty($context) and $context->contextlevel == CONTEXT_COURSE) {
2346 // cleanup leftover course groups/subscriptions etc when user has
2347 // no capability to view course
2348 // this may be slow, but this is the proper way of doing it
2349 if (!has_capability('moodle/course:view', $context, $ra->userid)) {
2350 // remove from groups
2351 if ($groups = groups_get_all_groups($context->instanceid)) {
2352 foreach ($groups as $group) {
2353 delete_records('groups_members', 'groupid', $group->id, 'userid', $ra->userid);
2357 // delete lastaccess records
2358 delete_records('user_lastaccess', 'userid', $ra->userid, 'courseid', $context->instanceid);
2361 //unassign roles in metacourses if needed
2362 if ($parents = get_records('course_meta', 'child_course', $context->instanceid)) {
2363 foreach ($parents as $parent) {
2364 sync_metacourse($parent->parent_course);
2372 return $success;
2376 * A convenience function to take care of the common case where you
2377 * just want to enrol someone using the default role into a course
2379 * @param object $course
2380 * @param object $user
2381 * @param string $enrol - the plugin used to do this enrolment
2383 function enrol_into_course($course, $user, $enrol) {
2385 $timestart = time();
2386 // remove time part from the timestamp and keep only the date part
2387 $timestart = make_timestamp(date('Y', $timestart), date('m', $timestart), date('d', $timestart), 0, 0, 0);
2388 if ($course->enrolperiod) {
2389 $timeend = $timestart + $course->enrolperiod;
2390 } else {
2391 $timeend = 0;
2394 if ($role = get_default_course_role($course)) {
2396 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2398 if (!role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, $enrol)) {
2399 return false;
2402 email_welcome_message_to_user($course, $user);
2404 add_to_log($course->id, 'course', 'enrol', 'view.php?id='.$course->id, $user->id);
2406 return true;
2409 return false;
2413 * Add last access times to user_lastaccess as required
2414 * @param $userid
2415 * @param $context
2416 * @return boolean - success or failure
2418 function role_add_lastaccess_entries($userid, $context) {
2420 global $USER, $CFG;
2422 if (empty($context->contextlevel)) {
2423 return false;
2426 $lastaccess = new object; // Reusable object below
2427 $lastaccess->userid = $userid;
2428 $lastaccess->timeaccess = 0;
2430 switch ($context->contextlevel) {
2432 case CONTEXT_SYSTEM: // For the whole site
2433 if ($courses = get_record('course')) {
2434 foreach ($courses as $course) {
2435 $lastaccess->courseid = $course->id;
2436 role_set_lastaccess($lastaccess);
2439 break;
2441 case CONTEXT_CATEGORY: // For a whole category
2442 if ($courses = get_record('course', 'category', $context->instanceid)) {
2443 foreach ($courses as $course) {
2444 $lastaccess->courseid = $course->id;
2445 role_set_lastaccess($lastaccess);
2448 if ($categories = get_record('course_categories', 'parent', $context->instanceid)) {
2449 foreach ($categories as $category) {
2450 $subcontext = get_context_instance(CONTEXT_CATEGORY, $category->id);
2451 role_add_lastaccess_entries($userid, $subcontext);
2454 break;
2457 case CONTEXT_COURSE: // For a whole course
2458 if ($course = get_record('course', 'id', $context->instanceid)) {
2459 $lastaccess->courseid = $course->id;
2460 role_set_lastaccess($lastaccess);
2462 break;
2467 * Delete last access times from user_lastaccess as required
2468 * @param $userid
2469 * @param $context
2470 * @return boolean - success or failure
2472 function role_remove_lastaccess_entries($userid, $context) {
2474 global $USER, $CFG;
2480 * Loads the capability definitions for the component (from file). If no
2481 * capabilities are defined for the component, we simply return an empty array.
2482 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2483 * @return array of capabilities
2485 function load_capability_def($component) {
2486 global $CFG;
2488 if ($component == 'moodle') {
2489 $defpath = $CFG->libdir.'/db/access.php';
2490 $varprefix = 'moodle';
2491 } else {
2492 $compparts = explode('/', $component);
2494 if ($compparts[0] == 'block') {
2495 // Blocks are an exception. Blocks directory is 'blocks', and not
2496 // 'block'. So we need to jump through hoops.
2497 $defpath = $CFG->dirroot.'/'.$compparts[0].
2498 's/'.$compparts[1].'/db/access.php';
2499 $varprefix = $compparts[0].'_'.$compparts[1];
2501 } else if ($compparts[0] == 'format') {
2502 // Similar to the above, course formats are 'format' while they
2503 // are stored in 'course/format'.
2504 $defpath = $CFG->dirroot.'/course/'.$component.'/db/access.php';
2505 $varprefix = $compparts[0].'_'.$compparts[1];
2507 } else if ($compparts[0] == 'gradeimport') {
2508 $defpath = $CFG->dirroot.'/grade/import/'.$compparts[1].'/db/access.php';
2509 $varprefix = $compparts[0].'_'.$compparts[1];
2511 } else if ($compparts[0] == 'gradeexport') {
2512 $defpath = $CFG->dirroot.'/grade/export/'.$compparts[1].'/db/access.php';
2513 $varprefix = $compparts[0].'_'.$compparts[1];
2515 } else if ($compparts[0] == 'gradereport') {
2516 $defpath = $CFG->dirroot.'/grade/report/'.$compparts[1].'/db/access.php';
2517 $varprefix = $compparts[0].'_'.$compparts[1];
2519 } else {
2520 $defpath = $CFG->dirroot.'/'.$component.'/db/access.php';
2521 $varprefix = str_replace('/', '_', $component);
2524 $capabilities = array();
2526 if (file_exists($defpath)) {
2527 require($defpath);
2528 $capabilities = ${$varprefix.'_capabilities'};
2530 return $capabilities;
2535 * Gets the capabilities that have been cached in the database for this
2536 * component.
2537 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2538 * @return array of capabilities
2540 function get_cached_capabilities($component='moodle') {
2541 if ($component == 'moodle') {
2542 $storedcaps = get_records_select('capabilities',
2543 "name LIKE 'moodle/%:%'");
2544 } else {
2545 $storedcaps = get_records_select('capabilities',
2546 "name LIKE '$component:%'");
2548 return $storedcaps;
2552 * Returns default capabilities for given legacy role type.
2554 * @param string legacy role name
2555 * @return array
2557 function get_default_capabilities($legacyrole) {
2558 if (!$allcaps = get_records('capabilities')) {
2559 error('Error: no capabilitites defined!');
2561 $alldefs = array();
2562 $defaults = array();
2563 $components = array();
2564 foreach ($allcaps as $cap) {
2565 if (!in_array($cap->component, $components)) {
2566 $components[] = $cap->component;
2567 $alldefs = array_merge($alldefs, load_capability_def($cap->component));
2570 foreach($alldefs as $name=>$def) {
2571 if (isset($def['legacy'][$legacyrole])) {
2572 $defaults[$name] = $def['legacy'][$legacyrole];
2576 //some exceptions
2577 $defaults['moodle/legacy:'.$legacyrole] = CAP_ALLOW;
2578 if ($legacyrole == 'admin') {
2579 $defaults['moodle/site:doanything'] = CAP_ALLOW;
2581 return $defaults;
2585 * Reset role capabilitites to default according to selected legacy capability.
2586 * If several legacy caps selected, use the first from get_default_capabilities.
2587 * If no legacy selected, removes all capabilities.
2589 * @param int @roleid
2591 function reset_role_capabilities($roleid) {
2592 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
2593 $legacyroles = get_legacy_roles();
2595 $defaultcaps = array();
2596 foreach($legacyroles as $ltype=>$lcap) {
2597 $localoverride = get_local_override($roleid, $sitecontext->id, $lcap);
2598 if (!empty($localoverride->permission) and $localoverride->permission == CAP_ALLOW) {
2599 //choose first selected legacy capability
2600 $defaultcaps = get_default_capabilities($ltype);
2601 break;
2605 delete_records('role_capabilities', 'roleid', $roleid);
2606 if (!empty($defaultcaps)) {
2607 foreach($defaultcaps as $cap=>$permission) {
2608 assign_capability($cap, $permission, $roleid, $sitecontext->id);
2614 * Updates the capabilities table with the component capability definitions.
2615 * If no parameters are given, the function updates the core moodle
2616 * capabilities.
2618 * Note that the absence of the db/access.php capabilities definition file
2619 * will cause any stored capabilities for the component to be removed from
2620 * the database.
2622 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2623 * @return boolean
2625 function update_capabilities($component='moodle') {
2627 $storedcaps = array();
2629 $filecaps = load_capability_def($component);
2630 $cachedcaps = get_cached_capabilities($component);
2631 if ($cachedcaps) {
2632 foreach ($cachedcaps as $cachedcap) {
2633 array_push($storedcaps, $cachedcap->name);
2634 // update risk bitmasks and context levels in existing capabilities if needed
2635 if (array_key_exists($cachedcap->name, $filecaps)) {
2636 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2637 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
2639 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
2640 $updatecap = new object();
2641 $updatecap->id = $cachedcap->id;
2642 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2643 if (!update_record('capabilities', $updatecap)) {
2644 return false;
2648 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2649 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2651 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2652 $updatecap = new object();
2653 $updatecap->id = $cachedcap->id;
2654 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2655 if (!update_record('capabilities', $updatecap)) {
2656 return false;
2663 // Are there new capabilities in the file definition?
2664 $newcaps = array();
2666 foreach ($filecaps as $filecap => $def) {
2667 if (!$storedcaps ||
2668 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2669 if (!array_key_exists('riskbitmask', $def)) {
2670 $def['riskbitmask'] = 0; // no risk if not specified
2672 $newcaps[$filecap] = $def;
2675 // Add new capabilities to the stored definition.
2676 foreach ($newcaps as $capname => $capdef) {
2677 $capability = new object;
2678 $capability->name = $capname;
2679 $capability->captype = $capdef['captype'];
2680 $capability->contextlevel = $capdef['contextlevel'];
2681 $capability->component = $component;
2682 $capability->riskbitmask = $capdef['riskbitmask'];
2684 if (!insert_record('capabilities', $capability, false, 'id')) {
2685 return false;
2689 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $storedcaps)){
2690 if ($rolecapabilities = get_records('role_capabilities', 'capability', $capdef['clonepermissionsfrom'])){
2691 foreach ($rolecapabilities as $rolecapability){
2692 //assign_capability will update rather than insert if capability exists
2693 if (!assign_capability($capname, $rolecapability->permission,
2694 $rolecapability->roleid, $rolecapability->contextid, true)){
2695 notify('Could not clone capabilities for '.$capname);
2699 // Do we need to assign the new capabilities to roles that have the
2700 // legacy capabilities moodle/legacy:* as well?
2701 // we ignore legacy key if we have cloned permissions
2702 } else if (isset($capdef['legacy']) && is_array($capdef['legacy']) &&
2703 !assign_legacy_capabilities($capname, $capdef['legacy'])) {
2704 notify('Could not assign legacy capabilities for '.$capname);
2707 // Are there any capabilities that have been removed from the file
2708 // definition that we need to delete from the stored capabilities and
2709 // role assignments?
2710 capabilities_cleanup($component, $filecaps);
2712 return true;
2717 * Deletes cached capabilities that are no longer needed by the component.
2718 * Also unassigns these capabilities from any roles that have them.
2719 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2720 * @param $newcapdef - array of the new capability definitions that will be
2721 * compared with the cached capabilities
2722 * @return int - number of deprecated capabilities that have been removed
2724 function capabilities_cleanup($component, $newcapdef=NULL) {
2726 $removedcount = 0;
2728 if ($cachedcaps = get_cached_capabilities($component)) {
2729 foreach ($cachedcaps as $cachedcap) {
2730 if (empty($newcapdef) ||
2731 array_key_exists($cachedcap->name, $newcapdef) === false) {
2733 // Remove from capabilities cache.
2734 if (!delete_records('capabilities', 'name', $cachedcap->name)) {
2735 error('Could not delete deprecated capability '.$cachedcap->name);
2736 } else {
2737 $removedcount++;
2739 // Delete from roles.
2740 if($roles = get_roles_with_capability($cachedcap->name)) {
2741 foreach($roles as $role) {
2742 if (!unassign_capability($cachedcap->name, $role->id)) {
2743 error('Could not unassign deprecated capability '.
2744 $cachedcap->name.' from role '.$role->name);
2748 } // End if.
2751 return $removedcount;
2756 /****************
2757 * UI FUNCTIONS *
2758 ****************/
2762 * prints human readable context identifier.
2764 function print_context_name($context, $withprefix = true, $short = false) {
2766 $name = '';
2767 switch ($context->contextlevel) {
2769 case CONTEXT_SYSTEM: // by now it's a definite an inherit
2770 $name = get_string('coresystem');
2771 break;
2773 case CONTEXT_PERSONAL:
2774 $name = get_string('personal');
2775 break;
2777 case CONTEXT_USER:
2778 if ($user = get_record('user', 'id', $context->instanceid)) {
2779 if ($withprefix){
2780 $name = get_string('user').': ';
2782 $name .= fullname($user);
2784 break;
2786 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
2787 if ($category = get_record('course_categories', 'id', $context->instanceid)) {
2788 if ($withprefix){
2789 $name = get_string('category').': ';
2791 $name .=format_string($category->name);
2793 break;
2795 case CONTEXT_COURSE: // 1 to 1 to course cat
2796 if ($course = get_record('course', 'id', $context->instanceid)) {
2797 if ($withprefix){
2798 if ($context->instanceid == SITEID) {
2799 $name = get_string('site').': ';
2800 } else {
2801 $name = get_string('course').': ';
2804 if ($short){
2805 $name .=format_string($course->shortname);
2806 } else {
2807 $name .=format_string($course->fullname);
2811 break;
2813 case CONTEXT_GROUP: // 1 to 1 to course
2814 if ($name = groups_get_group_name($context->instanceid)) {
2815 if ($withprefix){
2816 $name = get_string('group').': '. $name;
2819 break;
2821 case CONTEXT_MODULE: // 1 to 1 to course
2822 if ($cm = get_record('course_modules','id',$context->instanceid)) {
2823 if ($module = get_record('modules','id',$cm->module)) {
2824 if ($mod = get_record($module->name, 'id', $cm->instance)) {
2825 if ($withprefix){
2826 $name = get_string('activitymodule').': ';
2828 $name .= $mod->name;
2832 break;
2834 case CONTEXT_BLOCK: // 1 to 1 to course
2835 if ($blockinstance = get_record('block_instance','id',$context->instanceid)) {
2836 if ($block = get_record('block','id',$blockinstance->blockid)) {
2837 global $CFG;
2838 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
2839 require_once("$CFG->dirroot/blocks/$block->name/block_$block->name.php");
2840 $blockname = "block_$block->name";
2841 if ($blockobject = new $blockname()) {
2842 if ($withprefix){
2843 $name = get_string('block').': ';
2845 $name .= $blockobject->title;
2849 break;
2851 default:
2852 error ('This is an unknown context (' . $context->contextlevel . ') in print_context_name!');
2853 return false;
2856 return $name;
2861 * Extracts the relevant capabilities given a contextid.
2862 * All case based, example an instance of forum context.
2863 * Will fetch all forum related capabilities, while course contexts
2864 * Will fetch all capabilities
2865 * @param object context
2866 * @return array();
2868 * capabilities
2869 * `name` varchar(150) NOT NULL,
2870 * `captype` varchar(50) NOT NULL,
2871 * `contextlevel` int(10) NOT NULL,
2872 * `component` varchar(100) NOT NULL,
2874 function fetch_context_capabilities($context) {
2876 global $CFG;
2878 $sort = 'ORDER BY contextlevel,component,id'; // To group them sensibly for display
2880 switch ($context->contextlevel) {
2882 case CONTEXT_SYSTEM: // all
2883 $SQL = "select * from {$CFG->prefix}capabilities";
2884 break;
2886 case CONTEXT_PERSONAL:
2887 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_PERSONAL;
2888 break;
2890 case CONTEXT_USER:
2891 $SQL = "SELECT *
2892 FROM {$CFG->prefix}capabilities
2893 WHERE contextlevel = ".CONTEXT_USER;
2894 break;
2896 case CONTEXT_COURSECAT: // all
2897 $SQL = "select * from {$CFG->prefix}capabilities";
2898 break;
2900 case CONTEXT_COURSE: // all
2901 $SQL = "select * from {$CFG->prefix}capabilities";
2902 break;
2904 case CONTEXT_GROUP: // group caps
2905 break;
2907 case CONTEXT_MODULE: // mod caps
2908 $cm = get_record('course_modules', 'id', $context->instanceid);
2909 $module = get_record('modules', 'id', $cm->module);
2911 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_MODULE."
2912 and component = 'mod/$module->name'";
2913 break;
2915 case CONTEXT_BLOCK: // block caps
2916 $cb = get_record('block_instance', 'id', $context->instanceid);
2917 $block = get_record('block', 'id', $cb->blockid);
2919 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_BLOCK."
2920 and ( component = 'block/$block->name' or component = 'moodle')";
2921 break;
2923 default:
2924 return false;
2927 if (!$records = get_records_sql($SQL.' '.$sort)) {
2928 $records = array();
2931 /// the rest of code is a bit hacky, think twice before modifying it :-(
2933 // special sorting of core system capabiltites and enrollments
2934 if (in_array($context->contextlevel, array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE))) {
2935 $first = array();
2936 foreach ($records as $key=>$record) {
2937 if (preg_match('|^moodle/|', $record->name) and $record->contextlevel == CONTEXT_SYSTEM) {
2938 $first[$key] = $record;
2939 unset($records[$key]);
2940 } else if (count($first)){
2941 break;
2944 if (count($first)) {
2945 $records = $first + $records; // merge the two arrays keeping the keys
2947 } else {
2948 $contextindependentcaps = fetch_context_independent_capabilities();
2949 $records = array_merge($contextindependentcaps, $records);
2952 return $records;
2958 * Gets the context-independent capabilities that should be overrridable in
2959 * any context.
2960 * @return array of capability records from the capabilities table.
2962 function fetch_context_independent_capabilities() {
2964 //only CONTEXT_SYSTEM capabilities here or it will break the hack in fetch_context_capabilities()
2965 $contextindependentcaps = array(
2966 'moodle/site:accessallgroups'
2969 $records = array();
2971 foreach ($contextindependentcaps as $capname) {
2972 $record = get_record('capabilities', 'name', $capname);
2973 array_push($records, $record);
2975 return $records;
2980 * This function pulls out all the resolved capabilities (overrides and
2981 * defaults) of a role used in capability overrides in contexts at a given
2982 * context.
2983 * @param obj $context
2984 * @param int $roleid
2985 * @param bool self - if set to true, resolve till this level, else stop at immediate parent level
2986 * @return array
2988 function role_context_capabilities($roleid, $context, $cap='') {
2989 global $CFG;
2991 $contexts = get_parent_contexts($context);
2992 $contexts[] = $context->id;
2993 $contexts = '('.implode(',', $contexts).')';
2995 if ($cap) {
2996 $search = " AND rc.capability = '$cap' ";
2997 } else {
2998 $search = '';
3001 $SQL = "SELECT rc.*
3002 FROM {$CFG->prefix}role_capabilities rc,
3003 {$CFG->prefix}context c
3004 WHERE rc.contextid in $contexts
3005 AND rc.roleid = $roleid
3006 AND rc.contextid = c.id $search
3007 ORDER BY c.contextlevel DESC,
3008 rc.capability DESC";
3010 $capabilities = array();
3012 if ($records = get_records_sql($SQL)) {
3013 // We are traversing via reverse order.
3014 foreach ($records as $record) {
3015 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
3016 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
3017 $capabilities[$record->capability] = $record->permission;
3021 return $capabilities;
3025 * Recursive function which, given a context, find all parent context ids,
3026 * and return the array in reverse order, i.e. parent first, then grand
3027 * parent, etc.
3028 * @param object $context
3029 * @return array()
3031 function get_parent_contexts($context) {
3033 static $pcontexts; // cache
3034 if (isset($pcontexts[$context->id])) {
3035 return ($pcontexts[$context->id]);
3038 switch ($context->contextlevel) {
3040 case CONTEXT_SYSTEM: // no parent
3041 return array();
3042 break;
3044 case CONTEXT_PERSONAL:
3045 if (!$parent = get_context_instance(CONTEXT_SYSTEM)) {
3046 return array();
3047 } else {
3048 $res = array($parent->id);
3049 $pcontexts[$context->id] = $res;
3050 return $res;
3052 break;
3054 case CONTEXT_USER:
3055 if (!$parent = get_context_instance(CONTEXT_SYSTEM)) {
3056 return array();
3057 } else {
3058 $res = array($parent->id);
3059 $pcontexts[$context->id] = $res;
3060 return $res;
3062 break;
3064 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
3065 if (!$coursecat = get_record('course_categories','id',$context->instanceid)) {
3066 return array();
3068 if (!empty($coursecat->parent)) { // return parent value if exist
3069 $parent = get_context_instance(CONTEXT_COURSECAT, $coursecat->parent);
3070 $res = array_merge(array($parent->id), get_parent_contexts($parent));
3071 $pcontexts[$context->id] = $res;
3072 return $res;
3073 } else { // else return site value
3074 $parent = get_context_instance(CONTEXT_SYSTEM);
3075 $res = array($parent->id);
3076 $pcontexts[$context->id] = $res;
3077 return $res;
3079 break;
3081 case CONTEXT_COURSE: // 1 to 1 to course cat
3082 if (!$course = get_record('course','id',$context->instanceid)) {
3083 return array();
3085 if ($course->id != SITEID) {
3086 $parent = get_context_instance(CONTEXT_COURSECAT, $course->category);
3087 $res = array_merge(array($parent->id), get_parent_contexts($parent));
3088 return $res;
3089 } else {
3090 // Yu: Separating site and site course context
3091 $parent = get_context_instance(CONTEXT_SYSTEM);
3092 $res = array($parent->id);
3093 $pcontexts[$context->id] = $res;
3094 return $res;
3096 break;
3098 case CONTEXT_GROUP: // 1 to 1 to course
3099 if (! $group = groups_get_group($context->instanceid)) {
3100 return array();
3102 if ($parent = get_context_instance(CONTEXT_COURSE, $group->courseid)) {
3103 $res = array_merge(array($parent->id), get_parent_contexts($parent));
3104 $pcontexts[$context->id] = $res;
3105 return $res;
3106 } else {
3107 return array();
3109 break;
3111 case CONTEXT_MODULE: // 1 to 1 to course
3112 if (!$cm = get_record('course_modules','id',$context->instanceid)) {
3113 return array();
3115 if ($parent = get_context_instance(CONTEXT_COURSE, $cm->course)) {
3116 $res = array_merge(array($parent->id), get_parent_contexts($parent));
3117 $pcontexts[$context->id] = $res;
3118 return $res;
3119 } else {
3120 return array();
3122 break;
3124 case CONTEXT_BLOCK: // 1 to 1 to course
3125 if (!$block = get_record('block_instance','id',$context->instanceid)) {
3126 return array();
3128 // fix for MDL-9656, block parents are not necessarily courses
3129 if ($block->pagetype == 'course-view') {
3130 $parent = get_context_instance(CONTEXT_COURSE, $block->pageid);
3131 } else {
3132 $parent = get_context_instance(CONTEXT_SYSTEM);
3135 if ($parent) {
3136 $res = array_merge(array($parent->id), get_parent_contexts($parent));
3137 $pcontexts[$context->id] = $res;
3138 return $res;
3139 } else {
3140 return array();
3142 break;
3144 default:
3145 error('This is an unknown context (' . $context->contextlevel . ') in get_parent_contexts!');
3146 return false;
3152 * Recursive function which, given a context, find all its children context ids.
3153 * @param object $context.
3154 * @return array of children context ids.
3156 function get_child_contexts($context) {
3158 global $CFG;
3159 $children = array();
3161 switch ($context->contextlevel) {
3163 case CONTEXT_BLOCK:
3164 // No children.
3165 return array();
3166 break;
3168 case CONTEXT_MODULE:
3169 // No children.
3170 return array();
3171 break;
3173 case CONTEXT_GROUP:
3174 // No children.
3175 return array();
3176 break;
3178 case CONTEXT_COURSE:
3179 // Find all block instances for the course.
3180 $page = new page_course;
3181 $page->id = $context->instanceid;
3182 $page->type = 'course-view';
3183 if ($blocks = blocks_get_by_page_pinned($page)) {
3184 foreach ($blocks['l'] as $leftblock) {
3185 if ($child = get_context_instance(CONTEXT_BLOCK, $leftblock->id)) {
3186 array_push($children, $child->id);
3189 foreach ($blocks['r'] as $rightblock) {
3190 if ($child = get_context_instance(CONTEXT_BLOCK, $rightblock->id)) {
3191 array_push($children, $child->id);
3195 // Find all module instances for the course.
3196 if ($modules = get_records('course_modules', 'course', $context->instanceid, '', 'id')) {
3197 foreach ($modules as $module) {
3198 if ($child = get_context_instance(CONTEXT_MODULE, $module->id)) {
3199 array_push($children, $child->id);
3203 // Find all group instances for the course.
3204 if ($groups = get_records('groups', 'courseid', $context->instanceid, '', 'id')) {
3205 foreach ($groups as $group) {
3206 if ($child = get_context_instance(CONTEXT_GROUP, $group->id)) {
3207 array_push($children, $child->id);
3211 return $children;
3212 break;
3214 case CONTEXT_COURSECAT:
3215 // We need to get the contexts for:
3216 // 1) The subcategories of the given category
3217 // 2) The courses in the given category and all its subcategories
3218 // 3) All the child contexts for these courses
3220 $categories = get_all_subcategories($context->instanceid);
3222 // Add the contexts for all the subcategories.
3223 foreach ($categories as $catid) {
3224 if ($catci = get_context_instance(CONTEXT_COURSECAT, $catid)) {
3225 array_push($children, $catci->id);
3229 // Add the parent category as well so we can find the contexts
3230 // for its courses.
3231 array_unshift($categories, $context->instanceid);
3233 foreach ($categories as $catid) {
3234 // Find all courses for the category.
3235 if ($courses = get_records('course', 'category', $catid, '', 'id')) {
3236 foreach ($courses as $course) {
3237 if ($courseci = get_context_instance(CONTEXT_COURSE, $course->id)) {
3238 array_push($children, $courseci->id);
3239 $children = array_merge($children, get_child_contexts($courseci));
3244 return $children;
3245 break;
3247 case CONTEXT_USER:
3248 // No children.
3249 return array();
3250 break;
3252 case CONTEXT_PERSONAL:
3253 // No children.
3254 return array();
3255 break;
3257 case CONTEXT_SYSTEM:
3258 // Just get all the contexts except for CONTEXT_SYSTEM level.
3259 $sql = 'SELECT c.id '.
3260 'FROM '.$CFG->prefix.'context AS c '.
3261 'WHERE contextlevel != '.CONTEXT_SYSTEM;
3263 $contexts = get_records_sql($sql);
3264 foreach ($contexts as $cid) {
3265 array_push($children, $cid->id);
3267 return $children;
3268 break;
3270 default:
3271 error('This is an unknown context (' . $context->contextlevel . ') in get_child_contexts!');
3272 return false;
3278 * Gets a string for sql calls, searching for stuff in this context or above
3279 * @param object $context
3280 * @return string
3282 function get_related_contexts_string($context) {
3283 if ($parents = get_parent_contexts($context)) {
3284 return (' IN ('.$context->id.','.implode(',', $parents).')');
3285 } else {
3286 return (' ='.$context->id);
3292 * This function gets the capability of a role in a given context.
3293 * It is needed when printing override forms.
3294 * @param int $contextid
3295 * @param string $capability
3296 * @param array $capabilities - array loaded using role_context_capabilities
3297 * @return int (allow, prevent, prohibit, inherit)
3299 function get_role_context_capability($contextid, $capability, $capabilities) {
3300 if (isset($capabilities[$contextid][$capability])) {
3301 return $capabilities[$contextid][$capability];
3303 else {
3304 return false;
3310 * Returns the human-readable, translated version of the capability.
3311 * Basically a big switch statement.
3312 * @param $capabilityname - e.g. mod/choice:readresponses
3314 function get_capability_string($capabilityname) {
3316 // Typical capabilityname is mod/choice:readresponses
3318 $names = split('/', $capabilityname);
3319 $stringname = $names[1]; // choice:readresponses
3320 $components = split(':', $stringname);
3321 $componentname = $components[0]; // choice
3323 switch ($names[0]) {
3324 case 'mod':
3325 $string = get_string($stringname, $componentname);
3326 break;
3328 case 'block':
3329 $string = get_string($stringname, 'block_'.$componentname);
3330 break;
3332 case 'moodle':
3333 $string = get_string($stringname, 'role');
3334 break;
3336 case 'enrol':
3337 $string = get_string($stringname, 'enrol_'.$componentname);
3338 break;
3340 case 'format':
3341 $string = get_string($stringname, 'format_'.$componentname);
3342 break;
3344 default:
3345 $string = get_string($stringname);
3346 break;
3349 return $string;
3354 * This gets the mod/block/course/core etc strings.
3355 * @param $component
3356 * @param $contextlevel
3358 function get_component_string($component, $contextlevel) {
3360 switch ($contextlevel) {
3362 case CONTEXT_SYSTEM:
3363 if (preg_match('|^enrol/|', $component)) {
3364 $langname = str_replace('/', '_', $component);
3365 $string = get_string('enrolname', $langname);
3366 } else if (preg_match('|^block/|', $component)) {
3367 $langname = str_replace('/', '_', $component);
3368 $string = get_string('blockname', $langname);
3369 } else {
3370 $string = get_string('coresystem');
3372 break;
3374 case CONTEXT_PERSONAL:
3375 $string = get_string('personal');
3376 break;
3378 case CONTEXT_USER:
3379 $string = get_string('users');
3380 break;
3382 case CONTEXT_COURSECAT:
3383 $string = get_string('categories');
3384 break;
3386 case CONTEXT_COURSE:
3387 if (preg_match('|^gradeimport/|', $component)
3388 || preg_match('|^gradeexport/|', $component)
3389 || preg_match('|^gradereport/|', $component)) {
3390 $string = get_string('gradebook', 'admin');
3391 } else {
3392 $string = get_string('course');
3394 break;
3396 case CONTEXT_GROUP:
3397 $string = get_string('group');
3398 break;
3400 case CONTEXT_MODULE:
3401 $string = get_string('modulename', basename($component));
3402 break;
3404 case CONTEXT_BLOCK:
3405 if( $component == 'moodle' ){
3406 $string = get_string('block');
3407 }else{
3408 $string = get_string('blockname', 'block_'.basename($component));
3410 break;
3412 default:
3413 error ('This is an unknown context $contextlevel (' . $contextlevel . ') in get_component_string!');
3414 return false;
3417 return $string;
3421 * Gets the list of roles assigned to this context and up (parents)
3422 * @param object $context
3423 * @param view - set to true when roles are pulled for display only
3424 * this is so that we can filter roles with no visible
3425 * assignment, for example, you might want to "hide" all
3426 * course creators when browsing the course participants
3427 * list.
3428 * @return array
3430 function get_roles_used_in_context($context, $view = false) {
3432 global $CFG;
3434 // filter for roles with all hidden assignments
3435 // no need to return when only pulling roles for reviewing
3436 // e.g. participants page.
3437 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))? ' AND ra.hidden = 0 ':'';
3438 $contextlist = get_related_contexts_string($context);
3440 $sql = "SELECT DISTINCT r.id,
3441 r.name,
3442 r.shortname,
3443 r.sortorder
3444 FROM {$CFG->prefix}role_assignments ra,
3445 {$CFG->prefix}role r
3446 WHERE r.id = ra.roleid
3447 AND ra.contextid $contextlist
3448 $hiddensql
3449 ORDER BY r.sortorder ASC";
3451 return get_records_sql($sql);
3454 /** this function is used to print roles column in user profile page.
3455 * @param int userid
3456 * @param int contextid
3457 * @return string
3459 function get_user_roles_in_context($userid, $contextid){
3460 global $CFG;
3462 $rolestring = '';
3463 $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';
3464 if ($roles = get_records_sql($SQL)) {
3465 foreach ($roles as $userrole) {
3466 $rolestring .= '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$userrole->contextid.'&amp;roleid='.$userrole->roleid.'">'.$userrole->name.'</a>, ';
3470 return rtrim($rolestring, ', ');
3475 * Checks if a user can override capabilities of a particular role in this context
3476 * @param object $context
3477 * @param int targetroleid - the id of the role you want to override
3478 * @return boolean
3480 function user_can_override($context, $targetroleid) {
3481 // first check if user has override capability
3482 // if not return false;
3483 if (!has_capability('moodle/role:override', $context)) {
3484 return false;
3486 // pull out all active roles of this user from this context(or above)
3487 if ($userroles = get_user_roles($context)) {
3488 foreach ($userroles as $userrole) {
3489 // if any in the role_allow_override table, then it's ok
3490 if (get_record('role_allow_override', 'roleid', $userrole->roleid, 'allowoverride', $targetroleid)) {
3491 return true;
3496 return false;
3501 * Checks if a user can assign users to a particular role in this context
3502 * @param object $context
3503 * @param int targetroleid - the id of the role you want to assign users to
3504 * @return boolean
3506 function user_can_assign($context, $targetroleid) {
3508 // first check if user has override capability
3509 // if not return false;
3510 if (!has_capability('moodle/role:assign', $context)) {
3511 return false;
3513 // pull out all active roles of this user from this context(or above)
3514 if ($userroles = get_user_roles($context)) {
3515 foreach ($userroles as $userrole) {
3516 // if any in the role_allow_override table, then it's ok
3517 if (get_record('role_allow_assign', 'roleid', $userrole->roleid, 'allowassign', $targetroleid)) {
3518 return true;
3523 return false;
3526 /** Returns all site roles in correct sort order.
3529 function get_all_roles() {
3530 return get_records('role', '', '', 'sortorder ASC');
3534 * gets all the user roles assigned in this context, or higher contexts
3535 * this is mainly used when checking if a user can assign a role, or overriding a role
3536 * i.e. we need to know what this user holds, in order to verify against allow_assign and
3537 * allow_override tables
3538 * @param object $context
3539 * @param int $userid
3540 * @param view - set to true when roles are pulled for display only
3541 * this is so that we can filter roles with no visible
3542 * assignment, for example, you might want to "hide" all
3543 * course creators when browsing the course participants
3544 * list.
3545 * @return array
3547 function get_user_roles($context, $userid=0, $checkparentcontexts=true, $order='c.contextlevel DESC, r.sortorder ASC', $view=false) {
3549 global $USER, $CFG, $db;
3551 if (empty($userid)) {
3552 if (empty($USER->id)) {
3553 return array();
3555 $userid = $USER->id;
3557 // set up hidden sql
3558 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))? ' AND ra.hidden = 0 ':'';
3560 if ($checkparentcontexts && ($parents = get_parent_contexts($context))) {
3561 $contexts = ' ra.contextid IN ('.implode(',' , $parents).','.$context->id.')';
3562 } else {
3563 $contexts = ' ra.contextid = \''.$context->id.'\'';
3566 return get_records_sql('SELECT ra.*, r.name, r.shortname
3567 FROM '.$CFG->prefix.'role_assignments ra,
3568 '.$CFG->prefix.'role r,
3569 '.$CFG->prefix.'context c
3570 WHERE ra.userid = '.$userid.
3571 ' AND ra.roleid = r.id
3572 AND ra.contextid = c.id
3573 AND '.$contexts . $hiddensql .
3574 ' ORDER BY '.$order);
3578 * Creates a record in the allow_override table
3579 * @param int sroleid - source roleid
3580 * @param int troleid - target roleid
3581 * @return int - id or false
3583 function allow_override($sroleid, $troleid) {
3584 $record = new object();
3585 $record->roleid = $sroleid;
3586 $record->allowoverride = $troleid;
3587 return insert_record('role_allow_override', $record);
3591 * Creates a record in the allow_assign table
3592 * @param int sroleid - source roleid
3593 * @param int troleid - target roleid
3594 * @return int - id or false
3596 function allow_assign($sroleid, $troleid) {
3597 $record = new object;
3598 $record->roleid = $sroleid;
3599 $record->allowassign = $troleid;
3600 return insert_record('role_allow_assign', $record);
3604 * Gets a list of roles that this user can assign in this context
3605 * @param object $context
3606 * @return array
3608 function get_assignable_roles ($context, $field="name") {
3610 $options = array();
3612 if ($roles = get_all_roles()) {
3613 foreach ($roles as $role) {
3614 if (user_can_assign($context, $role->id)) {
3615 $options[$role->id] = strip_tags(format_string($role->{$field}, true));
3619 return $options;
3623 * Gets a list of roles that this user can override in this context
3624 * @param object $context
3625 * @return array
3627 function get_overridable_roles($context) {
3629 $options = array();
3631 if ($roles = get_all_roles()) {
3632 foreach ($roles as $role) {
3633 if (user_can_override($context, $role->id)) {
3634 $options[$role->id] = strip_tags(format_string($role->name, true));
3639 return $options;
3643 * Returns a role object that is the default role for new enrolments
3644 * in a given course
3646 * @param object $course
3647 * @return object $role
3649 function get_default_course_role($course) {
3650 global $CFG;
3652 /// First let's take the default role the course may have
3653 if (!empty($course->defaultrole)) {
3654 if ($role = get_record('role', 'id', $course->defaultrole)) {
3655 return $role;
3659 /// Otherwise the site setting should tell us
3660 if ($CFG->defaultcourseroleid) {
3661 if ($role = get_record('role', 'id', $CFG->defaultcourseroleid)) {
3662 return $role;
3666 /// It's unlikely we'll get here, but just in case, try and find a student role
3667 if ($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW)) {
3668 return array_shift($studentroles); /// Take the first one
3671 return NULL;
3676 * who has this capability in this context
3677 * does not handling user level resolving!!!
3678 * (!)pleaes note if $fields is empty this function attempts to get u.*
3679 * which can get rather large.
3680 * i.e 1 person has 2 roles 1 allow, 1 prevent, this will not work properly
3681 * @param $context - object
3682 * @param $capability - string capability
3683 * @param $fields - fields to be pulled
3684 * @param $sort - the sort order
3685 * @param $limitfrom - number of records to skip (offset)
3686 * @param $limitnum - number of records to fetch
3687 * @param $groups - single group or array of groups - only return
3688 * users who are in one of these group(s).
3689 * @param $exceptions - list of users to exclude
3690 * @param view - set to true when roles are pulled for display only
3691 * this is so that we can filter roles with no visible
3692 * assignment, for example, you might want to "hide" all
3693 * course creators when browsing the course participants
3694 * list.
3695 * @param boolean $useviewallgroups if $groups is set the return users who
3696 * have capability both $capability and moodle/site:accessallgroups
3697 * in this context, as well as users who have $capability and who are
3698 * in $groups.
3700 function get_users_by_capability($context, $capability, $fields='', $sort='',
3701 $limitfrom='', $limitnum='', $groups='', $exceptions='', $doanything=true,
3702 $view=false, $useviewallgroups=false) {
3703 global $CFG;
3705 /// Sorting out groups
3706 if ($groups) {
3707 if (is_array($groups)) {
3708 $grouptest = 'gm.groupid IN (' . implode(',', $groups) . ')';
3709 } else {
3710 $grouptest = 'gm.groupid = ' . $groups;
3712 $grouptest = 'ra.userid IN (SELECT userid FROM ' .
3713 $CFG->prefix . 'groups_members gm WHERE ' . $grouptest . ')';
3715 if ($useviewallgroups) {
3716 $viewallgroupsusers = get_users_by_capability($context,
3717 'moodle/site:accessallgroups', 'u.id, u,id', '', '', '', '', $exceptions);
3718 $groupsql = ' AND (' . $grouptest . ' OR ra.userid IN (' .
3719 implode(',', array_keys($viewallgroupsusers)) . '))';
3720 } else {
3721 $groupsql = ' AND ' . $grouptest;
3723 } else {
3724 $groupsql = '';
3727 /// Sorting out exceptions
3728 $exceptionsql = $exceptions ? "AND u.id NOT IN ($exceptions)" : '';
3730 /// Set up default fields
3731 if (empty($fields)) {
3732 $fields = 'u.*, ul.timeaccess as lastaccess, ra.hidden';
3735 /// Set up default sort
3736 if (empty($sort)) {
3737 $sort = 'ul.timeaccess';
3740 $sortby = $sort ? " ORDER BY $sort " : '';
3741 /// Set up hidden sql
3742 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))? ' AND ra.hidden = 0 ':'';
3744 /// If context is a course, then construct sql for ul
3745 if ($context->contextlevel == CONTEXT_COURSE) {
3746 $courseid = $context->instanceid;
3747 $coursesql1 = "AND ul.courseid = $courseid";
3748 } else {
3749 $coursesql1 = '';
3752 /// Sorting out roles with this capability set
3753 if ($possibleroles = get_roles_with_capability($capability, CAP_ALLOW, $context)) {
3754 if (!$doanything) {
3755 if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM)) {
3756 return false; // Something is seriously wrong
3758 $doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, $sitecontext);
3761 $validroleids = array();
3762 foreach ($possibleroles as $possiblerole) {
3763 if (!$doanything) {
3764 if (isset($doanythingroles[$possiblerole->id])) { // We don't want these included
3765 continue;
3768 if ($caps = role_context_capabilities($possiblerole->id, $context, $capability)) { // resolved list
3769 if (isset($caps[$capability]) && $caps[$capability] > 0) { // resolved capability > 0
3770 $validroleids[] = $possiblerole->id;
3774 if (empty($validroleids)) {
3775 return false;
3777 $roleids = '('.implode(',', $validroleids).')';
3778 } else {
3779 return false; // No need to continue, since no roles have this capability set
3782 /// Construct the main SQL
3783 $select = " SELECT $fields";
3784 $from = " FROM {$CFG->prefix}user u
3785 INNER JOIN {$CFG->prefix}role_assignments ra ON ra.userid = u.id
3786 INNER JOIN {$CFG->prefix}role r ON r.id = ra.roleid
3787 LEFT OUTER JOIN {$CFG->prefix}user_lastaccess ul ON (ul.userid = u.id $coursesql1)";
3788 $where = " WHERE ra.contextid ".get_related_contexts_string($context)."
3789 AND u.deleted = 0
3790 AND ra.roleid in $roleids
3791 $exceptionsql
3792 $groupsql
3793 $hiddensql";
3795 return get_records_sql($select.$from.$where.$sortby, $limitfrom, $limitnum);
3799 * gets all the users assigned this role in this context or higher
3800 * @param int roleid
3801 * @param int contextid
3802 * @param bool parent if true, get list of users assigned in higher context too
3803 * @return array()
3805 function get_role_users($roleid, $context, $parent=false, $fields='', $sort='u.lastname ASC', $view=false, $limitfrom='', $limitnum='', $group='') {
3806 global $CFG;
3808 if (empty($fields)) {
3809 $fields = 'u.id, u.confirmed, u.username, u.firstname, u.lastname, '.
3810 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.city, '.
3811 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
3812 'u.emailstop, u.lang, u.timezone';
3815 // whether this assignment is hidden
3816 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))? ' AND r.hidden = 0 ':'';
3817 if ($parent) {
3818 if ($contexts = get_parent_contexts($context)) {
3819 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
3820 } else {
3821 $parentcontexts = '';
3823 } else {
3824 $parentcontexts = '';
3827 if ($roleid) {
3828 $roleselect = "AND r.roleid = $roleid";
3829 } else {
3830 $roleselect = '';
3833 if ($group) {
3834 $groupsql = "{$CFG->prefix}groups_members gm, ";
3835 $groupwheresql = " AND gm.userid = u.id AND gm.groupid = $group ";
3836 } else {
3837 $groupsql = '';
3838 $groupwheresql = '';
3841 $SQL = "SELECT $fields
3842 FROM {$CFG->prefix}role_assignments r,
3843 $groupsql
3844 {$CFG->prefix}user u
3845 WHERE (r.contextid = $context->id $parentcontexts)
3846 $groupwheresql
3847 AND u.id = r.userid $roleselect
3848 $hiddensql
3849 ORDER BY $sort
3850 "; // join now so that we can just use fullname() later
3852 return get_records_sql($SQL, $limitfrom, $limitnum);
3856 * Counts all the users assigned this role in this context or higher
3857 * @param int roleid
3858 * @param int contextid
3859 * @param bool parent if true, get list of users assigned in higher context too
3860 * @return array()
3862 function count_role_users($roleid, $context, $parent=false) {
3863 global $CFG;
3865 if ($parent) {
3866 if ($contexts = get_parent_contexts($context)) {
3867 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
3868 } else {
3869 $parentcontexts = '';
3871 } else {
3872 $parentcontexts = '';
3875 $SQL = "SELECT count(*)
3876 FROM {$CFG->prefix}role_assignments r
3877 WHERE (r.contextid = $context->id $parentcontexts)
3878 AND r.roleid = $roleid";
3880 return count_records_sql($SQL);
3884 * This function gets the list of courses that this user has a particular capability in.
3885 * It is still not very efficient.
3886 * @param string $capability Capability in question
3887 * @param int $userid User ID or null for current user
3888 * @param bool $doanything True if 'doanything' is permitted (default)
3889 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
3890 * otherwise use a comma-separated list of the fields you require, not including id
3891 * @param string $orderby If set, use a comma-separated list of fields from course
3892 * table with sql modifiers (DESC) if needed
3893 * @return array Array of courses, may have zero entries. Or false if query failed.
3895 function get_user_capability_course($capability, $userid=NULL,$doanything=true,$fieldsexceptid='',$orderby='') {
3896 // Convert fields list and ordering
3897 $fieldlist='';
3898 if($fieldsexceptid) {
3899 $fields=explode(',',$fieldsexceptid);
3900 foreach($fields as $field) {
3901 $fieldlist.=',c.'.$field;
3904 if($orderby) {
3905 $fields=explode(',',$orderby);
3906 $orderby='';
3907 foreach($fields as $field) {
3908 if($orderby) {
3909 $orderby.=',';
3911 $orderby.='c.'.$field;
3913 $orderby='ORDER BY '.$orderby;
3916 // Obtain a list of everything relevant about all courses including context.
3917 // Note the result can be used directly as a context (we are going to), the course
3918 // fields are just appended.
3919 global $CFG;
3920 $rs=get_recordset_sql("
3921 SELECT
3922 x.*,c.id AS courseid$fieldlist
3923 FROM
3924 {$CFG->prefix}course c
3925 INNER JOIN {$CFG->prefix}context x ON c.id=x.instanceid AND x.contextlevel=".CONTEXT_COURSE."
3926 $orderby
3928 if(!$rs) {
3929 return false;
3932 // Check capability for each course in turn
3933 $courses=array();
3934 while($coursecontext=rs_fetch_next_record($rs)) {
3935 if(has_capability($capability,$coursecontext,$userid,$doanything)) {
3936 // We've got the capability. Make the record look like a course record
3937 // and store it
3938 $coursecontext->id=$coursecontext->courseid;
3939 unset($coursecontext->courseid);
3940 unset($coursecontext->contextlevel);
3941 unset($coursecontext->instanceid);
3942 $courses[]=$coursecontext;
3945 return $courses;
3948 /** This function finds the roles assigned directly to this context only
3949 * i.e. no parents role
3950 * @param object $context
3951 * @return array
3953 function get_roles_on_exact_context($context) {
3955 global $CFG;
3957 return get_records_sql("SELECT r.*
3958 FROM {$CFG->prefix}role_assignments ra,
3959 {$CFG->prefix}role r
3960 WHERE ra.roleid = r.id
3961 AND ra.contextid = $context->id");
3966 * Switches the current user to another role for the current session and only
3967 * in the given context. If roleid is not valid (eg 0) or the current user
3968 * doesn't have permissions to be switching roles then the user's session
3969 * is compltely reset to have their normal roles.
3970 * @param integer $roleid
3971 * @param object $context
3972 * @return bool
3974 function role_switch($roleid, $context) {
3975 global $USER, $CFG;
3977 /// If we can't use this or are already using it or no role was specified then bail completely and reset
3978 if (empty($roleid) || !has_capability('moodle/role:switchroles', $context)
3979 || !empty($USER->switchrole[$context->id]) || !confirm_sesskey()) {
3981 unset($USER->switchrole[$context->id]); // Delete old capabilities
3982 load_all_capabilities(); //reload user caps
3983 return true;
3986 /// We're allowed to switch but can we switch to the specified role? Use assignable roles to check.
3987 if (!$roles = get_assignable_roles($context)) {
3988 return false;
3991 /// unset default user role - it would not work anyway
3992 unset($roles[$CFG->defaultuserroleid]);
3994 if (empty($roles[$roleid])) { /// We can't switch to this particular role
3995 return false;
3998 /// We have a valid roleid that this user can switch to, so let's set up the session
4000 $USER->switchrole[$context->id] = $roleid; // So we know later what state we are in
4002 load_all_capabilities(); //reload switched role caps
4004 /// Add some permissions we are really going to always need, even if the role doesn't have them!
4006 $USER->capabilities[$context->id]['moodle/course:view'] = CAP_ALLOW;
4008 return true;
4013 // get any role that has an override on exact context
4014 function get_roles_with_override_on_context($context) {
4016 global $CFG;
4018 return get_records_sql("SELECT r.*
4019 FROM {$CFG->prefix}role_capabilities rc,
4020 {$CFG->prefix}role r
4021 WHERE rc.roleid = r.id
4022 AND rc.contextid = $context->id");
4025 // get all capabilities for this role on this context (overrids)
4026 function get_capabilities_from_role_on_context($role, $context) {
4028 global $CFG;
4030 return get_records_sql("SELECT *
4031 FROM {$CFG->prefix}role_capabilities
4032 WHERE contextid = $context->id
4033 AND roleid = $role->id");
4036 // find out which roles has assignment on this context
4037 function get_roles_with_assignment_on_context($context) {
4039 global $CFG;
4041 return get_records_sql("SELECT r.*
4042 FROM {$CFG->prefix}role_assignments ra,
4043 {$CFG->prefix}role r
4044 WHERE ra.roleid = r.id
4045 AND ra.contextid = $context->id");
4051 * Find all user assignemnt of users for this role, on this context
4053 function get_users_from_role_on_context($role, $context) {
4055 global $CFG;
4057 return get_records_sql("SELECT *
4058 FROM {$CFG->prefix}role_assignments
4059 WHERE contextid = $context->id
4060 AND roleid = $role->id");
4064 * Simple function returning a boolean true if roles exist, otherwise false
4066 function user_has_role_assignment($userid, $roleid, $contextid=0) {
4068 if ($contextid) {
4069 return record_exists('role_assignments', 'userid', $userid, 'roleid', $roleid, 'contextid', $contextid);
4070 } else {
4071 return record_exists('role_assignments', 'userid', $userid, 'roleid', $roleid);
4075 /**
4076 * Inserts all parental context and self into context_rel table
4078 * @param object $context-context to be deleted
4079 * @param bool deletechild - deltes child contexts dependencies
4081 function insert_context_rel($context, $deletechild=true, $deleteparent=true) {
4083 // first check validity
4084 // MDL-9057
4085 if (!validate_context($context->contextlevel, $context->instanceid)) {
4086 debugging('Error: Invalid context creation request for level "' .
4087 s($context->contextlevel) . '", instance "' . s($context->instanceid) . '".');
4088 return NULL;
4091 // removes all parents
4092 if ($deletechild) {
4093 delete_records('context_rel', 'c2', $context->id);
4096 if ($deleteparent) {
4097 delete_records('context_rel', 'c1', $context->id);
4099 // insert all parents
4100 if ($parents = get_parent_contexts($context)) {
4101 $parents[] = $context->id;
4102 foreach ($parents as $parent) {
4103 $rec = new object;
4104 $rec ->c1 = $context->id;
4105 $rec ->c2 = $parent;
4106 insert_record('context_rel', $rec);
4112 * rebuild context_rel table without deleting
4114 function build_context_rel() {
4116 global $CFG, $db;
4117 $savedb = $db->debug;
4119 // MDL-10679, only identify contexts with overrides in them
4120 $contexts = get_records_sql("SELECT c.* FROM {$CFG->prefix}context c,
4121 {$CFG->prefix}role_capabilities rc
4122 WHERE c.id = rc.contextid");
4123 // total number of records
4124 // subtract one because the site context should not be calculated, will not be processed
4125 $total = count($contexts) - 1;
4127 // processed records
4128 $done = 0;
4129 print_progress($done, $total, 10, 0, 'Processing context relations');
4130 $db->debug = false;
4132 //if ($contexts = get_records('context')) {
4133 foreach ($contexts as $context) {
4134 // no need to delete because it's all empty
4135 insert_context_rel($context, false, false);
4136 $db->debug = true;
4137 print_progress(++$done, $total, 10, 0, 'Processing context relations');
4138 $db->debug = false;
4141 $db->debug = $savedb;
4145 // gets the custom name of the role in course
4146 // TODO: proper documentation
4147 function role_get_name($role, $context) {
4149 if ($r = get_record('role_names','roleid', $role->id,'contextid', $context->id)) {
4150 return format_string($r->text);
4151 } else {
4152 return format_string($role->name);
4157 * @param int object - context object (node), from which we find all it's children
4158 * and rebuild all associated context_rel info
4159 * this is needed when a course or course category is moved
4160 * as the children's relationship to grandparents needs to be fixed
4161 * @return int number of contexts rebuilt
4163 function rebuild_context_rel($context) {
4165 $contextlist = array();
4167 if (record_exists('role_capabilities', 'contextid', $context->id)) {
4168 $contextlist[] = $context;
4171 // find all children used in context_rel
4172 if ($childcontexts = get_records('context_rel', 'c2', $context->id)) {
4173 foreach ($childcontexts as $childcontext) {
4174 $contextlist[$childcontext->c1] = get_record('context', 'id', $childcontext->c1);
4178 $i = 0;
4179 // rebuild all the contexts of this list
4180 foreach ($contextlist as $c) {
4181 insert_context_rel($c);
4182 $i++;
4185 return $i;
4189 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
4190 * when we read in a new capability
4191 * most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
4192 * but when we are in grade, all reports/import/export capabilites should be together
4193 * @param string a - component string a
4194 * @param string b - component string b
4195 * @return bool - whether 2 component are in different "sections"
4197 function component_level_changed($cap, $comp, $contextlevel) {
4199 if ($cap->component == 'enrol/authorize' && $comp =='enrol/authorize') {
4200 return false;
4203 if (strstr($cap->component, '/') && strstr($comp, '/')) {
4204 $compsa = explode('/', $cap->component);
4205 $compsb = explode('/', $comp);
4209 // we are in gradebook, still
4210 if (($compsa[0] == 'gradeexport' || $compsa[0] == 'gradeimport' || $compsa[0] == 'gradereport') &&
4211 ($compsb[0] == 'gradeexport' || $compsb[0] == 'gradeimport' || $compsb[0] == 'gradereport')) {
4212 return false;
4216 return ($cap->component != $comp || $cap->contextlevel != $contextlevel);