mirrored from git://git.moodle.org/moodle.git
/
accesslib.php
executable file
·3421 lines (2832 loc) · 115 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
/**
* 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);
$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
/**
* Loads the capabilities for the default guest role to the current user in a
* specific context.
* @return object
*/
function load_guest_role($context=NULL) {
global $USER;
static $guestrole;
if (!isloggedin()) {
return false;
}
if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM)) {
return false;
}
if (empty($context)) {
$context = $sitecontext;
}
if (empty($guestrole)) {
if (!$guestrole = get_guest_role()) {
return false;
}
}
$searchcontexts = array(); // get_child_contexts($context); SEE MDL-8385
array_push($searchcontexts, $context->id);
foreach ($searchcontexts as $scid) {
if ($capabilities = get_records_select('role_capabilities',
"roleid = $guestrole->id
AND contextid = $scid")) {
foreach ($capabilities as $capability) {
$USER->capabilities[$scid][$capability->capability] = $capability->permission;
}
}
}
has_capability('clearcache');
return true;
}
/**
* Load default not logged in role capabilities when user is not logged in
* @return bool
*/
function load_notloggedin_role() {
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 ($capabilities = get_records_select('role_capabilities',
"roleid = $CFG->notloggedinroleid AND contextid = $sitecontext->id")) {
foreach ($capabilities as $capability) {
$USER->capabilities[$sitecontext->id][$capability->capability] = $capability->permission;
}
has_capability('clearcache');
}
return true;
}
/**
* Load default not logged in role capabilities when user is not logged in
* @return bool
*/
function load_defaultuser_role() {
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;
}
}
if ($capabilities = get_records_select('role_capabilities',
"roleid = $CFG->defaultuserroleid AND contextid = $sitecontext->id AND permission <> 0")) {
foreach ($capabilities as $capability) {
if (!isset($USER->capabilities[$sitecontext->id][$capability->capability])) { // Don't overwrite
$USER->capabilities[$sitecontext->id][$capability->capability] = $capability->permission;
}
}
// SPECIAL EXCEPTION: If the default user role is actually a guest role, then
// remove some capabilities so this user doesn't get confused with a REAL guest
if (isset($USER->capabilities[$sitecontext->id]['moodle/legacy:guest']) and $USER->username != 'guest') {
unset($USER->capabilities[$sitecontext->id]['moodle/legacy:guest']);
unset($USER->capabilities[$sitecontext->id]['moodle/course:view']); // No access to courses by default
}
has_capability('clearcache');
}
return true;
}
/**
* Get the default guest role
* @return object role
*/
function get_guest_role() {
if ($roles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW)) {
return array_shift($roles); // Pick the first one
} else {
return false;
}
}
/**
* This functions get all the course categories in proper order
* @param object $context
* @param int $type
* @return array of contextids
*/
function get_parent_cats($context, $type) {
$parents = array();
switch ($type) {
case CONTEXT_COURSECAT:
if (!$cat = get_record('course_categories','id',$context->instanceid)) {
break;
}
while (!empty($cat->parent)) {
if (!$context = get_context_instance(CONTEXT_COURSECAT, $cat->parent)) {
break;
}
$parents[] = $context->id;
$cat = get_record('course_categories','id',$cat->parent);
}
break;
case CONTEXT_COURSE:
if (!$course = get_record('course', 'id', $context->instanceid)) {
break;
}
if (!$catinstance = get_context_instance(CONTEXT_COURSECAT, $course->category)) {
break;
}
$parents[] = $catinstance->id;
if (!$cat = get_record('course_categories','id',$course->category)) {
break;
}
while (!empty($cat->parent)) {
if (!$context = get_context_instance(CONTEXT_COURSECAT, $cat->parent)) {
break;
}
$parents[] = $context->id;
$cat = get_record('course_categories','id',$cat->parent);
}
break;
default:
break;
}
return array_reverse($parents);
}
/**
* 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);
}
}
/**
* This function returns whether the current user has the capability of performing a function
* For example, we can do has_capability('mod/forum:replypost',$cm) in forum
* only one of the 4 (moduleinstance, courseid, site, userid) would be set at 1 time
* This is a recursive funciton.
* @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()) {
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.
$cachekey = $capability.'_'.$context->id.'_'.intval($userid).'_'.intval($doanything);
if (isset($capcache[$cachekey])) {
return $capcache[$cachekey];
}
/// Set up user's default roles
if (empty($userid) && empty($USER->capabilities)) { // Real user, first time here
if (isloggedin()) {
load_defaultuser_role(); // All users get this by default
} else {
load_notloggedin_role(); // others get this by default
}
}
/// Load up the capabilities list or item as necessary
if ($userid && (($USER === NULL) or ($userid != $USER->id))) {
if (empty($USER->id) or ($userid != $USER->id)) {
$capabilities = load_user_capability($capability, $context, $userid); // expensive
} else { //$USER->id == $userid
$capabilities = empty($USER->capabilities) ? NULL : $USER->capabilities;
}
} else { // no userid
$capabilities = empty($USER->capabilities) ? NULL : $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;
}
}
switch ($context->contextlevel) {
case CONTEXT_COURSECAT:
// Check parent cats.
$parentcats = get_parent_cats($context, CONTEXT_COURSECAT);
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, CONTEXT_COURSE);
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.
$group = get_record('groups','id',$context->instanceid);
$courseinstance = get_context_instance(CONTEXT_COURSE, $group->courseid);
$parentcats = get_parent_cats($courseinstance, CONTEXT_COURSE);
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, CONTEXT_COURSE)) {
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, CONTEXT_COURSE);
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;
}
} else { // if not course-view type of blocks, check site
if (isset($capabilities[$sitecontext->id]['do_anything'])) {
$result = (0 < $capabilities[$sitecontext->id]['do_anything']);
$capcache[$cachekey] = $result;
return $result;
}
}
break;
default:
// CONTEXT_SYSTEM: CONTEXT_PERSONAL: CONTEXT_USER:
// Do nothing.
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
* @return permission (int)
*/
function capability_search($capability, $context, $capabilities, $switchroleactive=false) {
global $USER, $CFG;
if (!isset($context->id)) {
return 0;
}
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_COURSECAT: // Coursecat -> coursecat or site
$coursecat = get_record('course_categories','id',$context->instanceid);
if (!empty($coursecat->parent)) { // return parent value if it exists
$parentcontext = get_context_instance(CONTEXT_COURSECAT, $coursecat->parent);
} else { // else return site value
$parentcontext = get_context_instance(CONTEXT_SYSTEM);
}
$permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
break;
case CONTEXT_COURSE: // 1 to 1 to course cat
if (empty($switchroleactive)) {
// find the course cat, and return its value
$course = get_record('course','id',$context->instanceid);
$parentcontext = get_context_instance(CONTEXT_COURSECAT, $course->category);
$permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
}
break;
case CONTEXT_GROUP: // 1 to 1 to course
$group = get_record('groups','id',$context->instanceid);
$parentcontext = get_context_instance(CONTEXT_COURSE, $group->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);
}
$permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
break;
default:
error ('This is an unknown context!');
return false;
}
return $permission;
}
// auxillary function for load_user_capabilities()
// if context c1 is a parent (or itself) of context c2
// returns true
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
*/
function roles_context_cmp($contexta, $contextb) {
if ($contexta->contextlevel == $contextb->contextlevel) {
return 0;
}
return ($contexta->contextlevel < $contextb->contextlevel) ? -1 : 1;
}
/**
* This function should be called immediately after a login, when $USER is set.
* 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
* @return array of permissions (or nothing if they get assigned to $USER)
*/
function load_user_capability($capability='', $context = NULL, $userid='') {
global $USER, $CFG;
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
check_enrolment_plugins($USER); // Call "enrol" system to ensure that we have the correct picture
$userid = $USER->id;
$otheruserid = false;
} else {
if (!$user = get_record('user', 'id', $userid)) {
debugging('Non-existent userid in load_user_capability!');
return false;
}
check_enrolment_plugins($user); // Ensure that we have the correct picture
$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) {
$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) {
$capsearch = " AND rc.capability = '$capability' ";
} else {
$capsearch ="";
}
/// Set up SQL fragments for timestart, timeend etc
$now = time();
$timesql = "AND ((ra.timestart = 0 OR ra.timestart < $now) AND (ra.timeend = 0 OR ra.timeend > $now))";
/// 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
$timesql
GROUP BY
rc.capability, (c1.contextlevel * 100), c1.id
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
$SQL2 = "SELECT rc.capability, c1.id as id1, c2.id as id2, (c1.contextlevel * 100 + c2.contextlevel) AS aggrlevel,
rc.permission AS sum
FROM
{$CFG->prefix}role_assignments ra,
{$CFG->prefix}role_capabilities rc,
{$CFG->prefix}context c1,
{$CFG->prefix}context c2
WHERE
ra.contextid=c1.id AND
ra.roleid=rc.roleid AND
ra.userid=$userid AND
rc.contextid=c2.id AND
$searchcontexts1
rc.contextid != $siteinstance->id
$capsearch
$timesql
GROUP BY
rc.capability, (c1.contextlevel * 100 + c2.contextlevel), c1.id, c2.id, rc.permission
ORDER BY
aggrlevel ASC
";
if (!$rs = get_recordset_sql($SQL2)) {
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;
}
}
// for overrides, we have to make sure that context2 is a child of context1
// otherwise the combination makes no sense
if (is_parent_context($temprecord->id1, $temprecord->id2)) {
$capabilities[] = $temprecord;
} // only write if relevant
}
rs_close($rs);
}
// this step sorts capabilities according to the contextlevel
// it is very important because the order matters when we
// go through each capabilities later. (i.e. higher level contextlevel
// will override lower contextlevel settings
usort($capabilities, 'roles_context_cmp');
/* so up to this point we should have somethign like this
* $capabilities[1] ->contextlevel = 1000
->module = SITEID
->capability = do_anything
->id = 1 (id is the context id)
->sum = 0
* $capabilities[2] ->contextlevel = 1000
->module = SITEID
->capability = post_messages
->id = 1
->sum = -9000
* $capabilittes[3] ->contextlevel = 3000
->module = course
->capability = view_course_activities
->id = 25
->sum = 1
* $capabilittes[4] ->contextlevel = 3000
->module = course
->capability = view_course_activities
->id = 26
->sum = 0 (this is another course)
* $capabilities[5] ->contextlevel = 3050
->module = course
->capability = view_course_activities
->id = 25 (override in course 25)
->sum = -1
* ....
* now we proceed to write the session array, going from top to bottom
* at anypoint, we need to go up and check parent to look for prohibit
*/
// print_object($capabilities);
/* This is where we write to the actualy capabilities array
* what we need to do from here on is
* going down the array from lowest level to highest level
* 1) recursively check for prohibit,
* if any, we write prohibit
* else, we write the value
* 2) at an override level, we overwrite current level
* if it's not set to prohibit already, and if different
* ........ that should be it ........
*/
// This is the flag used for detecting the current context level. Since we are going through
// the array in ascending order of context level. For normal capabilities, there should only
// be 1 value per (capability, contextlevel, context), because they are already summed. But,
// for overrides, since we are processing them separate, we need to sum the relevcant entries.
// We set this flag when we hit a new level.
// If the flag is already set, we keep adding (summing), otherwise, we just override previous
// settings (from lower level contexts)
$capflags = array(); // (contextid, contextlevel, capability)
$usercap = array(); // for other user's capabilities
foreach ($capabilities as $capability) {
if (!$context = get_context_instance_by_id($capability->id2)) {
continue; // incorrect stale context
}
if (!empty($otheruserid)) { // we are pulling out other user's capabilities, do not write to session
if (capability_prohibits($capability->capability, $context, $capability->sum, $usercap)) {
$usercap[$capability->id2][$capability->capability] = CAP_PROHIBIT;
continue;
}
if (isset($usercap[$capability->id2][$capability->capability])) { // use isset because it can be sum 0
if (!empty($capflags[$capability->id2][$capability->contextlevel][$capability->capability])) {
$usercap[$capability->id2][$capability->capability] += $capability->sum;
} else { // else we override, and update flag
$usercap[$capability->id2][$capability->capability] = $capability->sum;
$capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
}
} else {
$usercap[$capability->id2][$capability->capability] = $capability->sum;
$capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
}
} else {
if (capability_prohibits($capability->capability, $context, $capability->sum)) { // if any parent or parent's parent is set to prohibit
$USER->capabilities[$capability->id2][$capability->capability] = CAP_PROHIBIT;
continue;
}
// if no parental prohibit set
// just write to session, i am not sure this is correct yet
// since 3050 shows up after 3000, and 3070 shows up after 3050,
// it should be ok just to overwrite like this, provided that there's no
// parental prohibits
// we need to write even if it's 0, because it could be an inherit override
if (isset($USER->capabilities[$capability->id2][$capability->capability])) {
if (!empty($capflags[$capability->id2][$capability->contextlevel][$capability->capability])) {
$USER->capabilities[$capability->id2][$capability->capability] += $capability->sum;
} else { // else we override, and update flag
$USER->capabilities[$capability->id2][$capability->capability] = $capability->sum;
$capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
}
} else {
$USER->capabilities[$capability->id2][$capability->capability] = $capability->sum;
$capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
}
}
}
// now we don't care about the huge array anymore, we can dispose it.
unset($capabilities);
unset($capflags);
if (!empty($otheruserid)) {
return $usercap; // return the array
}
}
/*
* A convenience function to completely load all the capabilities
* for the current user. This is what gets called from login, for example.
*/
function load_all_capabilities() {
global $USER;
if (empty($USER->username)) {
return;
}
load_user_capability(); // Load basic capabilities assigned to this user
if ($USER->username == 'guest') {
load_guest_role(); // All non-guest users get this by default
} else {
load_defaultuser_role(); // All non-guest users get this by default
}
}
/*
* Check all the login enrolment information for the given user object
* by querying the enrolment plugins
*/
function check_enrolment_plugins(&$user) {
global $CFG;
static $inprogress; // To prevent this function being called more than once in an invocation
if (!empty($inprogress[$user->id])) {