mirrored from git://git.moodle.org/moodle.git
/
accesslib.php
executable file
·4002 lines (3360 loc) · 140 KB
/
accesslib.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php // $Id$
///////////////////////////////////////////////////////////////////////////
// //
// NOTICE OF COPYRIGHT //
// //
// Moodle - Modular Object-Oriented Dynamic Learning Environment //
// http://moodle.org //
// //
// Copyright (C) 1999-2004 Martin Dougiamas http://dougiamas.com //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation; either version 2 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License for more details: //
// //
// http://www.gnu.org/copyleft/gpl.html //
// //
///////////////////////////////////////////////////////////////////////////
/**
* Capability session information format
* 2 x 2 array
* [context][capability]
* where context is the context id of the table 'context'
* and capability is a string defining the capability
* e.g.
*
* [Capabilities] => [26][mod/forum:viewpost] = 1
* [26][mod/forum:startdiscussion] = -8990
* [26][mod/forum:editallpost] = -1
* [273][moodle:blahblah] = 1
* [273][moodle:blahblahblah] = 2
*/
require_once $CFG->dirroot.'/lib/blocklib.php';
// permission definitions
define('CAP_INHERIT', 0);
define('CAP_ALLOW', 1);
define('CAP_PREVENT', -1);
define('CAP_PROHIBIT', -1000);
// context definitions
define('CONTEXT_SYSTEM', 10);
define('CONTEXT_PERSONAL', 20);
define('CONTEXT_USER', 30);
define('CONTEXT_COURSECAT', 40);
define('CONTEXT_COURSE', 50);
define('CONTEXT_GROUP', 60);
define('CONTEXT_MODULE', 70);
define('CONTEXT_BLOCK', 80);
// capability risks - see http://docs.moodle.org/en/Hardening_new_Roles_system
define('RISK_MANAGETRUST', 0x0001);
define('RISK_CONFIG', 0x0002);
define('RISK_XSS', 0x0004);
define('RISK_PERSONAL', 0x0008);
define('RISK_SPAM', 0x0010);
require_once($CFG->dirroot.'/group/lib.php');
$context_cache = array(); // Cache of all used context objects for performance (by level and instance)
$context_cache_id = array(); // Index to above cache by id
function get_role_context_caps($roleid, $context) {
//this is really slow!!!! - do not use above course context level!
$result = array();
$result[$context->id] = array();
// first emulate the parent context capabilities merging into context
$searchcontexts = array_reverse(get_parent_contexts($context));
array_push($searchcontexts, $context->id);
foreach ($searchcontexts as $cid) {
if ($capabilities = get_records_select('role_capabilities', "roleid = $roleid AND contextid = $cid")) {
foreach ($capabilities as $cap) {
if (!array_key_exists($cap->capability, $result[$context->id])) {
$result[$context->id][$cap->capability] = 0;
}
$result[$context->id][$cap->capability] += $cap->permission;
}
}
}
// now go through the contexts bellow given context
$searchcontexts = get_child_contexts($context);
foreach ($searchcontexts as $cid) {
if ($capabilities = get_records_select('role_capabilities', "roleid = $roleid AND contextid = $cid")) {
foreach ($capabilities as $cap) {
if (!array_key_exists($cap->contextid, $result)) {
$result[$cap->contextid] = array();
}
$result[$cap->contextid][$cap->capability] = $cap->permission;
}
}
}
return $result;
}
function get_role_caps($roleid) {
$result = array();
if ($capabilities = get_records_select('role_capabilities',"roleid = $roleid")) {
foreach ($capabilities as $cap) {
if (!array_key_exists($cap->contextid, $result)) {
$result[$cap->contextid] = array();
}
$result[$cap->contextid][$cap->capability] = $cap->permission;
}
}
return $result;
}
function merge_role_caps($caps, $mergecaps) {
if (empty($mergecaps)) {
return $caps;
}
if (empty($caps)) {
return $mergecaps;
}
foreach ($mergecaps as $contextid=>$capabilities) {
if (!array_key_exists($contextid, $caps)) {
$caps[$contextid] = array();
}
foreach ($capabilities as $capability=>$permission) {
if (!array_key_exists($capability, $caps[$contextid])) {
$caps[$contextid][$capability] = 0;
}
$caps[$contextid][$capability] += $permission;
}
}
return $caps;
}
/**
* Loads the capabilities for the default guest role to the current user in a
* specific context.
* @return object
*/
function load_guest_role($return=false) {
global $USER;
static $guestrole = false;
if ($guestrole === false) {
if (!$guestrole = get_guest_role()) {
return false;
}
}
if ($return) {
return get_role_caps($guestrole->id);
} else {
has_capability('clearcache');
$USER->capabilities = get_role_caps($guestrole->id);
return true;
}
}
/**
* Load default not logged in role capabilities when user is not logged in
* @return bool
*/
function load_notloggedin_role($return=false) {
global $CFG, $USER;
if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM)) {
return false;
}
if (empty($CFG->notloggedinroleid)) { // Let's set the default to the guest role
if ($role = get_guest_role()) {
set_config('notloggedinroleid', $role->id);
} else {
return false;
}
}
if ($return) {
return get_role_caps($CFG->notloggedinroleid);
} else {
has_capability('clearcache');
$USER->capabilities = get_role_caps($CFG->notloggedinroleid);
return true;
}
}
/**
* Load default logged in role capabilities for all logged in users
* @return bool
*/
function load_defaultuser_role($return=false) {
global $CFG, $USER;
if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM)) {
return false;
}
if (empty($CFG->defaultuserroleid)) { // Let's set the default to the guest role
if ($role = get_guest_role()) {
set_config('defaultuserroleid', $role->id);
} else {
return false;
}
}
$capabilities = get_role_caps($CFG->defaultuserroleid);
// fix the guest user heritage:
// If the default role is a guest role, then don't copy legacy:guest,
// otherwise this user could get confused with a REAL guest. Also don't copy
// course:view, which is a hack that's necessary because guest roles are
// not really handled properly (see MDL-7513)
if (!empty($capabilities[$sitecontext->id]['moodle/legacy:guest'])) {
unset($capabilities[$sitecontext->id]['moodle/legacy:guest']);
unset($capabilities[$sitecontext->id]['moodle/course:view']);
}
if ($return) {
return $capabilities;
} else {
has_capability('clearcache');
$USER->capabilities = $capabilities;
return true;
}
}
/**
* Get the default guest role
* @return object role
*/
function get_guest_role() {
global $CFG;
if (empty($CFG->guestroleid)) {
if ($roles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW)) {
$guestrole = array_shift($roles); // Pick the first one
set_config('guestroleid', $guestrole->id);
return $guestrole;
} else {
debugging('Can not find any guest role!');
return false;
}
} else {
if ($guestrole = get_record('role','id', $CFG->guestroleid)) {
return $guestrole;
} else {
//somebody is messing with guest roles, remove incorrect setting and try to find a new one
set_config('guestroleid', '');
return get_guest_role();
}
}
}
/**
* This functions get all the course categories in proper order
* (!)note this only gets course category contexts, and not the site
* context
* @param object $context
* @return array of contextids
*/
function get_parent_cats($context) {
global $COURSE;
switch ($context->contextlevel) {
// a category can be the parent of another category
// there is no limit of depth in this case
case CONTEXT_COURSECAT:
static $categoryparents = null; // cache for parent categories
if (!isset($categoryparents)) {
$categoryparents = array();
}
if (array_key_exists($context->instanceid, $categoryparents)) {
return $categoryparents[$context->instanceid];
}
if (!$cat = get_record('course_categories','id',$context->instanceid)) {
//error?
return array();
}
$parents = array();
while (!empty($cat->parent)) {
if (!$catcontext = get_context_instance(CONTEXT_COURSECAT, $cat->parent)) {
debugging('Incorrect category parent');
break;
}
$parents[] = $catcontext->id;
$cat = get_record('course_categories','id',$cat->parent);
}
return $categoryparents[$context->instanceid] = array_reverse($parents);
break;
// a course always fall into a category, unless it's a site course
// this happens when SITEID == $course->id
// in this case the parent of the course is site context
case CONTEXT_COURSE:
static $courseparents = null; // cache course parents
if (!isset($courseparents)) {
$courseparents = array();
}
if (array_key_exists($context->instanceid, $courseparents)) {
return $courseparents[$context->instanceid];
}
if (count($courseparents) > 1000) {
$courseparents = array(); // max cache size when looping through thousands of courses
}
if ($context->instanceid == SITEID) {
return $courseparents[$context->instanceid] = array(); // frontpage course does not have parent cats
}
if ($context->instanceid == $COURSE->id) {
$course = $COURSE;
} else if (!$course = get_record('course', 'id', $context->instanceid)) {
//error?
return array();;
}
if (empty($course->category)) {
// this should not happen
return $courseparents[$context->instanceid] = array();
}
if (!$catcontext = get_context_instance(CONTEXT_COURSECAT, $course->category)) {
debugging('Incorect course category');
return array();;
}
return $courseparents[$context->instanceid] = array_merge(get_parent_cats($catcontext), array($catcontext->id)); //recursion :-)
break;
default:
// something is very wrong!
return array();
break;
}
}
/**
* This function checks for a capability assertion being true. If it isn't
* then the page is terminated neatly with a standard error message
* @param string $capability - name of the capability
* @param object $context - a context object (record from context table)
* @param integer $userid - a userid number
* @param bool $doanything - if false, ignore do anything
* @param string $errorstring - an errorstring
* @param string $stringfile - which stringfile to get it from
*/
function require_capability($capability, $context=NULL, $userid=NULL, $doanything=true,
$errormessage='nopermissions', $stringfile='') {
global $USER, $CFG;
/// If the current user is not logged in, then make sure they are (if needed)
if (empty($userid) and empty($USER->capabilities)) {
if ($context && ($context->contextlevel == CONTEXT_COURSE)) {
require_login($context->instanceid);
} else if ($context && ($context->contextlevel == CONTEXT_MODULE)) {
if ($cm = get_record('course_modules','id',$context->instanceid)) {
if (!$course = get_record('course', 'id', $cm->course)) {
error('Incorrect course.');
}
require_course_login($course, true, $cm);
} else {
require_login();
}
} else if ($context && ($context->contextlevel == CONTEXT_SYSTEM)) {
if (!empty($CFG->forcelogin)) {
require_login();
}
} else {
require_login();
}
}
/// OK, if they still don't have the capability then print a nice error message
if (!has_capability($capability, $context, $userid, $doanything)) {
$capabilityname = get_capability_string($capability);
print_error($errormessage, $stringfile, '', $capabilityname);
}
}
/**
* Cheks if current user has allowed permission for any of submitted capabilities
* in given or child contexts.
* @param object $context - a context object (record from context table)
* @param array $capabilitynames array of strings, capability names
* @return boolean
*/
function has_capability_including_child_contexts($context, $capabilitynames) {
global $USER;
foreach ($capabilitynames as $capname) {
if (has_capability($capname, $context)) {
return true;
}
}
if ($children = get_child_contexts($context)) {
foreach ($capabilitynames as $capname) {
foreach ($children as $child) {
if (isset($USER->capabilities[$child][$capname]) and $USER->capabilities[$child][$capname] > 0) {
// extra check for inherited prevent and prohibit
if (has_capability($capname, get_context_instance_by_id($child), $USER->id, false)) {
return true;
}
}
}
}
}
return false;
}
/**
* This function returns whether the current user has the capability of performing a function
* For example, we can do has_capability('mod/forum:replypost',$context) in forum
* This is a recursive function.
* @uses $USER
* @param string $capability - name of the capability (or debugcache or clearcache)
* @param object $context - a context object (record from context table)
* @param integer $userid - a userid number
* @param bool $doanything - if false, ignore do anything
* @return bool
*/
function has_capability($capability, $context=NULL, $userid=NULL, $doanything=true) {
global $USER, $CONTEXT, $CFG;
static $capcache = array(); // Cache of capabilities
/// Cache management
if ($capability == 'clearcache') {
$capcache = array(); // Clear ALL the capability cache
return false;
}
/// Some sanity checks
if (debugging('',DEBUG_DEVELOPER)) {
if ($capability == 'debugcache') {
print_object($capcache);
return true;
}
if (!record_exists('capabilities', 'name', $capability)) {
debugging('Capability "'.$capability.'" was not found! This should be fixed in code.');
}
if ($doanything != true and $doanything != false) {
debugging('Capability parameter "doanything" is wierd ("'.$doanything.'"). This should be fixed in code.');
}
if (!is_object($context) && $context !== NULL) {
debugging('Incorrect context parameter "'.$context.'" for has_capability(), object expected! This should be fixed in code.');
}
}
/// Make sure we know the current context
if (empty($context)) { // Use default CONTEXT if none specified
if (empty($CONTEXT)) {
return false;
} else {
$context = $CONTEXT;
}
} else { // A context was given to us
if (empty($CONTEXT)) {
$CONTEXT = $context; // Store FIRST used context in this global as future default
}
}
/// Check and return cache in case we've processed this one before.
$requsteduser = empty($userid) ? $USER->id : $userid; // find out the requested user id, $USER->id might have been changed
$cachekey = $capability.'_'.$context->id.'_'.intval($requsteduser).'_'.intval($doanything);
if (isset($capcache[$cachekey])) {
return $capcache[$cachekey];
}
/// Load up the capabilities list or item as necessary
if ($userid) {
if (empty($USER->id) or ($userid != $USER->id) or empty($USER->capabilities)) {
//caching - helps user switching in cron
static $guestuserid = false; // guest user id
static $guestcaps = false; // guest caps
static $defcaps = false; // default user caps - this might help cron
if ($guestuserid === false) {
$guestuserid = get_field('user', 'id', 'username', 'guest');
}
if ($userid == $guestuserid) {
if ($guestcaps === false) {
$guestcaps = load_guest_role(true);
}
$capabilities = $guestcaps;
} else {
// This big SQL is expensive! We reduce it a little by avoiding checking for changed enrolments (false)
$capabilities = load_user_capability($capability, $context, $userid, false);
if ($defcaps === false) {
$defcaps = load_defaultuser_role(true);
}
$capabilities = merge_role_caps($capabilities, $defcaps);
}
} else { //$USER->id == $userid and needed capabilities already present
$capabilities = $USER->capabilities;
}
} else { // no userid
if (empty($USER->capabilities)) {
load_all_capabilities(); // expensive - but we have to do it once anyway
}
$capabilities = $USER->capabilities;
$userid = $USER->id;
}
/// We act a little differently when switchroles is active
$switchroleactive = false; // Assume it isn't active in this context
/// First deal with the "doanything" capability
if ($doanything) {
/// First make sure that we aren't in a "switched role"
if (!empty($USER->switchrole)) { // Switchrole is active somewhere!
if (!empty($USER->switchrole[$context->id])) { // Because of current context
$switchroleactive = true;
} else { // Check parent contexts
if ($parentcontextids = get_parent_contexts($context)) {
foreach ($parentcontextids as $parentcontextid) {
if (!empty($USER->switchrole[$parentcontextid])) { // Yep, switchroles active here
$switchroleactive = true;
break;
}
}
}
}
}
/// Check the site context for doanything (most common) first
if (empty($switchroleactive)) { // Ignore site setting if switchrole is active
$sitecontext = get_context_instance(CONTEXT_SYSTEM);
if (isset($capabilities[$sitecontext->id]['moodle/site:doanything'])) {
$result = (0 < $capabilities[$sitecontext->id]['moodle/site:doanything']);
$capcache[$cachekey] = $result;
return $result;
}
}
/// If it's not set at site level, it is possible to be set on other levels
/// Though this usage is not common and can cause risks
switch ($context->contextlevel) {
case CONTEXT_COURSECAT:
// Check parent cats.
$parentcats = get_parent_cats($context);
foreach ($parentcats as $parentcat) {
if (isset($capabilities[$parentcat]['moodle/site:doanything'])) {
$result = (0 < $capabilities[$parentcat]['moodle/site:doanything']);
$capcache[$cachekey] = $result;
return $result;
}
}
break;
case CONTEXT_COURSE:
// Check parent cat.
$parentcats = get_parent_cats($context);
foreach ($parentcats as $parentcat) {
if (isset($capabilities[$parentcat]['do_anything'])) {
$result = (0 < $capabilities[$parentcat]['do_anything']);
$capcache[$cachekey] = $result;
return $result;
}
}
break;
case CONTEXT_GROUP:
// Find course.
$courseid = groups_get_course($context->instanceid);
$courseinstance = get_context_instance(CONTEXT_COURSE, $courseid);
$parentcats = get_parent_cats($courseinstance);
foreach ($parentcats as $parentcat) {
if (isset($capabilities[$parentcat]['do_anything'])) {
$result = (0 < $capabilities[$parentcat]['do_anything']);
$capcache[$cachekey] = $result;
return $result;
}
}
$coursecontext = '';
if (isset($capabilities[$courseinstance->id]['do_anything'])) {
$result = (0 < $capabilities[$courseinstance->id]['do_anything']);
$capcache[$cachekey] = $result;
return $result;
}
break;
case CONTEXT_MODULE:
// Find course.
$cm = get_record('course_modules', 'id', $context->instanceid);
$courseinstance = get_context_instance(CONTEXT_COURSE, $cm->course);
if ($parentcats = get_parent_cats($courseinstance)) {
foreach ($parentcats as $parentcat) {
if (isset($capabilities[$parentcat]['do_anything'])) {
$result = (0 < $capabilities[$parentcat]['do_anything']);
$capcache[$cachekey] = $result;
return $result;
}
}
}
if (isset($capabilities[$courseinstance->id]['do_anything'])) {
$result = (0 < $capabilities[$courseinstance->id]['do_anything']);
$capcache[$cachekey] = $result;
return $result;
}
break;
case CONTEXT_BLOCK:
// not necessarily 1 to 1 to course.
$block = get_record('block_instance','id',$context->instanceid);
if ($block->pagetype == 'course-view') {
$courseinstance = get_context_instance(CONTEXT_COURSE, $block->pageid); // needs check
$parentcats = get_parent_cats($courseinstance);
foreach ($parentcats as $parentcat) {
if (isset($capabilities[$parentcat]['do_anything'])) {
$result = (0 < $capabilities[$parentcat]['do_anything']);
$capcache[$cachekey] = $result;
return $result;
}
}
if (isset($capabilities[$courseinstance->id]['do_anything'])) {
$result = (0 < $capabilities[$courseinstance->id]['do_anything']);
$capcache[$cachekey] = $result;
return $result;
}
}
// blocks that do not have course as parent do not need to do any more checks - already done above
break;
default:
// CONTEXT_SYSTEM: CONTEXT_PERSONAL: CONTEXT_USER:
// Do nothing, because the parents are site context
// which has been checked already
break;
}
// Last: check self.
if (isset($capabilities[$context->id]['do_anything'])) {
$result = (0 < $capabilities[$context->id]['do_anything']);
$capcache[$cachekey] = $result;
return $result;
}
}
// do_anything has not been set, we now look for it the normal way.
$result = (0 < capability_search($capability, $context, $capabilities, $switchroleactive));
$capcache[$cachekey] = $result;
return $result;
}
/**
* In a separate function so that we won't have to deal with do_anything.
* again. Used by function has_capability().
* @param $capability - capability string
* @param $context - the context object
* @param $capabilities - either $USER->capability or loaded array (for other users)
* @return permission (int)
*/
function capability_search($capability, $context, $capabilities, $switchroleactive=false) {
global $USER, $CFG, $COURSE;
if (!isset($context->id)) {
return 0;
}
// if already set in the array explicitly, no need to look for it in parent
// context any longer
if (isset($capabilities[$context->id][$capability])) {
return ($capabilities[$context->id][$capability]);
}
/* Then, we check the cache recursively */
$permission = 0;
switch ($context->contextlevel) {
case CONTEXT_SYSTEM: // by now it's a definite an inherit
$permission = 0;
break;
case CONTEXT_PERSONAL:
$parentcontext = get_context_instance(CONTEXT_SYSTEM);
$permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
break;
case CONTEXT_USER:
$parentcontext = get_context_instance(CONTEXT_SYSTEM);
$permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
break;
case CONTEXT_COURSE:
if ($switchroleactive) {
// if switchrole active, do not check permissions above the course context, blocks are an exception
break;
}
// break is not here intentionally - because the code is the same for category and course
case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
$parents = get_parent_cats($context); // cached internally
// non recursive - should be faster
foreach ($parents as $parentid) {
$parentcontext = get_context_instance_by_id($parentid);
if (isset($capabilities[$parentcontext->id][$capability])) {
return ($capabilities[$parentcontext->id][$capability]);
}
}
// finally check system context
$parentcontext = get_context_instance(CONTEXT_SYSTEM);
$permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
break;
case CONTEXT_GROUP: // 1 to 1 to course
$courseid = groups_get_course($context->instanceid);
$parentcontext = get_context_instance(CONTEXT_COURSE, $courseid);
$permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
break;
case CONTEXT_MODULE: // 1 to 1 to course
$cm = get_record('course_modules','id',$context->instanceid);
$parentcontext = get_context_instance(CONTEXT_COURSE, $cm->course);
$permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
break;
case CONTEXT_BLOCK: // not necessarily 1 to 1 to course
$block = get_record('block_instance','id',$context->instanceid);
if ($block->pagetype == 'course-view') {
$parentcontext = get_context_instance(CONTEXT_COURSE, $block->pageid); // needs check
} else {
$parentcontext = get_context_instance(CONTEXT_SYSTEM);
}
// ignore the $switchroleactive beause we want the real block view capability defined in system context
$permission = capability_search($capability, $parentcontext, $capabilities, false);
break;
default:
error ('This is an unknown context (' . $context->contextlevel . ') in capability_search!');
return false;
}
return $permission;
}
/**
* auxillary function for load_user_capabilities()
* checks if context c1 is a parent (or itself) of context c2
* @param int $c1 - context id of context 1
* @param int $c2 - context id of context 2
* @return bool
*/
function is_parent_context($c1, $c2) {
static $parentsarray;
// context can be itself and this is ok
if ($c1 == $c2) {
return true;
}
// hit in cache?
if (isset($parentsarray[$c1][$c2])) {
return $parentsarray[$c1][$c2];
}
if (!$co2 = get_record('context', 'id', $c2)) {
return false;
}
if (!$parents = get_parent_contexts($co2)) {
return false;
}
foreach ($parents as $parent) {
$parentsarray[$parent][$c2] = true;
}
if (in_array($c1, $parents)) {
return true;
} else { // else not a parent, set the cache anyway
$parentsarray[$c1][$c2] = false;
return false;
}
}
/**
* auxillary function for load_user_capabilities()
* handler in usort() to sort contexts according to level
* @param object contexta
* @param object contextb
* @return int
*/
function roles_context_cmp($contexta, $contextb) {
if ($contexta->contextlevel == $contextb->contextlevel) {
return 0;
}
return ($contexta->contextlevel < $contextb->contextlevel) ? -1 : 1;
}
/**
* It will build an array of all the capabilities at each level
* i.e. site/metacourse/course_category/course/moduleinstance
* Note we should only load capabilities if they are explicitly assigned already,
* we should not load all module's capability!
*
* [Capabilities] => [26][forum_post] = 1
* [26][forum_start] = -8990
* [26][forum_edit] = -1
* [273][blah blah] = 1
* [273][blah blah blah] = 2
*
* @param $capability string - Only get a specific capability (string)
* @param $context object - Only get capabilities for a specific context object
* @param $userid integer - the id of the user whose capabilities we want to load
* @param $checkenrolments boolean - Should we checkenrolment plugins (potentially expensive)
* @return array of permissions (or nothing if they get assigned to $USER)
*/
function load_user_capability($capability='', $context=NULL, $userid=NULL, $checkenrolments=true) {
global $USER, $CFG;
// this flag has not been set!
// (not clean install, or upgraded successfully to 1.7 and up)
if (empty($CFG->rolesactive)) {
return false;
}
if (empty($userid)) {
if (empty($USER->id)) { // We have no user to get capabilities for
debugging('User not logged in for load_user_capability!');
return false;
}
unset($USER->capabilities); // We don't want possible older capabilites hanging around
if ($checkenrolments) { // Call "enrol" system to ensure that we have the correct picture
check_enrolment_plugins($USER);
}
$userid = $USER->id;
$otheruserid = false;
} else {
if (!$user = get_record('user', 'id', $userid)) {
debugging('Non-existent userid in load_user_capability!');
return false;
}
if ($checkenrolments) { // Call "enrol" system to ensure that we have the correct picture
check_enrolment_plugins($user);
}
$otheruserid = $userid;
}
/// First we generate a list of all relevant contexts of the user
$usercontexts = array();
if ($context) { // if context is specified
$usercontexts = get_parent_contexts($context);
$usercontexts[] = $context->id; // Add the current context as well
} else { // else, we load everything
if ($userroles = get_records('role_assignments','userid',$userid)) {
foreach ($userroles as $userrole) {
if (!in_array($userrole->contextid, $usercontexts)) {
$usercontexts[] = $userrole->contextid;
}
}
}
}
/// Set up SQL fragments for searching contexts
if ($usercontexts) {
$listofcontexts = '('.implode(',', $usercontexts).')';
$searchcontexts1 = "c1.id IN $listofcontexts AND";
} else {
$searchcontexts1 = '';
}
if ($capability) {
// the doanything may override the requested capability
$capsearch = " AND (rc.capability = '$capability' OR rc.capability = 'moodle/site:doanything') ";
} else {
$capsearch ="";
}
/// Then we use 1 giant SQL to bring out all relevant capabilities.
/// The first part gets the capabilities of orginal role.
/// The second part gets the capabilities of overriden roles.
$siteinstance = get_context_instance(CONTEXT_SYSTEM);
$capabilities = array(); // Reinitialize.
// SQL for normal capabilities
$SQL1 = "SELECT rc.capability, c1.id as id1, c1.id as id2, (c1.contextlevel * 100) AS aggrlevel,
SUM(rc.permission) AS sum
FROM
{$CFG->prefix}role_assignments ra,
{$CFG->prefix}role_capabilities rc,
{$CFG->prefix}context c1
WHERE
ra.contextid=c1.id AND
ra.roleid=rc.roleid AND
ra.userid=$userid AND
$searchcontexts1
rc.contextid=$siteinstance->id
$capsearch
GROUP BY
rc.capability, c1.id, c1.contextlevel * 100
HAVING
SUM(rc.permission) != 0
UNION ALL
SELECT rc.capability, c1.id as id1, c2.id as id2, (c1.contextlevel * 100 + c2.contextlevel) AS aggrlevel,
SUM(rc.permission) AS sum
FROM
{$CFG->prefix}role_assignments ra LEFT JOIN
{$CFG->prefix}role_capabilities rc on ra.roleid = rc.roleid LEFT JOIN
{$CFG->prefix}context c1 on ra.contextid = c1.id LEFT JOIN
{$CFG->prefix}context c2 on rc.contextid = c2.id LEFT JOIN
{$CFG->prefix}context_rel cr on cr.c1 = c2.id
WHERE
ra.userid=$userid AND
$searchcontexts1
rc.contextid != $siteinstance->id
$capsearch
AND cr.c2 = c1.id
GROUP BY
rc.capability, c1.id, c2.id, c1.contextlevel * 100 + c2.contextlevel
HAVING
SUM(rc.permission) != 0
ORDER BY
aggrlevel ASC";
if (!$rs = get_recordset_sql($SQL1)) {
error("Query failed in load_user_capability.");
}
if ($rs && $rs->RecordCount() > 0) {
while ($caprec = rs_fetch_next_record($rs)) {
$array = (array)$caprec;
$temprecord = new object;
foreach ($array as $key=>$val) {
if ($key == 'aggrlevel') {
$temprecord->contextlevel = $val;
} else {
$temprecord->{$key} = $val;
}
}
$capabilities[] = $temprecord;
}
rs_close($rs);
}
// SQL for overrides
// this is take out because we have no way of making sure c1 is indeed related to c2 (parent)
// if we do not group by sum, it is possible to have multiple records of rc.capability, c1.id, c2.id, tuple having
// different values, we can maually sum it when we go through the list