forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
accesslib.php
executable file
·6320 lines (5600 loc) · 218 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
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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 3 of the License, or
// (at your option) any later version.
//
// Moodle 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.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains functions for managing user access
*
* <b>Public API vs internals</b>
*
* General users probably only care about
*
* Context handling
* - get_context_instance()
* - get_context_instance_by_id()
* - get_parent_contexts()
* - get_child_contexts()
*
* Whether the user can do something...
* - has_capability()
* - has_any_capability()
* - has_all_capabilities()
* - require_capability()
* - require_login() (from moodlelib)
*
* What courses has this user access to?
* - get_user_courses_bycap()
*
* What users can do X in this context?
* - get_users_by_capability()
*
* Enrol/unenrol
* - enrol_into_course()
* - role_assign()/role_unassign()
*
*
* Advanced use
* - load_all_capabilities()
* - reload_all_capabilities()
* - has_capability_in_accessdata()
* - is_siteadmin()
* - get_user_access_sitewide()
* - load_subcontext()
* - get_role_access_bycontext()
*
* <b>Name conventions</b>
*
* "ctx" means context
*
* <b>accessdata</b>
*
* Access control data is held in the "accessdata" array
* which - for the logged-in user, will be in $USER->access
*
* For other users can be generated and passed around (but may also be cached
* against userid in $ACCESSLIB_PRIVATE->accessdatabyuser.
*
* $accessdata is a multidimensional array, holding
* role assignments (RAs), role-capabilities-perm sets
* (role defs) and a list of courses we have loaded
* data for.
*
* Things are keyed on "contextpaths" (the path field of
* the context table) for fast walking up/down the tree.
* <code>
* $accessdata[ra][$contextpath]= array($roleid)
* [$contextpath]= array($roleid)
* [$contextpath]= array($roleid)
* </code>
*
* Role definitions are stored like this
* (no cap merge is done - so it's compact)
*
* <code>
* $accessdata[rdef][$contextpath:$roleid][mod/forum:viewpost] = 1
* [mod/forum:editallpost] = -1
* [mod/forum:startdiscussion] = -1000
* </code>
*
* See how has_capability_in_accessdata() walks up/down the tree.
*
* Normally - specially for the logged-in user, we only load
* rdef and ra down to the course level, but not below. This
* keeps accessdata small and compact. Below-the-course ra/rdef
* are loaded as needed. We keep track of which courses we
* have loaded ra/rdef in
* <code>
* $accessdata[loaded] = array($contextpath, $contextpath)
* </code>
*
* <b>Stale accessdata</b>
*
* For the logged-in user, accessdata is long-lived.
*
* On each pageload we load $ACCESSLIB_PRIVATE->dirtycontexts which lists
* context paths affected by changes. Any check at-or-below
* a dirty context will trigger a transparent reload of accessdata.
*
* Changes at the sytem level will force the reload for everyone.
*
* <b>Default role caps</b>
* The default role assignment is not in the DB, so we
* add it manually to accessdata.
*
* This means that functions that work directly off the
* DB need to ensure that the default role caps
* are dealt with appropriately.
*
* @package moodlecore
* @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/** permission definitions */
define('CAP_INHERIT', 0);
/** permission definitions */
define('CAP_ALLOW', 1);
/** permission definitions */
define('CAP_PREVENT', -1);
/** permission definitions */
define('CAP_PROHIBIT', -1000);
/** context definitions */
define('CONTEXT_SYSTEM', 10);
/** context definitions */
define('CONTEXT_USER', 30);
/** context definitions */
define('CONTEXT_COURSECAT', 40);
/** context definitions */
define('CONTEXT_COURSE', 50);
/** context definitions */
define('CONTEXT_MODULE', 70);
/** context definitions */
define('CONTEXT_BLOCK', 80);
/** capability risks - see {@link http://docs.moodle.org/en/Development:Hardening_new_Roles_system} */
define('RISK_MANAGETRUST', 0x0001);
/** capability risks - see {@link http://docs.moodle.org/en/Development:Hardening_new_Roles_system} */
define('RISK_CONFIG', 0x0002);
/** capability risks - see {@link http://docs.moodle.org/en/Development:Hardening_new_Roles_system} */
define('RISK_XSS', 0x0004);
/** capability risks - see {@link http://docs.moodle.org/en/Development:Hardening_new_Roles_system} */
define('RISK_PERSONAL', 0x0008);
/** capability risks - see {@link http://docs.moodle.org/en/Development:Hardening_new_Roles_system} */
define('RISK_SPAM', 0x0010);
/** capability risks - see {@link http://docs.moodle.org/en/Development:Hardening_new_Roles_system} */
define('RISK_DATALOSS', 0x0020);
/** rolename displays - the name as defined in the role definition */
define('ROLENAME_ORIGINAL', 0);
/** rolename displays - the name as defined by a role alias */
define('ROLENAME_ALIAS', 1);
/** rolename displays - Both, like this: Role alias (Original)*/
define('ROLENAME_BOTH', 2);
/** rolename displays - the name as defined in the role definition and the shortname in brackets*/
define('ROLENAME_ORIGINALANDSHORT', 3);
/** rolename displays - the name as defined by a role alias, in raw form suitable for editing*/
define('ROLENAME_ALIAS_RAW', 4);
/** size limit for context cache */
if (!defined('MAX_CONTEXT_CACHE_SIZE')) {
define('MAX_CONTEXT_CACHE_SIZE', 5000);
}
/**
* Although this looks like a global variable, it isn't really.
*
* It is just a private implementation detail to accesslib that MUST NOT be used elsewhere.
* It is used to cache various bits of data between function calls for performance reasons.
* Sadly, a PHP global variale is the only way to impleemnt this, withough rewriting everything
* as methods of a class, instead of functions.
*
* @global stdClass $ACCESSLIB_PRIVATE
* @name $ACCESSLIB_PRIVATE
*/
$ACCESSLIB_PRIVATE = new stdClass;
$ACCESSLIB_PRIVATE->contexts = array(); // Cache of context objects by level and instance
$ACCESSLIB_PRIVATE->contextsbyid = array(); // Cache of context objects by id
$ACCESSLIB_PRIVATE->systemcontext = null; // Used in get_system_context
$ACCESSLIB_PRIVATE->dirtycontexts = null; // Dirty contexts cache
$ACCESSLIB_PRIVATE->accessdatabyuser = array(); // Holds the $accessdata structure for users other than $USER
$ACCESSLIB_PRIVATE->roledefinitions = array(); // role definitions cache - helps a lot with mem usage in cron
$ACCESSLIB_PRIVATE->croncache = array(); // Used in get_role_access
$ACCESSLIB_PRIVATE->preloadedcourses = array(); // Used in preload_course_contexts.
$ACCESSLIB_PRIVATE->capabilitynames = null; // Used in is_valid_capability (only in developer debug mode)
/**
* Clears accesslib's private caches. ONLY BE USED BY UNIT TESTS
*
* This method should ONLY BE USED BY UNIT TESTS. It clears all of
* accesslib's private caches. You need to do this before setting up test data,
* and also at the end fo the tests.
* @global object
* @global object
* @global object
*/
function accesslib_clear_all_caches_for_unit_testing() {
global $UNITTEST, $USER, $ACCESSLIB_PRIVATE;
if (empty($UNITTEST->running)) {
throw new coding_exception('You must not call clear_all_caches outside of unit tests.');
}
$ACCESSLIB_PRIVATE->contexts = array();
$ACCESSLIB_PRIVATE->contextsbyid = array();
$ACCESSLIB_PRIVATE->systemcontext = null;
$ACCESSLIB_PRIVATE->dirtycontexts = null;
$ACCESSLIB_PRIVATE->accessdatabyuser = array();
$ACCESSLIB_PRIVATE->roledefinitions = array();
$ACCESSLIB_PRIVATE->croncache = array();
$ACCESSLIB_PRIVATE->preloadedcourses = array();
$ACCESSLIB_PRIVATE->capabilitynames = null;
unset($USER->access);
}
/**
* Private function. Add a context object to accesslib's caches.
* @global object
* @param object $context
*/
function cache_context($context) {
global $ACCESSLIB_PRIVATE;
// If there are too many items in the cache already, remove items until
// there is space
while (count($ACCESSLIB_PRIVATE->contextsbyid) >= MAX_CONTEXT_CACHE_SIZE) {
$first = reset($ACCESSLIB_PRIVATE->contextsbyid);
unset($ACCESSLIB_PRIVATE->contextsbyid[$first->id]);
unset($ACCESSLIB_PRIVATE->contexts[$first->contextlevel][$first->instanceid]);
}
$ACCESSLIB_PRIVATE->contexts[$context->contextlevel][$context->instanceid] = $context;
$ACCESSLIB_PRIVATE->contextsbyid[$context->id] = $context;
}
/**
* This is really slow!!! do not use above course context level
*
* @global object
* @param int $roleid
* @param object $context
* @return array
*/
function get_role_context_caps($roleid, $context) {
global $DB;
//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 = $DB->get_records('role_capabilities', array('roleid'=>$roleid, '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 = array_keys(get_child_contexts($context));
foreach ($searchcontexts as $cid) {
if ($capabilities = $DB->get_records('role_capabilities', array('roleid'=>$roleid, '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;
}
/**
* Gets the accessdata for role "sitewide" (system down to course)
*
* @global object
* @global object
* @param int $roleid
* @param array $accessdata defaults to null
* @return array
*/
function get_role_access($roleid, $accessdata=NULL) {
global $CFG, $DB;
/* Get it in 1 cheap DB query...
* - relevant role caps at the root and down
* to the course level - but not below
*/
if (is_null($accessdata)) {
$accessdata = array(); // named list
$accessdata['ra'] = array();
$accessdata['rdef'] = array();
$accessdata['loaded'] = array();
}
//
// Overrides for the role IN ANY CONTEXTS
// down to COURSE - not below -
//
$sql = "SELECT ctx.path,
rc.capability, rc.permission
FROM {context} ctx
JOIN {role_capabilities} rc
ON rc.contextid=ctx.id
WHERE rc.roleid = ?
AND ctx.contextlevel <= ".CONTEXT_COURSE."
ORDER BY ctx.depth, ctx.path";
$params = array($roleid);
// we need extra caching in CLI scripts and cron
if (CLI_SCRIPT) {
global $ACCESSLIB_PRIVATE;
if (!isset($ACCESSLIB_PRIVATE->croncache[$roleid])) {
$ACCESSLIB_PRIVATE->croncache[$roleid] = array();
if ($rs = $DB->get_recordset_sql($sql, $params)) {
foreach ($rs as $rd) {
$ACCESSLIB_PRIVATE->croncache[$roleid][] = $rd;
}
$rs->close();
}
}
foreach ($ACCESSLIB_PRIVATE->croncache[$roleid] as $rd) {
$k = "{$rd->path}:{$roleid}";
$accessdata['rdef'][$k][$rd->capability] = $rd->permission;
}
} else {
if ($rs = $DB->get_recordset_sql($sql, $params)) {
foreach ($rs as $rd) {
$k = "{$rd->path}:{$roleid}";
$accessdata['rdef'][$k][$rd->capability] = $rd->permission;
}
unset($rd);
$rs->close();
}
}
return $accessdata;
}
/**
* Gets the accessdata for role "sitewide" (system down to course)
*
* @global object
* @global object
* @param int $roleid
* @param array $accessdata defaults to null
* @return array
*/
function get_default_frontpage_role_access($roleid, $accessdata=NULL) {
global $CFG, $DB;
$frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
$base = '/'. SYSCONTEXTID .'/'. $frontpagecontext->id;
//
// Overrides for the role in any contexts related to the course
//
$sql = "SELECT ctx.path,
rc.capability, rc.permission
FROM {context} ctx
JOIN {role_capabilities} rc
ON rc.contextid=ctx.id
WHERE rc.roleid = ?
AND (ctx.id = ".SYSCONTEXTID." OR ctx.path LIKE ?)
AND ctx.contextlevel <= ".CONTEXT_COURSE."
ORDER BY ctx.depth, ctx.path";
$params = array($roleid, "$base/%");
if ($rs = $DB->get_recordset_sql($sql, $params)) {
foreach ($rs as $rd) {
$k = "{$rd->path}:{$roleid}";
$accessdata['rdef'][$k][$rd->capability] = $rd->permission;
}
unset($rd);
$rs->close();
}
return $accessdata;
}
/**
* Get the default guest role
*
* @global object
* @global object
* @return object role
*/
function get_guest_role() {
global $CFG, $DB;
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 = $DB->get_record('role', array('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();
}
}
}
/**
* Check whether a user has a paritcular capability in a given context.
*
* For example::
* $context = get_context_instance(CONTEXT_MODULE, $cm->id);
* has_capability('mod/forum:replypost',$context)
*
* By default checks the capabilties of the current user, but you can pass a
* different userid. By default will return true for admin-like users who have the
* moodle/site:doanything capability, but you can override that with the fourth argument.
*
* @param string $capability the name of the capability to check. For example mod/forum:view
* @param object $context the context to check the capability in. You normally get this with {@link get_context_instance}.
* @param integer $userid A user id. By default (null) checks the permissions of the current user.
* @param boolean $doanything If false, ignore the special moodle/site:doanything capability that admin-like roles have.
* @return boolean true if the user has this capability. Otherwise false.
*/
function has_capability($capability, $context, $userid=NULL, $doanything=true) {
global $USER, $CFG, $DB, $SCRIPT, $ACCESSLIB_PRIVATE;
if (during_initial_install()) {
if ($SCRIPT === "/$CFG->admin/index.php" or $SCRIPT === "/$CFG->admin/cliupgrade.php") {
// we are in an installer - roles can not work yet
return true;
} else {
return false;
}
}
// the original $CONTEXT here was hiding serious errors
// for security reasons do not reuse previous context
if (empty($context)) {
debugging('Incorrect context specified');
return false;
}
/// Some sanity checks
if (debugging('',DEBUG_DEVELOPER)) {
if (!is_valid_capability($capability)) {
debugging('Capability "'.$capability.'" was not found! This should be fixed in code.');
}
if (!is_bool($doanything)) {
debugging('Capability parameter "doanything" is wierd ("'.$doanything.'"). This should be fixed in code.');
}
}
if (empty($userid)) { // we must accept null, 0, '0', '' etc. in $userid
if (empty($USER->id)) {
// Session not set up yet.
$userid = 0;
} else {
$userid = $USER->id;
}
}
if (is_null($context->path) or $context->depth == 0) {
//this should not happen
$contexts = array(SYSCONTEXTID, $context->id);
$context->path = '/'.SYSCONTEXTID.'/'.$context->id;
debugging('Context id '.$context->id.' does not have valid path, please use build_context_path()', DEBUG_DEVELOPER);
} else {
$contexts = explode('/', $context->path);
array_shift($contexts);
}
if (CLI_SCRIPT && !isset($USER->access)) {
// In cron, some modules setup a 'fake' $USER,
// ensure we load the appropriate accessdata.
if (isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
$ACCESSLIB_PRIVATE->dirtycontexts = NULL; //load fresh dirty contexts
} else {
load_user_accessdata($userid);
$ACCESSLIB_PRIVATE->dirtycontexts = array();
}
$USER->access = $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
} else if (isset($USER->id) && ($USER->id == $userid) && !isset($USER->access)) {
// caps not loaded yet - better to load them to keep BC with 1.8
// not-logged-in user or $USER object set up manually first time here
load_all_capabilities();
$ACCESSLIB_PRIVATE->accessdatabyuser = array(); // reset the cache for other users too, the dirty contexts are empty now
$ACCESSLIB_PRIVATE->roledefinitions = array();
}
// Load dirty contexts list if needed
if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
if (isset($USER->access['time'])) {
$ACCESSLIB_PRIVATE->dirtycontexts = get_dirty_contexts($USER->access['time']);
}
else {
$ACCESSLIB_PRIVATE->dirtycontexts = array();
}
}
// Careful check for staleness...
if (count($ACCESSLIB_PRIVATE->dirtycontexts) !== 0 and is_contextpath_dirty($contexts, $ACCESSLIB_PRIVATE->dirtycontexts)) {
// reload all capabilities - preserving loginas, roleswitches, etc
// and then cleanup any marks of dirtyness... at least from our short
// term memory! :-)
$ACCESSLIB_PRIVATE->accessdatabyuser = array();
$ACCESSLIB_PRIVATE->roledefinitions = array();
if (CLI_SCRIPT) {
load_user_accessdata($userid);
$USER->access = $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
$ACCESSLIB_PRIVATE->dirtycontexts = array();
} else {
reload_all_capabilities();
}
}
// divulge how many times we are called
//// error_log("has_capability: id:{$context->id} path:{$context->path} userid:$userid cap:$capability");
if (isset($USER->id) && ($USER->id == $userid)) { // we must accept strings and integers in $userid
//
// For the logged in user, we have $USER->access
// which will have all RAs and caps preloaded for
// course and above contexts.
//
// Contexts below courses && contexts that do not
// hang from courses are loaded into $USER->access
// on demand, and listed in $USER->access[loaded]
//
if ($context->contextlevel <= CONTEXT_COURSE) {
// Course and above are always preloaded
return has_capability_in_accessdata($capability, $context, $USER->access, $doanything);
}
// Load accessdata for below-the-course contexts
if (!path_inaccessdata($context->path,$USER->access)) {
// error_log("loading access for context {$context->path} for $capability at {$context->contextlevel} {$context->id}");
// $bt = debug_backtrace();
// error_log("bt {$bt[0]['file']} {$bt[0]['line']}");
load_subcontext($USER->id, $context, $USER->access);
}
return has_capability_in_accessdata($capability, $context, $USER->access, $doanything);
}
if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
load_user_accessdata($userid);
}
if ($context->contextlevel <= CONTEXT_COURSE) {
// Course and above are always preloaded
return has_capability_in_accessdata($capability, $context, $ACCESSLIB_PRIVATE->accessdatabyuser[$userid], $doanything);
}
// Load accessdata for below-the-course contexts as needed
if (!path_inaccessdata($context->path, $ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
// error_log("loading access for context {$context->path} for $capability at {$context->contextlevel} {$context->id}");
// $bt = debug_backtrace();
// error_log("bt {$bt[0]['file']} {$bt[0]['line']}");
load_subcontext($userid, $context, $ACCESSLIB_PRIVATE->accessdatabyuser[$userid]);
}
return has_capability_in_accessdata($capability, $context, $ACCESSLIB_PRIVATE->accessdatabyuser[$userid], $doanything);
}
/**
* Check if the user has any one of several capabilities from a list.
*
* This is just a utility method that calls has_capability in a loop. Try to put
* the capabilities that most users are likely to have first in the list for best
* performance.
*
* There are probably tricks that could be done to improve the performance here, for example,
* check the capabilities that are already cached first.
*
* @see has_capability()
* @param array $capabilities an array of capability names.
* @param object $context the context to check the capability in. You normally get this with {@link get_context_instance}.
* @param integer $userid A user id. By default (null) checks the permissions of the current user.
* @param boolean $doanything If false, ignore the special moodle/site:doanything capability that admin-like roles have.
* @return boolean true if the user has any of these capabilities. Otherwise false.
*/
function has_any_capability($capabilities, $context, $userid=NULL, $doanything=true) {
if (!is_array($capabilities)) {
debugging('Incorrect $capabilities parameter in has_any_capabilities() call - must be an array');
return false;
}
foreach ($capabilities as $capability) {
if (has_capability($capability, $context, $userid, $doanything)) {
return true;
}
}
return false;
}
/**
* Check if the user has all the capabilities in a list.
*
* This is just a utility method that calls has_capability in a loop. Try to put
* the capabilities that fewest users are likely to have first in the list for best
* performance.
*
* There are probably tricks that could be done to improve the performance here, for example,
* check the capabilities that are already cached first.
*
* @see has_capability()
* @param array $capabilities an array of capability names.
* @param object $context the context to check the capability in. You normally get this with {@link get_context_instance}.
* @param integer $userid A user id. By default (null) checks the permissions of the current user.
* @param boolean $doanything If false, ignore the special moodle/site:doanything capability that admin-like roles have.
* @return boolean true if the user has all of these capabilities. Otherwise false.
*/
function has_all_capabilities($capabilities, $context, $userid=NULL, $doanything=true) {
if (!is_array($capabilities)) {
debugging('Incorrect $capabilities parameter in has_all_capabilities() call - must be an array');
return false;
}
foreach ($capabilities as $capability) {
if (!has_capability($capability, $context, $userid, $doanything)) {
return false;
}
}
return true;
}
/**
* Check if the user is an admin at the site level
*
* Uses 1 DB query to answer whether a user is an admin at the sitelevel.
* It depends on DB schema >=1.7 but does not depend on the new datastructures
* in v1.9 (context.path, or $USER->access)
*
* Will return true if the userid has any of
* - moodle/site:config
* - moodle/legacy:admin
* - moodle/site:doanything
*
* @global object
* @global object
* @param int $userid
* @returns bool true is user can administer server settings
*/
function is_siteadmin($userid) {
global $CFG, $DB;
$sql = "SELECT SUM(rc.permission)
FROM {role_capabilities} rc
JOIN {context} ctx
ON ctx.id=rc.contextid
JOIN {role_assignments} ra
ON ra.roleid=rc.roleid AND ra.contextid=ctx.id
WHERE ctx.contextlevel=10
AND ra.userid=?
AND rc.capability IN (?, ?, ?)
GROUP BY rc.capability
HAVING SUM(rc.permission) > 0";
$params = array($userid, 'moodle/site:config', 'moodle/legacy:admin', 'moodle/site:doanything');
return $DB->record_exists_sql($sql, $params);
}
/**
* Check whether a role is an admin at the site level
*
* Will return true if the userid has any of
* - moodle/site:config
* - moodle/legacy:admin
* - moodle/site:doanything
*
* @global object
* @param integer $roleid a role id.
* @return boolean, whether this role is an admin role.
*/
function is_admin_role($roleid) {
global $DB;
$sql = "SELECT 1
FROM {role_capabilities} rc
JOIN {context} ctx ON ctx.id = rc.contextid
WHERE ctx.contextlevel = 10
AND rc.roleid = ?
AND rc.capability IN (?, ?, ?)
GROUP BY rc.capability
HAVING SUM(rc.permission) > 0";
$params = array($roleid, 'moodle/site:config', 'moodle/legacy:admin', 'moodle/site:doanything');
return $DB->record_exists_sql($sql, $params);
}
/**
* Returns all the roles for which is_admin_role($role->id) is true.
*
* @global object
* @return array
*/
function get_admin_roles() {
global $DB;
$sql = "SELECT *
FROM {role} r
WHERE EXISTS (
SELECT 1
FROM {role_capabilities} rc
JOIN {context} ctx ON ctx.id = rc.contextid
WHERE ctx.contextlevel = 10
AND rc.roleid = r.id
AND rc.capability IN (?, ?, ?)
GROUP BY rc.capability
HAVING SUM(rc.permission) > 0
)
ORDER BY r.sortorder";
$params = array('moodle/site:config', 'moodle/legacy:admin', 'moodle/site:doanything');
return $DB->get_records_sql($sql, $params);
}
/**
* @param string $path
* @return string
*/
function get_course_from_path ($path) {
// assume that nothing is more than 1 course deep
if (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
return $matches[1];
}
return false;
}
/**
* @param string $path
* @param array $accessdata
* @return bool
*/
function path_inaccessdata($path, $accessdata) {
// assume that contexts hang from sys or from a course
// this will only work well with stuff that hangs from a course
if (in_array($path, $accessdata['loaded'], true)) {
// error_log("found it!");
return true;
}
$base = '/' . SYSCONTEXTID;
while (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
$path = $matches[1];
if ($path === $base) {
return false;
}
if (in_array($path, $accessdata['loaded'], true)) {
return true;
}
}
return false;
}
/**
*
* Walk the accessdata array and return true/false
*
* Walk the accessdata array and return true/false.
* Deals with prohibits, roleswitching, aggregating
* capabilities, etc.
*
* The main feature of here is being FAST and with no
* side effects.
*
* Notes:
*
* Switch Roles exits early
* -----------------------
* cap checks within a switchrole need to exit early
* in our bottom up processing so they don't "see" that
* there are real RAs that can do all sorts of things.
*
* Switch Role merges with default role
* ------------------------------------
* If you are a teacher in course X, you have at least
* teacher-in-X + defaultloggedinuser-sitewide. So in the
* course you'll have techer+defaultloggedinuser.
* We try to mimic that in switchrole.
*
* Local-most role definition and role-assignment wins
* ---------------------------------------------------
* So if the local context has said 'allow', it wins
* over a high-level context that says 'deny'.
* This is applied when walking rdefs, and RAs.
* Only at the same context the values are SUM()med.
*
* The exception is CAP_PROHIBIT.
*
* "Guest default role" exception
* ------------------------------
*
* See MDL-7513 and $ignoreguest below for details.
*
* The rule is that
*
* IF we are being asked about moodle/legacy:guest
* OR moodle/course:view
* FOR a real, logged-in user
* AND we reached the top of the path in ra and rdef
* AND that role has moodle/legacy:guest === 1...
* THEN we act as if we hadn't seen it.
*
* Note that this function must be kept in synch with has_capability_in_accessdata.
*
* To Do:
* @todo Document how it works
* @todo Rewrite in ASM
*
* @global object
* @param string $capability
* @param object $context
* @param array $accessdata
* @param bool $doanything
* @return bool
*/
function has_capability_in_accessdata($capability, $context, $accessdata, $doanything) {
global $CFG;
$path = $context->path;
// build $contexts as a list of "paths" of the current
// contexts and parents with the order top-to-bottom
$contexts = array($path);
while (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
$path = $matches[1];
array_unshift($contexts, $path);
}
$ignoreguest = false;
if (isset($accessdata['dr'])
&& ($capability == 'moodle/course:view'
|| $capability == 'moodle/legacy:guest')) {
// At the base, ignore rdefs where moodle/legacy:guest
// is set
$ignoreguest = $accessdata['dr'];
}
// Coerce it to an int
$CAP_PROHIBIT = (int)CAP_PROHIBIT;
$cc = count($contexts);
$can = 0;
$capdepth = 0;
//
// role-switches loop
//
if (isset($accessdata['rsw'])) {
// check for isset() is fast
// empty() is slow...
if (empty($accessdata['rsw'])) {
unset($accessdata['rsw']); // keep things fast and unambiguous
break;
}
// From the bottom up...
for ($n=$cc-1;$n>=0;$n--) {
$ctxp = $contexts[$n];
if (isset($accessdata['rsw'][$ctxp])) {
// Found a switchrole assignment
// check for that role _plus_ the default user role
$ras = array($accessdata['rsw'][$ctxp],$CFG->defaultuserroleid);
for ($rn=0;$rn<2;$rn++) {
$roleid = (int)$ras[$rn];
// Walk the path for capabilities
// from the bottom up...
for ($m=$cc-1;$m>=0;$m--) {
$capctxp = $contexts[$m];
if (isset($accessdata['rdef']["{$capctxp}:$roleid"][$capability])) {
$perm = (int)$accessdata['rdef']["{$capctxp}:$roleid"][$capability];
// The most local permission (first to set) wins
// the only exception is CAP_PROHIBIT
if ($can === 0) {
$can = $perm;
} elseif ($perm === $CAP_PROHIBIT) {
$can = $perm;
break;
}
}
}
}
// As we are dealing with a switchrole,
// we return _here_, do _not_ walk up
// the hierarchy any further
if ($can < 1) {
if ($doanything) {
// didn't find it as an explicit cap,
// but maybe the user can doanything in this context...
return has_capability_in_accessdata('moodle/site:doanything', $context, $accessdata, false);
} else {
return false;
}
} else {
return true;
}
}
}
}
//
// Main loop for normal RAs
// From the bottom up...
//
for ($n=$cc-1;$n>=0;$n--) {
$ctxp = $contexts[$n];
if (isset($accessdata['ra'][$ctxp])) {
// Found role assignments on this leaf
$ras = $accessdata['ra'][$ctxp];
$rc = count($ras);
$ctxcan = 0;
$ctxcapdepth = 0;
for ($rn=0;$rn<$rc;$rn++) {
$roleid = (int)$ras[$rn];
$rolecan = 0;
$rolecapdepth = 0;
// Walk the path for capabilities
// from the bottom up...
for ($m=$cc-1;$m>=0;$m--) {
$capctxp = $contexts[$m];
// ignore some guest caps
// at base ra and rdef
if ($ignoreguest == $roleid
&& $n === 0
&& $m === 0
&& isset($accessdata['rdef']["{$capctxp}:$roleid"]['moodle/legacy:guest'])
&& $accessdata['rdef']["{$capctxp}:$roleid"]['moodle/legacy:guest'] > 0) {
continue;
}
if (isset($accessdata['rdef']["{$capctxp}:$roleid"][$capability])) {
$perm = (int)$accessdata['rdef']["{$capctxp}:$roleid"][$capability];
// The most local permission (first to set) wins
// the only exception is CAP_PROHIBIT
if ($rolecan === 0) {
$rolecan = $perm;
$rolecapdepth = $m;
} elseif ($perm === $CAP_PROHIBIT) {
$rolecan = $perm;
$rolecapdepth = $m;
break;
}
}
}
// Rules for RAs at the same context...
// - prohibits always wins
// - permissions at the same ctxlevel & capdepth are added together
// - deeper capdepth wins
if ($ctxcan === $CAP_PROHIBIT || $rolecan === $CAP_PROHIBIT) {
$ctxcan = $CAP_PROHIBIT;
$ctxcapdepth = 0;
} elseif ($ctxcapdepth === $rolecapdepth) {
$ctxcan += $rolecan;
} elseif ($ctxcapdepth < $rolecapdepth) {
$ctxcan = $rolecan;
$ctxcapdepth = $rolecapdepth;
} else { // ctxcaptdepth is deeper
// rolecap ignored
}
}
// The most local RAs with a defined
// permission ($ctxcan) win, except
// for CAP_PROHIBIT
// NOTE: If we want the deepest RDEF to
// win regardless of the depth of the RA,
// change the elseif below to read
// ($can === 0 || $capdepth < $ctxcapdepth) {
if ($ctxcan === $CAP_PROHIBIT) {
$can = $ctxcan;
break;