forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 1
/
accesslib.php
7398 lines (6508 loc) · 252 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
* - context_course::instance($courseid), context_module::instance($cm->id), context_coursecat::instance($catid)
* - context::instance_by_id($contextid)
* - $context->get_parent_contexts();
* - $context->get_child_contexts();
*
* Whether the user can do something...
* - has_capability()
* - has_any_capability()
* - has_all_capabilities()
* - require_capability()
* - require_login() (from moodlelib)
* - is_enrolled()
* - is_viewing()
* - is_guest()
* - is_siteadmin()
* - isguestuser()
* - isloggedin()
*
* What courses has this user access to?
* - get_enrolled_users()
*
* What users can do X in this context?
* - get_enrolled_users() - at and bellow course context
* - get_users_by_capability() - above course context
*
* Modify roles
* - role_assign()
* - role_unassign()
* - role_unassign_all()
*
* Advanced - for internal use only
* - load_all_capabilities()
* - reload_all_capabilities()
* - has_capability_in_accessdata()
* - get_user_access_sitewide()
* - load_course_context()
* - load_role_access_by_context()
* - etc.
*
* <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=>$roleid)
* [$contextpath] = array($roleid=>$roleid)
* [$contextpath] = array($roleid=>$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 the tree.
*
* First 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($courseid1=>1, $courseid2=>1)
* </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 system 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 core_access
* @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
/** No capability change */
define('CAP_INHERIT', 0);
/** Allow permission, overrides CAP_PREVENT defined in parent contexts */
define('CAP_ALLOW', 1);
/** Prevent permission, overrides CAP_ALLOW defined in parent contexts */
define('CAP_PREVENT', -1);
/** Prohibit permission, overrides everything in current and child contexts */
define('CAP_PROHIBIT', -1000);
/** System context level - only one instance in every system */
define('CONTEXT_SYSTEM', 10);
/** User context level - one instance for each user describing what others can do to user */
define('CONTEXT_USER', 30);
/** Course category context level - one instance for each category */
define('CONTEXT_COURSECAT', 40);
/** Course context level - one instances for each course */
define('CONTEXT_COURSE', 50);
/** Course module context level - one instance for each course module */
define('CONTEXT_MODULE', 70);
/**
* Block context level - one instance for each block, sticky blocks are tricky
* because ppl think they should be able to override them at lower contexts.
* Any other context level instance can be parent of block context.
*/
define('CONTEXT_BLOCK', 80);
/** Capability allow management of trusts - NOT IMPLEMENTED YET - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
define('RISK_MANAGETRUST', 0x0001);
/** Capability allows changes in system configuration - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
define('RISK_CONFIG', 0x0002);
/** Capability allows user to add scripted content - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
define('RISK_XSS', 0x0004);
/** Capability allows access to personal user information - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
define('RISK_PERSONAL', 0x0008);
/** Capability allows users to add content others may see - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
define('RISK_SPAM', 0x0010);
/** capability allows mass delete of data belonging to other users - see {@link http://docs.moodle.org/dev/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);
/** rolename displays - the name is simply short role name */
define('ROLENAME_SHORT', 5);
if (!defined('CONTEXT_CACHE_MAX_SIZE')) {
/** maximum size of context cache - it is possible to tweak this config.php or in any script before inclusion of context.php */
define('CONTEXT_CACHE_MAX_SIZE', 2500);
}
/**
* 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 variable is the only way to implement this, without rewriting everything
* as methods of a class, instead of functions.
*
* @access private
* @global stdClass $ACCESSLIB_PRIVATE
* @name $ACCESSLIB_PRIVATE
*/
global $ACCESSLIB_PRIVATE;
$ACCESSLIB_PRIVATE = new stdClass();
$ACCESSLIB_PRIVATE->dirtycontexts = null; // Dirty contexts cache, loaded from DB once per page
$ACCESSLIB_PRIVATE->accessdatabyuser = array(); // Holds the cache of $accessdata structure for users (including $USER)
$ACCESSLIB_PRIVATE->rolepermissions = array(); // role permissions cache - helps a lot with mem usage
$ACCESSLIB_PRIVATE->capabilities = null; // detailed information about the capabilities
/**
* 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 of the tests.
*
* @access private
* @return void
*/
function accesslib_clear_all_caches_for_unit_testing() {
global $UNITTEST, $USER;
if (empty($UNITTEST->running) and !PHPUNIT_TEST) {
throw new coding_exception('You must not call clear_all_caches outside of unit tests.');
}
accesslib_clear_all_caches(true);
unset($USER->access);
}
/**
* Clears accesslib's private caches. ONLY BE USED FROM THIS LIBRARY FILE!
*
* This reset does not touch global $USER.
*
* @access private
* @param bool $resetcontexts
* @return void
*/
function accesslib_clear_all_caches($resetcontexts) {
global $ACCESSLIB_PRIVATE;
$ACCESSLIB_PRIVATE->dirtycontexts = null;
$ACCESSLIB_PRIVATE->accessdatabyuser = array();
$ACCESSLIB_PRIVATE->rolepermissions = array();
$ACCESSLIB_PRIVATE->capabilities = null;
if ($resetcontexts) {
context_helper::reset_caches();
}
}
/**
* Gets the accessdata for role "sitewide" (system down to course)
*
* @access private
* @param int $roleid
* @return array
*/
function get_role_access($roleid) {
global $DB, $ACCESSLIB_PRIVATE;
/* Get it in 1 DB query...
* - relevant role caps at the root and down
* to the course level - but not below
*/
//TODO: MUC - this could be cached in shared memory to speed up first page loading, web crawlers, etc.
$accessdata = get_empty_accessdata();
$accessdata['ra']['/'.SYSCONTEXTID] = array((int)$roleid => (int)$roleid);
//
// 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
LEFT JOIN {context} cctx
ON (cctx.contextlevel = ".CONTEXT_COURSE." AND ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'").")
WHERE rc.roleid = ? AND cctx.id IS NULL";
$params = array($roleid);
// we need extra caching in CLI scripts and cron
$rs = $DB->get_recordset_sql($sql, $params);
foreach ($rs as $rd) {
$k = "{$rd->path}:{$roleid}";
$accessdata['rdef'][$k][$rd->capability] = (int)$rd->permission;
}
$rs->close();
// share the role definitions
foreach ($accessdata['rdef'] as $k=>$unused) {
if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
$ACCESSLIB_PRIVATE->rolepermissions[$k] = $accessdata['rdef'][$k];
}
$accessdata['rdef_count']++;
$accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
}
return $accessdata;
}
/**
* Get the default guest role, this is used for guest account,
* search engine spiders, etc.
*
* @return stdClass role record
*/
function get_guest_role() {
global $CFG, $DB;
if (empty($CFG->guestroleid)) {
if ($roles = $DB->get_records('role', array('archetype'=>'guest'))) {
$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 particular capability in a given context.
*
* For example:
* $context = context_module::instance($cm->id);
* has_capability('mod/forum:replypost', $context)
*
* By default checks the capabilities of the current user, but you can pass a
* different userid. By default will return true for admin users, but you can override that with the fourth argument.
*
* Guest and not-logged-in users can never get any dangerous capability - that is any write capability
* or capabilities with XSS, config or data loss risks.
*
* @category access
*
* @param string $capability the name of the capability to check. For example mod/forum:view
* @param context $context the context to check the capability in. You normally get this with instance method of a context class.
* @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
* @param boolean $doanything If false, ignores effect of admin role assignment
* @return boolean true if the user has this capability. Otherwise false.
*/
function has_capability($capability, context $context, $user = null, $doanything = true) {
global $USER, $CFG, $SCRIPT, $ACCESSLIB_PRIVATE;
if (during_initial_install()) {
if ($SCRIPT === "/$CFG->admin/index.php" or $SCRIPT === "/$CFG->admin/cli/install.php" or $SCRIPT === "/$CFG->admin/cli/install_database.php") {
// we are in an installer - roles can not work yet
return true;
} else {
return false;
}
}
if (strpos($capability, 'moodle/legacy:') === 0) {
throw new coding_exception('Legacy capabilities can not be used any more!');
}
if (!is_bool($doanything)) {
throw new coding_exception('Capability parameter "doanything" is wierd, only true or false is allowed. This has to be fixed in code.');
}
// capability must exist
if (!$capinfo = get_capability_info($capability)) {
debugging('Capability "'.$capability.'" was not found! This has to be fixed in code.');
return false;
}
if (!isset($USER->id)) {
// should never happen
$USER->id = 0;
}
// make sure there is a real user specified
if ($user === null) {
$userid = $USER->id;
} else {
$userid = is_object($user) ? $user->id : $user;
}
// make sure forcelogin cuts off not-logged-in users if enabled
if (!empty($CFG->forcelogin) and $userid == 0) {
return false;
}
// make sure the guest account and not-logged-in users never get any risky caps no matter what the actual settings are.
if (($capinfo->captype === 'write') or ($capinfo->riskbitmask & (RISK_XSS | RISK_CONFIG | RISK_DATALOSS))) {
if (isguestuser($userid) or $userid == 0) {
return false;
}
}
// somehow make sure the user is not deleted and actually exists
if ($userid != 0) {
if ($userid == $USER->id and isset($USER->deleted)) {
// this prevents one query per page, it is a bit of cheating,
// but hopefully session is terminated properly once user is deleted
if ($USER->deleted) {
return false;
}
} else {
if (!context_user::instance($userid, IGNORE_MISSING)) {
// no user context == invalid userid
return false;
}
}
}
// context path/depth must be valid
if (empty($context->path) or $context->depth == 0) {
// this should not happen often, each upgrade tries to rebuild the context paths
debugging('Context id '.$context->id.' does not have valid path, please use build_context_path()');
if (is_siteadmin($userid)) {
return true;
} else {
return false;
}
}
// Find out if user is admin - it is not possible to override the doanything in any way
// and it is not possible to switch to admin role either.
if ($doanything) {
if (is_siteadmin($userid)) {
if ($userid != $USER->id) {
return true;
}
// make sure switchrole is not used in this context
if (empty($USER->access['rsw'])) {
return true;
}
$parts = explode('/', trim($context->path, '/'));
$path = '';
$switched = false;
foreach ($parts as $part) {
$path .= '/' . $part;
if (!empty($USER->access['rsw'][$path])) {
$switched = true;
break;
}
}
if (!$switched) {
return true;
}
//ok, admin switched role in this context, let's use normal access control rules
}
}
// Careful check for staleness...
$context->reload_if_dirty();
if ($USER->id == $userid) {
if (!isset($USER->access)) {
load_all_capabilities();
}
$access =& $USER->access;
} else {
// make sure user accessdata is really loaded
get_user_accessdata($userid, true);
$access =& $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
}
// Load accessdata for below-the-course context if necessary,
// all contexts at and above all courses are already loaded
if ($context->contextlevel != CONTEXT_COURSE and $coursecontext = $context->get_course_context(false)) {
load_course_context($userid, $coursecontext, $access);
}
return has_capability_in_accessdata($capability, $context, $access);
}
/**
* 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.
*
* @category access
* @see has_capability()
*
* @param array $capabilities an array of capability names.
* @param context $context the context to check the capability in. You normally get this with instance method of a context class.
* @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
* @param boolean $doanything If false, ignore effect of admin role assignment
* @return boolean true if the user has any of these capabilities. Otherwise false.
*/
function has_any_capability(array $capabilities, context $context, $user = null, $doanything = true) {
foreach ($capabilities as $capability) {
if (has_capability($capability, $context, $user, $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.
*
* @category access
* @see has_capability()
*
* @param array $capabilities an array of capability names.
* @param context $context the context to check the capability in. You normally get this with instance method of a context class.
* @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
* @param boolean $doanything If false, ignore effect of admin role assignment
* @return boolean true if the user has all of these capabilities. Otherwise false.
*/
function has_all_capabilities(array $capabilities, context $context, $user = null, $doanything = true) {
foreach ($capabilities as $capability) {
if (!has_capability($capability, $context, $user, $doanything)) {
return false;
}
}
return true;
}
/**
* Check if the user is an admin at the site level.
*
* Please note that use of proper capabilities is always encouraged,
* this function is supposed to be used from core or for temporary hacks.
*
* @category access
*
* @param int|stdClass $user_or_id user id or user object
* @return bool true if user is one of the administrators, false otherwise
*/
function is_siteadmin($user_or_id = null) {
global $CFG, $USER;
if ($user_or_id === null) {
$user_or_id = $USER;
}
if (empty($user_or_id)) {
return false;
}
if (!empty($user_or_id->id)) {
$userid = $user_or_id->id;
} else {
$userid = $user_or_id;
}
$siteadmins = explode(',', $CFG->siteadmins);
return in_array($userid, $siteadmins);
}
/**
* Returns true if user has at least one role assign
* of 'coursecontact' role (is potentially listed in some course descriptions).
*
* @param int $userid
* @return bool
*/
function has_coursecontact_role($userid) {
global $DB, $CFG;
if (empty($CFG->coursecontact)) {
return false;
}
$sql = "SELECT 1
FROM {role_assignments}
WHERE userid = :userid AND roleid IN ($CFG->coursecontact)";
return $DB->record_exists_sql($sql, array('userid'=>$userid));
}
/**
* Does the user have a capability to do something?
*
* Walk the accessdata array and return true/false.
* Deals with prohibits, role switching, aggregating
* capabilities, etc.
*
* The main feature of here is being FAST and with no
* side effects.
*
* Notes:
*
* 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.
*
* Permission evaluation
* ---------------------
* Originally there was an extremely complicated way
* to determine the user access that dealt with
* "locality" or role assignments and role overrides.
* Now we simply evaluate access for each role separately
* and then verify if user has at least one role with allow
* and at the same time no role with prohibit.
*
* @access private
* @param string $capability
* @param context $context
* @param array $accessdata
* @return bool
*/
function has_capability_in_accessdata($capability, context $context, array &$accessdata) {
global $CFG;
// Build $paths as a list of current + all parent "paths" with order bottom-to-top
$path = $context->path;
$paths = array($path);
while($path = rtrim($path, '0123456789')) {
$path = rtrim($path, '/');
if ($path === '') {
break;
}
$paths[] = $path;
}
$roles = array();
$switchedrole = false;
// Find out if role switched
if (!empty($accessdata['rsw'])) {
// From the bottom up...
foreach ($paths as $path) {
if (isset($accessdata['rsw'][$path])) {
// Found a switchrole assignment - check for that role _plus_ the default user role
$roles = array($accessdata['rsw'][$path]=>null, $CFG->defaultuserroleid=>null);
$switchedrole = true;
break;
}
}
}
if (!$switchedrole) {
// get all users roles in this context and above
foreach ($paths as $path) {
if (isset($accessdata['ra'][$path])) {
foreach ($accessdata['ra'][$path] as $roleid) {
$roles[$roleid] = null;
}
}
}
}
// Now find out what access is given to each role, going bottom-->up direction
$allowed = false;
foreach ($roles as $roleid => $ignored) {
foreach ($paths as $path) {
if (isset($accessdata['rdef']["{$path}:$roleid"][$capability])) {
$perm = (int)$accessdata['rdef']["{$path}:$roleid"][$capability];
if ($perm === CAP_PROHIBIT) {
// any CAP_PROHIBIT found means no permission for the user
return false;
}
if (is_null($roles[$roleid])) {
$roles[$roleid] = $perm;
}
}
}
// CAP_ALLOW in any role means the user has a permission, we continue only to detect prohibits
$allowed = ($allowed or $roles[$roleid] === CAP_ALLOW);
}
return $allowed;
}
/**
* A convenience function that tests has_capability, and displays an error if
* the user does not have that capability.
*
* NOTE before Moodle 2.0, this function attempted to make an appropriate
* require_login call before checking the capability. This is no longer the case.
* You must call require_login (or one of its variants) if you want to check the
* user is logged in, before you call this function.
*
* @see has_capability()
*
* @param string $capability the name of the capability to check. For example mod/forum:view
* @param context $context the context to check the capability in. You normally get this with {@link get_context_instance}.
* @param int $userid A user id. By default (null) checks the permissions of the current user.
* @param bool $doanything If false, ignore effect of admin role assignment
* @param string $errormessage The error string to to user. Defaults to 'nopermissions'.
* @param string $stringfile The language file to load the error string from. Defaults to 'error'.
* @return void terminates with an error if the user does not have the given capability.
*/
function require_capability($capability, context $context, $userid = null, $doanything = true,
$errormessage = 'nopermissions', $stringfile = '') {
if (!has_capability($capability, $context, $userid, $doanything)) {
throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
}
}
/**
* Return a nested array showing role assignments
* all relevant role capabilities for the user at
* site/course_category/course levels
*
* We do _not_ delve deeper than courses because the number of
* overrides at the module/block levels can be HUGE.
*
* [ra] => [/path][roleid]=roleid
* [rdef] => [/path:roleid][capability]=permission
*
* @access private
* @param int $userid - the id of the user
* @return array access info array
*/
function get_user_access_sitewide($userid) {
global $CFG, $DB, $ACCESSLIB_PRIVATE;
/* Get in a few cheap DB queries...
* - role assignments
* - relevant role caps
* - above and within this user's RAs
* - below this user's RAs - limited to course level
*/
// raparents collects paths & roles we need to walk up the parenthood to build the minimal rdef
$raparents = array();
$accessdata = get_empty_accessdata();
// start with the default role
if (!empty($CFG->defaultuserroleid)) {
$syscontext = context_system::instance();
$accessdata['ra'][$syscontext->path][(int)$CFG->defaultuserroleid] = (int)$CFG->defaultuserroleid;
$raparents[$CFG->defaultuserroleid][$syscontext->id] = $syscontext->id;
}
// load the "default frontpage role"
if (!empty($CFG->defaultfrontpageroleid)) {
$frontpagecontext = context_course::instance(get_site()->id);
if ($frontpagecontext->path) {
$accessdata['ra'][$frontpagecontext->path][(int)$CFG->defaultfrontpageroleid] = (int)$CFG->defaultfrontpageroleid;
$raparents[$CFG->defaultfrontpageroleid][$frontpagecontext->id] = $frontpagecontext->id;
}
}
// preload every assigned role at and above course context
$sql = "SELECT ctx.path, ra.roleid, ra.contextid
FROM {role_assignments} ra
JOIN {context} ctx
ON ctx.id = ra.contextid
LEFT JOIN {block_instances} bi
ON (ctx.contextlevel = ".CONTEXT_BLOCK." AND bi.id = ctx.instanceid)
LEFT JOIN {context} bpctx
ON (bpctx.id = bi.parentcontextid)
WHERE ra.userid = :userid
AND (ctx.contextlevel <= ".CONTEXT_COURSE." OR bpctx.contextlevel < ".CONTEXT_COURSE.")";
$params = array('userid'=>$userid);
$rs = $DB->get_recordset_sql($sql, $params);
foreach ($rs as $ra) {
// RAs leafs are arrays to support multi-role assignments...
$accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
$raparents[$ra->roleid][$ra->contextid] = $ra->contextid;
}
$rs->close();
if (empty($raparents)) {
return $accessdata;
}
// now get overrides of interesting roles in all interesting child contexts
// hopefully we will not run out of SQL limits here,
// users would have to have very many roles at/above course context...
$sqls = array();
$params = array();
static $cp = 0;
foreach ($raparents as $roleid=>$ras) {
$cp++;
list($sqlcids, $cids) = $DB->get_in_or_equal($ras, SQL_PARAMS_NAMED, 'c'.$cp.'_');
$params = array_merge($params, $cids);
$params['r'.$cp] = $roleid;
$sqls[] = "(SELECT ctx.path, rc.roleid, rc.capability, rc.permission
FROM {role_capabilities} rc
JOIN {context} ctx
ON (ctx.id = rc.contextid)
JOIN {context} pctx
ON (pctx.id $sqlcids
AND (ctx.id = pctx.id
OR ctx.path LIKE ".$DB->sql_concat('pctx.path',"'/%'")."
OR pctx.path LIKE ".$DB->sql_concat('ctx.path',"'/%'")."))
LEFT JOIN {block_instances} bi
ON (ctx.contextlevel = ".CONTEXT_BLOCK." AND bi.id = ctx.instanceid)
LEFT JOIN {context} bpctx
ON (bpctx.id = bi.parentcontextid)
WHERE rc.roleid = :r{$cp}
AND (ctx.contextlevel <= ".CONTEXT_COURSE." OR bpctx.contextlevel < ".CONTEXT_COURSE.")
)";
}
// fixed capability order is necessary for rdef dedupe
$rs = $DB->get_recordset_sql(implode("\nUNION\n", $sqls). "ORDER BY capability", $params);
foreach ($rs as $rd) {
$k = $rd->path.':'.$rd->roleid;
$accessdata['rdef'][$k][$rd->capability] = (int)$rd->permission;
}
$rs->close();
// share the role definitions
foreach ($accessdata['rdef'] as $k=>$unused) {
if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
$ACCESSLIB_PRIVATE->rolepermissions[$k] = $accessdata['rdef'][$k];
}
$accessdata['rdef_count']++;
$accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
}
return $accessdata;
}
/**
* Add to the access ctrl array the data needed by a user for a given course.
*
* This function injects all course related access info into the accessdata array.
*
* @access private
* @param int $userid the id of the user
* @param context_course $coursecontext course context
* @param array $accessdata accessdata array (modified)
* @return void modifies $accessdata parameter
*/
function load_course_context($userid, context_course $coursecontext, &$accessdata) {
global $DB, $CFG, $ACCESSLIB_PRIVATE;
if (empty($coursecontext->path)) {
// weird, this should not happen
return;
}
if (isset($accessdata['loaded'][$coursecontext->instanceid])) {
// already loaded, great!
return;
}
$roles = array();
if (empty($userid)) {
if (!empty($CFG->notloggedinroleid)) {
$roles[$CFG->notloggedinroleid] = $CFG->notloggedinroleid;
}
} else if (isguestuser($userid)) {
if ($guestrole = get_guest_role()) {
$roles[$guestrole->id] = $guestrole->id;
}
} else {
// Interesting role assignments at, above and below the course context
list($parentsaself, $params) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
$params['userid'] = $userid;
$params['children'] = $coursecontext->path."/%";
$sql = "SELECT ra.*, ctx.path
FROM {role_assignments} ra
JOIN {context} ctx ON ra.contextid = ctx.id
WHERE ra.userid = :userid AND (ctx.id $parentsaself OR ctx.path LIKE :children)";
$rs = $DB->get_recordset_sql($sql, $params);
// add missing role definitions
foreach ($rs as $ra) {
$accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
$roles[$ra->roleid] = $ra->roleid;
}
$rs->close();
// add the "default frontpage role" when on the frontpage
if (!empty($CFG->defaultfrontpageroleid)) {
$frontpagecontext = context_course::instance(get_site()->id);
if ($frontpagecontext->id == $coursecontext->id) {
$roles[$CFG->defaultfrontpageroleid] = $CFG->defaultfrontpageroleid;
}
}
// do not forget the default role
if (!empty($CFG->defaultuserroleid)) {
$roles[$CFG->defaultuserroleid] = $CFG->defaultuserroleid;
}
}
if (!$roles) {
// weird, default roles must be missing...
$accessdata['loaded'][$coursecontext->instanceid] = 1;
return;
}
// now get overrides of interesting roles in all interesting contexts (this course + children + parents)
$params = array('c'=>$coursecontext->id);
list($parentsaself, $rparams) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
$params = array_merge($params, $rparams);
list($roleids, $rparams) = $DB->get_in_or_equal($roles, SQL_PARAMS_NAMED, 'r_');
$params = array_merge($params, $rparams);
$sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
FROM {role_capabilities} rc
JOIN {context} ctx
ON (ctx.id = rc.contextid)
JOIN {context} cctx
ON (cctx.id = :c
AND (ctx.id $parentsaself OR ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'")."))
WHERE rc.roleid $roleids
ORDER BY rc.capability"; // fixed capability order is necessary for rdef dedupe
$rs = $DB->get_recordset_sql($sql, $params);
$newrdefs = array();
foreach ($rs as $rd) {
$k = $rd->path.':'.$rd->roleid;
if (isset($accessdata['rdef'][$k])) {
continue;
}
$newrdefs[$k][$rd->capability] = (int)$rd->permission;
}
$rs->close();
// share new role definitions
foreach ($newrdefs as $k=>$unused) {
if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
$ACCESSLIB_PRIVATE->rolepermissions[$k] = $newrdefs[$k];
}
$accessdata['rdef_count']++;
$accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
}
$accessdata['loaded'][$coursecontext->instanceid] = 1;
// we want to deduplicate the USER->access from time to time, this looks like a good place,
// because we have to do it before the end of session
dedupe_user_access();
}
/**
* Add to the access ctrl array the data needed by a role for a given context.
*
* The data is added in the rdef key.
* This role-centric function is useful for role_switching
* and temporary course roles.
*
* @access private
* @param int $roleid the id of the user
* @param context $context needs path!
* @param array $accessdata accessdata array (is modified)
* @return array
*/
function load_role_access_by_context($roleid, context $context, &$accessdata) {
global $DB, $ACCESSLIB_PRIVATE;
/* Get the relevant rolecaps into rdef
* - relevant role caps
* - at ctx and above
* - below this ctx
*/
if (empty($context->path)) {
// weird, this should not happen
return;
}
list($parentsaself, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
$params['roleid'] = $roleid;
$params['childpath'] = $context->path.'/%';
$sql = "SELECT ctx.path, rc.capability, rc.permission
FROM {role_capabilities} rc
JOIN {context} ctx ON (rc.contextid = ctx.id)
WHERE rc.roleid = :roleid AND (ctx.id $parentsaself OR ctx.path LIKE :childpath)
ORDER BY rc.capability"; // fixed capability order is necessary for rdef dedupe
$rs = $DB->get_recordset_sql($sql, $params);
$newrdefs = array();
foreach ($rs as $rd) {
$k = $rd->path.':'.$roleid;
if (isset($accessdata['rdef'][$k])) {
continue;
}
$newrdefs[$k][$rd->capability] = (int)$rd->permission;
}
$rs->close();
// share new role definitions
foreach ($newrdefs as $k=>$unused) {
if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
$ACCESSLIB_PRIVATE->rolepermissions[$k] = $newrdefs[$k];
}
$accessdata['rdef_count']++;
$accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];