Changing one generic class-name to a glossary specific one.
[pfb-moodle.git] / lib / accesslib.php
bloba091f0889d20be424da70269daa56eceab47d06e
1 <?php
2 /**
3 * Capability session information format
4 * 2 x 2 array
5 * [context][capability]
6 * where context is the context id of the table 'context'
7 * and capability is a string defining the capability
8 * e.g.
10 * [Capabilities] => [26][mod/forum:viewpost] = 1
11 * [26][mod/forum:startdiscussion] = -8990
12 * [26][mod/forum:editallpost] = -1
13 * [273][moodle:blahblah] = 1
14 * [273][moodle:blahblahblah] = 2
17 require_once $CFG->dirroot.'/lib/blocklib.php';
19 // permission definitions
20 define('CAP_INHERIT', 0);
21 define('CAP_ALLOW', 1);
22 define('CAP_PREVENT', -1);
23 define('CAP_PROHIBIT', -1000);
25 // context definitions
26 define('CONTEXT_SYSTEM', 10);
27 define('CONTEXT_PERSONAL', 20);
28 define('CONTEXT_USER', 30);
29 define('CONTEXT_COURSECAT', 40);
30 define('CONTEXT_COURSE', 50);
31 define('CONTEXT_GROUP', 60);
32 define('CONTEXT_MODULE', 70);
33 define('CONTEXT_BLOCK', 80);
35 // capability risks - see http://docs.moodle.org/en/Hardening_new_Roles_system
36 define('RISK_MANAGETRUST', 0x0001);
37 define('RISK_CONFIG', 0x0002);
38 define('RISK_XSS', 0x0004);
39 define('RISK_PERSONAL', 0x0008);
40 define('RISK_SPAM', 0x0010);
42 require_once($CFG->dirroot.'/group/lib.php');
44 $context_cache = array(); // Cache of all used context objects for performance (by level and instance)
45 $context_cache_id = array(); // Index to above cache by id
48 function get_role_context_caps($roleid, $context) {
49 //this is really slow!!!! - do not use above course context level!
50 $result = array();
51 $result[$context->id] = array();
53 // first emulate the parent context capabilities merging into context
54 $searchcontexts = array_reverse(get_parent_contexts($context));
55 array_push($searchcontexts, $context->id);
56 foreach ($searchcontexts as $cid) {
57 if ($capabilities = get_records_select('role_capabilities', "roleid = $roleid AND contextid = $cid")) {
58 foreach ($capabilities as $cap) {
59 if (!array_key_exists($cap->capability, $result[$context->id])) {
60 $result[$context->id][$cap->capability] = 0;
62 $result[$context->id][$cap->capability] += $cap->permission;
67 // now go through the contexts bellow given context
68 $searchcontexts = get_child_contexts($context);
69 foreach ($searchcontexts as $cid) {
70 if ($capabilities = get_records_select('role_capabilities', "roleid = $roleid AND contextid = $cid")) {
71 foreach ($capabilities as $cap) {
72 if (!array_key_exists($cap->contextid, $result)) {
73 $result[$cap->contextid] = array();
75 $result[$cap->contextid][$cap->capability] = $cap->permission;
80 return $result;
83 function get_role_caps($roleid) {
84 $result = array();
85 if ($capabilities = get_records_select('role_capabilities',"roleid = $roleid")) {
86 foreach ($capabilities as $cap) {
87 if (!array_key_exists($cap->contextid, $result)) {
88 $result[$cap->contextid] = array();
90 $result[$cap->contextid][$cap->capability] = $cap->permission;
93 return $result;
96 function merge_role_caps($caps, $mergecaps) {
97 if (empty($mergecaps)) {
98 return $caps;
101 if (empty($caps)) {
102 return $mergecaps;
105 foreach ($mergecaps as $contextid=>$capabilities) {
106 if (!array_key_exists($contextid, $caps)) {
107 $caps[$contextid] = array();
109 foreach ($capabilities as $capability=>$permission) {
110 if (!array_key_exists($capability, $caps[$contextid])) {
111 $caps[$contextid][$capability] = 0;
113 $caps[$contextid][$capability] += $permission;
116 return $caps;
120 * Loads the capabilities for the default guest role to the current user in a
121 * specific context.
122 * @return object
124 function load_guest_role($return=false) {
125 global $USER;
127 static $guestrole = false;
129 if ($guestrole === false) {
130 if (!$guestrole = get_guest_role()) {
131 return false;
135 if ($return) {
136 return get_role_caps($guestrole->id);
137 } else {
138 has_capability('clearcache');
139 $USER->capabilities = get_role_caps($guestrole->id);
140 return true;
145 * Load default not logged in role capabilities when user is not logged in
146 * @return bool
148 function load_notloggedin_role($return=false) {
149 global $CFG, $USER;
151 if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM)) {
152 return false;
155 if (empty($CFG->notloggedinroleid)) { // Let's set the default to the guest role
156 if ($role = get_guest_role()) {
157 set_config('notloggedinroleid', $role->id);
158 } else {
159 return false;
163 if ($return) {
164 return get_role_caps($CFG->notloggedinroleid);
165 } else {
166 has_capability('clearcache');
167 $USER->capabilities = get_role_caps($CFG->notloggedinroleid);
168 return true;
173 * Load default logged in role capabilities for all logged in users
174 * @return bool
176 function load_defaultuser_role($return=false) {
177 global $CFG, $USER;
179 if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM)) {
180 return false;
183 if (empty($CFG->defaultuserroleid)) { // Let's set the default to the guest role
184 if ($role = get_guest_role()) {
185 set_config('defaultuserroleid', $role->id);
186 } else {
187 return false;
191 $capabilities = get_role_caps($CFG->defaultuserroleid);
193 // fix the guest user heritage:
194 // If the default role is a guest role, then don't copy legacy:guest,
195 // otherwise this user could get confused with a REAL guest. Also don't copy
196 // course:view, which is a hack that's necessary because guest roles are
197 // not really handled properly (see MDL-7513)
198 if (!empty($capabilities[$sitecontext->id]['moodle/legacy:guest'])) {
199 unset($capabilities[$sitecontext->id]['moodle/legacy:guest']);
200 unset($capabilities[$sitecontext->id]['moodle/course:view']);
203 if ($return) {
204 return $capabilities;
205 } else {
206 has_capability('clearcache');
207 $USER->capabilities = $capabilities;
208 return true;
214 * Get the default guest role
215 * @return object role
217 function get_guest_role() {
218 global $CFG;
220 if (empty($CFG->guestroleid)) {
221 if ($roles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW)) {
222 $guestrole = array_shift($roles); // Pick the first one
223 set_config('guestroleid', $guestrole->id);
224 return $guestrole;
225 } else {
226 debugging('Can not find any guest role!');
227 return false;
229 } else {
230 if ($guestrole = get_record('role','id', $CFG->guestroleid)) {
231 return $guestrole;
232 } else {
233 //somebody is messing with guest roles, remove incorrect setting and try to find a new one
234 set_config('guestroleid', '');
235 return get_guest_role();
242 * This functions get all the course categories in proper order
243 * (!)note this only gets course category contexts, and not the site
244 * context
245 * @param object $context
246 * @param int $type
247 * @return array of contextids
249 function get_parent_cats($context, $type) {
251 $parents = array();
253 switch ($type) {
254 // a category can be the parent of another category
255 // there is no limit of depth in this case
256 case CONTEXT_COURSECAT:
257 if (!$cat = get_record('course_categories','id',$context->instanceid)) {
258 break;
261 while (!empty($cat->parent)) {
262 if (!$context = get_context_instance(CONTEXT_COURSECAT, $cat->parent)) {
263 break;
265 $parents[] = $context->id;
266 $cat = get_record('course_categories','id',$cat->parent);
268 break;
270 // a course always fall into a category, unless it's a site course
271 // this happens when SITEID == $course->id
272 // in this case the parent of the course is site context
273 case CONTEXT_COURSE:
274 if (!$course = get_record('course', 'id', $context->instanceid)) {
275 break;
277 if (!$catinstance = get_context_instance(CONTEXT_COURSECAT, $course->category)) {
278 break;
281 $parents[] = $catinstance->id;
283 if (!$cat = get_record('course_categories','id',$course->category)) {
284 break;
286 // Yu: Separating site and site course context
287 if ($course->id == SITEID) {
288 break;
291 while (!empty($cat->parent)) {
292 if (!$context = get_context_instance(CONTEXT_COURSECAT, $cat->parent)) {
293 break;
295 $parents[] = $context->id;
296 $cat = get_record('course_categories','id',$cat->parent);
298 break;
300 default:
301 break;
303 return array_reverse($parents);
309 * This function checks for a capability assertion being true. If it isn't
310 * then the page is terminated neatly with a standard error message
311 * @param string $capability - name of the capability
312 * @param object $context - a context object (record from context table)
313 * @param integer $userid - a userid number
314 * @param bool $doanything - if false, ignore do anything
315 * @param string $errorstring - an errorstring
316 * @param string $stringfile - which stringfile to get it from
318 function require_capability($capability, $context=NULL, $userid=NULL, $doanything=true,
319 $errormessage='nopermissions', $stringfile='') {
321 global $USER, $CFG;
323 /// If the current user is not logged in, then make sure they are (if needed)
325 if (empty($userid) and empty($USER->capabilities)) {
326 if ($context && ($context->contextlevel == CONTEXT_COURSE)) {
327 require_login($context->instanceid);
328 } else if ($context && ($context->contextlevel == CONTEXT_MODULE)) {
329 if ($cm = get_record('course_modules','id',$context->instanceid)) {
330 if (!$course = get_record('course', 'id', $cm->course)) {
331 error('Incorrect course.');
333 require_course_login($course, true, $cm);
335 } else {
336 require_login();
338 } else if ($context && ($context->contextlevel == CONTEXT_SYSTEM)) {
339 if (!empty($CFG->forcelogin)) {
340 require_login();
343 } else {
344 require_login();
348 /// OK, if they still don't have the capability then print a nice error message
350 if (!has_capability($capability, $context, $userid, $doanything)) {
351 $capabilityname = get_capability_string($capability);
352 print_error($errormessage, $stringfile, '', $capabilityname);
358 * This function returns whether the current user has the capability of performing a function
359 * For example, we can do has_capability('mod/forum:replypost',$cm) in forum
360 * only one of the 4 (moduleinstance, courseid, site, userid) would be set at 1 time
361 * This is a recursive funciton.
362 * @uses $USER
363 * @param string $capability - name of the capability (or debugcache or clearcache)
364 * @param object $context - a context object (record from context table)
365 * @param integer $userid - a userid number
366 * @param bool $doanything - if false, ignore do anything
367 * @return bool
369 function has_capability($capability, $context=NULL, $userid=NULL, $doanything=true) {
371 global $USER, $CONTEXT, $CFG;
373 static $capcache = array(); // Cache of capabilities
376 /// Cache management
378 if ($capability == 'clearcache') {
379 $capcache = array(); // Clear ALL the capability cache
380 return false;
383 /// Some sanity checks
384 if (debugging('',DEBUG_DEVELOPER)) {
385 if ($capability == 'debugcache') {
386 print_object($capcache);
387 return true;
389 if (!record_exists('capabilities', 'name', $capability)) {
390 debugging('Capability "'.$capability.'" was not found! This should be fixed in code.');
392 if ($doanything != true and $doanything != false) {
393 debugging('Capability parameter "doanything" is wierd ("'.$doanything.'"). This should be fixed in code.');
395 if (!is_object($context) && $context !== NULL) {
396 debugging('Incorrect context parameter "'.$context.'" for has_capability(), object expected! This should be fixed in code.');
400 /// Make sure we know the current context
401 if (empty($context)) { // Use default CONTEXT if none specified
402 if (empty($CONTEXT)) {
403 return false;
404 } else {
405 $context = $CONTEXT;
407 } else { // A context was given to us
408 if (empty($CONTEXT)) {
409 $CONTEXT = $context; // Store FIRST used context in this global as future default
413 /// Check and return cache in case we've processed this one before.
414 $requsteduser = empty($userid) ? $USER->id : $userid; // find out the requested user id, $USER->id might have been changed
415 $cachekey = $capability.'_'.$context->id.'_'.intval($requsteduser).'_'.intval($doanything);
417 if (isset($capcache[$cachekey])) {
418 return $capcache[$cachekey];
422 /// Load up the capabilities list or item as necessary
423 if ($userid) {
424 if (empty($USER->id) or ($userid != $USER->id) or empty($USER->capabilities)) {
426 //caching - helps user switching in cron
427 static $guestuserid = false; // guest user id
428 static $guestcaps = false; // guest caps
429 static $defcaps = false; // default user caps - this might help cron
431 if ($guestuserid === false) {
432 $guestuserid = get_field('user', 'id', 'username', 'guest');
435 if ($userid == $guestuserid) {
436 if ($guestcaps === false) {
437 $guestcaps = load_guest_role(true);
439 $capabilities = $guestcaps;
441 } else {
442 // this is expensive!
443 $capabilities = load_user_capability($capability, $context, $userid);
444 if ($defcaps === false) {
445 $defcaps = load_defaultuser_role(true);
447 $capabilities = merge_role_caps($capabilities, $defcaps);
450 } else { //$USER->id == $userid and needed capabilities already present
451 $capabilities = $USER->capabilities;
454 } else { // no userid
455 if (empty($USER->capabilities)) {
456 load_all_capabilities(); // expensive - but we have to do it once anyway
458 $capabilities = $USER->capabilities;
459 $userid = $USER->id;
462 /// We act a little differently when switchroles is active
464 $switchroleactive = false; // Assume it isn't active in this context
467 /// First deal with the "doanything" capability
469 if ($doanything) {
471 /// First make sure that we aren't in a "switched role"
473 if (!empty($USER->switchrole)) { // Switchrole is active somewhere!
474 if (!empty($USER->switchrole[$context->id])) { // Because of current context
475 $switchroleactive = true;
476 } else { // Check parent contexts
477 if ($parentcontextids = get_parent_contexts($context)) {
478 foreach ($parentcontextids as $parentcontextid) {
479 if (!empty($USER->switchrole[$parentcontextid])) { // Yep, switchroles active here
480 $switchroleactive = true;
481 break;
488 /// Check the site context for doanything (most common) first
490 if (empty($switchroleactive)) { // Ignore site setting if switchrole is active
491 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
492 if (isset($capabilities[$sitecontext->id]['moodle/site:doanything'])) {
493 $result = (0 < $capabilities[$sitecontext->id]['moodle/site:doanything']);
494 $capcache[$cachekey] = $result;
495 return $result;
498 /// If it's not set at site level, it is possible to be set on other levels
499 /// Though this usage is not common and can cause risks
500 switch ($context->contextlevel) {
502 case CONTEXT_COURSECAT:
503 // Check parent cats.
504 $parentcats = get_parent_cats($context, CONTEXT_COURSECAT);
505 foreach ($parentcats as $parentcat) {
506 if (isset($capabilities[$parentcat]['moodle/site:doanything'])) {
507 $result = (0 < $capabilities[$parentcat]['moodle/site:doanything']);
508 $capcache[$cachekey] = $result;
509 return $result;
512 break;
514 case CONTEXT_COURSE:
515 // Check parent cat.
516 $parentcats = get_parent_cats($context, CONTEXT_COURSE);
518 foreach ($parentcats as $parentcat) {
519 if (isset($capabilities[$parentcat]['do_anything'])) {
520 $result = (0 < $capabilities[$parentcat]['do_anything']);
521 $capcache[$cachekey] = $result;
522 return $result;
525 break;
527 case CONTEXT_GROUP:
528 // Find course.
529 $courseid = groups_get_course($context->instanceid);
530 $courseinstance = get_context_instance(CONTEXT_COURSE, $courseid);
532 $parentcats = get_parent_cats($courseinstance, CONTEXT_COURSE);
533 foreach ($parentcats as $parentcat) {
534 if (isset($capabilities[$parentcat]['do_anything'])) {
535 $result = (0 < $capabilities[$parentcat]['do_anything']);
536 $capcache[$cachekey] = $result;
537 return $result;
541 $coursecontext = '';
542 if (isset($capabilities[$courseinstance->id]['do_anything'])) {
543 $result = (0 < $capabilities[$courseinstance->id]['do_anything']);
544 $capcache[$cachekey] = $result;
545 return $result;
548 break;
550 case CONTEXT_MODULE:
551 // Find course.
552 $cm = get_record('course_modules', 'id', $context->instanceid);
553 $courseinstance = get_context_instance(CONTEXT_COURSE, $cm->course);
555 if ($parentcats = get_parent_cats($courseinstance, CONTEXT_COURSE)) {
556 foreach ($parentcats as $parentcat) {
557 if (isset($capabilities[$parentcat]['do_anything'])) {
558 $result = (0 < $capabilities[$parentcat]['do_anything']);
559 $capcache[$cachekey] = $result;
560 return $result;
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_BLOCK:
574 // not necessarily 1 to 1 to course.
575 $block = get_record('block_instance','id',$context->instanceid);
576 if ($block->pagetype == 'course-view') {
577 $courseinstance = get_context_instance(CONTEXT_COURSE, $block->pageid); // needs check
578 $parentcats = get_parent_cats($courseinstance, CONTEXT_COURSE);
580 foreach ($parentcats as $parentcat) {
581 if (isset($capabilities[$parentcat]['do_anything'])) {
582 $result = (0 < $capabilities[$parentcat]['do_anything']);
583 $capcache[$cachekey] = $result;
584 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;
593 } else { // if not course-view type of blocks, check site
594 if (isset($capabilities[$sitecontext->id]['do_anything'])) {
595 $result = (0 < $capabilities[$sitecontext->id]['do_anything']);
596 $capcache[$cachekey] = $result;
597 return $result;
600 break;
602 default:
603 // CONTEXT_SYSTEM: CONTEXT_PERSONAL: CONTEXT_USER:
604 // Do nothing, because the parents are site context
605 // which has been checked already
606 break;
609 // Last: check self.
610 if (isset($capabilities[$context->id]['do_anything'])) {
611 $result = (0 < $capabilities[$context->id]['do_anything']);
612 $capcache[$cachekey] = $result;
613 return $result;
616 // do_anything has not been set, we now look for it the normal way.
617 $result = (0 < capability_search($capability, $context, $capabilities, $switchroleactive));
618 $capcache[$cachekey] = $result;
619 return $result;
625 * In a separate function so that we won't have to deal with do_anything.
626 * again. Used by function has_capability().
627 * @param $capability - capability string
628 * @param $context - the context object
629 * @param $capabilities - either $USER->capability or loaded array (for other users)
630 * @return permission (int)
632 function capability_search($capability, $context, $capabilities, $switchroleactive=false) {
634 global $USER, $CFG;
636 if (!isset($context->id)) {
637 return 0;
639 // if already set in the array explicitly, no need to look for it in parent
640 // context any longer
641 if (isset($capabilities[$context->id][$capability])) {
642 return ($capabilities[$context->id][$capability]);
645 /* Then, we check the cache recursively */
646 $permission = 0;
648 switch ($context->contextlevel) {
650 case CONTEXT_SYSTEM: // by now it's a definite an inherit
651 $permission = 0;
652 break;
654 case CONTEXT_PERSONAL:
655 $parentcontext = get_context_instance(CONTEXT_SYSTEM);
656 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
657 break;
659 case CONTEXT_USER:
660 $parentcontext = get_context_instance(CONTEXT_SYSTEM);
661 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
662 break;
664 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
665 $coursecat = get_record('course_categories','id',$context->instanceid);
666 if (!empty($coursecat->parent)) { // return parent value if it exists
667 $parentcontext = get_context_instance(CONTEXT_COURSECAT, $coursecat->parent);
668 } else { // else return site value
669 $parentcontext = get_context_instance(CONTEXT_SYSTEM);
671 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
672 break;
674 case CONTEXT_COURSE: // 1 to 1 to course cat
675 if (empty($switchroleactive)) {
676 // find the course cat, and return its value
677 $course = get_record('course','id',$context->instanceid);
678 if ($course->id == SITEID) { // In 1.8 we've separated site course and system
679 $parentcontext = get_context_instance(CONTEXT_SYSTEM);
680 } else {
681 $parentcontext = get_context_instance(CONTEXT_COURSECAT, $course->category);
683 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
685 break;
687 case CONTEXT_GROUP: // 1 to 1 to course
688 $courseid = groups_get_course($context->instanceid);
689 $parentcontext = get_context_instance(CONTEXT_COURSE, $courseid);
690 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
691 break;
693 case CONTEXT_MODULE: // 1 to 1 to course
694 $cm = get_record('course_modules','id',$context->instanceid);
695 $parentcontext = get_context_instance(CONTEXT_COURSE, $cm->course);
696 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
697 break;
699 case CONTEXT_BLOCK: // not necessarily 1 to 1 to course
700 $block = get_record('block_instance','id',$context->instanceid);
701 if ($block->pagetype == 'course-view') {
702 $parentcontext = get_context_instance(CONTEXT_COURSE, $block->pageid); // needs check
703 } else {
704 $parentcontext = get_context_instance(CONTEXT_SYSTEM);
706 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
707 break;
709 default:
710 error ('This is an unknown context (' . $context->contextlevel . ') in capability_search!');
711 return false;
714 return $permission;
718 * auxillary function for load_user_capabilities()
719 * checks if context c1 is a parent (or itself) of context c2
720 * @param int $c1 - context id of context 1
721 * @param int $c2 - context id of context 2
722 * @return bool
724 function is_parent_context($c1, $c2) {
725 static $parentsarray;
727 // context can be itself and this is ok
728 if ($c1 == $c2) {
729 return true;
731 // hit in cache?
732 if (isset($parentsarray[$c1][$c2])) {
733 return $parentsarray[$c1][$c2];
736 if (!$co2 = get_record('context', 'id', $c2)) {
737 return false;
740 if (!$parents = get_parent_contexts($co2)) {
741 return false;
744 foreach ($parents as $parent) {
745 $parentsarray[$parent][$c2] = true;
748 if (in_array($c1, $parents)) {
749 return true;
750 } else { // else not a parent, set the cache anyway
751 $parentsarray[$c1][$c2] = false;
752 return false;
758 * auxillary function for load_user_capabilities()
759 * handler in usort() to sort contexts according to level
760 * @param object contexta
761 * @param object contextb
762 * @return int
764 function roles_context_cmp($contexta, $contextb) {
765 if ($contexta->contextlevel == $contextb->contextlevel) {
766 return 0;
768 return ($contexta->contextlevel < $contextb->contextlevel) ? -1 : 1;
772 * It will build an array of all the capabilities at each level
773 * i.e. site/metacourse/course_category/course/moduleinstance
774 * Note we should only load capabilities if they are explicitly assigned already,
775 * we should not load all module's capability!
777 * [Capabilities] => [26][forum_post] = 1
778 * [26][forum_start] = -8990
779 * [26][forum_edit] = -1
780 * [273][blah blah] = 1
781 * [273][blah blah blah] = 2
783 * @param $capability string - Only get a specific capability (string)
784 * @param $context object - Only get capabilities for a specific context object
785 * @param $userid integer - the id of the user whose capabilities we want to load
786 * @return array of permissions (or nothing if they get assigned to $USER)
788 function load_user_capability($capability='', $context = NULL, $userid='') {
790 global $USER, $CFG;
792 // this flag has not been set!
793 // (not clean install, or upgraded successfully to 1.7 and up)
794 if (empty($CFG->rolesactive)) {
795 return false;
798 if (empty($userid)) {
799 if (empty($USER->id)) { // We have no user to get capabilities for
800 debugging('User not logged in for load_user_capability!');
801 return false;
803 unset($USER->capabilities); // We don't want possible older capabilites hanging around
805 check_enrolment_plugins($USER); // Call "enrol" system to ensure that we have the correct picture
807 $userid = $USER->id;
808 $otheruserid = false;
809 } else {
810 if (!$user = get_record('user', 'id', $userid)) {
811 debugging('Non-existent userid in load_user_capability!');
812 return false;
815 check_enrolment_plugins($user); // Ensure that we have the correct picture
817 $otheruserid = $userid;
821 /// First we generate a list of all relevant contexts of the user
823 $usercontexts = array();
825 if ($context) { // if context is specified
826 $usercontexts = get_parent_contexts($context);
827 $usercontexts[] = $context->id; // Add the current context as well
828 } else { // else, we load everything
829 if ($userroles = get_records('role_assignments','userid',$userid)) {
830 foreach ($userroles as $userrole) {
831 if (!in_array($userrole->contextid, $usercontexts)) {
832 $usercontexts[] = $userrole->contextid;
838 /// Set up SQL fragments for searching contexts
840 if ($usercontexts) {
841 $listofcontexts = '('.implode(',', $usercontexts).')';
842 $searchcontexts1 = "c1.id IN $listofcontexts AND";
843 } else {
844 $searchcontexts1 = '';
847 if ($capability) {
848 $capsearch = " AND rc.capability = '$capability' ";
849 } else {
850 $capsearch ="";
853 /// Then we use 1 giant SQL to bring out all relevant capabilities.
854 /// The first part gets the capabilities of orginal role.
855 /// The second part gets the capabilities of overriden roles.
857 $siteinstance = get_context_instance(CONTEXT_SYSTEM);
858 $capabilities = array(); // Reinitialize.
860 // SQL for normal capabilities
861 $SQL1 = "SELECT rc.capability, c1.id as id1, c1.id as id2, (c1.contextlevel * 100) AS aggrlevel,
862 SUM(rc.permission) AS sum
863 FROM
864 {$CFG->prefix}role_assignments ra,
865 {$CFG->prefix}role_capabilities rc,
866 {$CFG->prefix}context c1
867 WHERE
868 ra.contextid=c1.id AND
869 ra.roleid=rc.roleid AND
870 ra.userid=$userid AND
871 $searchcontexts1
872 rc.contextid=$siteinstance->id
873 $capsearch
874 GROUP BY
875 rc.capability, c1.id, c1.contextlevel * 100
876 HAVING
877 SUM(rc.permission) != 0
879 UNION ALL
881 SELECT rc.capability, c1.id as id1, c2.id as id2, (c1.contextlevel * 100 + c2.contextlevel) AS aggrlevel,
882 SUM(rc.permission) AS sum
883 FROM
884 {$CFG->prefix}role_assignments ra LEFT JOIN
885 {$CFG->prefix}role_capabilities rc on ra.roleid = rc.roleid LEFT JOIN
886 {$CFG->prefix}context c1 on ra.contextid = c1.id LEFT JOIN
887 {$CFG->prefix}context c2 on rc.contextid = c2.id LEFT JOIN
888 {$CFG->prefix}context_rel cr on cr.c1 = c2.id
889 WHERE
890 ra.userid=$userid AND
891 $searchcontexts1
892 rc.contextid != $siteinstance->id
893 $capsearch
894 AND cr.c2 = c1.id
895 GROUP BY
896 rc.capability, c1.id, c2.id, c1.contextlevel * 100 + c2.contextlevel
897 HAVING
898 SUM(rc.permission) != 0
899 ORDER BY
900 aggrlevel ASC";
902 if (!$rs = get_recordset_sql($SQL1)) {
903 error("Query failed in load_user_capability.");
906 if ($rs && $rs->RecordCount() > 0) {
907 while ($caprec = rs_fetch_next_record($rs)) {
908 $array = (array)$caprec;
909 $temprecord = new object;
911 foreach ($array as $key=>$val) {
912 if ($key == 'aggrlevel') {
913 $temprecord->contextlevel = $val;
914 } else {
915 $temprecord->{$key} = $val;
918 $capabilities[] = $temprecord;
920 rs_close($rs);
923 // SQL for overrides
924 // this is take out because we have no way of making sure c1 is indeed related to c2 (parent)
925 // if we do not group by sum, it is possible to have multiple records of rc.capability, c1.id, c2.id, tuple having
926 // different values, we can maually sum it when we go through the list
930 $SQL2 = "SELECT rc.capability, c1.id as id1, c2.id as id2, (c1.contextlevel * 100 + c2.contextlevel) AS aggrlevel,
931 rc.permission AS sum
932 FROM
933 {$CFG->prefix}role_assignments ra,
934 {$CFG->prefix}role_capabilities rc,
935 {$CFG->prefix}context c1,
936 {$CFG->prefix}context c2
937 WHERE
938 ra.contextid=c1.id AND
939 ra.roleid=rc.roleid AND
940 ra.userid=$userid AND
941 rc.contextid=c2.id AND
942 $searchcontexts1
943 rc.contextid != $siteinstance->id
944 $capsearch
946 GROUP BY
947 rc.capability, (c1.contextlevel * 100 + c2.contextlevel), c1.id, c2.id, rc.permission
948 ORDER BY
949 aggrlevel ASC
950 ";*/
953 if (!$rs = get_recordset_sql($SQL2)) {
954 error("Query failed in load_user_capability.");
957 if ($rs && $rs->RecordCount() > 0) {
958 while ($caprec = rs_fetch_next_record($rs)) {
959 $array = (array)$caprec;
960 $temprecord = new object;
962 foreach ($array as $key=>$val) {
963 if ($key == 'aggrlevel') {
964 $temprecord->contextlevel = $val;
965 } else {
966 $temprecord->{$key} = $val;
969 // for overrides, we have to make sure that context2 is a child of context1
970 // otherwise the combination makes no sense
971 //if (is_parent_context($temprecord->id1, $temprecord->id2)) {
972 $capabilities[] = $temprecord;
973 //} // only write if relevant
975 rs_close($rs);
978 // this step sorts capabilities according to the contextlevel
979 // it is very important because the order matters when we
980 // go through each capabilities later. (i.e. higher level contextlevel
981 // will override lower contextlevel settings
982 usort($capabilities, 'roles_context_cmp');
984 /* so up to this point we should have somethign like this
985 * $capabilities[1] ->contextlevel = 1000
986 ->module = 0 // changed from SITEID in 1.8 (??)
987 ->capability = do_anything
988 ->id = 1 (id is the context id)
989 ->sum = 0
991 * $capabilities[2] ->contextlevel = 1000
992 ->module = 0 // changed from SITEID in 1.8 (??)
993 ->capability = post_messages
994 ->id = 1
995 ->sum = -9000
997 * $capabilittes[3] ->contextlevel = 3000
998 ->module = course
999 ->capability = view_course_activities
1000 ->id = 25
1001 ->sum = 1
1003 * $capabilittes[4] ->contextlevel = 3000
1004 ->module = course
1005 ->capability = view_course_activities
1006 ->id = 26
1007 ->sum = 0 (this is another course)
1009 * $capabilities[5] ->contextlevel = 3050
1010 ->module = course
1011 ->capability = view_course_activities
1012 ->id = 25 (override in course 25)
1013 ->sum = -1
1014 * ....
1015 * now we proceed to write the session array, going from top to bottom
1016 * at anypoint, we need to go up and check parent to look for prohibit
1018 // print_object($capabilities);
1020 /* This is where we write to the actualy capabilities array
1021 * what we need to do from here on is
1022 * going down the array from lowest level to highest level
1023 * 1) recursively check for prohibit,
1024 * if any, we write prohibit
1025 * else, we write the value
1026 * 2) at an override level, we overwrite current level
1027 * if it's not set to prohibit already, and if different
1028 * ........ that should be it ........
1031 // This is the flag used for detecting the current context level. Since we are going through
1032 // the array in ascending order of context level. For normal capabilities, there should only
1033 // be 1 value per (capability, contextlevel, context), because they are already summed. But,
1034 // for overrides, since we are processing them separate, we need to sum the relevcant entries.
1035 // We set this flag when we hit a new level.
1036 // If the flag is already set, we keep adding (summing), otherwise, we just override previous
1037 // settings (from lower level contexts)
1038 $capflags = array(); // (contextid, contextlevel, capability)
1039 $usercap = array(); // for other user's capabilities
1040 foreach ($capabilities as $capability) {
1042 if (!$context = get_context_instance_by_id($capability->id2)) {
1043 continue; // incorrect stale context
1046 if (!empty($otheruserid)) { // we are pulling out other user's capabilities, do not write to session
1048 if (capability_prohibits($capability->capability, $context, $capability->sum, $usercap)) {
1049 $usercap[$capability->id2][$capability->capability] = CAP_PROHIBIT;
1050 continue;
1052 if (isset($usercap[$capability->id2][$capability->capability])) { // use isset because it can be sum 0
1053 if (!empty($capflags[$capability->id2][$capability->contextlevel][$capability->capability])) {
1054 $usercap[$capability->id2][$capability->capability] += $capability->sum;
1055 } else { // else we override, and update flag
1056 $usercap[$capability->id2][$capability->capability] = $capability->sum;
1057 $capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
1059 } else {
1060 $usercap[$capability->id2][$capability->capability] = $capability->sum;
1061 $capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
1064 } else {
1066 if (capability_prohibits($capability->capability, $context, $capability->sum)) { // if any parent or parent's parent is set to prohibit
1067 $USER->capabilities[$capability->id2][$capability->capability] = CAP_PROHIBIT;
1068 continue;
1071 // if no parental prohibit set
1072 // just write to session, i am not sure this is correct yet
1073 // since 3050 shows up after 3000, and 3070 shows up after 3050,
1074 // it should be ok just to overwrite like this, provided that there's no
1075 // parental prohibits
1076 // we need to write even if it's 0, because it could be an inherit override
1077 if (isset($USER->capabilities[$capability->id2][$capability->capability])) {
1078 if (!empty($capflags[$capability->id2][$capability->contextlevel][$capability->capability])) {
1079 $USER->capabilities[$capability->id2][$capability->capability] += $capability->sum;
1080 } else { // else we override, and update flag
1081 $USER->capabilities[$capability->id2][$capability->capability] = $capability->sum;
1082 $capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
1084 } else {
1085 $USER->capabilities[$capability->id2][$capability->capability] = $capability->sum;
1086 $capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
1091 // now we don't care about the huge array anymore, we can dispose it.
1092 unset($capabilities);
1093 unset($capflags);
1095 if (!empty($otheruserid)) {
1096 return $usercap; // return the array
1102 * A convenience function to completely load all the capabilities
1103 * for the current user. This is what gets called from login, for example.
1105 function load_all_capabilities() {
1106 global $USER;
1108 //caching - helps user switching in cron
1109 static $defcaps = false;
1111 unset($USER->mycourses); // Reset a cache used by get_my_courses
1113 if (isguestuser()) {
1114 load_guest_role(); // All non-guest users get this by default
1116 } else if (isloggedin()) {
1117 if ($defcaps === false) {
1118 $defcaps = load_defaultuser_role(true);
1121 if (empty($USER->realuser)) {
1122 load_user_capability();
1123 } else {
1124 if ($USER->loginascontext->contextlevel != CONTEXT_SYSTEM) {
1125 // load only course caqpabilitites - it may not always work as expected
1126 load_user_capability('', $USER->loginascontext);
1127 // find all child contexts and unset the rest
1128 $children = get_child_contexts($USER->loginascontext);
1129 $children[] = $USER->loginascontext->id;
1130 foreach ($USER->capabilities as $conid => $caps) {
1131 if (!in_array($conid, $children)) {
1132 unset($USER->capabilities[$conid]);
1135 } else {
1136 load_user_capability();
1140 if (!empty($USER->switchrole)) {
1142 foreach ($USER->switchrole as $contextid => $roleid) {
1143 $context = get_context_instance_by_id($contextid);
1145 // first prune context and any child contexts
1146 $children = get_child_contexts($context);
1147 foreach ($children as $childid) {
1148 unset($USER->capabilities[$childid]);
1150 unset($USER->capabilities[$contextid]);
1152 // now merge all switched role caps in context and bellow
1153 $swithccaps = get_role_context_caps($roleid, $context);
1154 $USER->capabilities = merge_role_caps($USER->capabilities, $swithccaps);
1158 $USER->capabilities = merge_role_caps($USER->capabilities, $defcaps);
1160 } else {
1161 load_notloggedin_role();
1167 * Check all the login enrolment information for the given user object
1168 * by querying the enrolment plugins
1170 function check_enrolment_plugins(&$user) {
1171 global $CFG;
1173 static $inprogress; // To prevent this function being called more than once in an invocation
1175 if (!empty($inprogress[$user->id])) {
1176 return;
1179 $inprogress[$user->id] = true; // Set the flag
1181 require_once($CFG->dirroot .'/enrol/enrol.class.php');
1183 if (!($plugins = explode(',', $CFG->enrol_plugins_enabled))) {
1184 $plugins = array($CFG->enrol);
1187 foreach ($plugins as $plugin) {
1188 $enrol = enrolment_factory::factory($plugin);
1189 if (method_exists($enrol, 'setup_enrolments')) { /// Plugin supports Roles (Moodle 1.7 and later)
1190 $enrol->setup_enrolments($user);
1191 } else { /// Run legacy enrolment methods
1192 if (method_exists($enrol, 'get_student_courses')) {
1193 $enrol->get_student_courses($user);
1195 if (method_exists($enrol, 'get_teacher_courses')) {
1196 $enrol->get_teacher_courses($user);
1199 /// deal with $user->students and $user->teachers stuff
1200 unset($user->student);
1201 unset($user->teacher);
1203 unset($enrol);
1206 unset($inprogress[$user->id]); // Unset the flag
1211 * This is a recursive function that checks whether the capability in this
1212 * context, or the parent capabilities are set to prohibit.
1214 * At this point, we can probably just use the values already set in the
1215 * session variable, since we are going down the level. Any prohit set in
1216 * parents would already reflect in the session.
1218 * @param $capability - capability name
1219 * @param $sum - sum of all capabilities values
1220 * @param $context - the context object
1221 * @param $array - when loading another user caps, their caps are not stored in session but an array
1223 function capability_prohibits($capability, $context, $sum='', $array='') {
1224 global $USER;
1226 // caching, mainly to save unnecessary sqls
1227 static $prohibits; //[capability][contextid]
1228 if (isset($prohibits[$capability][$context->id])) {
1229 return $prohibits[$capability][$context->id];
1232 if (empty($context->id)) {
1233 $prohibits[$capability][$context->id] = false;
1234 return false;
1237 if (empty($capability)) {
1238 $prohibits[$capability][$context->id] = false;
1239 return false;
1242 if ($sum < (CAP_PROHIBIT/2)) {
1243 // If this capability is set to prohibit.
1244 $prohibits[$capability][$context->id] = true;
1245 return true;
1248 if (!empty($array)) {
1249 if (isset($array[$context->id][$capability])
1250 && $array[$context->id][$capability] < (CAP_PROHIBIT/2)) {
1251 $prohibits[$capability][$context->id] = true;
1252 return true;
1254 } else {
1255 // Else if set in session.
1256 if (isset($USER->capabilities[$context->id][$capability])
1257 && $USER->capabilities[$context->id][$capability] < (CAP_PROHIBIT/2)) {
1258 $prohibits[$capability][$context->id] = true;
1259 return true;
1262 switch ($context->contextlevel) {
1264 case CONTEXT_SYSTEM:
1265 // By now it's a definite an inherit.
1266 return 0;
1267 break;
1269 case CONTEXT_PERSONAL:
1270 $parent = get_context_instance(CONTEXT_SYSTEM);
1271 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1272 return $prohibits[$capability][$context->id];
1273 break;
1275 case CONTEXT_USER:
1276 $parent = get_context_instance(CONTEXT_SYSTEM);
1277 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1278 return $prohibits[$capability][$context->id];
1279 break;
1281 case CONTEXT_COURSECAT:
1282 // Coursecat -> coursecat or site.
1283 if (!$coursecat = get_record('course_categories','id',$context->instanceid)) {
1284 $prohibits[$capability][$context->id] = false;
1285 return false;
1287 if (!empty($coursecat->parent)) {
1288 // return parent value if exist.
1289 $parent = get_context_instance(CONTEXT_COURSECAT, $coursecat->parent);
1290 } else {
1291 // Return site value.
1292 $parent = get_context_instance(CONTEXT_SYSTEM);
1294 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1295 return $prohibits[$capability][$context->id];
1296 break;
1298 case CONTEXT_COURSE:
1299 // 1 to 1 to course cat.
1300 // Find the course cat, and return its value.
1301 if (!$course = get_record('course','id',$context->instanceid)) {
1302 $prohibits[$capability][$context->id] = false;
1303 return false;
1305 // Yu: Separating site and site course context
1306 if ($course->id == SITEID) {
1307 $parent = get_context_instance(CONTEXT_SYSTEM);
1308 } else {
1309 $parent = get_context_instance(CONTEXT_COURSECAT, $course->category);
1311 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1312 return $prohibits[$capability][$context->id];
1313 break;
1315 case CONTEXT_GROUP:
1316 // 1 to 1 to course.
1317 if (!$courseid = groups_get_course($context->instanceid)) {
1318 $prohibits[$capability][$context->id] = false;
1319 return false;
1321 $parent = get_context_instance(CONTEXT_COURSE, $courseid);
1322 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1323 return $prohibits[$capability][$context->id];
1324 break;
1326 case CONTEXT_MODULE:
1327 // 1 to 1 to course.
1328 if (!$cm = get_record('course_modules','id',$context->instanceid)) {
1329 $prohibits[$capability][$context->id] = false;
1330 return false;
1332 $parent = get_context_instance(CONTEXT_COURSE, $cm->course);
1333 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1334 return $prohibits[$capability][$context->id];
1335 break;
1337 case CONTEXT_BLOCK:
1338 // 1 to 1 to course.
1339 if (!$block = get_record('block_instance','id',$context->instanceid)) {
1340 $prohibits[$capability][$context->id] = false;
1341 return false;
1343 $parent = get_context_instance(CONTEXT_COURSE, $block->pageid); // needs check
1344 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1345 return $prohibits[$capability][$context->id];
1346 break;
1348 default:
1349 print_error('unknowncontext');
1350 return false;
1356 * A print form function. This should either grab all the capabilities from
1357 * files or a central table for that particular module instance, then present
1358 * them in check boxes. Only relevant capabilities should print for known
1359 * context.
1360 * @param $mod - module id of the mod
1362 function print_capabilities($modid=0) {
1363 global $CFG;
1365 $capabilities = array();
1367 if ($modid) {
1368 // We are in a module specific context.
1370 // Get the mod's name.
1371 // Call the function that grabs the file and parse.
1372 $cm = get_record('course_modules', 'id', $modid);
1373 $module = get_record('modules', 'id', $cm->module);
1375 } else {
1376 // Print all capabilities.
1377 foreach ($capabilities as $capability) {
1378 // Prints the check box component.
1385 * Installs the roles system.
1386 * This function runs on a fresh install as well as on an upgrade from the old
1387 * hard-coded student/teacher/admin etc. roles to the new roles system.
1389 function moodle_install_roles() {
1391 global $CFG, $db;
1393 /// Create a system wide context for assignemnt.
1394 $systemcontext = $context = get_context_instance(CONTEXT_SYSTEM);
1397 /// Create default/legacy roles and capabilities.
1398 /// (1 legacy capability per legacy role at system level).
1400 $adminrole = create_role(addslashes(get_string('administrator')), 'admin',
1401 addslashes(get_string('administratordescription')), 'moodle/legacy:admin');
1402 $coursecreatorrole = create_role(addslashes(get_string('coursecreators')), 'coursecreator',
1403 addslashes(get_string('coursecreatorsdescription')), 'moodle/legacy:coursecreator');
1404 $editteacherrole = create_role(addslashes(get_string('defaultcourseteacher')), 'editingteacher',
1405 addslashes(get_string('defaultcourseteacherdescription')), 'moodle/legacy:editingteacher');
1406 $noneditteacherrole = create_role(addslashes(get_string('noneditingteacher')), 'teacher',
1407 addslashes(get_string('noneditingteacherdescription')), 'moodle/legacy:teacher');
1408 $studentrole = create_role(addslashes(get_string('defaultcoursestudent')), 'student',
1409 addslashes(get_string('defaultcoursestudentdescription')), 'moodle/legacy:student');
1410 $guestrole = create_role(addslashes(get_string('guest')), 'guest',
1411 addslashes(get_string('guestdescription')), 'moodle/legacy:guest');
1412 $userrole = create_role(addslashes(get_string('authenticateduser')), 'user',
1413 addslashes(get_string('authenticateduserdescription')), 'moodle/legacy:user');
1415 /// Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles
1417 if (!assign_capability('moodle/site:doanything', CAP_ALLOW, $adminrole, $systemcontext->id)) {
1418 error('Could not assign moodle/site:doanything to the admin role');
1420 if (!update_capabilities()) {
1421 error('Had trouble upgrading the core capabilities for the Roles System');
1424 /// Look inside user_admin, user_creator, user_teachers, user_students and
1425 /// assign above new roles. If a user has both teacher and student role,
1426 /// only teacher role is assigned. The assignment should be system level.
1428 $dbtables = $db->MetaTables('TABLES');
1430 /// Set up the progress bar
1432 $usertables = array('user_admins', 'user_coursecreators', 'user_teachers', 'user_students');
1434 $totalcount = $progresscount = 0;
1435 foreach ($usertables as $usertable) {
1436 if (in_array($CFG->prefix.$usertable, $dbtables)) {
1437 $totalcount += count_records($usertable);
1441 print_progress(0, $totalcount, 5, 1, 'Processing role assignments');
1443 /// Upgrade the admins.
1444 /// Sort using id ASC, first one is primary admin.
1446 if (in_array($CFG->prefix.'user_admins', $dbtables)) {
1447 if ($rs = get_recordset_sql('SELECT * from '.$CFG->prefix.'user_admins ORDER BY ID ASC')) {
1448 while ($admin = rs_fetch_next_record($rs)) {
1449 role_assign($adminrole, $admin->userid, 0, $systemcontext->id);
1450 $progresscount++;
1451 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1453 rs_close($rs);
1455 } else {
1456 // This is a fresh install.
1460 /// Upgrade course creators.
1461 if (in_array($CFG->prefix.'user_coursecreators', $dbtables)) {
1462 if ($rs = get_recordset('user_coursecreators')) {
1463 while ($coursecreator = rs_fetch_next_record($rs)) {
1464 role_assign($coursecreatorrole, $coursecreator->userid, 0, $systemcontext->id);
1465 $progresscount++;
1466 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1468 rs_close($rs);
1473 /// Upgrade editting teachers and non-editting teachers.
1474 if (in_array($CFG->prefix.'user_teachers', $dbtables)) {
1475 if ($rs = get_recordset('user_teachers')) {
1476 while ($teacher = rs_fetch_next_record($rs)) {
1478 // removed code here to ignore site level assignments
1479 // since the contexts are separated now
1481 // populate the user_lastaccess table
1482 $access = new object();
1483 $access->timeaccess = $teacher->timeaccess;
1484 $access->userid = $teacher->userid;
1485 $access->courseid = $teacher->course;
1486 insert_record('user_lastaccess', $access);
1488 // assign the default student role
1489 $coursecontext = get_context_instance(CONTEXT_COURSE, $teacher->course); // needs cache
1490 // hidden teacher
1491 if ($teacher->authority == 0) {
1492 $hiddenteacher = 1;
1493 } else {
1494 $hiddenteacher = 0;
1497 if ($teacher->editall) { // editting teacher
1498 role_assign($editteacherrole, $teacher->userid, 0, $coursecontext->id, 0, 0, $hiddenteacher);
1499 } else {
1500 role_assign($noneditteacherrole, $teacher->userid, 0, $coursecontext->id, 0, 0, $hiddenteacher);
1502 $progresscount++;
1503 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1505 rs_close($rs);
1510 /// Upgrade students.
1511 if (in_array($CFG->prefix.'user_students', $dbtables)) {
1512 if ($rs = get_recordset('user_students')) {
1513 while ($student = rs_fetch_next_record($rs)) {
1515 // populate the user_lastaccess table
1516 $access = new object;
1517 $access->timeaccess = $student->timeaccess;
1518 $access->userid = $student->userid;
1519 $access->courseid = $student->course;
1520 insert_record('user_lastaccess', $access);
1522 // assign the default student role
1523 $coursecontext = get_context_instance(CONTEXT_COURSE, $student->course);
1524 role_assign($studentrole, $student->userid, 0, $coursecontext->id);
1525 $progresscount++;
1526 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1528 rs_close($rs);
1533 /// Upgrade guest (only 1 entry).
1534 if ($guestuser = get_record('user', 'username', 'guest')) {
1535 role_assign($guestrole, $guestuser->id, 0, $systemcontext->id);
1537 print_progress($totalcount, $totalcount, 5, 1, 'Processing role assignments');
1540 /// Insert the correct records for legacy roles
1541 allow_assign($adminrole, $adminrole);
1542 allow_assign($adminrole, $coursecreatorrole);
1543 allow_assign($adminrole, $noneditteacherrole);
1544 allow_assign($adminrole, $editteacherrole);
1545 allow_assign($adminrole, $studentrole);
1546 allow_assign($adminrole, $guestrole);
1548 allow_assign($coursecreatorrole, $noneditteacherrole);
1549 allow_assign($coursecreatorrole, $editteacherrole);
1550 allow_assign($coursecreatorrole, $studentrole);
1551 allow_assign($coursecreatorrole, $guestrole);
1553 allow_assign($editteacherrole, $noneditteacherrole);
1554 allow_assign($editteacherrole, $studentrole);
1555 allow_assign($editteacherrole, $guestrole);
1557 /// Set up default permissions for overrides
1558 allow_override($adminrole, $adminrole);
1559 allow_override($adminrole, $coursecreatorrole);
1560 allow_override($adminrole, $noneditteacherrole);
1561 allow_override($adminrole, $editteacherrole);
1562 allow_override($adminrole, $studentrole);
1563 allow_override($adminrole, $guestrole);
1564 allow_override($adminrole, $userrole);
1567 /// Delete the old user tables when we are done
1569 drop_table(new XMLDBTable('user_students'));
1570 drop_table(new XMLDBTable('user_teachers'));
1571 drop_table(new XMLDBTable('user_coursecreators'));
1572 drop_table(new XMLDBTable('user_admins'));
1577 * Returns array of all legacy roles.
1579 function get_legacy_roles() {
1580 return array(
1581 'admin' => 'moodle/legacy:admin',
1582 'coursecreator' => 'moodle/legacy:coursecreator',
1583 'editingteacher' => 'moodle/legacy:editingteacher',
1584 'teacher' => 'moodle/legacy:teacher',
1585 'student' => 'moodle/legacy:student',
1586 'guest' => 'moodle/legacy:guest',
1587 'user' => 'moodle/legacy:user'
1591 function get_legacy_type($roleid) {
1592 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
1593 $legacyroles = get_legacy_roles();
1595 $result = '';
1596 foreach($legacyroles as $ltype=>$lcap) {
1597 $localoverride = get_local_override($roleid, $sitecontext->id, $lcap);
1598 if (!empty($localoverride->permission) and $localoverride->permission == CAP_ALLOW) {
1599 //choose first selected legacy capability - reset the rest
1600 if (empty($result)) {
1601 $result = $ltype;
1602 } else {
1603 unassign_capability($lcap, $roleid);
1608 return $result;
1612 * Assign the defaults found in this capabality definition to roles that have
1613 * the corresponding legacy capabilities assigned to them.
1614 * @param $legacyperms - an array in the format (example):
1615 * 'guest' => CAP_PREVENT,
1616 * 'student' => CAP_ALLOW,
1617 * 'teacher' => CAP_ALLOW,
1618 * 'editingteacher' => CAP_ALLOW,
1619 * 'coursecreator' => CAP_ALLOW,
1620 * 'admin' => CAP_ALLOW
1621 * @return boolean - success or failure.
1623 function assign_legacy_capabilities($capability, $legacyperms) {
1625 $legacyroles = get_legacy_roles();
1627 foreach ($legacyperms as $type => $perm) {
1629 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
1631 if (!array_key_exists($type, $legacyroles)) {
1632 error('Incorrect legacy role definition for type: '.$type);
1635 if ($roles = get_roles_with_capability($legacyroles[$type], CAP_ALLOW)) {
1636 foreach ($roles as $role) {
1637 // Assign a site level capability.
1638 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1639 return false;
1644 return true;
1649 * Checks to see if a capability is a legacy capability.
1650 * @param $capabilityname
1651 * @return boolean
1653 function islegacy($capabilityname) {
1654 if (strpos($capabilityname, 'moodle/legacy') === 0) {
1655 return true;
1656 } else {
1657 return false;
1663 /**********************************
1664 * Context Manipulation functions *
1665 **********************************/
1668 * Create a new context record for use by all roles-related stuff
1669 * @param $level
1670 * @param $instanceid
1672 * @return object newly created context (or existing one with a debug warning)
1674 function create_context($contextlevel, $instanceid) {
1675 if (!$context = get_record('context','contextlevel',$contextlevel,'instanceid',$instanceid)) {
1676 if (!validate_context($contextlevel, $instanceid)) {
1677 debugging('Error: Invalid context creation request for level "'.s($contextlevel).'", instance "'.s($instanceid).'".');
1678 return NULL;
1680 if ($contextlevel == CONTEXT_SYSTEM) {
1681 return create_system_context();
1684 $context = new object();
1685 $context->contextlevel = $contextlevel;
1686 $context->instanceid = $instanceid;
1687 if ($id = insert_record('context',$context)) {
1688 // we need to populate context_rel for every new context inserted
1689 $c = get_record('context','id',$id);
1690 insert_context_rel ($c);
1691 return $c;
1692 } else {
1693 debugging('Error: could not insert new context level "'.s($contextlevel).'", instance "'.s($instanceid).'".');
1694 return NULL;
1696 } else {
1697 debugging('Warning: Context id "'.s($context->id).'" not created, because it already exists.');
1698 return $context;
1703 * This hacky function is needed because we can not change system context instanceid using normal upgrade routine.
1705 function create_system_context() {
1706 if ($context = get_record('context', 'contextlevel', CONTEXT_SYSTEM, 'instanceid', SITEID)) {
1707 // we are going to change instanceid of system context to 0 now
1708 $context->instanceid = 0;
1709 update_record('context', $context);
1710 //context rel not affected
1711 return $context;
1713 } else {
1714 $context = new object();
1715 $context->contextlevel = CONTEXT_SYSTEM;
1716 $context->instanceid = 0;
1717 if ($context->id = insert_record('context',$context)) {
1718 // we need not to populate context_rel for system context
1719 return $context;
1720 } else {
1721 debugging('Can not create system context');
1722 return NULL;
1727 * Create a new context record for use by all roles-related stuff
1728 * @param $level
1729 * @param $instanceid
1731 * @return true if properly deleted
1733 function delete_context($contextlevel, $instanceid) {
1734 if ($context = get_context_instance($contextlevel, $instanceid)) {
1735 delete_records('context_rel', 'c2', $context->id); // might not be a parent
1736 return delete_records('context', 'id', $context->id) &&
1737 delete_records('role_assignments', 'contextid', $context->id) &&
1738 delete_records('role_capabilities', 'contextid', $context->id) &&
1739 delete_records('context_rel', 'c1', $context->id);
1741 return true;
1745 * Validate that object with instanceid really exists in given context level.
1747 * return if instanceid object exists
1749 function validate_context($contextlevel, $instanceid) {
1750 switch ($contextlevel) {
1752 case CONTEXT_SYSTEM:
1753 return ($instanceid == 0);
1755 case CONTEXT_PERSONAL:
1756 return (boolean)count_records('user', 'id', $instanceid);
1758 case CONTEXT_USER:
1759 return (boolean)count_records('user', 'id', $instanceid);
1761 case CONTEXT_COURSECAT:
1762 if ($instanceid == 0) {
1763 return true; // site course category
1765 return (boolean)count_records('course_categories', 'id', $instanceid);
1767 case CONTEXT_COURSE:
1768 return (boolean)count_records('course', 'id', $instanceid);
1770 case CONTEXT_GROUP:
1771 //return (boolean)count_records('groups_groups', 'id', $instanceid); //TODO:DONOTCOMMIT:
1772 return groups_group_exists($instanceid);
1774 case CONTEXT_MODULE:
1775 return (boolean)count_records('course_modules', 'id', $instanceid);
1777 case CONTEXT_BLOCK:
1778 return (boolean)count_records('block_instance', 'id', $instanceid);
1780 default:
1781 return false;
1786 * Get the context instance as an object. This function will create the
1787 * context instance if it does not exist yet.
1788 * @param $level
1789 * @param $instance
1791 function get_context_instance($contextlevel=NULL, $instance=0) {
1793 global $context_cache, $context_cache_id, $CONTEXT;
1794 static $allowed_contexts = array(CONTEXT_SYSTEM, CONTEXT_PERSONAL, CONTEXT_USER, CONTEXT_COURSECAT, CONTEXT_COURSE, CONTEXT_GROUP, CONTEXT_MODULE, CONTEXT_BLOCK);
1796 // Yu: Separating site and site course context - removed CONTEXT_COURSE override when SITEID
1798 /// If no level is supplied then return the current global context if there is one
1799 if (empty($contextlevel)) {
1800 if (empty($CONTEXT)) {
1801 //fatal error, code must be fixed
1802 error("Error: get_context_instance() called without a context");
1803 } else {
1804 return $CONTEXT;
1808 /// Backwards compatibility with obsoleted (CONTEXT_SYSTEM, SITEID)
1809 if ($contextlevel == CONTEXT_SYSTEM) {
1810 $instance = 0;
1813 /// check allowed context levels
1814 if (!in_array($contextlevel, $allowed_contexts)) {
1815 // fatal error, code must be fixed - probably typo or switched parameters
1816 error('Error: get_context_instance() called with incorrect context level "'.s($contextlevel).'"');
1819 /// Check the cache
1820 if (isset($context_cache[$contextlevel][$instance])) { // Already cached
1821 return $context_cache[$contextlevel][$instance];
1824 /// Get it from the database, or create it
1825 if (!$context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance)) {
1826 create_context($contextlevel, $instance);
1827 $context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance);
1830 /// Only add to cache if context isn't empty.
1831 if (!empty($context)) {
1832 $context_cache[$contextlevel][$instance] = $context; // Cache it for later
1833 $context_cache_id[$context->id] = $context; // Cache it for later
1836 return $context;
1841 * Get a context instance as an object, from a given id.
1842 * @param $id
1844 function get_context_instance_by_id($id) {
1846 global $context_cache, $context_cache_id;
1848 if (isset($context_cache_id[$id])) { // Already cached
1849 return $context_cache_id[$id];
1852 if ($context = get_record('context', 'id', $id)) { // Update the cache and return
1853 $context_cache[$context->contextlevel][$context->instanceid] = $context;
1854 $context_cache_id[$context->id] = $context;
1855 return $context;
1858 return false;
1863 * Get the local override (if any) for a given capability in a role in a context
1864 * @param $roleid
1865 * @param $contextid
1866 * @param $capability
1868 function get_local_override($roleid, $contextid, $capability) {
1869 return get_record('role_capabilities', 'roleid', $roleid, 'capability', $capability, 'contextid', $contextid);
1874 /************************************
1875 * DB TABLE RELATED FUNCTIONS *
1876 ************************************/
1879 * function that creates a role
1880 * @param name - role name
1881 * @param shortname - role short name
1882 * @param description - role description
1883 * @param legacy - optional legacy capability
1884 * @return id or false
1886 function create_role($name, $shortname, $description, $legacy='') {
1888 // check for duplicate role name
1890 if ($role = get_record('role','name', $name)) {
1891 error('there is already a role with this name!');
1894 if ($role = get_record('role','shortname', $shortname)) {
1895 error('there is already a role with this shortname!');
1898 $role = new object();
1899 $role->name = $name;
1900 $role->shortname = $shortname;
1901 $role->description = $description;
1903 //find free sortorder number
1904 $role->sortorder = count_records('role');
1905 while (get_record('role','sortorder', $role->sortorder)) {
1906 $role->sortorder += 1;
1909 if (!$context = get_context_instance(CONTEXT_SYSTEM)) {
1910 return false;
1913 if ($id = insert_record('role', $role)) {
1914 if ($legacy) {
1915 assign_capability($legacy, CAP_ALLOW, $id, $context->id);
1918 /// By default, users with role:manage at site level
1919 /// should be able to assign users to this new role, and override this new role's capabilities
1921 // find all admin roles
1922 if ($adminroles = get_roles_with_capability('moodle/role:manage', CAP_ALLOW, $context)) {
1923 // foreach admin role
1924 foreach ($adminroles as $arole) {
1925 // write allow_assign and allow_overrid
1926 allow_assign($arole->id, $id);
1927 allow_override($arole->id, $id);
1931 return $id;
1932 } else {
1933 return false;
1939 * function that deletes a role and cleanups up after it
1940 * @param roleid - id of role to delete
1941 * @return success
1943 function delete_role($roleid) {
1944 $success = true;
1946 // first unssign all users
1947 if (!role_unassign($roleid)) {
1948 debugging("Error while unassigning all users from role with ID $roleid!");
1949 $success = false;
1952 // cleanup all references to this role, ignore errors
1953 if ($success) {
1954 delete_records('role_capabilities', 'roleid', $roleid);
1955 delete_records('role_allow_assign', 'roleid', $roleid);
1956 delete_records('role_allow_assign', 'allowassign', $roleid);
1957 delete_records('role_allow_override', 'roleid', $roleid);
1958 delete_records('role_allow_override', 'allowoverride', $roleid);
1959 delete_records('role_names', 'roleid', $roleid);
1962 // finally delete the role itself
1963 if ($success and !delete_records('role', 'id', $roleid)) {
1964 debugging("Could not delete role record with ID $roleid!");
1965 $success = false;
1968 return $success;
1972 * Function to write context specific overrides, or default capabilities.
1973 * @param module - string name
1974 * @param capability - string name
1975 * @param contextid - context id
1976 * @param roleid - role id
1977 * @param permission - int 1,-1 or -1000
1978 * should not be writing if permission is 0
1980 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite=false) {
1982 global $USER;
1984 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
1985 unassign_capability($capability, $roleid, $contextid);
1986 return true;
1989 $existing = get_record('role_capabilities', 'contextid', $contextid, 'roleid', $roleid, 'capability', $capability);
1991 if ($existing and !$overwrite) { // We want to keep whatever is there already
1992 return true;
1995 $cap = new object;
1996 $cap->contextid = $contextid;
1997 $cap->roleid = $roleid;
1998 $cap->capability = $capability;
1999 $cap->permission = $permission;
2000 $cap->timemodified = time();
2001 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
2003 if ($existing) {
2004 $cap->id = $existing->id;
2005 return update_record('role_capabilities', $cap);
2006 } else {
2007 return insert_record('role_capabilities', $cap);
2013 * Unassign a capability from a role.
2014 * @param $roleid - the role id
2015 * @param $capability - the name of the capability
2016 * @return boolean - success or failure
2018 function unassign_capability($capability, $roleid, $contextid=NULL) {
2020 if (isset($contextid)) {
2021 $status = delete_records('role_capabilities', 'capability', $capability,
2022 'roleid', $roleid, 'contextid', $contextid);
2023 } else {
2024 $status = delete_records('role_capabilities', 'capability', $capability,
2025 'roleid', $roleid);
2027 return $status;
2032 * Get the roles that have a given capability assigned to it. This function
2033 * does not resolve the actual permission of the capability. It just checks
2034 * for assignment only.
2035 * @param $capability - capability name (string)
2036 * @param $permission - optional, the permission defined for this capability
2037 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT
2038 * @return array or role objects
2040 function get_roles_with_capability($capability, $permission=NULL, $context='') {
2042 global $CFG;
2044 if ($context) {
2045 if ($contexts = get_parent_contexts($context)) {
2046 $listofcontexts = '('.implode(',', $contexts).')';
2047 } else {
2048 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
2049 $listofcontexts = '('.$sitecontext->id.')'; // must be site
2051 $contextstr = "AND (rc.contextid = '$context->id' OR rc.contextid IN $listofcontexts)";
2052 } else {
2053 $contextstr = '';
2056 $selectroles = "SELECT r.*
2057 FROM {$CFG->prefix}role r,
2058 {$CFG->prefix}role_capabilities rc
2059 WHERE rc.capability = '$capability'
2060 AND rc.roleid = r.id $contextstr";
2062 if (isset($permission)) {
2063 $selectroles .= " AND rc.permission = '$permission'";
2065 return get_records_sql($selectroles);
2070 * This function makes a role-assignment (a role for a user or group in a particular context)
2071 * @param $roleid - the role of the id
2072 * @param $userid - userid
2073 * @param $groupid - group id
2074 * @param $contextid - id of the context
2075 * @param $timestart - time this assignment becomes effective
2076 * @param $timeend - time this assignemnt ceases to be effective
2077 * @uses $USER
2078 * @return id - new id of the assigment
2080 function role_assign($roleid, $userid, $groupid, $contextid, $timestart=0, $timeend=0, $hidden=0, $enrol='manual') {
2081 global $USER, $CFG;
2083 debugging("Assign roleid $roleid userid $userid contextid $contextid", DEBUG_DEVELOPER);
2085 /// Do some data validation
2087 if (empty($roleid)) {
2088 debugging('Role ID not provided');
2089 return false;
2092 if (empty($userid) && empty($groupid)) {
2093 debugging('Either userid or groupid must be provided');
2094 return false;
2097 if ($userid && !record_exists('user', 'id', $userid)) {
2098 debugging('User ID '.intval($userid).' does not exist!');
2099 return false;
2102 if ($groupid && !groups_group_exists($groupid)) {
2103 debugging('Group ID '.intval($groupid).' does not exist!');
2104 return false;
2107 if (!$context = get_context_instance_by_id($contextid)) {
2108 debugging('Context ID '.intval($contextid).' does not exist!');
2109 return false;
2112 if (($timestart and $timeend) and ($timestart > $timeend)) {
2113 debugging('The end time can not be earlier than the start time');
2114 return false;
2118 /// Check for existing entry
2119 if ($userid) {
2120 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id, 'userid', $userid);
2121 } else {
2122 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id, 'groupid', $groupid);
2126 $newra = new object;
2128 if (empty($ra)) { // Create a new entry
2129 $newra->roleid = $roleid;
2130 $newra->contextid = $context->id;
2131 $newra->userid = $userid;
2132 $newra->hidden = $hidden;
2133 $newra->enrol = $enrol;
2134 /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
2135 /// by repeating queries with the same exact parameters in a 100 secs time window
2136 $newra->timestart = round($timestart, -2);
2137 $newra->timeend = $timeend;
2138 $newra->timemodified = time();
2139 $newra->modifierid = empty($USER->id) ? 0 : $USER->id;
2141 $success = insert_record('role_assignments', $newra);
2143 } else { // We already have one, just update it
2145 $newra->id = $ra->id;
2146 $newra->hidden = $hidden;
2147 $newra->enrol = $enrol;
2148 /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
2149 /// by repeating queries with the same exact parameters in a 100 secs time window
2150 $newra->timestart = round($timestart, -2);
2151 $newra->timeend = $timeend;
2152 $newra->timemodified = time();
2153 $newra->modifierid = empty($USER->id) ? 0 : $USER->id;
2155 $success = update_record('role_assignments', $newra);
2158 if ($success) { /// Role was assigned, so do some other things
2160 /// If the user is the current user, then reload the capabilities too.
2161 if (!empty($USER->id) && $USER->id == $userid) {
2162 load_all_capabilities();
2165 /// Ask all the modules if anything needs to be done for this user
2166 if ($mods = get_list_of_plugins('mod')) {
2167 foreach ($mods as $mod) {
2168 include_once($CFG->dirroot.'/mod/'.$mod.'/lib.php');
2169 $functionname = $mod.'_role_assign';
2170 if (function_exists($functionname)) {
2171 $functionname($userid, $context);
2176 /// Make sure they have an entry in user_lastaccess for courses they can access
2177 // role_add_lastaccess_entries($userid, $context);
2180 /// now handle metacourse role assignments if in course context
2181 if ($success and $context->contextlevel == CONTEXT_COURSE) {
2182 if ($parents = get_records('course_meta', 'child_course', $context->instanceid)) {
2183 foreach ($parents as $parent) {
2184 sync_metacourse($parent->parent_course);
2189 return $success;
2194 * Deletes one or more role assignments. You must specify at least one parameter.
2195 * @param $roleid
2196 * @param $userid
2197 * @param $groupid
2198 * @param $contextid
2199 * @return boolean - success or failure
2201 function role_unassign($roleid=0, $userid=0, $groupid=0, $contextid=0) {
2203 global $USER, $CFG;
2205 $success = true;
2207 $args = array('roleid', 'userid', 'groupid', 'contextid');
2208 $select = array();
2209 foreach ($args as $arg) {
2210 if ($$arg) {
2211 $select[] = $arg.' = '.$$arg;
2215 if ($select) {
2216 if ($ras = get_records_select('role_assignments', implode(' AND ', $select))) {
2217 $mods = get_list_of_plugins('mod');
2218 foreach($ras as $ra) {
2219 /// infinite loop protection when deleting recursively
2220 if (!$ra = get_record('role_assignments', 'id', $ra->id)) {
2221 continue;
2223 $success = delete_records('role_assignments', 'id', $ra->id) and $success;
2225 /// If the user is the current user, then reload the capabilities too.
2226 if (!empty($USER->id) && $USER->id == $ra->userid) {
2227 load_all_capabilities();
2229 $context = get_record('context', 'id', $ra->contextid);
2231 /// Ask all the modules if anything needs to be done for this user
2232 foreach ($mods as $mod) {
2233 include_once($CFG->dirroot.'/mod/'.$mod.'/lib.php');
2234 $functionname = $mod.'_role_unassign';
2235 if (function_exists($functionname)) {
2236 $functionname($ra->userid, $context); // watch out, $context might be NULL if something goes wrong
2240 /// now handle metacourse role unassigment and removing from goups if in course context
2241 if (!empty($context) and $context->contextlevel == CONTEXT_COURSE) {
2242 //remove from groups when user has no role
2243 $roles = get_user_roles($context, $ra->userid, true);
2244 if (empty($roles)) {
2245 if ($groups = get_groups($context->instanceid, $ra->userid)) {
2246 foreach ($groups as $group) {
2247 delete_records('groups_members', 'groupid', $group->id, 'userid', $ra->userid);
2251 //unassign roles in metacourses if needed
2252 if ($parents = get_records('course_meta', 'child_course', $context->instanceid)) {
2253 foreach ($parents as $parent) {
2254 sync_metacourse($parent->parent_course);
2262 return $success;
2266 * A convenience function to take care of the common case where you
2267 * just want to enrol someone using the default role into a course
2269 * @param object $course
2270 * @param object $user
2271 * @param string $enrol - the plugin used to do this enrolment
2273 function enrol_into_course($course, $user, $enrol) {
2275 if ($course->enrolperiod) {
2276 $timestart = time();
2277 $timeend = time() + $course->enrolperiod;
2278 } else {
2279 $timestart = $timeend = 0;
2282 if ($role = get_default_course_role($course)) {
2284 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2286 if (!role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, $enrol)) {
2287 return false;
2290 email_welcome_message_to_user($course, $user);
2292 add_to_log($course->id, 'course', 'enrol', 'view.php?id='.$course->id, $user->id);
2294 return true;
2297 return false;
2301 * Add last access times to user_lastaccess as required
2302 * @param $userid
2303 * @param $context
2304 * @return boolean - success or failure
2306 function role_add_lastaccess_entries($userid, $context) {
2308 global $USER, $CFG;
2310 if (empty($context->contextlevel)) {
2311 return false;
2314 $lastaccess = new object; // Reusable object below
2315 $lastaccess->userid = $userid;
2316 $lastaccess->timeaccess = 0;
2318 switch ($context->contextlevel) {
2320 case CONTEXT_SYSTEM: // For the whole site
2321 if ($courses = get_record('course')) {
2322 foreach ($courses as $course) {
2323 $lastaccess->courseid = $course->id;
2324 role_set_lastaccess($lastaccess);
2327 break;
2329 case CONTEXT_CATEGORY: // For a whole category
2330 if ($courses = get_record('course', 'category', $context->instanceid)) {
2331 foreach ($courses as $course) {
2332 $lastaccess->courseid = $course->id;
2333 role_set_lastaccess($lastaccess);
2336 if ($categories = get_record('course_categories', 'parent', $context->instanceid)) {
2337 foreach ($categories as $category) {
2338 $subcontext = get_context_instance(CONTEXT_CATEGORY, $category->id);
2339 role_add_lastaccess_entries($userid, $subcontext);
2342 break;
2345 case CONTEXT_COURSE: // For a whole course
2346 if ($course = get_record('course', 'id', $context->instanceid)) {
2347 $lastaccess->courseid = $course->id;
2348 role_set_lastaccess($lastaccess);
2350 break;
2355 * Delete last access times from user_lastaccess as required
2356 * @param $userid
2357 * @param $context
2358 * @return boolean - success or failure
2360 function role_remove_lastaccess_entries($userid, $context) {
2362 global $USER, $CFG;
2368 * Loads the capability definitions for the component (from file). If no
2369 * capabilities are defined for the component, we simply return an empty array.
2370 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2371 * @return array of capabilities
2373 function load_capability_def($component) {
2374 global $CFG;
2376 if ($component == 'moodle') {
2377 $defpath = $CFG->libdir.'/db/access.php';
2378 $varprefix = 'moodle';
2379 } else {
2380 $compparts = explode('/', $component);
2382 if ($compparts[0] == 'block') {
2383 // Blocks are an exception. Blocks directory is 'blocks', and not
2384 // 'block'. So we need to jump through hoops.
2385 $defpath = $CFG->dirroot.'/'.$compparts[0].
2386 's/'.$compparts[1].'/db/access.php';
2387 $varprefix = $compparts[0].'_'.$compparts[1];
2388 } else if ($compparts[0] == 'format') {
2389 // Similar to the above, course formats are 'format' while they
2390 // are stored in 'course/format'.
2391 $defpath = $CFG->dirroot.'/course/'.$component.'/db/access.php';
2392 $varprefix = $compparts[0].'_'.$compparts[1];
2393 } else {
2394 $defpath = $CFG->dirroot.'/'.$component.'/db/access.php';
2395 $varprefix = str_replace('/', '_', $component);
2398 $capabilities = array();
2400 if (file_exists($defpath)) {
2401 require($defpath);
2402 $capabilities = ${$varprefix.'_capabilities'};
2404 return $capabilities;
2409 * Gets the capabilities that have been cached in the database for this
2410 * component.
2411 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2412 * @return array of capabilities
2414 function get_cached_capabilities($component='moodle') {
2415 if ($component == 'moodle') {
2416 $storedcaps = get_records_select('capabilities',
2417 "name LIKE 'moodle/%:%'");
2418 } else {
2419 $storedcaps = get_records_select('capabilities',
2420 "name LIKE '$component:%'");
2422 return $storedcaps;
2426 * Returns default capabilities for given legacy role type.
2428 * @param string legacy role name
2429 * @return array
2431 function get_default_capabilities($legacyrole) {
2432 if (!$allcaps = get_records('capabilities')) {
2433 error('Error: no capabilitites defined!');
2435 $alldefs = array();
2436 $defaults = array();
2437 $components = array();
2438 foreach ($allcaps as $cap) {
2439 if (!in_array($cap->component, $components)) {
2440 $components[] = $cap->component;
2441 $alldefs = array_merge($alldefs, load_capability_def($cap->component));
2444 foreach($alldefs as $name=>$def) {
2445 if (isset($def['legacy'][$legacyrole])) {
2446 $defaults[$name] = $def['legacy'][$legacyrole];
2450 //some exceptions
2451 $defaults['moodle/legacy:'.$legacyrole] = CAP_ALLOW;
2452 if ($legacyrole == 'admin') {
2453 $defaults['moodle/site:doanything'] = CAP_ALLOW;
2455 return $defaults;
2459 * Reset role capabilitites to default according to selected legacy capability.
2460 * If several legacy caps selected, use the first from get_default_capabilities.
2461 * If no legacy selected, removes all capabilities.
2463 * @param int @roleid
2465 function reset_role_capabilities($roleid) {
2466 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
2467 $legacyroles = get_legacy_roles();
2469 $defaultcaps = array();
2470 foreach($legacyroles as $ltype=>$lcap) {
2471 $localoverride = get_local_override($roleid, $sitecontext->id, $lcap);
2472 if (!empty($localoverride->permission) and $localoverride->permission == CAP_ALLOW) {
2473 //choose first selected legacy capability
2474 $defaultcaps = get_default_capabilities($ltype);
2475 break;
2479 delete_records('role_capabilities', 'roleid', $roleid);
2480 if (!empty($defaultcaps)) {
2481 foreach($defaultcaps as $cap=>$permission) {
2482 assign_capability($cap, $permission, $roleid, $sitecontext->id);
2488 * Updates the capabilities table with the component capability definitions.
2489 * If no parameters are given, the function updates the core moodle
2490 * capabilities.
2492 * Note that the absence of the db/access.php capabilities definition file
2493 * will cause any stored capabilities for the component to be removed from
2494 * the database.
2496 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2497 * @return boolean
2499 function update_capabilities($component='moodle') {
2501 $storedcaps = array();
2503 $filecaps = load_capability_def($component);
2504 $cachedcaps = get_cached_capabilities($component);
2505 if ($cachedcaps) {
2506 foreach ($cachedcaps as $cachedcap) {
2507 array_push($storedcaps, $cachedcap->name);
2508 // update risk bitmasks and context levels in existing capabilities if needed
2509 if (array_key_exists($cachedcap->name, $filecaps)) {
2510 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2511 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
2513 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
2514 $updatecap = new object();
2515 $updatecap->id = $cachedcap->id;
2516 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2517 if (!update_record('capabilities', $updatecap)) {
2518 return false;
2522 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2523 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2525 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2526 $updatecap = new object();
2527 $updatecap->id = $cachedcap->id;
2528 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2529 if (!update_record('capabilities', $updatecap)) {
2530 return false;
2537 // Are there new capabilities in the file definition?
2538 $newcaps = array();
2540 foreach ($filecaps as $filecap => $def) {
2541 if (!$storedcaps ||
2542 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2543 if (!array_key_exists('riskbitmask', $def)) {
2544 $def['riskbitmask'] = 0; // no risk if not specified
2546 $newcaps[$filecap] = $def;
2549 // Add new capabilities to the stored definition.
2550 foreach ($newcaps as $capname => $capdef) {
2551 $capability = new object;
2552 $capability->name = $capname;
2553 $capability->captype = $capdef['captype'];
2554 $capability->contextlevel = $capdef['contextlevel'];
2555 $capability->component = $component;
2556 $capability->riskbitmask = $capdef['riskbitmask'];
2558 if (!insert_record('capabilities', $capability, false, 'id')) {
2559 return false;
2562 // Do we need to assign the new capabilities to roles that have the
2563 // legacy capabilities moodle/legacy:* as well?
2564 if (isset($capdef['legacy']) && is_array($capdef['legacy']) &&
2565 !assign_legacy_capabilities($capname, $capdef['legacy'])) {
2566 notify('Could not assign legacy capabilities for '.$capname);
2569 // Are there any capabilities that have been removed from the file
2570 // definition that we need to delete from the stored capabilities and
2571 // role assignments?
2572 capabilities_cleanup($component, $filecaps);
2574 return true;
2579 * Deletes cached capabilities that are no longer needed by the component.
2580 * Also unassigns these capabilities from any roles that have them.
2581 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2582 * @param $newcapdef - array of the new capability definitions that will be
2583 * compared with the cached capabilities
2584 * @return int - number of deprecated capabilities that have been removed
2586 function capabilities_cleanup($component, $newcapdef=NULL) {
2588 $removedcount = 0;
2590 if ($cachedcaps = get_cached_capabilities($component)) {
2591 foreach ($cachedcaps as $cachedcap) {
2592 if (empty($newcapdef) ||
2593 array_key_exists($cachedcap->name, $newcapdef) === false) {
2595 // Remove from capabilities cache.
2596 if (!delete_records('capabilities', 'name', $cachedcap->name)) {
2597 error('Could not delete deprecated capability '.$cachedcap->name);
2598 } else {
2599 $removedcount++;
2601 // Delete from roles.
2602 if($roles = get_roles_with_capability($cachedcap->name)) {
2603 foreach($roles as $role) {
2604 if (!unassign_capability($cachedcap->name, $role->id)) {
2605 error('Could not unassign deprecated capability '.
2606 $cachedcap->name.' from role '.$role->name);
2610 } // End if.
2613 return $removedcount;
2618 /****************
2619 * UI FUNCTIONS *
2620 ****************/
2624 * prints human readable context identifier.
2626 function print_context_name($context) {
2628 $name = '';
2629 switch ($context->contextlevel) {
2631 case CONTEXT_SYSTEM: // by now it's a definite an inherit
2632 $name = get_string('coresystem');
2633 break;
2635 case CONTEXT_PERSONAL:
2636 $name = get_string('personal');
2637 break;
2639 case CONTEXT_USER:
2640 if ($user = get_record('user', 'id', $context->instanceid)) {
2641 $name = get_string('user').': '.fullname($user);
2643 break;
2645 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
2646 if ($category = get_record('course_categories', 'id', $context->instanceid)) {
2647 $name = get_string('category').': '. format_string($category->name);
2649 break;
2651 case CONTEXT_COURSE: // 1 to 1 to course cat
2652 if ($course = get_record('course', 'id', $context->instanceid)) {
2654 if ($context->instanceid == SITEID) {
2655 $name = get_string('site').': '. format_string($course->fullname);
2656 } else {
2657 $name = get_string('course').': '. format_string($course->fullname);
2660 break;
2662 case CONTEXT_GROUP: // 1 to 1 to course
2663 if ($name = groups_get_group_name($context->instanceid)) {
2664 $name = get_string('group').': '. $name;
2666 break;
2668 case CONTEXT_MODULE: // 1 to 1 to course
2669 if ($cm = get_record('course_modules','id',$context->instanceid)) {
2670 if ($module = get_record('modules','id',$cm->module)) {
2671 if ($mod = get_record($module->name, 'id', $cm->instance)) {
2672 $name = get_string('activitymodule').': '.$mod->name;
2676 break;
2678 case CONTEXT_BLOCK: // 1 to 1 to course
2679 if ($blockinstance = get_record('block_instance','id',$context->instanceid)) {
2680 if ($block = get_record('block','id',$blockinstance->blockid)) {
2681 global $CFG;
2682 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
2683 require_once("$CFG->dirroot/blocks/$block->name/block_$block->name.php");
2684 $blockname = "block_$block->name";
2685 if ($blockobject = new $blockname()) {
2686 $name = $blockobject->title.' ('.get_string('block').')';
2690 break;
2692 default:
2693 error ('This is an unknown context (' . $context->contextlevel . ') in print_context_name!');
2694 return false;
2697 return $name;
2702 * Extracts the relevant capabilities given a contextid.
2703 * All case based, example an instance of forum context.
2704 * Will fetch all forum related capabilities, while course contexts
2705 * Will fetch all capabilities
2706 * @param object context
2707 * @return array();
2709 * capabilities
2710 * `name` varchar(150) NOT NULL,
2711 * `captype` varchar(50) NOT NULL,
2712 * `contextlevel` int(10) NOT NULL,
2713 * `component` varchar(100) NOT NULL,
2715 function fetch_context_capabilities($context) {
2717 global $CFG;
2719 $sort = 'ORDER BY contextlevel,component,id'; // To group them sensibly for display
2721 switch ($context->contextlevel) {
2723 case CONTEXT_SYSTEM: // all
2724 $SQL = "select * from {$CFG->prefix}capabilities";
2725 break;
2727 case CONTEXT_PERSONAL:
2728 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_PERSONAL;
2729 break;
2731 case CONTEXT_USER:
2732 $SQL = "SELECT *
2733 FROM {$CFG->prefix}capabilities
2734 WHERE contextlevel = ".CONTEXT_USER;
2735 break;
2737 case CONTEXT_COURSECAT: // all
2738 $SQL = "select * from {$CFG->prefix}capabilities";
2739 break;
2741 case CONTEXT_COURSE: // all
2742 $SQL = "select * from {$CFG->prefix}capabilities";
2743 break;
2745 case CONTEXT_GROUP: // group caps
2746 break;
2748 case CONTEXT_MODULE: // mod caps
2749 $cm = get_record('course_modules', 'id', $context->instanceid);
2750 $module = get_record('modules', 'id', $cm->module);
2752 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_MODULE."
2753 and component = 'mod/$module->name'";
2754 break;
2756 case CONTEXT_BLOCK: // block caps
2757 $cb = get_record('block_instance', 'id', $context->instanceid);
2758 $block = get_record('block', 'id', $cb->blockid);
2760 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_BLOCK."
2761 and component = 'block/$block->name'";
2762 break;
2764 default:
2765 return false;
2768 if (!$records = get_records_sql($SQL.' '.$sort)) {
2769 $records = array();
2772 /// the rest of code is a bit hacky, think twice before modifying it :-(
2774 // special sorting of core system capabiltites and enrollments
2775 if (in_array($context->contextlevel, array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE))) {
2776 $first = array();
2777 foreach ($records as $key=>$record) {
2778 if (preg_match('|^moodle/|', $record->name) and $record->contextlevel == CONTEXT_SYSTEM) {
2779 $first[$key] = $record;
2780 unset($records[$key]);
2781 } else if (count($first)){
2782 break;
2785 if (count($first)) {
2786 $records = $first + $records; // merge the two arrays keeping the keys
2788 } else {
2789 $contextindependentcaps = fetch_context_independent_capabilities();
2790 $records = array_merge($contextindependentcaps, $records);
2793 return $records;
2799 * Gets the context-independent capabilities that should be overrridable in
2800 * any context.
2801 * @return array of capability records from the capabilities table.
2803 function fetch_context_independent_capabilities() {
2805 //only CONTEXT_SYSTEM capabilities here or it will break the hack in fetch_context_capabilities()
2806 $contextindependentcaps = array(
2807 'moodle/site:accessallgroups'
2810 $records = array();
2812 foreach ($contextindependentcaps as $capname) {
2813 $record = get_record('capabilities', 'name', $capname);
2814 array_push($records, $record);
2816 return $records;
2821 * This function pulls out all the resolved capabilities (overrides and
2822 * defaults) of a role used in capability overrides in contexts at a given
2823 * context.
2824 * @param obj $context
2825 * @param int $roleid
2826 * @param bool self - if set to true, resolve till this level, else stop at immediate parent level
2827 * @return array
2829 function role_context_capabilities($roleid, $context, $cap='') {
2830 global $CFG;
2832 $contexts = get_parent_contexts($context);
2833 $contexts[] = $context->id;
2834 $contexts = '('.implode(',', $contexts).')';
2836 if ($cap) {
2837 $search = " AND rc.capability = '$cap' ";
2838 } else {
2839 $search = '';
2842 $SQL = "SELECT rc.*
2843 FROM {$CFG->prefix}role_capabilities rc,
2844 {$CFG->prefix}context c
2845 WHERE rc.contextid in $contexts
2846 AND rc.roleid = $roleid
2847 AND rc.contextid = c.id $search
2848 ORDER BY c.contextlevel DESC,
2849 rc.capability DESC";
2851 $capabilities = array();
2853 if ($records = get_records_sql($SQL)) {
2854 // We are traversing via reverse order.
2855 foreach ($records as $record) {
2856 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2857 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2858 $capabilities[$record->capability] = $record->permission;
2862 return $capabilities;
2866 * Recursive function which, given a context, find all parent context ids,
2867 * and return the array in reverse order, i.e. parent first, then grand
2868 * parent, etc.
2869 * @param object $context
2870 * @return array()
2872 function get_parent_contexts($context) {
2874 static $pcontexts; // cache
2875 if (isset($pcontexts[$context->id])) {
2876 return ($pcontexts[$context->id]);
2879 switch ($context->contextlevel) {
2881 case CONTEXT_SYSTEM: // no parent
2882 return array();
2883 break;
2885 case CONTEXT_PERSONAL:
2886 if (!$parent = get_context_instance(CONTEXT_SYSTEM)) {
2887 return array();
2888 } else {
2889 $res = array($parent->id);
2890 $pcontexts[$context->id] = $res;
2891 return $res;
2893 break;
2895 case CONTEXT_USER:
2896 if (!$parent = get_context_instance(CONTEXT_SYSTEM)) {
2897 return array();
2898 } else {
2899 $res = array($parent->id);
2900 $pcontexts[$context->id] = $res;
2901 return $res;
2903 break;
2905 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
2906 if (!$coursecat = get_record('course_categories','id',$context->instanceid)) {
2907 return array();
2909 if (!empty($coursecat->parent)) { // return parent value if exist
2910 $parent = get_context_instance(CONTEXT_COURSECAT, $coursecat->parent);
2911 $res = array_merge(array($parent->id), get_parent_contexts($parent));
2912 $pcontexts[$context->id] = $res;
2913 return $res;
2914 } else { // else return site value
2915 $parent = get_context_instance(CONTEXT_SYSTEM);
2916 $res = array($parent->id);
2917 $pcontexts[$context->id] = $res;
2918 return $res;
2920 break;
2922 case CONTEXT_COURSE: // 1 to 1 to course cat
2923 if (!$course = get_record('course','id',$context->instanceid)) {
2924 return array();
2926 if ($course->id != SITEID) {
2927 $parent = get_context_instance(CONTEXT_COURSECAT, $course->category);
2928 $res = array_merge(array($parent->id), get_parent_contexts($parent));
2929 return $res;
2930 } else {
2931 // Yu: Separating site and site course context
2932 $parent = get_context_instance(CONTEXT_SYSTEM);
2933 $res = array($parent->id);
2934 $pcontexts[$context->id] = $res;
2935 return $res;
2937 break;
2939 case CONTEXT_GROUP: // 1 to 1 to course
2940 if (! $group = groups_get_group($context->instanceid)) {
2941 return array();
2943 if ($parent = get_context_instance(CONTEXT_COURSE, $group->courseid)) {
2944 $res = array_merge(array($parent->id), get_parent_contexts($parent));
2945 $pcontexts[$context->id] = $res;
2946 return $res;
2947 } else {
2948 return array();
2950 break;
2952 case CONTEXT_MODULE: // 1 to 1 to course
2953 if (!$cm = get_record('course_modules','id',$context->instanceid)) {
2954 return array();
2956 if ($parent = get_context_instance(CONTEXT_COURSE, $cm->course)) {
2957 $res = array_merge(array($parent->id), get_parent_contexts($parent));
2958 $pcontexts[$context->id] = $res;
2959 return $res;
2960 } else {
2961 return array();
2963 break;
2965 case CONTEXT_BLOCK: // 1 to 1 to course
2966 if (!$block = get_record('block_instance','id',$context->instanceid)) {
2967 return array();
2969 if ($parent = get_context_instance(CONTEXT_COURSE, $block->pageid)) {
2970 $res = array_merge(array($parent->id), get_parent_contexts($parent));
2971 $pcontexts[$context->id] = $res;
2972 return $res;
2973 } else {
2974 return array();
2976 break;
2978 default:
2979 error('This is an unknown context (' . $context->contextlevel . ') in get_parent_contexts!');
2980 return false;
2986 * Recursive function which, given a context, find all its children context ids.
2987 * @param object $context.
2988 * @return array of children context ids.
2990 function get_child_contexts($context) {
2992 global $CFG;
2993 $children = array();
2995 switch ($context->contextlevel) {
2997 case CONTEXT_BLOCK:
2998 // No children.
2999 return array();
3000 break;
3002 case CONTEXT_MODULE:
3003 // No children.
3004 return array();
3005 break;
3007 case CONTEXT_GROUP:
3008 // No children.
3009 return array();
3010 break;
3012 case CONTEXT_COURSE:
3013 // Find all block instances for the course.
3014 $page = new page_course;
3015 $page->id = $context->instanceid;
3016 $page->type = 'course-view';
3017 if ($blocks = blocks_get_by_page_pinned($page)) {
3018 foreach ($blocks['l'] as $leftblock) {
3019 if ($child = get_context_instance(CONTEXT_BLOCK, $leftblock->id)) {
3020 array_push($children, $child->id);
3023 foreach ($blocks['r'] as $rightblock) {
3024 if ($child = get_context_instance(CONTEXT_BLOCK, $rightblock->id)) {
3025 array_push($children, $child->id);
3029 // Find all module instances for the course.
3030 if ($modules = get_records('course_modules', 'course', $context->instanceid)) {
3031 foreach ($modules as $module) {
3032 if ($child = get_context_instance(CONTEXT_MODULE, $module->id)) {
3033 array_push($children, $child->id);
3037 // Find all group instances for the course.
3038 if ($groupids = groups_get_groups($context->instanceid)) {
3039 foreach ($groupids as $groupid) {
3040 if ($child = get_context_instance(CONTEXT_GROUP, $groupid)) {
3041 array_push($children, $child->id);
3045 return $children;
3046 break;
3048 case CONTEXT_COURSECAT:
3049 // We need to get the contexts for:
3050 // 1) The subcategories of the given category
3051 // 2) The courses in the given category and all its subcategories
3052 // 3) All the child contexts for these courses
3054 $categories = get_all_subcategories($context->instanceid);
3056 // Add the contexts for all the subcategories.
3057 foreach ($categories as $catid) {
3058 if ($catci = get_context_instance(CONTEXT_COURSECAT, $catid)) {
3059 array_push($children, $catci->id);
3063 // Add the parent category as well so we can find the contexts
3064 // for its courses.
3065 array_unshift($categories, $context->instanceid);
3067 foreach ($categories as $catid) {
3068 // Find all courses for the category.
3069 if ($courses = get_records('course', 'category', $catid)) {
3070 foreach ($courses as $course) {
3071 if ($courseci = get_context_instance(CONTEXT_COURSE, $course->id)) {
3072 array_push($children, $courseci->id);
3073 $children = array_merge($children, get_child_contexts($courseci));
3078 return $children;
3079 break;
3081 case CONTEXT_USER:
3082 // No children.
3083 return array();
3084 break;
3086 case CONTEXT_PERSONAL:
3087 // No children.
3088 return array();
3089 break;
3091 case CONTEXT_SYSTEM:
3092 // Just get all the contexts except for CONTEXT_SYSTEM level.
3093 $sql = 'SELECT c.id '.
3094 'FROM '.$CFG->prefix.'context AS c '.
3095 'WHERE contextlevel != '.CONTEXT_SYSTEM;
3097 $contexts = get_records_sql($sql);
3098 foreach ($contexts as $cid) {
3099 array_push($children, $cid->id);
3101 return $children;
3102 break;
3104 default:
3105 error('This is an unknown context (' . $context->contextlevel . ') in get_child_contexts!');
3106 return false;
3112 * Gets a string for sql calls, searching for stuff in this context or above
3113 * @param object $context
3114 * @return string
3116 function get_related_contexts_string($context) {
3117 if ($parents = get_parent_contexts($context)) {
3118 return (' IN ('.$context->id.','.implode(',', $parents).')');
3119 } else {
3120 return (' ='.$context->id);
3126 * This function gets the capability of a role in a given context.
3127 * It is needed when printing override forms.
3128 * @param int $contextid
3129 * @param string $capability
3130 * @param array $capabilities - array loaded using role_context_capabilities
3131 * @return int (allow, prevent, prohibit, inherit)
3133 function get_role_context_capability($contextid, $capability, $capabilities) {
3134 if (isset($capabilities[$contextid][$capability])) {
3135 return $capabilities[$contextid][$capability];
3137 else {
3138 return false;
3144 * Returns the human-readable, translated version of the capability.
3145 * Basically a big switch statement.
3146 * @param $capabilityname - e.g. mod/choice:readresponses
3148 function get_capability_string($capabilityname) {
3150 // Typical capabilityname is mod/choice:readresponses
3152 $names = split('/', $capabilityname);
3153 $stringname = $names[1]; // choice:readresponses
3154 $components = split(':', $stringname);
3155 $componentname = $components[0]; // choice
3157 switch ($names[0]) {
3158 case 'mod':
3159 $string = get_string($stringname, $componentname);
3160 break;
3162 case 'block':
3163 $string = get_string($stringname, 'block_'.$componentname);
3164 break;
3166 case 'moodle':
3167 $string = get_string($stringname, 'role');
3168 break;
3170 case 'enrol':
3171 $string = get_string($stringname, 'enrol_'.$componentname);
3172 break;
3174 case 'format':
3175 $string = get_string($stringname, 'format_'.$componentname);
3176 break;
3178 default:
3179 $string = get_string($stringname);
3180 break;
3183 return $string;
3188 * This gets the mod/block/course/core etc strings.
3189 * @param $component
3190 * @param $contextlevel
3192 function get_component_string($component, $contextlevel) {
3194 switch ($contextlevel) {
3196 case CONTEXT_SYSTEM:
3197 if (preg_match('|^enrol/|', $component)) {
3198 $langname = str_replace('/', '_', $component);
3199 $string = get_string('enrolname', $langname);
3200 } else if (preg_match('|^block/|', $component)) {
3201 $langname = str_replace('/', '_', $component);
3202 $string = get_string('blockname', $langname);
3203 } else {
3204 $string = get_string('coresystem');
3206 break;
3208 case CONTEXT_PERSONAL:
3209 $string = get_string('personal');
3210 break;
3212 case CONTEXT_USER:
3213 $string = get_string('users');
3214 break;
3216 case CONTEXT_COURSECAT:
3217 $string = get_string('categories');
3218 break;
3220 case CONTEXT_COURSE:
3221 $string = get_string('course');
3222 break;
3224 case CONTEXT_GROUP:
3225 $string = get_string('group');
3226 break;
3228 case CONTEXT_MODULE:
3229 $string = get_string('modulename', basename($component));
3230 break;
3232 case CONTEXT_BLOCK:
3233 $string = get_string('blockname', 'block_'.basename($component));
3234 break;
3236 default:
3237 error ('This is an unknown context $contextlevel (' . $contextlevel . ') in get_component_string!');
3238 return false;
3241 return $string;
3245 * Gets the list of roles assigned to this context and up (parents)
3246 * @param object $context
3247 * @param view - set to true when roles are pulled for display only
3248 * this is so that we can filter roles with no visible
3249 * assignment, for example, you might want to "hide" all
3250 * course creators when browsing the course participants
3251 * list.
3252 * @return array
3254 function get_roles_used_in_context($context, $view = false) {
3256 global $CFG;
3258 // filter for roles with all hidden assignments
3259 // no need to return when only pulling roles for reviewing
3260 // e.g. participants page.
3261 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))? ' AND ra.hidden = 0 ':'';
3262 $contextlist = get_related_contexts_string($context);
3264 $sql = "SELECT DISTINCT r.id,
3265 r.name,
3266 r.shortname,
3267 r.sortorder
3268 FROM {$CFG->prefix}role_assignments ra,
3269 {$CFG->prefix}role r
3270 WHERE r.id = ra.roleid
3271 AND ra.contextid $contextlist
3272 $hiddensql
3273 ORDER BY r.sortorder ASC";
3275 return get_records_sql($sql);
3278 /** this function is used to print roles column in user profile page.
3279 * @param int userid
3280 * @param int contextid
3281 * @return string
3283 function get_user_roles_in_context($userid, $contextid){
3284 global $CFG;
3286 $rolestring = '';
3287 $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';
3288 if ($roles = get_records_sql($SQL)) {
3289 foreach ($roles as $userrole) {
3290 $rolestring .= '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$userrole->contextid.'&amp;roleid='.$userrole->roleid.'">'.$userrole->name.'</a>, ';
3294 return rtrim($rolestring, ', ');
3299 * Checks if a user can override capabilities of a particular role in this context
3300 * @param object $context
3301 * @param int targetroleid - the id of the role you want to override
3302 * @return boolean
3304 function user_can_override($context, $targetroleid) {
3305 // first check if user has override capability
3306 // if not return false;
3307 if (!has_capability('moodle/role:override', $context)) {
3308 return false;
3310 // pull out all active roles of this user from this context(or above)
3311 if ($userroles = get_user_roles($context)) {
3312 foreach ($userroles as $userrole) {
3313 // if any in the role_allow_override table, then it's ok
3314 if (get_record('role_allow_override', 'roleid', $userrole->roleid, 'allowoverride', $targetroleid)) {
3315 return true;
3320 return false;
3325 * Checks if a user can assign users to a particular role in this context
3326 * @param object $context
3327 * @param int targetroleid - the id of the role you want to assign users to
3328 * @return boolean
3330 function user_can_assign($context, $targetroleid) {
3332 // first check if user has override capability
3333 // if not return false;
3334 if (!has_capability('moodle/role:assign', $context)) {
3335 return false;
3337 // pull out all active roles of this user from this context(or above)
3338 if ($userroles = get_user_roles($context)) {
3339 foreach ($userroles as $userrole) {
3340 // if any in the role_allow_override table, then it's ok
3341 if (get_record('role_allow_assign', 'roleid', $userrole->roleid, 'allowassign', $targetroleid)) {
3342 return true;
3347 return false;
3350 /** Returns all site roles in correct sort order.
3353 function get_all_roles() {
3354 return get_records('role', '', '', 'sortorder ASC');
3358 * gets all the user roles assigned in this context, or higher contexts
3359 * this is mainly used when checking if a user can assign a role, or overriding a role
3360 * i.e. we need to know what this user holds, in order to verify against allow_assign and
3361 * allow_override tables
3362 * @param object $context
3363 * @param int $userid
3364 * @param view - set to true when roles are pulled for display only
3365 * this is so that we can filter roles with no visible
3366 * assignment, for example, you might want to "hide" all
3367 * course creators when browsing the course participants
3368 * list.
3369 * @return array
3371 function get_user_roles($context, $userid=0, $checkparentcontexts=true, $order='c.contextlevel DESC, r.sortorder ASC', $view=false) {
3373 global $USER, $CFG, $db;
3375 if (empty($userid)) {
3376 if (empty($USER->id)) {
3377 return array();
3379 $userid = $USER->id;
3381 // set up hidden sql
3382 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))? ' AND ra.hidden = 0 ':'';
3384 if ($checkparentcontexts && ($parents = get_parent_contexts($context))) {
3385 $contexts = ' ra.contextid IN ('.implode(',' , $parents).','.$context->id.')';
3386 } else {
3387 $contexts = ' ra.contextid = \''.$context->id.'\'';
3390 return get_records_sql('SELECT ra.*, r.name, r.shortname
3391 FROM '.$CFG->prefix.'role_assignments ra,
3392 '.$CFG->prefix.'role r,
3393 '.$CFG->prefix.'context c
3394 WHERE ra.userid = '.$userid.
3395 ' AND ra.roleid = r.id
3396 AND ra.contextid = c.id
3397 AND '.$contexts . $hiddensql .
3398 ' ORDER BY '.$order);
3402 * Creates a record in the allow_override table
3403 * @param int sroleid - source roleid
3404 * @param int troleid - target roleid
3405 * @return int - id or false
3407 function allow_override($sroleid, $troleid) {
3408 $record = new object();
3409 $record->roleid = $sroleid;
3410 $record->allowoverride = $troleid;
3411 return insert_record('role_allow_override', $record);
3415 * Creates a record in the allow_assign table
3416 * @param int sroleid - source roleid
3417 * @param int troleid - target roleid
3418 * @return int - id or false
3420 function allow_assign($sroleid, $troleid) {
3421 $record = new object;
3422 $record->roleid = $sroleid;
3423 $record->allowassign = $troleid;
3424 return insert_record('role_allow_assign', $record);
3428 * Gets a list of roles that this user can assign in this context
3429 * @param object $context
3430 * @return array
3432 function get_assignable_roles ($context, $field="name") {
3434 $options = array();
3436 if ($roles = get_all_roles()) {
3437 foreach ($roles as $role) {
3438 if (user_can_assign($context, $role->id)) {
3439 $options[$role->id] = strip_tags(format_string($role->{$field}, true));
3443 return $options;
3447 * Gets a list of roles that this user can override in this context
3448 * @param object $context
3449 * @return array
3451 function get_overridable_roles($context) {
3453 $options = array();
3455 if ($roles = get_all_roles()) {
3456 foreach ($roles as $role) {
3457 if (user_can_override($context, $role->id)) {
3458 $options[$role->id] = strip_tags(format_string($role->name, true));
3463 return $options;
3467 * Returns a role object that is the default role for new enrolments
3468 * in a given course
3470 * @param object $course
3471 * @return object $role
3473 function get_default_course_role($course) {
3474 global $CFG;
3476 /// First let's take the default role the course may have
3477 if (!empty($course->defaultrole)) {
3478 if ($role = get_record('role', 'id', $course->defaultrole)) {
3479 return $role;
3483 /// Otherwise the site setting should tell us
3484 if ($CFG->defaultcourseroleid) {
3485 if ($role = get_record('role', 'id', $CFG->defaultcourseroleid)) {
3486 return $role;
3490 /// It's unlikely we'll get here, but just in case, try and find a student role
3491 if ($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW)) {
3492 return array_shift($studentroles); /// Take the first one
3495 return NULL;
3500 * who has this capability in this context
3501 * does not handling user level resolving!!!
3502 * (!)pleaes note if $fields is empty this function attempts to get u.*
3503 * which can get rather large.
3504 * i.e 1 person has 2 roles 1 allow, 1 prevent, this will not work properly
3505 * @param $context - object
3506 * @param $capability - string capability
3507 * @param $fields - fields to be pulled
3508 * @param $sort - the sort order
3509 * @param $limitfrom - number of records to skip (offset)
3510 * @param $limitnum - number of records to fetch
3511 * @param $groups - single group or array of groups - group(s) user is in
3512 * @param $exceptions - list of users to exclude
3513 * @param view - set to true when roles are pulled for display only
3514 * this is so that we can filter roles with no visible
3515 * assignment, for example, you might want to "hide" all
3516 * course creators when browsing the course participants
3517 * list.
3519 function get_users_by_capability($context, $capability, $fields='', $sort='',
3520 $limitfrom='', $limitnum='', $groups='', $exceptions='', $doanything=true, $view=false) {
3521 global $CFG;
3523 /// Sorting out groups
3524 if ($groups) {
3525 $groupjoin = 'INNER JOIN '.$CFG->prefix.'groups_members gm ON gm.userid = ra.userid';
3527 if (is_array($groups)) {
3528 $groupsql = 'AND gm.groupid IN ('.implode(',', $groups).')';
3529 } else {
3530 $groupsql = 'AND gm.groupid = '.$groups;
3532 } else {
3533 $groupjoin = '';
3534 $groupsql = '';
3537 /// Sorting out exceptions
3538 $exceptionsql = $exceptions ? "AND u.id NOT IN ($exceptions)" : '';
3540 /// Set up default fields
3541 if (empty($fields)) {
3542 $fields = 'u.*, ul.timeaccess as lastaccess, ra.hidden';
3545 /// Set up default sort
3546 if (empty($sort)) {
3547 $sort = 'ul.timeaccess';
3550 $sortby = $sort ? " ORDER BY $sort " : '';
3551 /// Set up hidden sql
3552 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))? ' AND ra.hidden = 0 ':'';
3554 /// If context is a course, then construct sql for ul
3555 if ($context->contextlevel == CONTEXT_COURSE) {
3556 $courseid = $context->instanceid;
3557 $coursesql1 = "AND ul.courseid = $courseid";
3558 } else {
3559 $coursesql1 = '';
3562 /// Sorting out roles with this capability set
3563 if ($possibleroles = get_roles_with_capability($capability, CAP_ALLOW, $context)) {
3564 if (!$doanything) {
3565 if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM)) {
3566 return false; // Something is seriously wrong
3568 $doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, $sitecontext);
3571 $validroleids = array();
3572 foreach ($possibleroles as $possiblerole) {
3573 if (!$doanything) {
3574 if (isset($doanythingroles[$possiblerole->id])) { // We don't want these included
3575 continue;
3578 if ($caps = role_context_capabilities($possiblerole->id, $context, $capability)) { // resolved list
3579 if (isset($caps[$capability]) && $caps[$capability] > 0) { // resolved capability > 0
3580 $validroleids[] = $possiblerole->id;
3584 if (empty($validroleids)) {
3585 return false;
3587 $roleids = '('.implode(',', $validroleids).')';
3588 } else {
3589 return false; // No need to continue, since no roles have this capability set
3592 /// Construct the main SQL
3593 $select = " SELECT $fields";
3594 $from = " FROM {$CFG->prefix}user u
3595 INNER JOIN {$CFG->prefix}role_assignments ra ON ra.userid = u.id
3596 INNER JOIN {$CFG->prefix}role r ON r.id = ra.roleid
3597 LEFT OUTER JOIN {$CFG->prefix}user_lastaccess ul ON (ul.userid = u.id $coursesql1)
3598 $groupjoin";
3599 $where = " WHERE ra.contextid ".get_related_contexts_string($context)."
3600 AND u.deleted = 0
3601 AND ra.roleid in $roleids
3602 $exceptionsql
3603 $groupsql
3604 $hiddensql";
3606 return get_records_sql($select.$from.$where.$sortby, $limitfrom, $limitnum);
3610 * gets all the users assigned this role in this context or higher
3611 * @param int roleid
3612 * @param int contextid
3613 * @param bool parent if true, get list of users assigned in higher context too
3614 * @return array()
3616 function get_role_users($roleid, $context, $parent=false, $fields='', $sort='u.lastname ASC', $view=false) {
3617 global $CFG;
3619 if (empty($fields)) {
3620 $fields = 'u.id, u.confirmed, u.username, u.firstname, u.lastname, '.
3621 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.city, '.
3622 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
3623 'u.emailstop, u.lang, u.timezone';
3626 // whether this assignment is hidden
3627 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))? ' AND r.hidden = 0 ':'';
3628 if ($parent) {
3629 if ($contexts = get_parent_contexts($context)) {
3630 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
3631 } else {
3632 $parentcontexts = '';
3634 } else {
3635 $parentcontexts = '';
3638 if ($roleid) {
3639 $roleselect = "AND r.roleid = $roleid";
3640 } else {
3641 $roleselect = '';
3644 $SQL = "SELECT $fields
3645 FROM {$CFG->prefix}role_assignments r,
3646 {$CFG->prefix}user u
3647 WHERE (r.contextid = $context->id $parentcontexts)
3648 AND u.id = r.userid $roleselect
3649 $hiddensql
3650 ORDER BY $sort
3651 "; // join now so that we can just use fullname() later
3653 return get_records_sql($SQL);
3657 * Counts all the users assigned this role in this context or higher
3658 * @param int roleid
3659 * @param int contextid
3660 * @param bool parent if true, get list of users assigned in higher context too
3661 * @return array()
3663 function count_role_users($roleid, $context, $parent=false) {
3664 global $CFG;
3666 if ($parent) {
3667 if ($contexts = get_parent_contexts($context)) {
3668 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
3669 } else {
3670 $parentcontexts = '';
3672 } else {
3673 $parentcontexts = '';
3676 $SQL = "SELECT count(*)
3677 FROM {$CFG->prefix}role_assignments r
3678 WHERE (r.contextid = $context->id $parentcontexts)
3679 AND r.roleid = $roleid";
3681 return count_records_sql($SQL);
3685 * This function gets the list of courses that this user has a particular capability in
3686 * This is not the most efficient way of doing this
3687 * @param string capability
3688 * @param int $userid
3689 * @return array
3691 function get_user_capability_course($capability, $userid=NULL) {
3693 $usercourses = array();
3694 $courses = get_records_select('course', '', '', 'id, id');
3696 foreach ($courses as $course) {
3697 if (has_capability($capability, get_context_instance(CONTEXT_COURSE, $course->id), $userid)) {
3698 $usercourses[] = $course;
3701 return $usercourses;
3705 /** This function finds the roles assigned directly to this context only
3706 * i.e. no parents role
3707 * @param object $context
3708 * @return array
3710 function get_roles_on_exact_context($context) {
3712 global $CFG;
3714 return get_records_sql("SELECT r.*
3715 FROM {$CFG->prefix}role_assignments ra,
3716 {$CFG->prefix}role r
3717 WHERE ra.roleid = r.id
3718 AND ra.contextid = $context->id");
3723 * Switches the current user to another role for the current session and only
3724 * in the given context. If roleid is not valid (eg 0) or the current user
3725 * doesn't have permissions to be switching roles then the user's session
3726 * is compltely reset to have their normal roles.
3727 * @param integer $roleid
3728 * @param object $context
3729 * @return bool
3731 function role_switch($roleid, $context) {
3732 global $USER, $CFG;
3734 /// If we can't use this or are already using it or no role was specified then bail completely and reset
3735 if (empty($roleid) || !has_capability('moodle/role:switchroles', $context)
3736 || !empty($USER->switchrole[$context->id]) || !confirm_sesskey()) {
3738 unset($USER->switchrole[$context->id]); // Delete old capabilities
3739 load_all_capabilities(); //reload user caps
3740 return true;
3743 /// We're allowed to switch but can we switch to the specified role? Use assignable roles to check.
3744 if (!$roles = get_assignable_roles($context)) {
3745 return false;
3748 /// unset default user role - it would not work anyway
3749 unset($roles[$CFG->defaultuserroleid]);
3751 if (empty($roles[$roleid])) { /// We can't switch to this particular role
3752 return false;
3755 /// We have a valid roleid that this user can switch to, so let's set up the session
3757 $USER->switchrole[$context->id] = $roleid; // So we know later what state we are in
3759 load_all_capabilities(); //reload switched role caps
3761 /// Add some permissions we are really going to always need, even if the role doesn't have them!
3763 $USER->capabilities[$context->id]['moodle/course:view'] = CAP_ALLOW;
3765 return true;
3770 // get any role that has an override on exact context
3771 function get_roles_with_override_on_context($context) {
3773 global $CFG;
3775 return get_records_sql("SELECT r.*
3776 FROM {$CFG->prefix}role_capabilities rc,
3777 {$CFG->prefix}role r
3778 WHERE rc.roleid = r.id
3779 AND rc.contextid = $context->id");
3782 // get all capabilities for this role on this context (overrids)
3783 function get_capabilities_from_role_on_context($role, $context) {
3785 global $CFG;
3787 return get_records_sql("SELECT *
3788 FROM {$CFG->prefix}role_capabilities
3789 WHERE contextid = $context->id
3790 AND roleid = $role->id");
3793 // find out which roles has assignment on this context
3794 function get_roles_with_assignment_on_context($context) {
3796 global $CFG;
3798 return get_records_sql("SELECT r.*
3799 FROM {$CFG->prefix}role_assignments ra,
3800 {$CFG->prefix}role r
3801 WHERE ra.roleid = r.id
3802 AND ra.contextid = $context->id");
3808 * Find all user assignemnt of users for this role, on this context
3810 function get_users_from_role_on_context($role, $context) {
3812 global $CFG;
3814 return get_records_sql("SELECT *
3815 FROM {$CFG->prefix}role_assignments
3816 WHERE contextid = $context->id
3817 AND roleid = $role->id");
3821 * Simple function returning a boolean true if roles exist, otherwise false
3823 function user_has_role_assignment($userid, $roleid, $contextid=0) {
3825 if ($contextid) {
3826 return record_exists('role_assignments', 'userid', $userid, 'roleid', $roleid, 'contextid', $contextid);
3827 } else {
3828 return record_exists('role_assignments', 'userid', $userid, 'roleid', $roleid);
3832 /**
3833 * Inserts all parental context and self into context_rel table
3835 * @param object $context-context to be deleted
3836 * @param bool deletechild - deltes child contexts dependencies
3838 function insert_context_rel($context, $deletechild=true, $deleteparent=true) {
3839 // removes all parents
3840 if ($deletechild) {
3841 delete_records('context_rel', 'c2', $context->id);
3844 if ($deleteparent) {
3845 delete_records('context_rel', 'c1', $context->id);
3847 // insert all parents
3848 if ($parents = get_parent_contexts($context)) {
3849 $parents[] = $context->id;
3850 foreach ($parents as $parent) {
3851 $rec = new object;
3852 $rec ->c1 = $context->id;
3853 $rec ->c2 = $parent;
3854 insert_record('context_rel', $rec);
3861 * rebuild context_rel table without deleting
3863 function build_context_rel() {
3865 global $db;
3866 $savedb = $db->debug;
3868 // total number of records
3869 $total = count_records('context');
3870 // processed records
3871 $done = 0;
3872 print_progress($done, $total, 10, 0, 'Processing context relations');
3873 $db->debug = false;
3874 if ($contexts = get_records('context')) {
3875 foreach ($contexts as $context) {
3876 // no need to delete because it's all empty
3877 insert_context_rel($context, false, false);
3878 $db->debug = true;
3879 print_progress(++$done, $total, 10, 0, 'Processing context relations');
3880 $db->debug = false;
3884 $db->debug = $savedb;