adding current groupid to grade_export class - soon to be used in plugins
[moodle-pu.git] / lib / accesslib.php
blobb5ebc8e38fae395252e0ab081f2460d425c23102
1 <?php // $Id$
3 ///////////////////////////////////////////////////////////////////////////
4 // //
5 // NOTICE OF COPYRIGHT //
6 // //
7 // Moodle - Modular Object-Oriented Dynamic Learning Environment //
8 // http://moodle.org //
9 // //
10 // Copyright (C) 1999-2004 Martin Dougiamas http://dougiamas.com //
11 // //
12 // This program is free software; you can redistribute it and/or modify //
13 // it under the terms of the GNU General Public License as published by //
14 // the Free Software Foundation; either version 2 of the License, or //
15 // (at your option) any later version. //
16 // //
17 // This program is distributed in the hope that it will be useful, //
18 // but WITHOUT ANY WARRANTY; without even the implied warranty of //
19 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
20 // GNU General Public License for more details: //
21 // //
22 // http://www.gnu.org/copyleft/gpl.html //
23 // //
24 ///////////////////////////////////////////////////////////////////////////
26 /**
27 * Capability session information format
28 * 2 x 2 array
29 * [context][capability]
30 * where context is the context id of the table 'context'
31 * and capability is a string defining the capability
32 * e.g.
34 * [Capabilities] => [26][mod/forum:viewpost] = 1
35 * [26][mod/forum:startdiscussion] = -8990
36 * [26][mod/forum:editallpost] = -1
37 * [273][moodle:blahblah] = 1
38 * [273][moodle:blahblahblah] = 2
41 require_once $CFG->dirroot.'/lib/blocklib.php';
43 // permission definitions
44 define('CAP_INHERIT', 0);
45 define('CAP_ALLOW', 1);
46 define('CAP_PREVENT', -1);
47 define('CAP_PROHIBIT', -1000);
49 // context definitions
50 define('CONTEXT_SYSTEM', 10);
51 define('CONTEXT_PERSONAL', 20);
52 define('CONTEXT_USER', 30);
53 define('CONTEXT_COURSECAT', 40);
54 define('CONTEXT_COURSE', 50);
55 define('CONTEXT_GROUP', 60);
56 define('CONTEXT_MODULE', 70);
57 define('CONTEXT_BLOCK', 80);
59 // capability risks - see http://docs.moodle.org/en/Hardening_new_Roles_system
60 define('RISK_MANAGETRUST', 0x0001);
61 define('RISK_CONFIG', 0x0002);
62 define('RISK_XSS', 0x0004);
63 define('RISK_PERSONAL', 0x0008);
64 define('RISK_SPAM', 0x0010);
66 require_once($CFG->dirroot.'/group/lib.php');
68 $context_cache = array(); // Cache of all used context objects for performance (by level and instance)
69 $context_cache_id = array(); // Index to above cache by id
72 function get_role_context_caps($roleid, $context) {
73 //this is really slow!!!! - do not use above course context level!
74 $result = array();
75 $result[$context->id] = array();
77 // first emulate the parent context capabilities merging into context
78 $searchcontexts = array_reverse(get_parent_contexts($context));
79 array_push($searchcontexts, $context->id);
80 foreach ($searchcontexts as $cid) {
81 if ($capabilities = get_records_select('role_capabilities', "roleid = $roleid AND contextid = $cid")) {
82 foreach ($capabilities as $cap) {
83 if (!array_key_exists($cap->capability, $result[$context->id])) {
84 $result[$context->id][$cap->capability] = 0;
86 $result[$context->id][$cap->capability] += $cap->permission;
91 // now go through the contexts bellow given context
92 $searchcontexts = get_child_contexts($context);
93 foreach ($searchcontexts as $cid) {
94 if ($capabilities = get_records_select('role_capabilities', "roleid = $roleid AND contextid = $cid")) {
95 foreach ($capabilities as $cap) {
96 if (!array_key_exists($cap->contextid, $result)) {
97 $result[$cap->contextid] = array();
99 $result[$cap->contextid][$cap->capability] = $cap->permission;
104 return $result;
107 function get_role_caps($roleid) {
108 $result = array();
109 if ($capabilities = get_records_select('role_capabilities',"roleid = $roleid")) {
110 foreach ($capabilities as $cap) {
111 if (!array_key_exists($cap->contextid, $result)) {
112 $result[$cap->contextid] = array();
114 $result[$cap->contextid][$cap->capability] = $cap->permission;
117 return $result;
120 function merge_role_caps($caps, $mergecaps) {
121 if (empty($mergecaps)) {
122 return $caps;
125 if (empty($caps)) {
126 return $mergecaps;
129 foreach ($mergecaps as $contextid=>$capabilities) {
130 if (!array_key_exists($contextid, $caps)) {
131 $caps[$contextid] = array();
133 foreach ($capabilities as $capability=>$permission) {
134 if (!array_key_exists($capability, $caps[$contextid])) {
135 $caps[$contextid][$capability] = 0;
137 $caps[$contextid][$capability] += $permission;
140 return $caps;
144 * Loads the capabilities for the default guest role to the current user in a
145 * specific context.
146 * @return object
148 function load_guest_role($return=false) {
149 global $USER;
151 static $guestrole = false;
153 if ($guestrole === false) {
154 if (!$guestrole = get_guest_role()) {
155 return false;
159 if ($return) {
160 return get_role_caps($guestrole->id);
161 } else {
162 has_capability('clearcache');
163 $USER->capabilities = get_role_caps($guestrole->id);
164 return true;
169 * Load default not logged in role capabilities when user is not logged in
170 * @return bool
172 function load_notloggedin_role($return=false) {
173 global $CFG, $USER;
175 if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM)) {
176 return false;
179 if (empty($CFG->notloggedinroleid)) { // Let's set the default to the guest role
180 if ($role = get_guest_role()) {
181 set_config('notloggedinroleid', $role->id);
182 } else {
183 return false;
187 if ($return) {
188 return get_role_caps($CFG->notloggedinroleid);
189 } else {
190 has_capability('clearcache');
191 $USER->capabilities = get_role_caps($CFG->notloggedinroleid);
192 return true;
197 * Load default logged in role capabilities for all logged in users
198 * @return bool
200 function load_defaultuser_role($return=false) {
201 global $CFG, $USER;
203 if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM)) {
204 return false;
207 if (empty($CFG->defaultuserroleid)) { // Let's set the default to the guest role
208 if ($role = get_guest_role()) {
209 set_config('defaultuserroleid', $role->id);
210 } else {
211 return false;
215 $capabilities = get_role_caps($CFG->defaultuserroleid);
217 // fix the guest user heritage:
218 // If the default role is a guest role, then don't copy legacy:guest,
219 // otherwise this user could get confused with a REAL guest. Also don't copy
220 // course:view, which is a hack that's necessary because guest roles are
221 // not really handled properly (see MDL-7513)
222 if (!empty($capabilities[$sitecontext->id]['moodle/legacy:guest'])) {
223 unset($capabilities[$sitecontext->id]['moodle/legacy:guest']);
224 unset($capabilities[$sitecontext->id]['moodle/course:view']);
227 if ($return) {
228 return $capabilities;
229 } else {
230 has_capability('clearcache');
231 $USER->capabilities = $capabilities;
232 return true;
238 * Get the default guest role
239 * @return object role
241 function get_guest_role() {
242 global $CFG;
244 if (empty($CFG->guestroleid)) {
245 if ($roles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW)) {
246 $guestrole = array_shift($roles); // Pick the first one
247 set_config('guestroleid', $guestrole->id);
248 return $guestrole;
249 } else {
250 debugging('Can not find any guest role!');
251 return false;
253 } else {
254 if ($guestrole = get_record('role','id', $CFG->guestroleid)) {
255 return $guestrole;
256 } else {
257 //somebody is messing with guest roles, remove incorrect setting and try to find a new one
258 set_config('guestroleid', '');
259 return get_guest_role();
266 * This functions get all the course categories in proper order
267 * (!)note this only gets course category contexts, and not the site
268 * context
269 * @param object $context
270 * @return array of contextids
272 function get_parent_cats($context) {
273 global $COURSE;
275 switch ($context->contextlevel) {
276 // a category can be the parent of another category
277 // there is no limit of depth in this case
278 case CONTEXT_COURSECAT:
279 static $categoryparents = null; // cache for parent categories
280 if (!isset($categoryparents)) {
281 $categoryparents = array();
283 if (array_key_exists($context->instanceid, $categoryparents)) {
284 return $categoryparents[$context->instanceid];
287 if (!$cat = get_record('course_categories','id',$context->instanceid)) {
288 //error?
289 return array();
291 $parents = array();
292 while (!empty($cat->parent)) {
293 if (!$catcontext = get_context_instance(CONTEXT_COURSECAT, $cat->parent)) {
294 debugging('Incorrect category parent');
295 break;
297 $parents[] = $catcontext->id;
298 $cat = get_record('course_categories','id',$cat->parent);
300 return $categoryparents[$context->instanceid] = array_reverse($parents);
301 break;
303 // a course always fall into a category, unless it's a site course
304 // this happens when SITEID == $course->id
305 // in this case the parent of the course is site context
306 case CONTEXT_COURSE:
307 static $courseparents = null; // cache course parents
308 if (!isset($courseparents)) {
309 $courseparents = array();
311 if (array_key_exists($context->instanceid, $courseparents)) {
312 return $courseparents[$context->instanceid];
315 if (count($courseparents) > 1000) {
316 $courseparents = array(); // max cache size when looping through thousands of courses
319 if ($context->instanceid == SITEID) {
320 return $courseparents[$context->instanceid] = array(); // frontpage course does not have parent cats
322 if ($context->instanceid == $COURSE->id) {
323 $course = $COURSE;
324 } else if (!$course = get_record('course', 'id', $context->instanceid)) {
325 //error?
326 return array();;
329 if (empty($course->category)) {
330 // this should not happen
331 return $courseparents[$context->instanceid] = array();
334 if (!$catcontext = get_context_instance(CONTEXT_COURSECAT, $course->category)) {
335 debugging('Incorect course category');
336 return array();;
339 return $courseparents[$context->instanceid] = array_merge(get_parent_cats($catcontext), array($catcontext->id)); //recursion :-)
340 break;
342 default:
343 // something is very wrong!
344 return array();
345 break;
352 * This function checks for a capability assertion being true. If it isn't
353 * then the page is terminated neatly with a standard error message
354 * @param string $capability - name of the capability
355 * @param object $context - a context object (record from context table)
356 * @param integer $userid - a userid number
357 * @param bool $doanything - if false, ignore do anything
358 * @param string $errorstring - an errorstring
359 * @param string $stringfile - which stringfile to get it from
361 function require_capability($capability, $context=NULL, $userid=NULL, $doanything=true,
362 $errormessage='nopermissions', $stringfile='') {
364 global $USER, $CFG;
366 /// If the current user is not logged in, then make sure they are (if needed)
368 if (empty($userid) and empty($USER->capabilities)) {
369 if ($context && ($context->contextlevel == CONTEXT_COURSE)) {
370 require_login($context->instanceid);
371 } else if ($context && ($context->contextlevel == CONTEXT_MODULE)) {
372 if ($cm = get_record('course_modules','id',$context->instanceid)) {
373 if (!$course = get_record('course', 'id', $cm->course)) {
374 error('Incorrect course.');
376 require_course_login($course, true, $cm);
378 } else {
379 require_login();
381 } else if ($context && ($context->contextlevel == CONTEXT_SYSTEM)) {
382 if (!empty($CFG->forcelogin)) {
383 require_login();
386 } else {
387 require_login();
391 /// OK, if they still don't have the capability then print a nice error message
393 if (!has_capability($capability, $context, $userid, $doanything)) {
394 $capabilityname = get_capability_string($capability);
395 print_error($errormessage, $stringfile, '', $capabilityname);
400 * Cheks if current user has allowed permission for any of submitted capabilities
401 * in given or child contexts.
402 * @param object $context - a context object (record from context table)
403 * @param array $capabilitynames array of strings, capability names
404 * @return boolean
406 function has_capability_including_child_contexts($context, $capabilitynames) {
407 global $USER;
409 foreach ($capabilitynames as $capname) {
410 if (has_capability($capname, $context)) {
411 return true;
415 if ($children = get_child_contexts($context)) {
416 foreach ($capabilitynames as $capname) {
417 foreach ($children as $child) {
418 if (isset($USER->capabilities[$child][$capname]) and $USER->capabilities[$child][$capname] > 0) {
419 // extra check for inherited prevent and prohibit
420 if (has_capability($capname, get_context_instance_by_id($child), $USER->id, false)) {
421 return true;
428 return false;
432 * This function returns whether the current user has the capability of performing a function
433 * For example, we can do has_capability('mod/forum:replypost',$context) in forum
434 * This is a recursive function.
435 * @uses $USER
436 * @param string $capability - name of the capability (or debugcache or clearcache)
437 * @param object $context - a context object (record from context table)
438 * @param integer $userid - a userid number
439 * @param bool $doanything - if false, ignore do anything
440 * @return bool
442 function has_capability($capability, $context=NULL, $userid=NULL, $doanything=true) {
444 global $USER, $CONTEXT, $CFG;
446 static $capcache = array(); // Cache of capabilities
449 /// Cache management
451 if ($capability == 'clearcache') {
452 $capcache = array(); // Clear ALL the capability cache
453 return false;
456 /// Some sanity checks
457 if (debugging('',DEBUG_DEVELOPER)) {
458 if ($capability == 'debugcache') {
459 print_object($capcache);
460 return true;
462 if (!record_exists('capabilities', 'name', $capability)) {
463 debugging('Capability "'.$capability.'" was not found! This should be fixed in code.');
465 if ($doanything != true and $doanything != false) {
466 debugging('Capability parameter "doanything" is wierd ("'.$doanything.'"). This should be fixed in code.');
468 if (!is_object($context) && $context !== NULL) {
469 debugging('Incorrect context parameter "'.$context.'" for has_capability(), object expected! This should be fixed in code.');
473 /// Make sure we know the current context
474 if (empty($context)) { // Use default CONTEXT if none specified
475 if (empty($CONTEXT)) {
476 return false;
477 } else {
478 $context = $CONTEXT;
480 } else { // A context was given to us
481 if (empty($CONTEXT)) {
482 $CONTEXT = $context; // Store FIRST used context in this global as future default
486 /// Check and return cache in case we've processed this one before.
487 $requsteduser = empty($userid) ? $USER->id : $userid; // find out the requested user id, $USER->id might have been changed
488 $cachekey = $capability.'_'.$context->id.'_'.intval($requsteduser).'_'.intval($doanything);
490 if (isset($capcache[$cachekey])) {
491 return $capcache[$cachekey];
495 /// Load up the capabilities list or item as necessary
496 if ($userid) {
497 if (empty($USER->id) or ($userid != $USER->id) or empty($USER->capabilities)) {
499 //caching - helps user switching in cron
500 static $guestuserid = false; // guest user id
501 static $guestcaps = false; // guest caps
502 static $defcaps = false; // default user caps - this might help cron
504 if ($guestuserid === false) {
505 $guestuserid = get_field('user', 'id', 'username', 'guest');
508 if ($userid == $guestuserid) {
509 if ($guestcaps === false) {
510 $guestcaps = load_guest_role(true);
512 $capabilities = $guestcaps;
514 } else {
515 // This big SQL is expensive! We reduce it a little by avoiding checking for changed enrolments (false)
516 $capabilities = load_user_capability($capability, $context, $userid, false);
517 if ($defcaps === false) {
518 $defcaps = load_defaultuser_role(true);
520 $capabilities = merge_role_caps($capabilities, $defcaps);
523 } else { //$USER->id == $userid and needed capabilities already present
524 $capabilities = $USER->capabilities;
527 } else { // no userid
528 if (empty($USER->capabilities)) {
529 load_all_capabilities(); // expensive - but we have to do it once anyway
531 $capabilities = $USER->capabilities;
532 $userid = $USER->id;
535 /// We act a little differently when switchroles is active
537 $switchroleactive = false; // Assume it isn't active in this context
540 /// First deal with the "doanything" capability
542 if ($doanything) {
544 /// First make sure that we aren't in a "switched role"
546 if (!empty($USER->switchrole)) { // Switchrole is active somewhere!
547 if (!empty($USER->switchrole[$context->id])) { // Because of current context
548 $switchroleactive = true;
549 } else { // Check parent contexts
550 if ($parentcontextids = get_parent_contexts($context)) {
551 foreach ($parentcontextids as $parentcontextid) {
552 if (!empty($USER->switchrole[$parentcontextid])) { // Yep, switchroles active here
553 $switchroleactive = true;
554 break;
561 /// Check the site context for doanything (most common) first
563 if (empty($switchroleactive)) { // Ignore site setting if switchrole is active
564 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
565 if (isset($capabilities[$sitecontext->id]['moodle/site:doanything'])) {
566 $result = (0 < $capabilities[$sitecontext->id]['moodle/site:doanything']);
567 $capcache[$cachekey] = $result;
568 return $result;
571 /// If it's not set at site level, it is possible to be set on other levels
572 /// Though this usage is not common and can cause risks
573 switch ($context->contextlevel) {
575 case CONTEXT_COURSECAT:
576 // Check parent cats.
577 $parentcats = get_parent_cats($context);
578 foreach ($parentcats as $parentcat) {
579 if (isset($capabilities[$parentcat]['moodle/site:doanything'])) {
580 $result = (0 < $capabilities[$parentcat]['moodle/site:doanything']);
581 $capcache[$cachekey] = $result;
582 return $result;
585 break;
587 case CONTEXT_COURSE:
588 // Check parent cat.
589 $parentcats = get_parent_cats($context);
591 foreach ($parentcats as $parentcat) {
592 if (isset($capabilities[$parentcat]['do_anything'])) {
593 $result = (0 < $capabilities[$parentcat]['do_anything']);
594 $capcache[$cachekey] = $result;
595 return $result;
598 break;
600 case CONTEXT_GROUP:
601 // Find course.
602 $courseid = get_field('groups', 'courseid', 'id', $context->instanceid);
603 $courseinstance = get_context_instance(CONTEXT_COURSE, $courseid);
605 $parentcats = get_parent_cats($courseinstance);
606 foreach ($parentcats as $parentcat) {
607 if (isset($capabilities[$parentcat]['do_anything'])) {
608 $result = (0 < $capabilities[$parentcat]['do_anything']);
609 $capcache[$cachekey] = $result;
610 return $result;
614 $coursecontext = '';
615 if (isset($capabilities[$courseinstance->id]['do_anything'])) {
616 $result = (0 < $capabilities[$courseinstance->id]['do_anything']);
617 $capcache[$cachekey] = $result;
618 return $result;
621 break;
623 case CONTEXT_MODULE:
624 // Find course.
625 $cm = get_record('course_modules', 'id', $context->instanceid);
626 $courseinstance = get_context_instance(CONTEXT_COURSE, $cm->course);
628 if ($parentcats = get_parent_cats($courseinstance)) {
629 foreach ($parentcats as $parentcat) {
630 if (isset($capabilities[$parentcat]['do_anything'])) {
631 $result = (0 < $capabilities[$parentcat]['do_anything']);
632 $capcache[$cachekey] = $result;
633 return $result;
638 if (isset($capabilities[$courseinstance->id]['do_anything'])) {
639 $result = (0 < $capabilities[$courseinstance->id]['do_anything']);
640 $capcache[$cachekey] = $result;
641 return $result;
644 break;
646 case CONTEXT_BLOCK:
647 // not necessarily 1 to 1 to course.
648 $block = get_record('block_instance','id',$context->instanceid);
649 if ($block->pagetype == 'course-view') {
650 $courseinstance = get_context_instance(CONTEXT_COURSE, $block->pageid); // needs check
651 $parentcats = get_parent_cats($courseinstance);
653 foreach ($parentcats as $parentcat) {
654 if (isset($capabilities[$parentcat]['do_anything'])) {
655 $result = (0 < $capabilities[$parentcat]['do_anything']);
656 $capcache[$cachekey] = $result;
657 return $result;
661 if (isset($capabilities[$courseinstance->id]['do_anything'])) {
662 $result = (0 < $capabilities[$courseinstance->id]['do_anything']);
663 $capcache[$cachekey] = $result;
664 return $result;
667 // blocks that do not have course as parent do not need to do any more checks - already done above
669 break;
671 default:
672 // CONTEXT_SYSTEM: CONTEXT_PERSONAL: CONTEXT_USER:
673 // Do nothing, because the parents are site context
674 // which has been checked already
675 break;
678 // Last: check self.
679 if (isset($capabilities[$context->id]['do_anything'])) {
680 $result = (0 < $capabilities[$context->id]['do_anything']);
681 $capcache[$cachekey] = $result;
682 return $result;
685 // do_anything has not been set, we now look for it the normal way.
686 $result = (0 < capability_search($capability, $context, $capabilities, $switchroleactive));
687 $capcache[$cachekey] = $result;
688 return $result;
694 * In a separate function so that we won't have to deal with do_anything.
695 * again. Used by function has_capability().
696 * @param $capability - capability string
697 * @param $context - the context object
698 * @param $capabilities - either $USER->capability or loaded array (for other users)
699 * @return permission (int)
701 function capability_search($capability, $context, $capabilities, $switchroleactive=false) {
703 global $USER, $CFG, $COURSE;
705 if (!isset($context->id)) {
706 return 0;
708 // if already set in the array explicitly, no need to look for it in parent
709 // context any longer
710 if (isset($capabilities[$context->id][$capability])) {
711 return ($capabilities[$context->id][$capability]);
714 /* Then, we check the cache recursively */
715 $permission = 0;
717 switch ($context->contextlevel) {
719 case CONTEXT_SYSTEM: // by now it's a definite an inherit
720 $permission = 0;
721 break;
723 case CONTEXT_PERSONAL:
724 $parentcontext = get_context_instance(CONTEXT_SYSTEM);
725 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
726 break;
728 case CONTEXT_USER:
729 $parentcontext = get_context_instance(CONTEXT_SYSTEM);
730 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
731 break;
733 case CONTEXT_COURSE:
734 if ($switchroleactive) {
735 // if switchrole active, do not check permissions above the course context, blocks are an exception
736 break;
738 // break is not here intentionally - because the code is the same for category and course
739 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
740 $parents = get_parent_cats($context); // cached internally
742 // non recursive - should be faster
743 foreach ($parents as $parentid) {
744 $parentcontext = get_context_instance_by_id($parentid);
745 if (isset($capabilities[$parentcontext->id][$capability])) {
746 return ($capabilities[$parentcontext->id][$capability]);
749 // finally check system context
750 $parentcontext = get_context_instance(CONTEXT_SYSTEM);
751 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
752 break;
754 case CONTEXT_GROUP: // 1 to 1 to course
755 $courseid = get_field('groups', 'courseid', 'id', $context->instanceid);
756 $parentcontext = get_context_instance(CONTEXT_COURSE, $courseid);
757 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
758 break;
760 case CONTEXT_MODULE: // 1 to 1 to course
761 $cm = get_record('course_modules','id',$context->instanceid);
762 $parentcontext = get_context_instance(CONTEXT_COURSE, $cm->course);
763 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
764 break;
766 case CONTEXT_BLOCK: // not necessarily 1 to 1 to course
767 $block = get_record('block_instance','id',$context->instanceid);
768 if ($block->pagetype == 'course-view') {
769 $parentcontext = get_context_instance(CONTEXT_COURSE, $block->pageid); // needs check
770 } else {
771 $parentcontext = get_context_instance(CONTEXT_SYSTEM);
773 // ignore the $switchroleactive beause we want the real block view capability defined in system context
774 $permission = capability_search($capability, $parentcontext, $capabilities, false);
775 break;
777 default:
778 error ('This is an unknown context (' . $context->contextlevel . ') in capability_search!');
779 return false;
782 return $permission;
786 * auxillary function for load_user_capabilities()
787 * checks if context c1 is a parent (or itself) of context c2
788 * @param int $c1 - context id of context 1
789 * @param int $c2 - context id of context 2
790 * @return bool
792 function is_parent_context($c1, $c2) {
793 static $parentsarray;
795 // context can be itself and this is ok
796 if ($c1 == $c2) {
797 return true;
799 // hit in cache?
800 if (isset($parentsarray[$c1][$c2])) {
801 return $parentsarray[$c1][$c2];
804 if (!$co2 = get_record('context', 'id', $c2)) {
805 return false;
808 if (!$parents = get_parent_contexts($co2)) {
809 return false;
812 foreach ($parents as $parent) {
813 $parentsarray[$parent][$c2] = true;
816 if (in_array($c1, $parents)) {
817 return true;
818 } else { // else not a parent, set the cache anyway
819 $parentsarray[$c1][$c2] = false;
820 return false;
826 * auxillary function for load_user_capabilities()
827 * handler in usort() to sort contexts according to level
828 * @param object contexta
829 * @param object contextb
830 * @return int
832 function roles_context_cmp($contexta, $contextb) {
833 if ($contexta->contextlevel == $contextb->contextlevel) {
834 return 0;
836 return ($contexta->contextlevel < $contextb->contextlevel) ? -1 : 1;
840 * It will build an array of all the capabilities at each level
841 * i.e. site/metacourse/course_category/course/moduleinstance
842 * Note we should only load capabilities if they are explicitly assigned already,
843 * we should not load all module's capability!
845 * [Capabilities] => [26][forum_post] = 1
846 * [26][forum_start] = -8990
847 * [26][forum_edit] = -1
848 * [273][blah blah] = 1
849 * [273][blah blah blah] = 2
851 * @param $capability string - Only get a specific capability (string)
852 * @param $context object - Only get capabilities for a specific context object
853 * @param $userid integer - the id of the user whose capabilities we want to load
854 * @param $checkenrolments boolean - Should we check enrolment plugins (potentially expensive)
855 * @return array of permissions (or nothing if they get assigned to $USER)
857 function load_user_capability($capability='', $context=NULL, $userid=NULL, $checkenrolments=true) {
859 global $USER, $CFG;
861 // this flag has not been set!
862 // (not clean install, or upgraded successfully to 1.7 and up)
863 if (empty($CFG->rolesactive)) {
864 return false;
867 if (empty($userid)) {
868 if (empty($USER->id)) { // We have no user to get capabilities for
869 debugging('User not logged in for load_user_capability!');
870 return false;
872 unset($USER->capabilities); // We don't want possible older capabilites hanging around
874 if ($checkenrolments) { // Call "enrol" system to ensure that we have the correct picture
875 check_enrolment_plugins($USER);
878 $userid = $USER->id;
879 $otheruserid = false;
880 } else {
881 if (!$user = get_record('user', 'id', $userid)) {
882 debugging('Non-existent userid in load_user_capability!');
883 return false;
886 if ($checkenrolments) { // Call "enrol" system to ensure that we have the correct picture
887 check_enrolment_plugins($user);
890 $otheruserid = $userid;
894 /// First we generate a list of all relevant contexts of the user
896 $usercontexts = array();
898 if ($context) { // if context is specified
899 $usercontexts = get_parent_contexts($context);
900 $usercontexts[] = $context->id; // Add the current context as well
901 } else { // else, we load everything
902 if ($userroles = get_records('role_assignments','userid',$userid)) {
903 foreach ($userroles as $userrole) {
904 if (!in_array($userrole->contextid, $usercontexts)) {
905 $usercontexts[] = $userrole->contextid;
911 /// Set up SQL fragments for searching contexts
913 if ($usercontexts) {
914 $listofcontexts = '('.implode(',', $usercontexts).')';
915 $searchcontexts1 = "c1.id IN $listofcontexts AND";
916 } else {
917 $searchcontexts1 = '';
920 if ($capability) {
921 // the doanything may override the requested capability
922 $capsearch = " AND (rc.capability = '$capability' OR rc.capability = 'moodle/site:doanything') ";
923 } else {
924 $capsearch ="";
927 /// Then we use 1 giant SQL to bring out all relevant capabilities.
928 /// The first part gets the capabilities of orginal role.
929 /// The second part gets the capabilities of overriden roles.
931 $siteinstance = get_context_instance(CONTEXT_SYSTEM);
932 $capabilities = array(); // Reinitialize.
934 // SQL for normal capabilities
935 $SQL1 = "SELECT rc.capability, c1.id as id1, c1.id as id2, (c1.contextlevel * 100) AS aggrlevel,
936 SUM(rc.permission) AS sum
937 FROM
938 {$CFG->prefix}role_assignments ra,
939 {$CFG->prefix}role_capabilities rc,
940 {$CFG->prefix}context c1
941 WHERE
942 ra.contextid=c1.id AND
943 ra.roleid=rc.roleid AND
944 ra.userid=$userid AND
945 $searchcontexts1
946 rc.contextid=$siteinstance->id
947 $capsearch
948 GROUP BY
949 rc.capability, c1.id, c1.contextlevel * 100
950 HAVING
951 SUM(rc.permission) != 0
953 UNION ALL
955 SELECT rc.capability, c1.id as id1, c2.id as id2, (c1.contextlevel * 100 + c2.contextlevel) AS aggrlevel,
956 SUM(rc.permission) AS sum
957 FROM
958 {$CFG->prefix}role_assignments ra INNER JOIN
959 {$CFG->prefix}role_capabilities rc on ra.roleid = rc.roleid INNER JOIN
960 {$CFG->prefix}context c1 on ra.contextid = c1.id INNER JOIN
961 {$CFG->prefix}context c2 on rc.contextid = c2.id INNER JOIN
962 {$CFG->prefix}context_rel cr on cr.c1 = c2.id AND cr.c2 = c1.id
963 WHERE
964 ra.userid=$userid AND
965 $searchcontexts1
966 rc.contextid != $siteinstance->id
967 $capsearch
968 GROUP BY
969 rc.capability, c1.id, c2.id, c1.contextlevel * 100 + c2.contextlevel
970 HAVING
971 SUM(rc.permission) != 0
972 ORDER BY
973 aggrlevel ASC";
975 if (!$rs = get_recordset_sql($SQL1)) {
976 error("Query failed in load_user_capability.");
979 if ($rs && $rs->RecordCount() > 0) {
980 while ($caprec = rs_fetch_next_record($rs)) {
981 $array = (array)$caprec;
982 $temprecord = new object;
984 foreach ($array as $key=>$val) {
985 if ($key == 'aggrlevel') {
986 $temprecord->contextlevel = $val;
987 } else {
988 $temprecord->{$key} = $val;
991 $capabilities[] = $temprecord;
993 rs_close($rs);
996 // SQL for overrides
997 // this is take out because we have no way of making sure c1 is indeed related to c2 (parent)
998 // if we do not group by sum, it is possible to have multiple records of rc.capability, c1.id, c2.id, tuple having
999 // different values, we can maually sum it when we go through the list
1003 $SQL2 = "SELECT rc.capability, c1.id as id1, c2.id as id2, (c1.contextlevel * 100 + c2.contextlevel) AS aggrlevel,
1004 rc.permission AS sum
1005 FROM
1006 {$CFG->prefix}role_assignments ra,
1007 {$CFG->prefix}role_capabilities rc,
1008 {$CFG->prefix}context c1,
1009 {$CFG->prefix}context c2
1010 WHERE
1011 ra.contextid=c1.id AND
1012 ra.roleid=rc.roleid AND
1013 ra.userid=$userid AND
1014 rc.contextid=c2.id AND
1015 $searchcontexts1
1016 rc.contextid != $siteinstance->id
1017 $capsearch
1019 GROUP BY
1020 rc.capability, (c1.contextlevel * 100 + c2.contextlevel), c1.id, c2.id, rc.permission
1021 ORDER BY
1022 aggrlevel ASC
1023 ";*/
1026 if (!$rs = get_recordset_sql($SQL2)) {
1027 error("Query failed in load_user_capability.");
1030 if ($rs && $rs->RecordCount() > 0) {
1031 while ($caprec = rs_fetch_next_record($rs)) {
1032 $array = (array)$caprec;
1033 $temprecord = new object;
1035 foreach ($array as $key=>$val) {
1036 if ($key == 'aggrlevel') {
1037 $temprecord->contextlevel = $val;
1038 } else {
1039 $temprecord->{$key} = $val;
1042 // for overrides, we have to make sure that context2 is a child of context1
1043 // otherwise the combination makes no sense
1044 //if (is_parent_context($temprecord->id1, $temprecord->id2)) {
1045 $capabilities[] = $temprecord;
1046 //} // only write if relevant
1048 rs_close($rs);
1051 // this step sorts capabilities according to the contextlevel
1052 // it is very important because the order matters when we
1053 // go through each capabilities later. (i.e. higher level contextlevel
1054 // will override lower contextlevel settings
1055 usort($capabilities, 'roles_context_cmp');
1057 /* so up to this point we should have somethign like this
1058 * $capabilities[1] ->contextlevel = 1000
1059 ->module = 0 // changed from SITEID in 1.8 (??)
1060 ->capability = do_anything
1061 ->id = 1 (id is the context id)
1062 ->sum = 0
1064 * $capabilities[2] ->contextlevel = 1000
1065 ->module = 0 // changed from SITEID in 1.8 (??)
1066 ->capability = post_messages
1067 ->id = 1
1068 ->sum = -9000
1070 * $capabilittes[3] ->contextlevel = 3000
1071 ->module = course
1072 ->capability = view_course_activities
1073 ->id = 25
1074 ->sum = 1
1076 * $capabilittes[4] ->contextlevel = 3000
1077 ->module = course
1078 ->capability = view_course_activities
1079 ->id = 26
1080 ->sum = 0 (this is another course)
1082 * $capabilities[5] ->contextlevel = 3050
1083 ->module = course
1084 ->capability = view_course_activities
1085 ->id = 25 (override in course 25)
1086 ->sum = -1
1087 * ....
1088 * now we proceed to write the session array, going from top to bottom
1089 * at anypoint, we need to go up and check parent to look for prohibit
1091 // print_object($capabilities);
1093 /* This is where we write to the actualy capabilities array
1094 * what we need to do from here on is
1095 * going down the array from lowest level to highest level
1096 * 1) recursively check for prohibit,
1097 * if any, we write prohibit
1098 * else, we write the value
1099 * 2) at an override level, we overwrite current level
1100 * if it's not set to prohibit already, and if different
1101 * ........ that should be it ........
1104 // This is the flag used for detecting the current context level. Since we are going through
1105 // the array in ascending order of context level. For normal capabilities, there should only
1106 // be 1 value per (capability, contextlevel, context), because they are already summed. But,
1107 // for overrides, since we are processing them separate, we need to sum the relevcant entries.
1108 // We set this flag when we hit a new level.
1109 // If the flag is already set, we keep adding (summing), otherwise, we just override previous
1110 // settings (from lower level contexts)
1111 $capflags = array(); // (contextid, contextlevel, capability)
1112 $usercap = array(); // for other user's capabilities
1113 foreach ($capabilities as $capability) {
1115 if (!$context = get_context_instance_by_id($capability->id2)) {
1116 continue; // incorrect stale context
1119 if (!empty($otheruserid)) { // we are pulling out other user's capabilities, do not write to session
1121 if (capability_prohibits($capability->capability, $context, $capability->sum, $usercap)) {
1122 $usercap[$capability->id2][$capability->capability] = CAP_PROHIBIT;
1123 continue;
1125 if (isset($usercap[$capability->id2][$capability->capability])) { // use isset because it can be sum 0
1126 if (!empty($capflags[$capability->id2][$capability->contextlevel][$capability->capability])) {
1127 $usercap[$capability->id2][$capability->capability] += $capability->sum;
1128 } else { // else we override, and update flag
1129 $usercap[$capability->id2][$capability->capability] = $capability->sum;
1130 $capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
1132 } else {
1133 $usercap[$capability->id2][$capability->capability] = $capability->sum;
1134 $capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
1137 } else {
1139 if (capability_prohibits($capability->capability, $context, $capability->sum)) { // if any parent or parent's parent is set to prohibit
1140 $USER->capabilities[$capability->id2][$capability->capability] = CAP_PROHIBIT;
1141 continue;
1144 // if no parental prohibit set
1145 // just write to session, i am not sure this is correct yet
1146 // since 3050 shows up after 3000, and 3070 shows up after 3050,
1147 // it should be ok just to overwrite like this, provided that there's no
1148 // parental prohibits
1149 // we need to write even if it's 0, because it could be an inherit override
1150 if (isset($USER->capabilities[$capability->id2][$capability->capability])) {
1151 if (!empty($capflags[$capability->id2][$capability->contextlevel][$capability->capability])) {
1152 $USER->capabilities[$capability->id2][$capability->capability] += $capability->sum;
1153 } else { // else we override, and update flag
1154 $USER->capabilities[$capability->id2][$capability->capability] = $capability->sum;
1155 $capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
1157 } else {
1158 $USER->capabilities[$capability->id2][$capability->capability] = $capability->sum;
1159 $capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
1164 // now we don't care about the huge array anymore, we can dispose it.
1165 unset($capabilities);
1166 unset($capflags);
1168 if (!empty($otheruserid)) {
1169 return $usercap; // return the array
1175 * A convenience function to completely load all the capabilities
1176 * for the current user. This is what gets called from login, for example.
1178 function load_all_capabilities() {
1179 global $USER;
1181 //caching - helps user switching in cron
1182 static $defcaps = false;
1184 unset($USER->mycourses); // Reset a cache used by get_my_courses
1186 if (isguestuser()) {
1187 load_guest_role(); // All non-guest users get this by default
1189 } else if (isloggedin()) {
1190 if ($defcaps === false) {
1191 $defcaps = load_defaultuser_role(true);
1194 load_user_capability();
1196 // when in "course login as" - load only course caqpabilitites (it may not always work as expected)
1197 if (!empty($USER->realuser) and $USER->loginascontext->contextlevel != CONTEXT_SYSTEM) {
1198 $children = get_child_contexts($USER->loginascontext);
1199 $children[] = $USER->loginascontext->id;
1200 foreach ($USER->capabilities as $conid => $caps) {
1201 if (!in_array($conid, $children)) {
1202 unset($USER->capabilities[$conid]);
1207 // handle role switching in courses
1208 if (!empty($USER->switchrole)) {
1209 foreach ($USER->switchrole as $contextid => $roleid) {
1210 $context = get_context_instance_by_id($contextid);
1212 // first prune context and any child contexts
1213 $children = get_child_contexts($context);
1214 foreach ($children as $childid) {
1215 unset($USER->capabilities[$childid]);
1217 unset($USER->capabilities[$contextid]);
1219 // now merge all switched role caps in context and bellow
1220 $swithccaps = get_role_context_caps($roleid, $context);
1221 $USER->capabilities = merge_role_caps($USER->capabilities, $swithccaps);
1225 if (isset($USER->capabilities)) {
1226 $USER->capabilities = merge_role_caps($USER->capabilities, $defcaps);
1227 } else {
1228 $USER->capabilities = $defcaps;
1231 } else {
1232 load_notloggedin_role();
1238 * Check all the login enrolment information for the given user object
1239 * by querying the enrolment plugins
1241 function check_enrolment_plugins(&$user) {
1242 global $CFG;
1244 static $inprogress; // To prevent this function being called more than once in an invocation
1246 if (!empty($inprogress[$user->id])) {
1247 return;
1250 $inprogress[$user->id] = true; // Set the flag
1252 require_once($CFG->dirroot .'/enrol/enrol.class.php');
1254 if (!($plugins = explode(',', $CFG->enrol_plugins_enabled))) {
1255 $plugins = array($CFG->enrol);
1258 foreach ($plugins as $plugin) {
1259 $enrol = enrolment_factory::factory($plugin);
1260 if (method_exists($enrol, 'setup_enrolments')) { /// Plugin supports Roles (Moodle 1.7 and later)
1261 $enrol->setup_enrolments($user);
1262 } else { /// Run legacy enrolment methods
1263 if (method_exists($enrol, 'get_student_courses')) {
1264 $enrol->get_student_courses($user);
1266 if (method_exists($enrol, 'get_teacher_courses')) {
1267 $enrol->get_teacher_courses($user);
1270 /// deal with $user->students and $user->teachers stuff
1271 unset($user->student);
1272 unset($user->teacher);
1274 unset($enrol);
1277 unset($inprogress[$user->id]); // Unset the flag
1282 * This is a recursive function that checks whether the capability in this
1283 * context, or the parent capabilities are set to prohibit.
1285 * At this point, we can probably just use the values already set in the
1286 * session variable, since we are going down the level. Any prohit set in
1287 * parents would already reflect in the session.
1289 * @param $capability - capability name
1290 * @param $sum - sum of all capabilities values
1291 * @param $context - the context object
1292 * @param $array - when loading another user caps, their caps are not stored in session but an array
1294 function capability_prohibits($capability, $context, $sum='', $array='') {
1295 global $USER;
1297 // caching, mainly to save unnecessary sqls
1298 static $prohibits; //[capability][contextid]
1299 if (isset($prohibits[$capability][$context->id])) {
1300 return $prohibits[$capability][$context->id];
1303 if (empty($context->id)) {
1304 $prohibits[$capability][$context->id] = false;
1305 return false;
1308 if (empty($capability)) {
1309 $prohibits[$capability][$context->id] = false;
1310 return false;
1313 if ($sum < (CAP_PROHIBIT/2)) {
1314 // If this capability is set to prohibit.
1315 $prohibits[$capability][$context->id] = true;
1316 return true;
1319 if (!empty($array)) {
1320 if (isset($array[$context->id][$capability])
1321 && $array[$context->id][$capability] < (CAP_PROHIBIT/2)) {
1322 $prohibits[$capability][$context->id] = true;
1323 return true;
1325 } else {
1326 // Else if set in session.
1327 if (isset($USER->capabilities[$context->id][$capability])
1328 && $USER->capabilities[$context->id][$capability] < (CAP_PROHIBIT/2)) {
1329 $prohibits[$capability][$context->id] = true;
1330 return true;
1333 switch ($context->contextlevel) {
1335 case CONTEXT_SYSTEM:
1336 // By now it's a definite an inherit.
1337 return 0;
1338 break;
1340 case CONTEXT_PERSONAL:
1341 $parent = get_context_instance(CONTEXT_SYSTEM);
1342 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1343 return $prohibits[$capability][$context->id];
1344 break;
1346 case CONTEXT_USER:
1347 $parent = get_context_instance(CONTEXT_SYSTEM);
1348 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1349 return $prohibits[$capability][$context->id];
1350 break;
1352 case CONTEXT_COURSECAT:
1353 case CONTEXT_COURSE:
1354 $parents = get_parent_cats($context); // cached internally
1355 // no workaround for recursion now - it needs some more work and maybe fixing
1357 if (empty($parents)) {
1358 // system context - this is either top category or frontpage course
1359 $parent = get_context_instance(CONTEXT_SYSTEM);
1360 } else {
1361 // parent context - recursion
1362 $parentid = array_pop($parents);
1363 $parent = get_context_instance_by_id($parentid);
1365 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1366 return $prohibits[$capability][$context->id];
1367 break;
1369 case CONTEXT_GROUP:
1370 // 1 to 1 to course.
1371 if (!$courseid = get_field('groups', 'courseid', 'id', $context->instanceid)) {
1372 $prohibits[$capability][$context->id] = false;
1373 return false;
1375 $parent = get_context_instance(CONTEXT_COURSE, $courseid);
1376 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1377 return $prohibits[$capability][$context->id];
1378 break;
1380 case CONTEXT_MODULE:
1381 // 1 to 1 to course.
1382 if (!$cm = get_record('course_modules','id',$context->instanceid)) {
1383 $prohibits[$capability][$context->id] = false;
1384 return false;
1386 $parent = get_context_instance(CONTEXT_COURSE, $cm->course);
1387 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1388 return $prohibits[$capability][$context->id];
1389 break;
1391 case CONTEXT_BLOCK:
1392 // not necessarily 1 to 1 to course.
1393 if (!$block = get_record('block_instance','id',$context->instanceid)) {
1394 $prohibits[$capability][$context->id] = false;
1395 return false;
1397 if ($block->pagetype == 'course-view') {
1398 $parent = get_context_instance(CONTEXT_COURSE, $block->pageid); // needs check
1399 } else {
1400 $parent = get_context_instance(CONTEXT_SYSTEM);
1402 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1403 return $prohibits[$capability][$context->id];
1404 break;
1406 default:
1407 print_error('unknowncontext');
1408 return false;
1414 * A print form function. This should either grab all the capabilities from
1415 * files or a central table for that particular module instance, then present
1416 * them in check boxes. Only relevant capabilities should print for known
1417 * context.
1418 * @param $mod - module id of the mod
1420 function print_capabilities($modid=0) {
1421 global $CFG;
1423 $capabilities = array();
1425 if ($modid) {
1426 // We are in a module specific context.
1428 // Get the mod's name.
1429 // Call the function that grabs the file and parse.
1430 $cm = get_record('course_modules', 'id', $modid);
1431 $module = get_record('modules', 'id', $cm->module);
1433 } else {
1434 // Print all capabilities.
1435 foreach ($capabilities as $capability) {
1436 // Prints the check box component.
1443 * Installs the roles system.
1444 * This function runs on a fresh install as well as on an upgrade from the old
1445 * hard-coded student/teacher/admin etc. roles to the new roles system.
1447 function moodle_install_roles() {
1449 global $CFG, $db;
1451 /// Create a system wide context for assignemnt.
1452 $systemcontext = $context = get_context_instance(CONTEXT_SYSTEM);
1455 /// Create default/legacy roles and capabilities.
1456 /// (1 legacy capability per legacy role at system level).
1458 $adminrole = create_role(addslashes(get_string('administrator')), 'admin',
1459 addslashes(get_string('administratordescription')), 'moodle/legacy:admin');
1460 $coursecreatorrole = create_role(addslashes(get_string('coursecreators')), 'coursecreator',
1461 addslashes(get_string('coursecreatorsdescription')), 'moodle/legacy:coursecreator');
1462 $editteacherrole = create_role(addslashes(get_string('defaultcourseteacher')), 'editingteacher',
1463 addslashes(get_string('defaultcourseteacherdescription')), 'moodle/legacy:editingteacher');
1464 $noneditteacherrole = create_role(addslashes(get_string('noneditingteacher')), 'teacher',
1465 addslashes(get_string('noneditingteacherdescription')), 'moodle/legacy:teacher');
1466 $studentrole = create_role(addslashes(get_string('defaultcoursestudent')), 'student',
1467 addslashes(get_string('defaultcoursestudentdescription')), 'moodle/legacy:student');
1468 $guestrole = create_role(addslashes(get_string('guest')), 'guest',
1469 addslashes(get_string('guestdescription')), 'moodle/legacy:guest');
1470 $userrole = create_role(addslashes(get_string('authenticateduser')), 'user',
1471 addslashes(get_string('authenticateduserdescription')), 'moodle/legacy:user');
1473 /// Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles
1475 if (!assign_capability('moodle/site:doanything', CAP_ALLOW, $adminrole, $systemcontext->id)) {
1476 error('Could not assign moodle/site:doanything to the admin role');
1478 if (!update_capabilities()) {
1479 error('Had trouble upgrading the core capabilities for the Roles System');
1482 /// Look inside user_admin, user_creator, user_teachers, user_students and
1483 /// assign above new roles. If a user has both teacher and student role,
1484 /// only teacher role is assigned. The assignment should be system level.
1486 $dbtables = $db->MetaTables('TABLES');
1488 /// Set up the progress bar
1490 $usertables = array('user_admins', 'user_coursecreators', 'user_teachers', 'user_students');
1492 $totalcount = $progresscount = 0;
1493 foreach ($usertables as $usertable) {
1494 if (in_array($CFG->prefix.$usertable, $dbtables)) {
1495 $totalcount += count_records($usertable);
1499 print_progress(0, $totalcount, 5, 1, 'Processing role assignments');
1501 /// Upgrade the admins.
1502 /// Sort using id ASC, first one is primary admin.
1504 if (in_array($CFG->prefix.'user_admins', $dbtables)) {
1505 if ($rs = get_recordset_sql('SELECT * from '.$CFG->prefix.'user_admins ORDER BY ID ASC')) {
1506 while ($admin = rs_fetch_next_record($rs)) {
1507 role_assign($adminrole, $admin->userid, 0, $systemcontext->id);
1508 $progresscount++;
1509 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1511 rs_close($rs);
1513 } else {
1514 // This is a fresh install.
1518 /// Upgrade course creators.
1519 if (in_array($CFG->prefix.'user_coursecreators', $dbtables)) {
1520 if ($rs = get_recordset('user_coursecreators')) {
1521 while ($coursecreator = rs_fetch_next_record($rs)) {
1522 role_assign($coursecreatorrole, $coursecreator->userid, 0, $systemcontext->id);
1523 $progresscount++;
1524 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1526 rs_close($rs);
1531 /// Upgrade editting teachers and non-editting teachers.
1532 if (in_array($CFG->prefix.'user_teachers', $dbtables)) {
1533 if ($rs = get_recordset('user_teachers')) {
1534 while ($teacher = rs_fetch_next_record($rs)) {
1536 // removed code here to ignore site level assignments
1537 // since the contexts are separated now
1539 // populate the user_lastaccess table
1540 $access = new object();
1541 $access->timeaccess = $teacher->timeaccess;
1542 $access->userid = $teacher->userid;
1543 $access->courseid = $teacher->course;
1544 insert_record('user_lastaccess', $access);
1546 // assign the default student role
1547 $coursecontext = get_context_instance(CONTEXT_COURSE, $teacher->course); // needs cache
1548 // hidden teacher
1549 if ($teacher->authority == 0) {
1550 $hiddenteacher = 1;
1551 } else {
1552 $hiddenteacher = 0;
1555 if ($teacher->editall) { // editting teacher
1556 role_assign($editteacherrole, $teacher->userid, 0, $coursecontext->id, 0, 0, $hiddenteacher);
1557 } else {
1558 role_assign($noneditteacherrole, $teacher->userid, 0, $coursecontext->id, 0, 0, $hiddenteacher);
1560 $progresscount++;
1561 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1563 rs_close($rs);
1568 /// Upgrade students.
1569 if (in_array($CFG->prefix.'user_students', $dbtables)) {
1570 if ($rs = get_recordset('user_students')) {
1571 while ($student = rs_fetch_next_record($rs)) {
1573 // populate the user_lastaccess table
1574 $access = new object;
1575 $access->timeaccess = $student->timeaccess;
1576 $access->userid = $student->userid;
1577 $access->courseid = $student->course;
1578 insert_record('user_lastaccess', $access);
1580 // assign the default student role
1581 $coursecontext = get_context_instance(CONTEXT_COURSE, $student->course);
1582 role_assign($studentrole, $student->userid, 0, $coursecontext->id);
1583 $progresscount++;
1584 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1586 rs_close($rs);
1591 /// Upgrade guest (only 1 entry).
1592 if ($guestuser = get_record('user', 'username', 'guest')) {
1593 role_assign($guestrole, $guestuser->id, 0, $systemcontext->id);
1595 print_progress($totalcount, $totalcount, 5, 1, 'Processing role assignments');
1598 /// Insert the correct records for legacy roles
1599 allow_assign($adminrole, $adminrole);
1600 allow_assign($adminrole, $coursecreatorrole);
1601 allow_assign($adminrole, $noneditteacherrole);
1602 allow_assign($adminrole, $editteacherrole);
1603 allow_assign($adminrole, $studentrole);
1604 allow_assign($adminrole, $guestrole);
1606 allow_assign($coursecreatorrole, $noneditteacherrole);
1607 allow_assign($coursecreatorrole, $editteacherrole);
1608 allow_assign($coursecreatorrole, $studentrole);
1609 allow_assign($coursecreatorrole, $guestrole);
1611 allow_assign($editteacherrole, $noneditteacherrole);
1612 allow_assign($editteacherrole, $studentrole);
1613 allow_assign($editteacherrole, $guestrole);
1615 /// Set up default permissions for overrides
1616 allow_override($adminrole, $adminrole);
1617 allow_override($adminrole, $coursecreatorrole);
1618 allow_override($adminrole, $noneditteacherrole);
1619 allow_override($adminrole, $editteacherrole);
1620 allow_override($adminrole, $studentrole);
1621 allow_override($adminrole, $guestrole);
1622 allow_override($adminrole, $userrole);
1625 /// Delete the old user tables when we are done
1627 drop_table(new XMLDBTable('user_students'));
1628 drop_table(new XMLDBTable('user_teachers'));
1629 drop_table(new XMLDBTable('user_coursecreators'));
1630 drop_table(new XMLDBTable('user_admins'));
1635 * Returns array of all legacy roles.
1637 function get_legacy_roles() {
1638 return array(
1639 'admin' => 'moodle/legacy:admin',
1640 'coursecreator' => 'moodle/legacy:coursecreator',
1641 'editingteacher' => 'moodle/legacy:editingteacher',
1642 'teacher' => 'moodle/legacy:teacher',
1643 'student' => 'moodle/legacy:student',
1644 'guest' => 'moodle/legacy:guest',
1645 'user' => 'moodle/legacy:user'
1649 function get_legacy_type($roleid) {
1650 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
1651 $legacyroles = get_legacy_roles();
1653 $result = '';
1654 foreach($legacyroles as $ltype=>$lcap) {
1655 $localoverride = get_local_override($roleid, $sitecontext->id, $lcap);
1656 if (!empty($localoverride->permission) and $localoverride->permission == CAP_ALLOW) {
1657 //choose first selected legacy capability - reset the rest
1658 if (empty($result)) {
1659 $result = $ltype;
1660 } else {
1661 unassign_capability($lcap, $roleid);
1666 return $result;
1670 * Assign the defaults found in this capabality definition to roles that have
1671 * the corresponding legacy capabilities assigned to them.
1672 * @param $legacyperms - an array in the format (example):
1673 * 'guest' => CAP_PREVENT,
1674 * 'student' => CAP_ALLOW,
1675 * 'teacher' => CAP_ALLOW,
1676 * 'editingteacher' => CAP_ALLOW,
1677 * 'coursecreator' => CAP_ALLOW,
1678 * 'admin' => CAP_ALLOW
1679 * @return boolean - success or failure.
1681 function assign_legacy_capabilities($capability, $legacyperms) {
1683 $legacyroles = get_legacy_roles();
1685 foreach ($legacyperms as $type => $perm) {
1687 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
1689 if (!array_key_exists($type, $legacyroles)) {
1690 error('Incorrect legacy role definition for type: '.$type);
1693 if ($roles = get_roles_with_capability($legacyroles[$type], CAP_ALLOW)) {
1694 foreach ($roles as $role) {
1695 // Assign a site level capability.
1696 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1697 return false;
1702 return true;
1707 * Checks to see if a capability is a legacy capability.
1708 * @param $capabilityname
1709 * @return boolean
1711 function islegacy($capabilityname) {
1712 if (strpos($capabilityname, 'moodle/legacy') === 0) {
1713 return true;
1714 } else {
1715 return false;
1721 /**********************************
1722 * Context Manipulation functions *
1723 **********************************/
1726 * Create a new context record for use by all roles-related stuff
1727 * @param $level
1728 * @param $instanceid
1730 * @return object newly created context (or existing one with a debug warning)
1732 function create_context($contextlevel, $instanceid) {
1733 if (!$context = get_record('context','contextlevel',$contextlevel,'instanceid',$instanceid)) {
1734 if (!validate_context($contextlevel, $instanceid)) {
1735 debugging('Error: Invalid context creation request for level "'.s($contextlevel).'", instance "'.s($instanceid).'".');
1736 return NULL;
1738 if ($contextlevel == CONTEXT_SYSTEM) {
1739 return create_system_context();
1742 $context = new object();
1743 $context->contextlevel = $contextlevel;
1744 $context->instanceid = $instanceid;
1745 if ($id = insert_record('context',$context)) {
1746 $c = get_record('context','id',$id);
1747 return $c;
1748 } else {
1749 debugging('Error: could not insert new context level "'.s($contextlevel).'", instance "'.s($instanceid).'".');
1750 return NULL;
1752 } else {
1753 debugging('Warning: Context id "'.s($context->id).'" not created, because it already exists.');
1754 return $context;
1759 * This hacky function is needed because we can not change system context instanceid using normal upgrade routine.
1761 function create_system_context() {
1762 if ($context = get_record('context', 'contextlevel', CONTEXT_SYSTEM, 'instanceid', SITEID)) {
1763 // we are going to change instanceid of system context to 0 now
1764 $context->instanceid = 0;
1765 update_record('context', $context);
1766 //context rel not affected
1767 return $context;
1769 } else {
1770 $context = new object();
1771 $context->contextlevel = CONTEXT_SYSTEM;
1772 $context->instanceid = 0;
1773 if ($context->id = insert_record('context',$context)) {
1774 // we need not to populate context_rel for system context
1775 return $context;
1776 } else {
1777 debugging('Can not create system context');
1778 return NULL;
1783 * Create a new context record for use by all roles-related stuff
1784 * @param $level
1785 * @param $instanceid
1787 * @return true if properly deleted
1789 function delete_context($contextlevel, $instanceid) {
1790 if ($context = get_context_instance($contextlevel, $instanceid)) {
1791 delete_records('context_rel', 'c2', $context->id); // might not be a parent
1792 return delete_records('context', 'id', $context->id) &&
1793 delete_records('role_assignments', 'contextid', $context->id) &&
1794 delete_records('role_capabilities', 'contextid', $context->id) &&
1795 delete_records('context_rel', 'c1', $context->id);
1797 return true;
1801 * Validate that object with instanceid really exists in given context level.
1803 * return if instanceid object exists
1805 function validate_context($contextlevel, $instanceid) {
1806 switch ($contextlevel) {
1808 case CONTEXT_SYSTEM:
1809 return ($instanceid == 0);
1811 case CONTEXT_PERSONAL:
1812 return (boolean)count_records('user', 'id', $instanceid);
1814 case CONTEXT_USER:
1815 return (boolean)count_records('user', 'id', $instanceid);
1817 case CONTEXT_COURSECAT:
1818 if ($instanceid == 0) {
1819 return true; // site course category
1821 return (boolean)count_records('course_categories', 'id', $instanceid);
1823 case CONTEXT_COURSE:
1824 return (boolean)count_records('course', 'id', $instanceid);
1826 case CONTEXT_GROUP:
1827 return groups_group_exists($instanceid);
1829 case CONTEXT_MODULE:
1830 return (boolean)count_records('course_modules', 'id', $instanceid);
1832 case CONTEXT_BLOCK:
1833 return (boolean)count_records('block_instance', 'id', $instanceid);
1835 default:
1836 return false;
1841 * Get the context instance as an object. This function will create the
1842 * context instance if it does not exist yet.
1843 * @param integer $level The context level, for example CONTEXT_COURSE, or CONTEXT_MODULE.
1844 * @param integer $instance The instance id. For $level = CONTEXT_COURSE, this would be $course->id,
1845 * for $level = CONTEXT_MODULE, this would be $cm->id. And so on.
1846 * @return object The context object.
1848 function get_context_instance($contextlevel=NULL, $instance=0) {
1850 global $context_cache, $context_cache_id, $CONTEXT;
1851 static $allowed_contexts = array(CONTEXT_SYSTEM, CONTEXT_PERSONAL, CONTEXT_USER, CONTEXT_COURSECAT, CONTEXT_COURSE, CONTEXT_GROUP, CONTEXT_MODULE, CONTEXT_BLOCK);
1853 // Yu: Separating site and site course context - removed CONTEXT_COURSE override when SITEID
1855 // fix for MDL-9016
1856 if ($contextlevel == 'clearcache') {
1857 // Clear ALL cache
1858 $context_cache = array();
1859 $context_cache_id = array();
1860 $CONTEXT = '';
1861 return false;
1864 /// If no level is supplied then return the current global context if there is one
1865 if (empty($contextlevel)) {
1866 if (empty($CONTEXT)) {
1867 //fatal error, code must be fixed
1868 error("Error: get_context_instance() called without a context");
1869 } else {
1870 return $CONTEXT;
1874 /// Backwards compatibility with obsoleted (CONTEXT_SYSTEM, SITEID)
1875 if ($contextlevel == CONTEXT_SYSTEM) {
1876 $instance = 0;
1879 /// check allowed context levels
1880 if (!in_array($contextlevel, $allowed_contexts)) {
1881 // fatal error, code must be fixed - probably typo or switched parameters
1882 error('Error: get_context_instance() called with incorrect context level "'.s($contextlevel).'"');
1885 /// Check the cache
1886 if (isset($context_cache[$contextlevel][$instance])) { // Already cached
1887 return $context_cache[$contextlevel][$instance];
1890 /// Get it from the database, or create it
1891 if (!$context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance)) {
1892 create_context($contextlevel, $instance);
1893 $context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance);
1896 /// Only add to cache if context isn't empty.
1897 if (!empty($context)) {
1898 $context_cache[$contextlevel][$instance] = $context; // Cache it for later
1899 $context_cache_id[$context->id] = $context; // Cache it for later
1902 return $context;
1907 * Get a context instance as an object, from a given context id.
1908 * @param $id a context id.
1909 * @return object The context object.
1911 function get_context_instance_by_id($id) {
1913 global $context_cache, $context_cache_id;
1915 if (isset($context_cache_id[$id])) { // Already cached
1916 return $context_cache_id[$id];
1919 if ($context = get_record('context', 'id', $id)) { // Update the cache and return
1920 $context_cache[$context->contextlevel][$context->instanceid] = $context;
1921 $context_cache_id[$context->id] = $context;
1922 return $context;
1925 return false;
1930 * Get the local override (if any) for a given capability in a role in a context
1931 * @param $roleid
1932 * @param $contextid
1933 * @param $capability
1935 function get_local_override($roleid, $contextid, $capability) {
1936 return get_record('role_capabilities', 'roleid', $roleid, 'capability', $capability, 'contextid', $contextid);
1941 /************************************
1942 * DB TABLE RELATED FUNCTIONS *
1943 ************************************/
1946 * function that creates a role
1947 * @param name - role name
1948 * @param shortname - role short name
1949 * @param description - role description
1950 * @param legacy - optional legacy capability
1951 * @return id or false
1953 function create_role($name, $shortname, $description, $legacy='') {
1955 // check for duplicate role name
1957 if ($role = get_record('role','name', $name)) {
1958 error('there is already a role with this name!');
1961 if ($role = get_record('role','shortname', $shortname)) {
1962 error('there is already a role with this shortname!');
1965 $role = new object();
1966 $role->name = $name;
1967 $role->shortname = $shortname;
1968 $role->description = $description;
1970 //find free sortorder number
1971 $role->sortorder = count_records('role');
1972 while (get_record('role','sortorder', $role->sortorder)) {
1973 $role->sortorder += 1;
1976 if (!$context = get_context_instance(CONTEXT_SYSTEM)) {
1977 return false;
1980 if ($id = insert_record('role', $role)) {
1981 if ($legacy) {
1982 assign_capability($legacy, CAP_ALLOW, $id, $context->id);
1985 /// By default, users with role:manage at site level
1986 /// should be able to assign users to this new role, and override this new role's capabilities
1988 // find all admin roles
1989 if ($adminroles = get_roles_with_capability('moodle/role:manage', CAP_ALLOW, $context)) {
1990 // foreach admin role
1991 foreach ($adminroles as $arole) {
1992 // write allow_assign and allow_overrid
1993 allow_assign($arole->id, $id);
1994 allow_override($arole->id, $id);
1998 return $id;
1999 } else {
2000 return false;
2006 * function that deletes a role and cleanups up after it
2007 * @param roleid - id of role to delete
2008 * @return success
2010 function delete_role($roleid) {
2011 global $CFG;
2012 $success = true;
2014 // mdl 10149, check if this is the last active admin role
2015 // if we make the admin role not deletable then this part can go
2017 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
2019 if ($role = get_record('role', 'id', $roleid)) {
2020 if (record_exists('role_capabilities', 'contextid', $systemcontext->id, 'roleid', $roleid, 'capability', 'moodle/site:doanything')) {
2021 // deleting an admin role
2022 $status = false;
2023 if ($adminroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, $systemcontext)) {
2024 foreach ($adminroles as $adminrole) {
2025 if ($adminrole->id != $roleid) {
2026 // some other admin role
2027 if (record_exists('role_assignments', 'roleid', $adminrole->id, 'contextid', $systemcontext->id)) {
2028 // found another admin role with at least 1 user assigned
2029 $status = true;
2030 break;
2035 if ($status !== true) {
2036 error ('You can not delete this role because there is no other admin roles with users assigned');
2041 // first unssign all users
2042 if (!role_unassign($roleid)) {
2043 debugging("Error while unassigning all users from role with ID $roleid!");
2044 $success = false;
2047 // cleanup all references to this role, ignore errors
2048 if ($success) {
2050 // MDL-10679 find all contexts where this role has an override
2051 $contexts = get_records_sql("SELECT contextid, contextid
2052 FROM {$CFG->prefix}role_capabilities
2053 WHERE roleid = $roleid");
2055 delete_records('role_capabilities', 'roleid', $roleid);
2057 // MDL-10679, delete from context_rel if this role holds the last override in these contexts
2058 if ($contexts) {
2059 foreach ($contexts as $context) {
2060 if (!record_exists('role_capabilities', 'contextid', $context->contextid)) {
2061 delete_records('context_rel', 'c1', $context->contextid);
2066 delete_records('role_allow_assign', 'roleid', $roleid);
2067 delete_records('role_allow_assign', 'allowassign', $roleid);
2068 delete_records('role_allow_override', 'roleid', $roleid);
2069 delete_records('role_allow_override', 'allowoverride', $roleid);
2070 delete_records('role_names', 'roleid', $roleid);
2073 // finally delete the role itself
2074 if ($success and !delete_records('role', 'id', $roleid)) {
2075 debugging("Could not delete role record with ID $roleid!");
2076 $success = false;
2079 return $success;
2083 * Function to write context specific overrides, or default capabilities.
2084 * @param module - string name
2085 * @param capability - string name
2086 * @param contextid - context id
2087 * @param roleid - role id
2088 * @param permission - int 1,-1 or -1000
2089 * should not be writing if permission is 0
2091 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite=false) {
2093 global $USER;
2095 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
2096 unassign_capability($capability, $roleid, $contextid);
2097 return true;
2100 $existing = get_record('role_capabilities', 'contextid', $contextid, 'roleid', $roleid, 'capability', $capability);
2102 if ($existing and !$overwrite) { // We want to keep whatever is there already
2103 return true;
2106 $cap = new object;
2107 $cap->contextid = $contextid;
2108 $cap->roleid = $roleid;
2109 $cap->capability = $capability;
2110 $cap->permission = $permission;
2111 $cap->timemodified = time();
2112 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
2114 if ($existing) {
2115 $cap->id = $existing->id;
2116 return update_record('role_capabilities', $cap);
2117 } else {
2118 $c = get_record('context', 'id', $contextid);
2119 /// MDL-10679 insert context rel here
2120 insert_context_rel ($c);
2121 return insert_record('role_capabilities', $cap);
2127 * Unassign a capability from a role.
2128 * @param $roleid - the role id
2129 * @param $capability - the name of the capability
2130 * @return boolean - success or failure
2132 function unassign_capability($capability, $roleid, $contextid=NULL) {
2134 if (isset($contextid)) {
2135 // delete from context rel, if this is the last override in this context
2136 $status = delete_records('role_capabilities', 'capability', $capability,
2137 'roleid', $roleid, 'contextid', $contextid);
2139 // MDL-10679, if this is no more overrides for this context
2140 // delete entries from context where this context is a child
2141 if (!record_exists('role_capabilities', 'contextid', $contextid)) {
2142 delete_records('context_rel', 'c1', $contextid);
2145 } else {
2146 // There is no need to delete from context_rel here because
2147 // this is only used for legacy, for now
2148 $status = delete_records('role_capabilities', 'capability', $capability,
2149 'roleid', $roleid);
2151 return $status;
2156 * Get the roles that have a given capability assigned to it. This function
2157 * does not resolve the actual permission of the capability. It just checks
2158 * for assignment only.
2159 * @param $capability - capability name (string)
2160 * @param $permission - optional, the permission defined for this capability
2161 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT
2162 * @return array or role objects
2164 function get_roles_with_capability($capability, $permission=NULL, $context='') {
2166 global $CFG;
2168 if ($context) {
2169 if ($contexts = get_parent_contexts($context)) {
2170 $listofcontexts = '('.implode(',', $contexts).')';
2171 } else {
2172 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
2173 $listofcontexts = '('.$sitecontext->id.')'; // must be site
2175 $contextstr = "AND (rc.contextid = '$context->id' OR rc.contextid IN $listofcontexts)";
2176 } else {
2177 $contextstr = '';
2180 $selectroles = "SELECT r.*
2181 FROM {$CFG->prefix}role r,
2182 {$CFG->prefix}role_capabilities rc
2183 WHERE rc.capability = '$capability'
2184 AND rc.roleid = r.id $contextstr";
2186 if (isset($permission)) {
2187 $selectroles .= " AND rc.permission = '$permission'";
2189 return get_records_sql($selectroles);
2194 * This function makes a role-assignment (a role for a user or group in a particular context)
2195 * @param $roleid - the role of the id
2196 * @param $userid - userid
2197 * @param $groupid - group id
2198 * @param $contextid - id of the context
2199 * @param $timestart - time this assignment becomes effective
2200 * @param $timeend - time this assignemnt ceases to be effective
2201 * @uses $USER
2202 * @return id - new id of the assigment
2204 function role_assign($roleid, $userid, $groupid, $contextid, $timestart=0, $timeend=0, $hidden=0, $enrol='manual',$timemodified='') {
2205 global $USER, $CFG;
2207 debugging("Assign roleid $roleid userid $userid contextid $contextid", DEBUG_DEVELOPER);
2209 /// Do some data validation
2211 if (empty($roleid)) {
2212 debugging('Role ID not provided');
2213 return false;
2216 if (empty($userid) && empty($groupid)) {
2217 debugging('Either userid or groupid must be provided');
2218 return false;
2221 if ($userid && !record_exists('user', 'id', $userid)) {
2222 debugging('User ID '.intval($userid).' does not exist!');
2223 return false;
2226 if ($groupid && !groups_group_exists($groupid)) {
2227 debugging('Group ID '.intval($groupid).' does not exist!');
2228 return false;
2231 if (!$context = get_context_instance_by_id($contextid)) {
2232 debugging('Context ID '.intval($contextid).' does not exist!');
2233 return false;
2236 if (($timestart and $timeend) and ($timestart > $timeend)) {
2237 debugging('The end time can not be earlier than the start time');
2238 return false;
2241 if (!$timemodified) {
2242 $timemodified = time();
2245 /// Check for existing entry
2246 if ($userid) {
2247 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id, 'userid', $userid);
2248 } else {
2249 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id, 'groupid', $groupid);
2253 $newra = new object;
2255 if (empty($ra)) { // Create a new entry
2256 $newra->roleid = $roleid;
2257 $newra->contextid = $context->id;
2258 $newra->userid = $userid;
2259 $newra->hidden = $hidden;
2260 $newra->enrol = $enrol;
2261 /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
2262 /// by repeating queries with the same exact parameters in a 100 secs time window
2263 $newra->timestart = round($timestart, -2);
2264 $newra->timeend = $timeend;
2265 $newra->timemodified = $timemodified;
2266 $newra->modifierid = empty($USER->id) ? 0 : $USER->id;
2268 $success = insert_record('role_assignments', $newra);
2270 } else { // We already have one, just update it
2272 $newra->id = $ra->id;
2273 $newra->hidden = $hidden;
2274 $newra->enrol = $enrol;
2275 /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
2276 /// by repeating queries with the same exact parameters in a 100 secs time window
2277 $newra->timestart = round($timestart, -2);
2278 $newra->timeend = $timeend;
2279 $newra->timemodified = $timemodified;
2280 $newra->modifierid = empty($USER->id) ? 0 : $USER->id;
2282 $success = update_record('role_assignments', $newra);
2285 if ($success) { /// Role was assigned, so do some other things
2287 /// If the user is the current user, then reload the capabilities too.
2288 if (!empty($USER->id) && $USER->id == $userid) {
2289 load_all_capabilities();
2292 /// Ask all the modules if anything needs to be done for this user
2293 if ($mods = get_list_of_plugins('mod')) {
2294 foreach ($mods as $mod) {
2295 include_once($CFG->dirroot.'/mod/'.$mod.'/lib.php');
2296 $functionname = $mod.'_role_assign';
2297 if (function_exists($functionname)) {
2298 $functionname($userid, $context, $roleid);
2303 /// Make sure they have an entry in user_lastaccess for courses they can access
2304 // role_add_lastaccess_entries($userid, $context);
2307 /// now handle metacourse role assignments if in course context
2308 if ($success and $context->contextlevel == CONTEXT_COURSE) {
2309 if ($parents = get_records('course_meta', 'child_course', $context->instanceid)) {
2310 foreach ($parents as $parent) {
2311 sync_metacourse($parent->parent_course);
2316 return $success;
2321 * Deletes one or more role assignments. You must specify at least one parameter.
2322 * @param $roleid
2323 * @param $userid
2324 * @param $groupid
2325 * @param $contextid
2326 * @param $enrol unassign only if enrolment type matches, NULL means anything
2327 * @return boolean - success or failure
2329 function role_unassign($roleid=0, $userid=0, $groupid=0, $contextid=0, $enrol=NULL) {
2331 global $USER, $CFG;
2333 $success = true;
2335 $args = array('roleid', 'userid', 'groupid', 'contextid');
2336 $select = array();
2337 foreach ($args as $arg) {
2338 if ($$arg) {
2339 $select[] = $arg.' = '.$$arg;
2342 if (!empty($enrol)) {
2343 $select[] = "enrol='$enrol'";
2346 if ($select) {
2347 if ($ras = get_records_select('role_assignments', implode(' AND ', $select))) {
2348 $mods = get_list_of_plugins('mod');
2349 foreach($ras as $ra) {
2350 /// infinite loop protection when deleting recursively
2351 if (!$ra = get_record('role_assignments', 'id', $ra->id)) {
2352 continue;
2354 $success = delete_records('role_assignments', 'id', $ra->id) and $success;
2356 /// If the user is the current user, then reload the capabilities too.
2357 if (!empty($USER->id) && $USER->id == $ra->userid) {
2358 load_all_capabilities();
2360 $context = get_record('context', 'id', $ra->contextid);
2362 /// Ask all the modules if anything needs to be done for this user
2363 foreach ($mods as $mod) {
2364 include_once($CFG->dirroot.'/mod/'.$mod.'/lib.php');
2365 $functionname = $mod.'_role_unassign';
2366 if (function_exists($functionname)) {
2367 $functionname($ra->userid, $context); // watch out, $context might be NULL if something goes wrong
2371 /// now handle metacourse role unassigment and removing from goups if in course context
2372 if (!empty($context) and $context->contextlevel == CONTEXT_COURSE) {
2374 // cleanup leftover course groups/subscriptions etc when user has
2375 // no capability to view course
2376 // this may be slow, but this is the proper way of doing it
2377 if (!has_capability('moodle/course:view', $context, $ra->userid)) {
2378 // remove from groups
2379 if ($groups = groups_get_all_groups($context->instanceid)) {
2380 foreach ($groups as $group) {
2381 delete_records('groups_members', 'groupid', $group->id, 'userid', $ra->userid);
2385 // delete lastaccess records
2386 delete_records('user_lastaccess', 'userid', $ra->userid, 'courseid', $context->instanceid);
2389 //unassign roles in metacourses if needed
2390 if ($parents = get_records('course_meta', 'child_course', $context->instanceid)) {
2391 foreach ($parents as $parent) {
2392 sync_metacourse($parent->parent_course);
2400 return $success;
2404 * A convenience function to take care of the common case where you
2405 * just want to enrol someone using the default role into a course
2407 * @param object $course
2408 * @param object $user
2409 * @param string $enrol - the plugin used to do this enrolment
2411 function enrol_into_course($course, $user, $enrol) {
2413 $timestart = time();
2414 // remove time part from the timestamp and keep only the date part
2415 $timestart = make_timestamp(date('Y', $timestart), date('m', $timestart), date('d', $timestart), 0, 0, 0);
2416 if ($course->enrolperiod) {
2417 $timeend = $timestart + $course->enrolperiod;
2418 } else {
2419 $timeend = 0;
2422 if ($role = get_default_course_role($course)) {
2424 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2426 if (!role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, $enrol)) {
2427 return false;
2430 email_welcome_message_to_user($course, $user);
2432 add_to_log($course->id, 'course', 'enrol', 'view.php?id='.$course->id, $user->id);
2434 return true;
2437 return false;
2441 * Add last access times to user_lastaccess as required
2442 * @param $userid
2443 * @param $context
2444 * @return boolean - success or failure
2446 function role_add_lastaccess_entries($userid, $context) {
2448 global $USER, $CFG;
2450 if (empty($context->contextlevel)) {
2451 return false;
2454 $lastaccess = new object; // Reusable object below
2455 $lastaccess->userid = $userid;
2456 $lastaccess->timeaccess = 0;
2458 switch ($context->contextlevel) {
2460 case CONTEXT_SYSTEM: // For the whole site
2461 if ($courses = get_record('course')) {
2462 foreach ($courses as $course) {
2463 $lastaccess->courseid = $course->id;
2464 role_set_lastaccess($lastaccess);
2467 break;
2469 case CONTEXT_CATEGORY: // For a whole category
2470 if ($courses = get_record('course', 'category', $context->instanceid)) {
2471 foreach ($courses as $course) {
2472 $lastaccess->courseid = $course->id;
2473 role_set_lastaccess($lastaccess);
2476 if ($categories = get_record('course_categories', 'parent', $context->instanceid)) {
2477 foreach ($categories as $category) {
2478 $subcontext = get_context_instance(CONTEXT_CATEGORY, $category->id);
2479 role_add_lastaccess_entries($userid, $subcontext);
2482 break;
2485 case CONTEXT_COURSE: // For a whole course
2486 if ($course = get_record('course', 'id', $context->instanceid)) {
2487 $lastaccess->courseid = $course->id;
2488 role_set_lastaccess($lastaccess);
2490 break;
2495 * Delete last access times from user_lastaccess as required
2496 * @param $userid
2497 * @param $context
2498 * @return boolean - success or failure
2500 function role_remove_lastaccess_entries($userid, $context) {
2502 global $USER, $CFG;
2508 * Loads the capability definitions for the component (from file). If no
2509 * capabilities are defined for the component, we simply return an empty array.
2510 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2511 * @return array of capabilities
2513 function load_capability_def($component) {
2514 global $CFG;
2516 if ($component == 'moodle') {
2517 $defpath = $CFG->libdir.'/db/access.php';
2518 $varprefix = 'moodle';
2519 } else {
2520 $compparts = explode('/', $component);
2522 if ($compparts[0] == 'block') {
2523 // Blocks are an exception. Blocks directory is 'blocks', and not
2524 // 'block'. So we need to jump through hoops.
2525 $defpath = $CFG->dirroot.'/'.$compparts[0].
2526 's/'.$compparts[1].'/db/access.php';
2527 $varprefix = $compparts[0].'_'.$compparts[1];
2529 } else if ($compparts[0] == 'format') {
2530 // Similar to the above, course formats are 'format' while they
2531 // are stored in 'course/format'.
2532 $defpath = $CFG->dirroot.'/course/'.$component.'/db/access.php';
2533 $varprefix = $compparts[0].'_'.$compparts[1];
2535 } else if ($compparts[0] == 'gradeimport') {
2536 $defpath = $CFG->dirroot.'/grade/import/'.$compparts[1].'/db/access.php';
2537 $varprefix = $compparts[0].'_'.$compparts[1];
2539 } else if ($compparts[0] == 'gradeexport') {
2540 $defpath = $CFG->dirroot.'/grade/export/'.$compparts[1].'/db/access.php';
2541 $varprefix = $compparts[0].'_'.$compparts[1];
2543 } else if ($compparts[0] == 'gradereport') {
2544 $defpath = $CFG->dirroot.'/grade/report/'.$compparts[1].'/db/access.php';
2545 $varprefix = $compparts[0].'_'.$compparts[1];
2547 } else {
2548 $defpath = $CFG->dirroot.'/'.$component.'/db/access.php';
2549 $varprefix = str_replace('/', '_', $component);
2552 $capabilities = array();
2554 if (file_exists($defpath)) {
2555 require($defpath);
2556 $capabilities = ${$varprefix.'_capabilities'};
2558 return $capabilities;
2563 * Gets the capabilities that have been cached in the database for this
2564 * component.
2565 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2566 * @return array of capabilities
2568 function get_cached_capabilities($component='moodle') {
2569 if ($component == 'moodle') {
2570 $storedcaps = get_records_select('capabilities',
2571 "name LIKE 'moodle/%:%'");
2572 } else {
2573 $storedcaps = get_records_select('capabilities',
2574 "name LIKE '$component:%'");
2576 return $storedcaps;
2580 * Returns default capabilities for given legacy role type.
2582 * @param string legacy role name
2583 * @return array
2585 function get_default_capabilities($legacyrole) {
2586 if (!$allcaps = get_records('capabilities')) {
2587 error('Error: no capabilitites defined!');
2589 $alldefs = array();
2590 $defaults = array();
2591 $components = array();
2592 foreach ($allcaps as $cap) {
2593 if (!in_array($cap->component, $components)) {
2594 $components[] = $cap->component;
2595 $alldefs = array_merge($alldefs, load_capability_def($cap->component));
2598 foreach($alldefs as $name=>$def) {
2599 if (isset($def['legacy'][$legacyrole])) {
2600 $defaults[$name] = $def['legacy'][$legacyrole];
2604 //some exceptions
2605 $defaults['moodle/legacy:'.$legacyrole] = CAP_ALLOW;
2606 if ($legacyrole == 'admin') {
2607 $defaults['moodle/site:doanything'] = CAP_ALLOW;
2609 return $defaults;
2613 * Reset role capabilitites to default according to selected legacy capability.
2614 * If several legacy caps selected, use the first from get_default_capabilities.
2615 * If no legacy selected, removes all capabilities.
2617 * @param int @roleid
2619 function reset_role_capabilities($roleid) {
2620 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
2621 $legacyroles = get_legacy_roles();
2623 $defaultcaps = array();
2624 foreach($legacyroles as $ltype=>$lcap) {
2625 $localoverride = get_local_override($roleid, $sitecontext->id, $lcap);
2626 if (!empty($localoverride->permission) and $localoverride->permission == CAP_ALLOW) {
2627 //choose first selected legacy capability
2628 $defaultcaps = get_default_capabilities($ltype);
2629 break;
2633 delete_records('role_capabilities', 'roleid', $roleid);
2634 if (!empty($defaultcaps)) {
2635 foreach($defaultcaps as $cap=>$permission) {
2636 assign_capability($cap, $permission, $roleid, $sitecontext->id);
2642 * Updates the capabilities table with the component capability definitions.
2643 * If no parameters are given, the function updates the core moodle
2644 * capabilities.
2646 * Note that the absence of the db/access.php capabilities definition file
2647 * will cause any stored capabilities for the component to be removed from
2648 * the database.
2650 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2651 * @return boolean
2653 function update_capabilities($component='moodle') {
2655 $storedcaps = array();
2657 $filecaps = load_capability_def($component);
2658 $cachedcaps = get_cached_capabilities($component);
2659 if ($cachedcaps) {
2660 foreach ($cachedcaps as $cachedcap) {
2661 array_push($storedcaps, $cachedcap->name);
2662 // update risk bitmasks and context levels in existing capabilities if needed
2663 if (array_key_exists($cachedcap->name, $filecaps)) {
2664 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2665 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
2667 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
2668 $updatecap = new object();
2669 $updatecap->id = $cachedcap->id;
2670 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2671 if (!update_record('capabilities', $updatecap)) {
2672 return false;
2676 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2677 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2679 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2680 $updatecap = new object();
2681 $updatecap->id = $cachedcap->id;
2682 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2683 if (!update_record('capabilities', $updatecap)) {
2684 return false;
2691 // Are there new capabilities in the file definition?
2692 $newcaps = array();
2694 foreach ($filecaps as $filecap => $def) {
2695 if (!$storedcaps ||
2696 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2697 if (!array_key_exists('riskbitmask', $def)) {
2698 $def['riskbitmask'] = 0; // no risk if not specified
2700 $newcaps[$filecap] = $def;
2703 // Add new capabilities to the stored definition.
2704 foreach ($newcaps as $capname => $capdef) {
2705 $capability = new object;
2706 $capability->name = $capname;
2707 $capability->captype = $capdef['captype'];
2708 $capability->contextlevel = $capdef['contextlevel'];
2709 $capability->component = $component;
2710 $capability->riskbitmask = $capdef['riskbitmask'];
2712 if (!insert_record('capabilities', $capability, false, 'id')) {
2713 return false;
2717 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $storedcaps)){
2718 if ($rolecapabilities = get_records('role_capabilities', 'capability', $capdef['clonepermissionsfrom'])){
2719 foreach ($rolecapabilities as $rolecapability){
2720 //assign_capability will update rather than insert if capability exists
2721 if (!assign_capability($capname, $rolecapability->permission,
2722 $rolecapability->roleid, $rolecapability->contextid, true)){
2723 notify('Could not clone capabilities for '.$capname);
2727 // Do we need to assign the new capabilities to roles that have the
2728 // legacy capabilities moodle/legacy:* as well?
2729 // we ignore legacy key if we have cloned permissions
2730 } else if (isset($capdef['legacy']) && is_array($capdef['legacy']) &&
2731 !assign_legacy_capabilities($capname, $capdef['legacy'])) {
2732 notify('Could not assign legacy capabilities for '.$capname);
2735 // Are there any capabilities that have been removed from the file
2736 // definition that we need to delete from the stored capabilities and
2737 // role assignments?
2738 capabilities_cleanup($component, $filecaps);
2740 return true;
2745 * Deletes cached capabilities that are no longer needed by the component.
2746 * Also unassigns these capabilities from any roles that have them.
2747 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2748 * @param $newcapdef - array of the new capability definitions that will be
2749 * compared with the cached capabilities
2750 * @return int - number of deprecated capabilities that have been removed
2752 function capabilities_cleanup($component, $newcapdef=NULL) {
2754 $removedcount = 0;
2756 if ($cachedcaps = get_cached_capabilities($component)) {
2757 foreach ($cachedcaps as $cachedcap) {
2758 if (empty($newcapdef) ||
2759 array_key_exists($cachedcap->name, $newcapdef) === false) {
2761 // Remove from capabilities cache.
2762 if (!delete_records('capabilities', 'name', $cachedcap->name)) {
2763 error('Could not delete deprecated capability '.$cachedcap->name);
2764 } else {
2765 $removedcount++;
2767 // Delete from roles.
2768 if($roles = get_roles_with_capability($cachedcap->name)) {
2769 foreach($roles as $role) {
2770 if (!unassign_capability($cachedcap->name, $role->id)) {
2771 error('Could not unassign deprecated capability '.
2772 $cachedcap->name.' from role '.$role->name);
2776 } // End if.
2779 return $removedcount;
2784 /****************
2785 * UI FUNCTIONS *
2786 ****************/
2790 * prints human readable context identifier.
2792 function print_context_name($context, $withprefix = true, $short = false) {
2794 $name = '';
2795 switch ($context->contextlevel) {
2797 case CONTEXT_SYSTEM: // by now it's a definite an inherit
2798 $name = get_string('coresystem');
2799 break;
2801 case CONTEXT_PERSONAL:
2802 $name = get_string('personal');
2803 break;
2805 case CONTEXT_USER:
2806 if ($user = get_record('user', 'id', $context->instanceid)) {
2807 if ($withprefix){
2808 $name = get_string('user').': ';
2810 $name .= fullname($user);
2812 break;
2814 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
2815 if ($category = get_record('course_categories', 'id', $context->instanceid)) {
2816 if ($withprefix){
2817 $name = get_string('category').': ';
2819 $name .=format_string($category->name);
2821 break;
2823 case CONTEXT_COURSE: // 1 to 1 to course cat
2824 if ($course = get_record('course', 'id', $context->instanceid)) {
2825 if ($withprefix){
2826 if ($context->instanceid == SITEID) {
2827 $name = get_string('site').': ';
2828 } else {
2829 $name = get_string('course').': ';
2832 if ($short){
2833 $name .=format_string($course->shortname);
2834 } else {
2835 $name .=format_string($course->fullname);
2839 break;
2841 case CONTEXT_GROUP: // 1 to 1 to course
2842 if ($name = groups_get_group_name($context->instanceid)) {
2843 if ($withprefix){
2844 $name = get_string('group').': '. $name;
2847 break;
2849 case CONTEXT_MODULE: // 1 to 1 to course
2850 if ($cm = get_record('course_modules','id',$context->instanceid)) {
2851 if ($module = get_record('modules','id',$cm->module)) {
2852 if ($mod = get_record($module->name, 'id', $cm->instance)) {
2853 if ($withprefix){
2854 $name = get_string('activitymodule').': ';
2856 $name .= $mod->name;
2860 break;
2862 case CONTEXT_BLOCK: // not necessarily 1 to 1 to course
2863 if ($blockinstance = get_record('block_instance','id',$context->instanceid)) {
2864 if ($block = get_record('block','id',$blockinstance->blockid)) {
2865 global $CFG;
2866 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
2867 require_once("$CFG->dirroot/blocks/$block->name/block_$block->name.php");
2868 $blockname = "block_$block->name";
2869 if ($blockobject = new $blockname()) {
2870 if ($withprefix){
2871 $name = get_string('block').': ';
2873 $name .= $blockobject->title;
2877 break;
2879 default:
2880 error ('This is an unknown context (' . $context->contextlevel . ') in print_context_name!');
2881 return false;
2884 return $name;
2889 * Extracts the relevant capabilities given a contextid.
2890 * All case based, example an instance of forum context.
2891 * Will fetch all forum related capabilities, while course contexts
2892 * Will fetch all capabilities
2893 * @param object context
2894 * @return array();
2896 * capabilities
2897 * `name` varchar(150) NOT NULL,
2898 * `captype` varchar(50) NOT NULL,
2899 * `contextlevel` int(10) NOT NULL,
2900 * `component` varchar(100) NOT NULL,
2902 function fetch_context_capabilities($context) {
2904 global $CFG;
2906 $sort = 'ORDER BY contextlevel,component,id'; // To group them sensibly for display
2908 switch ($context->contextlevel) {
2910 case CONTEXT_SYSTEM: // all
2911 $SQL = "select * from {$CFG->prefix}capabilities";
2912 break;
2914 case CONTEXT_PERSONAL:
2915 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_PERSONAL;
2916 break;
2918 case CONTEXT_USER:
2919 $SQL = "SELECT *
2920 FROM {$CFG->prefix}capabilities
2921 WHERE contextlevel = ".CONTEXT_USER;
2922 break;
2924 case CONTEXT_COURSECAT: // all
2925 $SQL = "select * from {$CFG->prefix}capabilities";
2926 break;
2928 case CONTEXT_COURSE: // all
2929 $SQL = "select * from {$CFG->prefix}capabilities";
2930 break;
2932 case CONTEXT_GROUP: // group caps
2933 break;
2935 case CONTEXT_MODULE: // mod caps
2936 $cm = get_record('course_modules', 'id', $context->instanceid);
2937 $module = get_record('modules', 'id', $cm->module);
2939 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_MODULE."
2940 and component = 'mod/$module->name'";
2941 break;
2943 case CONTEXT_BLOCK: // block caps
2944 $cb = get_record('block_instance', 'id', $context->instanceid);
2945 $block = get_record('block', 'id', $cb->blockid);
2947 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_BLOCK."
2948 and ( component = 'block/$block->name' or component = 'moodle')";
2949 break;
2951 default:
2952 return false;
2955 if (!$records = get_records_sql($SQL.' '.$sort)) {
2956 $records = array();
2959 /// the rest of code is a bit hacky, think twice before modifying it :-(
2961 // special sorting of core system capabiltites and enrollments
2962 if (in_array($context->contextlevel, array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE))) {
2963 $first = array();
2964 foreach ($records as $key=>$record) {
2965 if (preg_match('|^moodle/|', $record->name) and $record->contextlevel == CONTEXT_SYSTEM) {
2966 $first[$key] = $record;
2967 unset($records[$key]);
2968 } else if (count($first)){
2969 break;
2972 if (count($first)) {
2973 $records = $first + $records; // merge the two arrays keeping the keys
2975 } else {
2976 $contextindependentcaps = fetch_context_independent_capabilities();
2977 $records = array_merge($contextindependentcaps, $records);
2980 return $records;
2986 * Gets the context-independent capabilities that should be overrridable in
2987 * any context.
2988 * @return array of capability records from the capabilities table.
2990 function fetch_context_independent_capabilities() {
2992 //only CONTEXT_SYSTEM capabilities here or it will break the hack in fetch_context_capabilities()
2993 $contextindependentcaps = array(
2994 'moodle/site:accessallgroups'
2997 $records = array();
2999 foreach ($contextindependentcaps as $capname) {
3000 $record = get_record('capabilities', 'name', $capname);
3001 array_push($records, $record);
3003 return $records;
3008 * This function pulls out all the resolved capabilities (overrides and
3009 * defaults) of a role used in capability overrides in contexts at a given
3010 * context.
3011 * @param obj $context
3012 * @param int $roleid
3013 * @param bool self - if set to true, resolve till this level, else stop at immediate parent level
3014 * @return array
3016 function role_context_capabilities($roleid, $context, $cap='') {
3017 global $CFG;
3019 $contexts = get_parent_contexts($context);
3020 $contexts[] = $context->id;
3021 $contexts = '('.implode(',', $contexts).')';
3023 if ($cap) {
3024 $search = " AND rc.capability = '$cap' ";
3025 } else {
3026 $search = '';
3029 $SQL = "SELECT rc.*
3030 FROM {$CFG->prefix}role_capabilities rc,
3031 {$CFG->prefix}context c
3032 WHERE rc.contextid in $contexts
3033 AND rc.roleid = $roleid
3034 AND rc.contextid = c.id $search
3035 ORDER BY c.contextlevel DESC,
3036 rc.capability DESC";
3038 $capabilities = array();
3040 if ($records = get_records_sql($SQL)) {
3041 // We are traversing via reverse order.
3042 foreach ($records as $record) {
3043 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
3044 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
3045 $capabilities[$record->capability] = $record->permission;
3049 return $capabilities;
3053 * Recursive function which, given a context, find all parent context ids,
3054 * and return the array in reverse order, i.e. parent first, then grand
3055 * parent, etc.
3056 * @param object $context
3057 * @return array()
3059 function get_parent_contexts($context) {
3061 static $pcontexts; // cache
3062 if (isset($pcontexts[$context->id])) {
3063 return ($pcontexts[$context->id]);
3066 switch ($context->contextlevel) {
3068 case CONTEXT_SYSTEM: // no parent
3069 return array();
3070 break;
3072 case CONTEXT_PERSONAL:
3073 if (!$parent = get_context_instance(CONTEXT_SYSTEM)) {
3074 return array();
3075 } else {
3076 $res = array($parent->id);
3077 $pcontexts[$context->id] = $res;
3078 return $res;
3080 break;
3082 case CONTEXT_USER:
3083 if (!$parent = get_context_instance(CONTEXT_SYSTEM)) {
3084 return array();
3085 } else {
3086 $res = array($parent->id);
3087 $pcontexts[$context->id] = $res;
3088 return $res;
3090 break;
3092 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
3093 case CONTEXT_COURSE: // 1 to 1 to course cat
3094 $parents = get_parent_cats($context);
3095 $parents = array_reverse($parents);
3096 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
3097 return $pcontexts[$context->id] = array_merge($parents, array($systemcontext->id));
3098 break;
3100 case CONTEXT_GROUP: // 1 to 1 to course
3101 if (! $group = groups_get_group($context->instanceid)) {
3102 return array();
3104 if ($parent = get_context_instance(CONTEXT_COURSE, $group->courseid)) {
3105 $res = array_merge(array($parent->id), get_parent_contexts($parent));
3106 $pcontexts[$context->id] = $res;
3107 return $res;
3108 } else {
3109 return array();
3111 break;
3113 case CONTEXT_MODULE: // 1 to 1 to course
3114 if (!$cm = get_record('course_modules','id',$context->instanceid)) {
3115 return array();
3117 if ($parent = get_context_instance(CONTEXT_COURSE, $cm->course)) {
3118 $res = array_merge(array($parent->id), get_parent_contexts($parent));
3119 $pcontexts[$context->id] = $res;
3120 return $res;
3121 } else {
3122 return array();
3124 break;
3126 case CONTEXT_BLOCK: // not necessarily 1 to 1 to course
3127 if (!$block = get_record('block_instance','id',$context->instanceid)) {
3128 return array();
3130 // fix for MDL-9656, block parents are not necessarily courses
3131 if ($block->pagetype == 'course-view') {
3132 $parent = get_context_instance(CONTEXT_COURSE, $block->pageid);
3133 } else {
3134 $parent = get_context_instance(CONTEXT_SYSTEM);
3137 if ($parent) {
3138 $res = array_merge(array($parent->id), get_parent_contexts($parent));
3139 $pcontexts[$context->id] = $res;
3140 return $res;
3141 } else {
3142 return array();
3144 break;
3146 default:
3147 error('This is an unknown context (' . $context->contextlevel . ') in get_parent_contexts!');
3148 return false;
3154 * Recursive function which, given a context, find all its children context ids.
3155 * @param object $context.
3156 * @return array of children context ids.
3158 function get_child_contexts($context) {
3160 global $CFG;
3161 $children = array();
3163 switch ($context->contextlevel) {
3165 case CONTEXT_BLOCK:
3166 // No children.
3167 return array();
3168 break;
3170 case CONTEXT_MODULE:
3171 // No children.
3172 return array();
3173 break;
3175 case CONTEXT_GROUP:
3176 // No children.
3177 return array();
3178 break;
3180 case CONTEXT_COURSE:
3181 // Find all block instances for the course.
3182 $page = new page_course;
3183 $page->id = $context->instanceid;
3184 $page->type = 'course-view';
3185 if ($blocks = blocks_get_by_page_pinned($page)) {
3186 foreach ($blocks['l'] as $leftblock) {
3187 if ($child = get_context_instance(CONTEXT_BLOCK, $leftblock->id)) {
3188 array_push($children, $child->id);
3191 foreach ($blocks['r'] as $rightblock) {
3192 if ($child = get_context_instance(CONTEXT_BLOCK, $rightblock->id)) {
3193 array_push($children, $child->id);
3197 // Find all module instances for the course.
3198 if ($modules = get_records('course_modules', 'course', $context->instanceid, '', 'id')) {
3199 foreach ($modules as $module) {
3200 if ($child = get_context_instance(CONTEXT_MODULE, $module->id)) {
3201 array_push($children, $child->id);
3205 // Find all group instances for the course.
3206 if ($groups = get_records('groups', 'courseid', $context->instanceid, '', 'id')) {
3207 foreach ($groups as $group) {
3208 if ($child = get_context_instance(CONTEXT_GROUP, $group->id)) {
3209 array_push($children, $child->id);
3213 return $children;
3214 break;
3216 case CONTEXT_COURSECAT:
3217 // We need to get the contexts for:
3218 // 1) The subcategories of the given category
3219 // 2) The courses in the given category and all its subcategories
3220 // 3) All the child contexts for these courses
3222 $categories = get_all_subcategories($context->instanceid);
3224 // Add the contexts for all the subcategories.
3225 foreach ($categories as $catid) {
3226 if ($catci = get_context_instance(CONTEXT_COURSECAT, $catid)) {
3227 array_push($children, $catci->id);
3231 // Add the parent category as well so we can find the contexts
3232 // for its courses.
3233 array_unshift($categories, $context->instanceid);
3235 foreach ($categories as $catid) {
3236 // Find all courses for the category.
3237 if ($courses = get_records('course', 'category', $catid, '', 'id')) {
3238 foreach ($courses as $course) {
3239 if ($courseci = get_context_instance(CONTEXT_COURSE, $course->id)) {
3240 array_push($children, $courseci->id);
3241 $children = array_merge($children, get_child_contexts($courseci));
3246 return $children;
3247 break;
3249 case CONTEXT_USER:
3250 // No children.
3251 return array();
3252 break;
3254 case CONTEXT_PERSONAL:
3255 // No children.
3256 return array();
3257 break;
3259 case CONTEXT_SYSTEM:
3260 // Just get all the contexts except for CONTEXT_SYSTEM level.
3261 $sql = 'SELECT c.id '.
3262 'FROM '.$CFG->prefix.'context AS c '.
3263 'WHERE contextlevel != '.CONTEXT_SYSTEM;
3265 $contexts = get_records_sql($sql);
3266 foreach ($contexts as $cid) {
3267 array_push($children, $cid->id);
3269 return $children;
3270 break;
3272 default:
3273 error('This is an unknown context (' . $context->contextlevel . ') in get_child_contexts!');
3274 return false;
3280 * Gets a string for sql calls, searching for stuff in this context or above
3281 * @param object $context
3282 * @return string
3284 function get_related_contexts_string($context) {
3285 if ($parents = get_parent_contexts($context)) {
3286 return (' IN ('.$context->id.','.implode(',', $parents).')');
3287 } else {
3288 return (' ='.$context->id);
3294 * This function gets the capability of a role in a given context.
3295 * It is needed when printing override forms.
3296 * @param int $contextid
3297 * @param string $capability
3298 * @param array $capabilities - array loaded using role_context_capabilities
3299 * @return int (allow, prevent, prohibit, inherit)
3301 function get_role_context_capability($contextid, $capability, $capabilities) {
3302 if (isset($capabilities[$contextid][$capability])) {
3303 return $capabilities[$contextid][$capability];
3305 else {
3306 return false;
3312 * Returns the human-readable, translated version of the capability.
3313 * Basically a big switch statement.
3314 * @param $capabilityname - e.g. mod/choice:readresponses
3316 function get_capability_string($capabilityname) {
3318 // Typical capabilityname is mod/choice:readresponses
3320 $names = split('/', $capabilityname);
3321 $stringname = $names[1]; // choice:readresponses
3322 $components = split(':', $stringname);
3323 $componentname = $components[0]; // choice
3325 switch ($names[0]) {
3326 case 'mod':
3327 $string = get_string($stringname, $componentname);
3328 break;
3330 case 'block':
3331 $string = get_string($stringname, 'block_'.$componentname);
3332 break;
3334 case 'moodle':
3335 $string = get_string($stringname, 'role');
3336 break;
3338 case 'enrol':
3339 $string = get_string($stringname, 'enrol_'.$componentname);
3340 break;
3342 case 'format':
3343 $string = get_string($stringname, 'format_'.$componentname);
3344 break;
3346 case 'gradeexport':
3347 $string = get_string($stringname, 'gradeexport_'.$componentname);
3348 break;
3350 case 'gradeimport':
3351 $string = get_string($stringname, 'gradeimport_'.$componentname);
3352 break;
3354 case 'gradereport':
3355 $string = get_string($stringname, 'gradereport_'.$componentname);
3356 break;
3358 default:
3359 $string = get_string($stringname);
3360 break;
3363 return $string;
3368 * This gets the mod/block/course/core etc strings.
3369 * @param $component
3370 * @param $contextlevel
3372 function get_component_string($component, $contextlevel) {
3374 switch ($contextlevel) {
3376 case CONTEXT_SYSTEM:
3377 if (preg_match('|^enrol/|', $component)) {
3378 $langname = str_replace('/', '_', $component);
3379 $string = get_string('enrolname', $langname);
3380 } else if (preg_match('|^block/|', $component)) {
3381 $langname = str_replace('/', '_', $component);
3382 $string = get_string('blockname', $langname);
3383 } else {
3384 $string = get_string('coresystem');
3386 break;
3388 case CONTEXT_PERSONAL:
3389 $string = get_string('personal');
3390 break;
3392 case CONTEXT_USER:
3393 $string = get_string('users');
3394 break;
3396 case CONTEXT_COURSECAT:
3397 $string = get_string('categories');
3398 break;
3400 case CONTEXT_COURSE:
3401 if (preg_match('|^gradeimport/|', $component)
3402 || preg_match('|^gradeexport/|', $component)
3403 || preg_match('|^gradereport/|', $component)) {
3404 $string = get_string('gradebook', 'admin');
3405 } else {
3406 $string = get_string('course');
3408 break;
3410 case CONTEXT_GROUP:
3411 $string = get_string('group');
3412 break;
3414 case CONTEXT_MODULE:
3415 $string = get_string('modulename', basename($component));
3416 break;
3418 case CONTEXT_BLOCK:
3419 if( $component == 'moodle' ){
3420 $string = get_string('block');
3421 }else{
3422 $string = get_string('blockname', 'block_'.basename($component));
3424 break;
3426 default:
3427 error ('This is an unknown context $contextlevel (' . $contextlevel . ') in get_component_string!');
3428 return false;
3431 return $string;
3435 * Gets the list of roles assigned to this context and up (parents)
3436 * @param object $context
3437 * @param view - set to true when roles are pulled for display only
3438 * this is so that we can filter roles with no visible
3439 * assignment, for example, you might want to "hide" all
3440 * course creators when browsing the course participants
3441 * list.
3442 * @return array
3444 function get_roles_used_in_context($context, $view = false) {
3446 global $CFG;
3448 // filter for roles with all hidden assignments
3449 // no need to return when only pulling roles for reviewing
3450 // e.g. participants page.
3451 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))? ' AND ra.hidden = 0 ':'';
3452 $contextlist = get_related_contexts_string($context);
3454 $sql = "SELECT DISTINCT r.id,
3455 r.name,
3456 r.shortname,
3457 r.sortorder
3458 FROM {$CFG->prefix}role_assignments ra,
3459 {$CFG->prefix}role r
3460 WHERE r.id = ra.roleid
3461 AND ra.contextid $contextlist
3462 $hiddensql
3463 ORDER BY r.sortorder ASC";
3465 return get_records_sql($sql);
3468 /** this function is used to print roles column in user profile page.
3469 * @param int userid
3470 * @param int contextid
3471 * @return string
3473 function get_user_roles_in_context($userid, $contextid){
3474 global $CFG;
3476 $rolestring = '';
3477 $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';
3478 if ($roles = get_records_sql($SQL)) {
3479 foreach ($roles as $userrole) {
3480 $rolestring .= '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$userrole->contextid.'&amp;roleid='.$userrole->roleid.'">'.$userrole->name.'</a>, ';
3484 return rtrim($rolestring, ', ');
3489 * Checks if a user can override capabilities of a particular role in this context
3490 * @param object $context
3491 * @param int targetroleid - the id of the role you want to override
3492 * @return boolean
3494 function user_can_override($context, $targetroleid) {
3495 // first check if user has override capability
3496 // if not return false;
3497 if (!has_capability('moodle/role:override', $context)) {
3498 return false;
3500 // pull out all active roles of this user from this context(or above)
3501 if ($userroles = get_user_roles($context)) {
3502 foreach ($userroles as $userrole) {
3503 // if any in the role_allow_override table, then it's ok
3504 if (get_record('role_allow_override', 'roleid', $userrole->roleid, 'allowoverride', $targetroleid)) {
3505 return true;
3510 return false;
3515 * Checks if a user can assign users to a particular role in this context
3516 * @param object $context
3517 * @param int targetroleid - the id of the role you want to assign users to
3518 * @return boolean
3520 function user_can_assign($context, $targetroleid) {
3522 // first check if user has override capability
3523 // if not return false;
3524 if (!has_capability('moodle/role:assign', $context)) {
3525 return false;
3527 // pull out all active roles of this user from this context(or above)
3528 if ($userroles = get_user_roles($context)) {
3529 foreach ($userroles as $userrole) {
3530 // if any in the role_allow_override table, then it's ok
3531 if (get_record('role_allow_assign', 'roleid', $userrole->roleid, 'allowassign', $targetroleid)) {
3532 return true;
3537 return false;
3540 /** Returns all site roles in correct sort order.
3543 function get_all_roles() {
3544 return get_records('role', '', '', 'sortorder ASC');
3548 * gets all the user roles assigned in this context, or higher contexts
3549 * this is mainly used when checking if a user can assign a role, or overriding a role
3550 * i.e. we need to know what this user holds, in order to verify against allow_assign and
3551 * allow_override tables
3552 * @param object $context
3553 * @param int $userid
3554 * @param view - set to true when roles are pulled for display only
3555 * this is so that we can filter roles with no visible
3556 * assignment, for example, you might want to "hide" all
3557 * course creators when browsing the course participants
3558 * list.
3559 * @return array
3561 function get_user_roles($context, $userid=0, $checkparentcontexts=true, $order='c.contextlevel DESC, r.sortorder ASC', $view=false) {
3563 global $USER, $CFG, $db;
3565 if (empty($userid)) {
3566 if (empty($USER->id)) {
3567 return array();
3569 $userid = $USER->id;
3571 // set up hidden sql
3572 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))? ' AND ra.hidden = 0 ':'';
3574 if ($checkparentcontexts && ($parents = get_parent_contexts($context))) {
3575 $contexts = ' ra.contextid IN ('.implode(',' , $parents).','.$context->id.')';
3576 } else {
3577 $contexts = ' ra.contextid = \''.$context->id.'\'';
3580 return get_records_sql('SELECT ra.*, r.name, r.shortname
3581 FROM '.$CFG->prefix.'role_assignments ra,
3582 '.$CFG->prefix.'role r,
3583 '.$CFG->prefix.'context c
3584 WHERE ra.userid = '.$userid.
3585 ' AND ra.roleid = r.id
3586 AND ra.contextid = c.id
3587 AND '.$contexts . $hiddensql .
3588 ' ORDER BY '.$order);
3592 * Creates a record in the allow_override table
3593 * @param int sroleid - source roleid
3594 * @param int troleid - target roleid
3595 * @return int - id or false
3597 function allow_override($sroleid, $troleid) {
3598 $record = new object();
3599 $record->roleid = $sroleid;
3600 $record->allowoverride = $troleid;
3601 return insert_record('role_allow_override', $record);
3605 * Creates a record in the allow_assign table
3606 * @param int sroleid - source roleid
3607 * @param int troleid - target roleid
3608 * @return int - id or false
3610 function allow_assign($sroleid, $troleid) {
3611 $record = new object;
3612 $record->roleid = $sroleid;
3613 $record->allowassign = $troleid;
3614 return insert_record('role_allow_assign', $record);
3618 * Gets a list of roles that this user can assign in this context
3619 * @param object $context
3620 * @return array
3622 function get_assignable_roles ($context, $field="name") {
3624 $options = array();
3626 if ($roles = get_all_roles()) {
3627 foreach ($roles as $role) {
3628 if (user_can_assign($context, $role->id)) {
3629 $options[$role->id] = strip_tags(format_string($role->{$field}, true));
3633 return $options;
3637 * Gets a list of roles that this user can override in this context
3638 * @param object $context
3639 * @return array
3641 function get_overridable_roles($context) {
3643 $options = array();
3645 if ($roles = get_all_roles()) {
3646 foreach ($roles as $role) {
3647 if (user_can_override($context, $role->id)) {
3648 $options[$role->id] = strip_tags(format_string($role->name, true));
3653 return $options;
3657 * Returns a role object that is the default role for new enrolments
3658 * in a given course
3660 * @param object $course
3661 * @return object $role
3663 function get_default_course_role($course) {
3664 global $CFG;
3666 /// First let's take the default role the course may have
3667 if (!empty($course->defaultrole)) {
3668 if ($role = get_record('role', 'id', $course->defaultrole)) {
3669 return $role;
3673 /// Otherwise the site setting should tell us
3674 if ($CFG->defaultcourseroleid) {
3675 if ($role = get_record('role', 'id', $CFG->defaultcourseroleid)) {
3676 return $role;
3680 /// It's unlikely we'll get here, but just in case, try and find a student role
3681 if ($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW)) {
3682 return array_shift($studentroles); /// Take the first one
3685 return NULL;
3690 * who has this capability in this context
3691 * does not handling user level resolving!!!
3692 * (!)pleaes note if $fields is empty this function attempts to get u.*
3693 * which can get rather large.
3694 * i.e 1 person has 2 roles 1 allow, 1 prevent, this will not work properly
3695 * @param $context - object
3696 * @param $capability - string capability
3697 * @param $fields - fields to be pulled
3698 * @param $sort - the sort order
3699 * @param $limitfrom - number of records to skip (offset)
3700 * @param $limitnum - number of records to fetch
3701 * @param $groups - single group or array of groups - only return
3702 * users who are in one of these group(s).
3703 * @param $exceptions - list of users to exclude
3704 * @param view - set to true when roles are pulled for display only
3705 * this is so that we can filter roles with no visible
3706 * assignment, for example, you might want to "hide" all
3707 * course creators when browsing the course participants
3708 * list.
3709 * @param boolean $useviewallgroups if $groups is set the return users who
3710 * have capability both $capability and moodle/site:accessallgroups
3711 * in this context, as well as users who have $capability and who are
3712 * in $groups.
3714 function get_users_by_capability($context, $capability, $fields='', $sort='',
3715 $limitfrom='', $limitnum='', $groups='', $exceptions='', $doanything=true,
3716 $view=false, $useviewallgroups=false) {
3717 global $CFG;
3719 /// Sorting out groups
3720 if ($groups) {
3721 if (is_array($groups)) {
3722 $grouptest = 'gm.groupid IN (' . implode(',', $groups) . ')';
3723 } else {
3724 $grouptest = 'gm.groupid = ' . $groups;
3726 $grouptest = 'ra.userid IN (SELECT userid FROM ' .
3727 $CFG->prefix . 'groups_members gm WHERE ' . $grouptest . ')';
3729 if ($useviewallgroups) {
3730 $viewallgroupsusers = get_users_by_capability($context,
3731 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
3732 $groupsql = ' AND (' . $grouptest . ' OR ra.userid IN (' .
3733 implode(',', array_keys($viewallgroupsusers)) . '))';
3734 } else {
3735 $groupsql = ' AND ' . $grouptest;
3737 } else {
3738 $groupsql = '';
3741 /// Sorting out exceptions
3742 $exceptionsql = $exceptions ? "AND u.id NOT IN ($exceptions)" : '';
3744 /// Set up default fields
3745 if (empty($fields)) {
3746 $fields = 'u.*, ul.timeaccess as lastaccess, ra.hidden';
3749 /// Set up default sort
3750 if (empty($sort)) {
3751 $sort = 'ul.timeaccess';
3754 $sortby = $sort ? " ORDER BY $sort " : '';
3755 /// Set up hidden sql
3756 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))? ' AND ra.hidden = 0 ':'';
3758 /// If context is a course, then construct sql for ul
3759 if ($context->contextlevel == CONTEXT_COURSE) {
3760 $courseid = $context->instanceid;
3761 $coursesql1 = "AND ul.courseid = $courseid";
3762 } else {
3763 $coursesql1 = '';
3766 /// Sorting out roles with this capability set
3767 if ($possibleroles = get_roles_with_capability($capability, CAP_ALLOW, $context)) {
3768 if (!$doanything) {
3769 if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM)) {
3770 return false; // Something is seriously wrong
3772 $doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, $sitecontext);
3775 $validroleids = array();
3776 foreach ($possibleroles as $possiblerole) {
3777 if (!$doanything) {
3778 if (isset($doanythingroles[$possiblerole->id])) { // We don't want these included
3779 continue;
3782 if ($caps = role_context_capabilities($possiblerole->id, $context, $capability)) { // resolved list
3783 if (isset($caps[$capability]) && $caps[$capability] > 0) { // resolved capability > 0
3784 $validroleids[] = $possiblerole->id;
3788 if (empty($validroleids)) {
3789 return false;
3791 $roleids = '('.implode(',', $validroleids).')';
3792 } else {
3793 return false; // No need to continue, since no roles have this capability set
3796 /// Construct the main SQL
3797 $select = " SELECT $fields";
3798 $from = " FROM {$CFG->prefix}user u
3799 INNER JOIN {$CFG->prefix}role_assignments ra ON ra.userid = u.id
3800 INNER JOIN {$CFG->prefix}role r ON r.id = ra.roleid
3801 LEFT OUTER JOIN {$CFG->prefix}user_lastaccess ul ON (ul.userid = u.id $coursesql1)";
3802 $where = " WHERE ra.contextid ".get_related_contexts_string($context)."
3803 AND u.deleted = 0
3804 AND ra.roleid in $roleids
3805 $exceptionsql
3806 $groupsql
3807 $hiddensql";
3809 return get_records_sql($select.$from.$where.$sortby, $limitfrom, $limitnum);
3813 * gets all the users assigned this role in this context or higher
3814 * @param int roleid
3815 * @param int contextid
3816 * @param bool parent if true, get list of users assigned in higher context too
3817 * @return array()
3819 function get_role_users($roleid, $context, $parent=false, $fields='', $sort='u.lastname ASC', $view=false, $limitfrom='', $limitnum='', $group='') {
3820 global $CFG;
3822 if (empty($fields)) {
3823 $fields = 'u.id, u.confirmed, u.username, u.firstname, u.lastname, '.
3824 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.city, '.
3825 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
3826 'u.emailstop, u.lang, u.timezone';
3829 // whether this assignment is hidden
3830 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))? ' AND r.hidden = 0 ':'';
3831 if ($parent) {
3832 if ($contexts = get_parent_contexts($context)) {
3833 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
3834 } else {
3835 $parentcontexts = '';
3837 } else {
3838 $parentcontexts = '';
3841 if ($roleid) {
3842 $roleselect = "AND r.roleid = $roleid";
3843 } else {
3844 $roleselect = '';
3847 if ($group) {
3848 $groupsql = "{$CFG->prefix}groups_members gm, ";
3849 $groupwheresql = " AND gm.userid = u.id AND gm.groupid = $group ";
3850 } else {
3851 $groupsql = '';
3852 $groupwheresql = '';
3855 $SQL = "SELECT $fields
3856 FROM {$CFG->prefix}role_assignments r,
3857 $groupsql
3858 {$CFG->prefix}user u
3859 WHERE (r.contextid = $context->id $parentcontexts)
3860 $groupwheresql
3861 AND u.id = r.userid $roleselect
3862 $hiddensql
3863 ORDER BY $sort
3864 "; // join now so that we can just use fullname() later
3866 return get_records_sql($SQL, $limitfrom, $limitnum);
3870 * Counts all the users assigned this role in this context or higher
3871 * @param int roleid
3872 * @param int contextid
3873 * @param bool parent if true, get list of users assigned in higher context too
3874 * @return array()
3876 function count_role_users($roleid, $context, $parent=false) {
3877 global $CFG;
3879 if ($parent) {
3880 if ($contexts = get_parent_contexts($context)) {
3881 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
3882 } else {
3883 $parentcontexts = '';
3885 } else {
3886 $parentcontexts = '';
3889 $SQL = "SELECT count(*)
3890 FROM {$CFG->prefix}role_assignments r
3891 WHERE (r.contextid = $context->id $parentcontexts)
3892 AND r.roleid = $roleid";
3894 return count_records_sql($SQL);
3898 * This function gets the list of courses that this user has a particular capability in.
3899 * It is still not very efficient.
3900 * @param string $capability Capability in question
3901 * @param int $userid User ID or null for current user
3902 * @param bool $doanything True if 'doanything' is permitted (default)
3903 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
3904 * otherwise use a comma-separated list of the fields you require, not including id
3905 * @param string $orderby If set, use a comma-separated list of fields from course
3906 * table with sql modifiers (DESC) if needed
3907 * @return array Array of courses, may have zero entries. Or false if query failed.
3909 function get_user_capability_course($capability, $userid=NULL,$doanything=true,$fieldsexceptid='',$orderby='') {
3910 // Convert fields list and ordering
3911 $fieldlist='';
3912 if($fieldsexceptid) {
3913 $fields=explode(',',$fieldsexceptid);
3914 foreach($fields as $field) {
3915 $fieldlist.=',c.'.$field;
3918 if($orderby) {
3919 $fields=explode(',',$orderby);
3920 $orderby='';
3921 foreach($fields as $field) {
3922 if($orderby) {
3923 $orderby.=',';
3925 $orderby.='c.'.$field;
3927 $orderby='ORDER BY '.$orderby;
3930 // Obtain a list of everything relevant about all courses including context.
3931 // Note the result can be used directly as a context (we are going to), the course
3932 // fields are just appended.
3933 global $CFG;
3934 $rs=get_recordset_sql("
3935 SELECT
3936 x.*,c.id AS courseid$fieldlist
3937 FROM
3938 {$CFG->prefix}course c
3939 INNER JOIN {$CFG->prefix}context x ON c.id=x.instanceid AND x.contextlevel=".CONTEXT_COURSE."
3940 $orderby
3942 if(!$rs) {
3943 return false;
3946 // Check capability for each course in turn
3947 $courses=array();
3948 while($coursecontext=rs_fetch_next_record($rs)) {
3949 if(has_capability($capability,$coursecontext,$userid,$doanything)) {
3950 // We've got the capability. Make the record look like a course record
3951 // and store it
3952 $coursecontext->id=$coursecontext->courseid;
3953 unset($coursecontext->courseid);
3954 unset($coursecontext->contextlevel);
3955 unset($coursecontext->instanceid);
3956 $courses[]=$coursecontext;
3959 return $courses;
3962 /** This function finds the roles assigned directly to this context only
3963 * i.e. no parents role
3964 * @param object $context
3965 * @return array
3967 function get_roles_on_exact_context($context) {
3969 global $CFG;
3971 return get_records_sql("SELECT r.*
3972 FROM {$CFG->prefix}role_assignments ra,
3973 {$CFG->prefix}role r
3974 WHERE ra.roleid = r.id
3975 AND ra.contextid = $context->id");
3980 * Switches the current user to another role for the current session and only
3981 * in the given context. If roleid is not valid (eg 0) or the current user
3982 * doesn't have permissions to be switching roles then the user's session
3983 * is compltely reset to have their normal roles.
3984 * @param integer $roleid
3985 * @param object $context
3986 * @return bool
3988 function role_switch($roleid, $context) {
3989 global $USER, $CFG;
3991 /// If we can't use this or are already using it or no role was specified then bail completely and reset
3992 if (empty($roleid) || !has_capability('moodle/role:switchroles', $context)
3993 || !empty($USER->switchrole[$context->id]) || !confirm_sesskey()) {
3995 unset($USER->switchrole[$context->id]); // Delete old capabilities
3996 unset($USER->courseeditallowed); // drop cache for course edit button
3997 load_all_capabilities(); //reload user caps
3998 return true;
4001 /// We're allowed to switch but can we switch to the specified role? Use assignable roles to check.
4002 if (!$roles = get_assignable_roles($context)) {
4003 return false;
4006 /// unset default user role - it would not work anyway
4007 unset($roles[$CFG->defaultuserroleid]);
4009 if (empty($roles[$roleid])) { /// We can't switch to this particular role
4010 return false;
4013 /// We have a valid roleid that this user can switch to, so let's set up the session
4015 $USER->switchrole[$context->id] = $roleid; // So we know later what state we are in
4016 unset($USER->courseeditallowed); // drop cache for course edit button
4018 load_all_capabilities(); //reload switched role caps
4020 /// Add some permissions we are really going to always need, even if the role doesn't have them!
4022 $USER->capabilities[$context->id]['moodle/course:view'] = CAP_ALLOW;
4024 return true;
4029 // get any role that has an override on exact context
4030 function get_roles_with_override_on_context($context) {
4032 global $CFG;
4034 return get_records_sql("SELECT r.*
4035 FROM {$CFG->prefix}role_capabilities rc,
4036 {$CFG->prefix}role r
4037 WHERE rc.roleid = r.id
4038 AND rc.contextid = $context->id");
4041 // get all capabilities for this role on this context (overrids)
4042 function get_capabilities_from_role_on_context($role, $context) {
4044 global $CFG;
4046 return get_records_sql("SELECT *
4047 FROM {$CFG->prefix}role_capabilities
4048 WHERE contextid = $context->id
4049 AND roleid = $role->id");
4052 // find out which roles has assignment on this context
4053 function get_roles_with_assignment_on_context($context) {
4055 global $CFG;
4057 return get_records_sql("SELECT r.*
4058 FROM {$CFG->prefix}role_assignments ra,
4059 {$CFG->prefix}role r
4060 WHERE ra.roleid = r.id
4061 AND ra.contextid = $context->id");
4067 * Find all user assignemnt of users for this role, on this context
4069 function get_users_from_role_on_context($role, $context) {
4071 global $CFG;
4073 return get_records_sql("SELECT *
4074 FROM {$CFG->prefix}role_assignments
4075 WHERE contextid = $context->id
4076 AND roleid = $role->id");
4080 * Simple function returning a boolean true if roles exist, otherwise false
4082 function user_has_role_assignment($userid, $roleid, $contextid=0) {
4084 if ($contextid) {
4085 return record_exists('role_assignments', 'userid', $userid, 'roleid', $roleid, 'contextid', $contextid);
4086 } else {
4087 return record_exists('role_assignments', 'userid', $userid, 'roleid', $roleid);
4091 /**
4092 * Inserts all parental context and self into context_rel table
4094 * @param object $context-context to be deleted
4095 * @param bool deletechild - deltes child contexts dependencies
4097 function insert_context_rel($context, $deletechild=true, $deleteparent=true) {
4099 // first check validity
4100 // MDL-9057
4101 if (!validate_context($context->contextlevel, $context->instanceid)) {
4102 debugging('Error: Invalid context creation request for level "' .
4103 s($context->contextlevel) . '", instance "' . s($context->instanceid) . '".');
4104 return NULL;
4107 // removes all parents
4108 if ($deletechild) {
4109 delete_records('context_rel', 'c2', $context->id);
4112 if ($deleteparent) {
4113 delete_records('context_rel', 'c1', $context->id);
4115 // insert all parents
4116 if ($parents = get_parent_contexts($context)) {
4117 $parents[] = $context->id;
4118 foreach ($parents as $parent) {
4119 $rec = new object;
4120 $rec ->c1 = $context->id;
4121 $rec ->c2 = $parent;
4122 insert_record('context_rel', $rec);
4128 * rebuild context_rel table without deleting
4130 function build_context_rel() {
4132 global $CFG, $db;
4133 $savedb = $db->debug;
4135 // MDL-10679, only identify contexts with overrides in them
4136 $contexts = get_records_sql("SELECT c.* FROM {$CFG->prefix}context c,
4137 {$CFG->prefix}role_capabilities rc
4138 WHERE c.id = rc.contextid");
4139 // total number of records
4140 // subtract one because the site context should not be calculated, will not be processed
4141 $total = count($contexts) - 1;
4143 // processed records
4144 $done = 0;
4145 print_progress($done, $total, 10, 0, 'Processing context relations');
4146 $db->debug = false;
4148 //if ($contexts = get_records('context')) {
4149 foreach ($contexts as $context) {
4150 // no need to delete because it's all empty
4151 insert_context_rel($context, false, false);
4152 $db->debug = true;
4153 print_progress(++$done, $total, 10, 0, 'Processing context relations');
4154 $db->debug = false;
4157 $db->debug = $savedb;
4161 // gets the custom name of the role in course
4162 // TODO: proper documentation
4163 function role_get_name($role, $context) {
4165 if ($r = get_record('role_names','roleid', $role->id,'contextid', $context->id)) {
4166 return format_string($r->text);
4167 } else {
4168 return format_string($role->name);
4173 * @param int object - context object (node), from which we find all it's children
4174 * and rebuild all associated context_rel info
4175 * this is needed when a course or course category is moved
4176 * as the children's relationship to grandparents needs to be fixed
4177 * @return int number of contexts rebuilt
4179 function rebuild_context_rel($context) {
4181 $contextlist = array();
4183 if (record_exists('role_capabilities', 'contextid', $context->id)) {
4184 $contextlist[] = $context;
4187 // find all children used in context_rel
4188 if ($childcontexts = get_records('context_rel', 'c2', $context->id)) {
4189 foreach ($childcontexts as $childcontext) {
4190 $contextlist[$childcontext->c1] = get_record('context', 'id', $childcontext->c1);
4194 $i = 0;
4195 // rebuild all the contexts of this list
4196 foreach ($contextlist as $c) {
4197 insert_context_rel($c);
4198 $i++;
4201 return $i;
4205 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
4206 * when we read in a new capability
4207 * most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
4208 * but when we are in grade, all reports/import/export capabilites should be together
4209 * @param string a - component string a
4210 * @param string b - component string b
4211 * @return bool - whether 2 component are in different "sections"
4213 function component_level_changed($cap, $comp, $contextlevel) {
4215 if ($cap->component == 'enrol/authorize' && $comp =='enrol/authorize') {
4216 return false;
4219 if (strstr($cap->component, '/') && strstr($comp, '/')) {
4220 $compsa = explode('/', $cap->component);
4221 $compsb = explode('/', $comp);
4225 // we are in gradebook, still
4226 if (($compsa[0] == 'gradeexport' || $compsa[0] == 'gradeimport' || $compsa[0] == 'gradereport') &&
4227 ($compsb[0] == 'gradeexport' || $compsb[0] == 'gradeimport' || $compsb[0] == 'gradereport')) {
4228 return false;
4232 return ($cap->component != $comp || $cap->contextlevel != $contextlevel);