forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.php
1784 lines (1546 loc) · 68.9 KB
/
lib.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/>.
/**
* Web services utility functions and classes
*
* @package core_webservice
* @copyright 2009 Jerome Mouneyrac <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once($CFG->libdir.'/externallib.php');
/**
* WEBSERVICE_AUTHMETHOD_USERNAME - username/password authentication (also called simple authentication)
*/
define('WEBSERVICE_AUTHMETHOD_USERNAME', 0);
/**
* WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN - most common token authentication (external app, mobile app...)
*/
define('WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN', 1);
/**
* WEBSERVICE_AUTHMETHOD_SESSION_TOKEN - token for embedded application (requires Moodle session)
*/
define('WEBSERVICE_AUTHMETHOD_SESSION_TOKEN', 2);
/**
* General web service library
*
* @package core_webservice
* @copyright 2010 Jerome Mouneyrac <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class webservice {
/**
* Authenticate user (used by download/upload file scripts)
*
* @param string $token
* @return array - contains the authenticated user, token and service objects
*/
public function authenticate_user($token) {
global $DB, $CFG;
// web service must be enabled to use this script
if (!$CFG->enablewebservices) {
throw new webservice_access_exception('Web services are not enabled in Advanced features.');
}
// Obtain token record
if (!$token = $DB->get_record('external_tokens', array('token' => $token))) {
//client may want to display login form => moodle_exception
throw new moodle_exception('invalidtoken', 'webservice');
}
$loginfaileddefaultparams = array(
'other' => array(
'method' => WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN,
'reason' => null,
'tokenid' => $token->id
)
);
// Validate token date
if ($token->validuntil and $token->validuntil < time()) {
$params = $loginfaileddefaultparams;
$params['other']['reason'] = 'token_expired';
$event = \core\event\webservice_login_failed::create($params);
$event->add_record_snapshot('external_tokens', $token);
$event->set_legacy_logdata(array(SITEID, 'webservice', get_string('tokenauthlog', 'webservice'), '',
get_string('invalidtimedtoken', 'webservice'), 0));
$event->trigger();
$DB->delete_records('external_tokens', array('token' => $token->token));
throw new webservice_access_exception('Invalid token - token expired - check validuntil time for the token');
}
// Check ip
if ($token->iprestriction and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
$params = $loginfaileddefaultparams;
$params['other']['reason'] = 'ip_restricted';
$event = \core\event\webservice_login_failed::create($params);
$event->add_record_snapshot('external_tokens', $token);
$event->set_legacy_logdata(array(SITEID, 'webservice', get_string('tokenauthlog', 'webservice'), '',
get_string('failedtolog', 'webservice') . ": " . getremoteaddr(), 0));
$event->trigger();
throw new webservice_access_exception('Invalid token - IP:' . getremoteaddr()
. ' is not supported');
}
//retrieve user link to the token
$user = $DB->get_record('user', array('id' => $token->userid, 'deleted' => 0), '*', MUST_EXIST);
// let enrol plugins deal with new enrolments if necessary
enrol_check_plugins($user);
// setup user session to check capability
\core\session\manager::set_user($user);
//assumes that if sid is set then there must be a valid associated session no matter the token type
if ($token->sid) {
if (!\core\session\manager::session_exists($token->sid)) {
$DB->delete_records('external_tokens', array('sid' => $token->sid));
throw new webservice_access_exception('Invalid session based token - session not found or expired');
}
}
//Non admin can not authenticate if maintenance mode
$hassiteconfig = has_capability('moodle/site:config', context_system::instance(), $user);
if (!empty($CFG->maintenance_enabled) and !$hassiteconfig) {
//this is usually temporary, client want to implement code logic => moodle_exception
throw new moodle_exception('sitemaintenance', 'admin');
}
//retrieve web service record
$service = $DB->get_record('external_services', array('id' => $token->externalserviceid, 'enabled' => 1));
if (empty($service)) {
// will throw exception if no token found
throw new webservice_access_exception('Web service is not available (it doesn\'t exist or might be disabled)');
}
//check if there is any required system capability
if ($service->requiredcapability and !has_capability($service->requiredcapability, context_system::instance(), $user)) {
throw new webservice_access_exception('The capability ' . $service->requiredcapability . ' is required.');
}
//specific checks related to user restricted service
if ($service->restrictedusers) {
$authoriseduser = $DB->get_record('external_services_users', array('externalserviceid' => $service->id, 'userid' => $user->id));
if (empty($authoriseduser)) {
throw new webservice_access_exception(
'The user is not allowed for this service. First you need to allow this user on the '
. $service->name . '\'s allowed users administration page.');
}
if (!empty($authoriseduser->validuntil) and $authoriseduser->validuntil < time()) {
throw new webservice_access_exception('Invalid service - service expired - check validuntil time for this allowed user');
}
if (!empty($authoriseduser->iprestriction) and !address_in_subnet(getremoteaddr(), $authoriseduser->iprestriction)) {
throw new webservice_access_exception('Invalid service - IP:' . getremoteaddr()
. ' is not supported - check this allowed user');
}
}
//only confirmed user should be able to call web service
if (empty($user->confirmed)) {
$params = $loginfaileddefaultparams;
$params['other']['reason'] = 'user_unconfirmed';
$event = \core\event\webservice_login_failed::create($params);
$event->add_record_snapshot('external_tokens', $token);
$event->set_legacy_logdata(array(SITEID, 'webservice', 'user unconfirmed', '', $user->username));
$event->trigger();
throw new moodle_exception('usernotconfirmed', 'moodle', '', $user->username);
}
//check the user is suspended
if (!empty($user->suspended)) {
$params = $loginfaileddefaultparams;
$params['other']['reason'] = 'user_suspended';
$event = \core\event\webservice_login_failed::create($params);
$event->add_record_snapshot('external_tokens', $token);
$event->set_legacy_logdata(array(SITEID, 'webservice', 'user suspended', '', $user->username));
$event->trigger();
throw new webservice_access_exception('Refused web service access for suspended username: ' . $user->username);
}
//check if the auth method is nologin (in this case refuse connection)
if ($user->auth == 'nologin') {
$params = $loginfaileddefaultparams;
$params['other']['reason'] = 'nologin';
$event = \core\event\webservice_login_failed::create($params);
$event->add_record_snapshot('external_tokens', $token);
$event->set_legacy_logdata(array(SITEID, 'webservice', 'nologin auth attempt with web service', '', $user->username));
$event->trigger();
throw new webservice_access_exception('Refused web service access for nologin authentication username: ' . $user->username);
}
//Check if the user password is expired
$auth = get_auth_plugin($user->auth);
if (!empty($auth->config->expiration) and $auth->config->expiration == 1) {
$days2expire = $auth->password_expire($user->username);
if (intval($days2expire) < 0) {
$params = $loginfaileddefaultparams;
$params['other']['reason'] = 'password_expired';
$event = \core\event\webservice_login_failed::create($params);
$event->add_record_snapshot('external_tokens', $token);
$event->set_legacy_logdata(array(SITEID, 'webservice', 'expired password', '', $user->username));
$event->trigger();
throw new moodle_exception('passwordisexpired', 'webservice');
}
}
// log token access
$DB->set_field('external_tokens', 'lastaccess', time(), array('id' => $token->id));
return array('user' => $user, 'token' => $token, 'service' => $service);
}
/**
* Allow user to call a service
*
* @param stdClass $user a user
*/
public function add_ws_authorised_user($user) {
global $DB;
$user->timecreated = time();
$DB->insert_record('external_services_users', $user);
}
/**
* Disallow a user to call a service
*
* @param stdClass $user a user
* @param int $serviceid
*/
public function remove_ws_authorised_user($user, $serviceid) {
global $DB;
$DB->delete_records('external_services_users',
array('externalserviceid' => $serviceid, 'userid' => $user->id));
}
/**
* Update allowed user settings (ip restriction, valid until...)
*
* @param stdClass $user
*/
public function update_ws_authorised_user($user) {
global $DB;
$DB->update_record('external_services_users', $user);
}
/**
* Return list of allowed users with their options (ip/timecreated / validuntil...)
* for a given service
*
* @param int $serviceid the service id to search against
* @return array $users
*/
public function get_ws_authorised_users($serviceid) {
global $DB, $CFG;
$params = array($CFG->siteguest, $serviceid);
$sql = " SELECT u.id as id, esu.id as serviceuserid, u.email as email, u.firstname as firstname,
u.lastname as lastname,
esu.iprestriction as iprestriction, esu.validuntil as validuntil,
esu.timecreated as timecreated
FROM {user} u, {external_services_users} esu
WHERE u.id <> ? AND u.deleted = 0 AND u.confirmed = 1
AND esu.userid = u.id
AND esu.externalserviceid = ?";
$users = $DB->get_records_sql($sql, $params);
return $users;
}
/**
* Return an authorised user with their options (ip/timecreated / validuntil...)
*
* @param int $serviceid the service id to search against
* @param int $userid the user to search against
* @return stdClass
*/
public function get_ws_authorised_user($serviceid, $userid) {
global $DB, $CFG;
$params = array($CFG->siteguest, $serviceid, $userid);
$sql = " SELECT u.id as id, esu.id as serviceuserid, u.email as email, u.firstname as firstname,
u.lastname as lastname,
esu.iprestriction as iprestriction, esu.validuntil as validuntil,
esu.timecreated as timecreated
FROM {user} u, {external_services_users} esu
WHERE u.id <> ? AND u.deleted = 0 AND u.confirmed = 1
AND esu.userid = u.id
AND esu.externalserviceid = ?
AND u.id = ?";
$user = $DB->get_record_sql($sql, $params);
return $user;
}
/**
* Generate all tokens of a specific user
*
* @param int $userid user id
*/
public function generate_user_ws_tokens($userid) {
global $CFG, $DB;
// generate a token for non admin if web service are enable and the user has the capability to create a token
if (!is_siteadmin() && has_capability('moodle/webservice:createtoken', context_system::instance(), $userid) && !empty($CFG->enablewebservices)) {
// for every service than the user is authorised on, create a token (if it doesn't already exist)
// get all services which are set to all user (no restricted to specific users)
$norestrictedservices = $DB->get_records('external_services', array('restrictedusers' => 0));
$serviceidlist = array();
foreach ($norestrictedservices as $service) {
$serviceidlist[] = $service->id;
}
// get all services which are set to the current user (the current user is specified in the restricted user list)
$servicesusers = $DB->get_records('external_services_users', array('userid' => $userid));
foreach ($servicesusers as $serviceuser) {
if (!in_array($serviceuser->externalserviceid,$serviceidlist)) {
$serviceidlist[] = $serviceuser->externalserviceid;
}
}
// get all services which already have a token set for the current user
$usertokens = $DB->get_records('external_tokens', array('userid' => $userid, 'tokentype' => EXTERNAL_TOKEN_PERMANENT));
$tokenizedservice = array();
foreach ($usertokens as $token) {
$tokenizedservice[] = $token->externalserviceid;
}
// create a token for the service which have no token already
foreach ($serviceidlist as $serviceid) {
if (!in_array($serviceid, $tokenizedservice)) {
// create the token for this service
$newtoken = new stdClass();
$newtoken->token = md5(uniqid(rand(),1));
// check that the user has capability on this service
$newtoken->tokentype = EXTERNAL_TOKEN_PERMANENT;
$newtoken->userid = $userid;
$newtoken->externalserviceid = $serviceid;
// TODO MDL-31190 find a way to get the context - UPDATE FOLLOWING LINE
$newtoken->contextid = context_system::instance()->id;
$newtoken->creatorid = $userid;
$newtoken->timecreated = time();
$DB->insert_record('external_tokens', $newtoken);
}
}
}
}
/**
* Return all tokens of a specific user
* + the service state (enabled/disabled)
* + the authorised user mode (restricted/not restricted)
*
* @param int $userid user id
* @return array
*/
public function get_user_ws_tokens($userid) {
global $DB;
//here retrieve token list (including linked users firstname/lastname and linked services name)
$sql = "SELECT
t.id, t.creatorid, t.token, u.firstname, u.lastname, s.id as wsid, s.name, s.enabled, s.restrictedusers, t.validuntil
FROM
{external_tokens} t, {user} u, {external_services} s
WHERE
t.userid=? AND t.tokentype = ".EXTERNAL_TOKEN_PERMANENT." AND s.id = t.externalserviceid AND t.userid = u.id";
$tokens = $DB->get_records_sql($sql, array( $userid));
return $tokens;
}
/**
* Return a token that has been created by the user (i.e. to created by an admin)
* If no tokens exist an exception is thrown
*
* The returned value is a stdClass:
* ->id token id
* ->token
* ->firstname user firstname
* ->lastname
* ->name service name
*
* @param int $userid user id
* @param int $tokenid token id
* @return stdClass
*/
public function get_created_by_user_ws_token($userid, $tokenid) {
global $DB;
$sql = "SELECT
t.id, t.token, u.firstname, u.lastname, s.name
FROM
{external_tokens} t, {user} u, {external_services} s
WHERE
t.creatorid=? AND t.id=? AND t.tokentype = "
. EXTERNAL_TOKEN_PERMANENT
. " AND s.id = t.externalserviceid AND t.userid = u.id";
//must be the token creator
$token = $DB->get_record_sql($sql, array($userid, $tokenid), MUST_EXIST);
return $token;
}
/**
* Return a database token record for a token id
*
* @param int $tokenid token id
* @return object token
*/
public function get_token_by_id($tokenid) {
global $DB;
return $DB->get_record('external_tokens', array('id' => $tokenid));
}
/**
* Delete a token
*
* @param int $tokenid token id
*/
public function delete_user_ws_token($tokenid) {
global $DB;
$DB->delete_records('external_tokens', array('id'=>$tokenid));
}
/**
* Delete a service
* Also delete function references and authorised user references.
*
* @param int $serviceid service id
*/
public function delete_service($serviceid) {
global $DB;
$DB->delete_records('external_services_users', array('externalserviceid' => $serviceid));
$DB->delete_records('external_services_functions', array('externalserviceid' => $serviceid));
$DB->delete_records('external_tokens', array('externalserviceid' => $serviceid));
$DB->delete_records('external_services', array('id' => $serviceid));
}
/**
* Get a full database token record for a given token value
*
* @param string $token
* @throws moodle_exception if there is multiple result
*/
public function get_user_ws_token($token) {
global $DB;
return $DB->get_record('external_tokens', array('token'=>$token), '*', MUST_EXIST);
}
/**
* Get the functions list of a service list (by id)
*
* @param array $serviceids service ids
* @return array of functions
*/
public function get_external_functions($serviceids) {
global $DB;
if (!empty($serviceids)) {
list($serviceids, $params) = $DB->get_in_or_equal($serviceids);
$sql = "SELECT f.*
FROM {external_functions} f
WHERE f.name IN (SELECT sf.functionname
FROM {external_services_functions} sf
WHERE sf.externalserviceid $serviceids)";
$functions = $DB->get_records_sql($sql, $params);
} else {
$functions = array();
}
return $functions;
}
/**
* Get the functions of a service list (by shortname). It can return only enabled functions if required.
*
* @param array $serviceshortnames service shortnames
* @param bool $enabledonly if true then only return functions for services that have been enabled
* @return array functions
*/
public function get_external_functions_by_enabled_services($serviceshortnames, $enabledonly = true) {
global $DB;
if (!empty($serviceshortnames)) {
$enabledonlysql = $enabledonly?' AND s.enabled = 1 ':'';
list($serviceshortnames, $params) = $DB->get_in_or_equal($serviceshortnames);
$sql = "SELECT f.*
FROM {external_functions} f
WHERE f.name IN (SELECT sf.functionname
FROM {external_services_functions} sf, {external_services} s
WHERE s.shortname $serviceshortnames
AND sf.externalserviceid = s.id
" . $enabledonlysql . ")";
$functions = $DB->get_records_sql($sql, $params);
} else {
$functions = array();
}
return $functions;
}
/**
* Get functions not included in a service
*
* @param int $serviceid service id
* @return array functions
*/
public function get_not_associated_external_functions($serviceid) {
global $DB;
$select = "name NOT IN (SELECT s.functionname
FROM {external_services_functions} s
WHERE s.externalserviceid = :sid
)";
$functions = $DB->get_records_select('external_functions',
$select, array('sid' => $serviceid), 'name');
return $functions;
}
/**
* Get list of required capabilities of a service, sorted by functions
* Example of returned value:
* Array
* (
* [moodle_group_create_groups] => Array
* (
* [0] => moodle/course:managegroups
* )
*
* [moodle_enrol_get_enrolled_users] => Array
* (
* [0] => moodle/site:viewparticipants
* [1] => moodle/course:viewparticipants
* [2] => moodle/role:review
* [3] => moodle/site:accessallgroups
* [4] => moodle/course:enrolreview
* )
* )
*
* @param int $serviceid service id
* @return array
*/
public function get_service_required_capabilities($serviceid) {
$functions = $this->get_external_functions(array($serviceid));
$requiredusercaps = array();
foreach ($functions as $function) {
$functioncaps = explode(',', $function->capabilities);
if (!empty($functioncaps) and !empty($functioncaps[0])) {
foreach ($functioncaps as $functioncap) {
$requiredusercaps[$function->name][] = trim($functioncap);
}
}
}
return $requiredusercaps;
}
/**
* Get user capabilities (with context)
* Only useful for documentation purpose
* WARNING: do not use this "broken" function. It was created in the goal to display some capabilities
* required by users. In theory we should not need to display this kind of information
* as the front end does not display it itself. In pratice,
* admins would like the info, for more info you can follow: MDL-29962
*
* @param int $userid user id
* @return array
*/
public function get_user_capabilities($userid) {
global $DB;
//retrieve the user capabilities
$sql = "SELECT DISTINCT rc.id, rc.capability FROM {role_capabilities} rc, {role_assignments} ra
WHERE rc.roleid=ra.roleid AND ra.userid= ? AND rc.permission = ?";
$dbusercaps = $DB->get_records_sql($sql, array($userid, CAP_ALLOW));
$usercaps = array();
foreach ($dbusercaps as $usercap) {
$usercaps[$usercap->capability] = true;
}
return $usercaps;
}
/**
* Get missing user capabilities for a given service
* WARNING: do not use this "broken" function. It was created in the goal to display some capabilities
* required by users. In theory we should not need to display this kind of information
* as the front end does not display it itself. In pratice,
* admins would like the info, for more info you can follow: MDL-29962
*
* @param array $users users
* @param int $serviceid service id
* @return array of missing capabilities, keys being the user ids
*/
public function get_missing_capabilities_by_users($users, $serviceid) {
global $DB;
$usersmissingcaps = array();
//retrieve capabilities required by the service
$servicecaps = $this->get_service_required_capabilities($serviceid);
//retrieve users missing capabilities
foreach ($users as $user) {
//cast user array into object to be a bit more flexible
if (is_array($user)) {
$user = (object) $user;
}
$usercaps = $this->get_user_capabilities($user->id);
//detect the missing capabilities
foreach ($servicecaps as $functioname => $functioncaps) {
foreach ($functioncaps as $functioncap) {
if (!array_key_exists($functioncap, $usercaps)) {
if (!isset($usersmissingcaps[$user->id])
or array_search($functioncap, $usersmissingcaps[$user->id]) === false) {
$usersmissingcaps[$user->id][] = $functioncap;
}
}
}
}
}
return $usersmissingcaps;
}
/**
* Get an external service for a given service id
*
* @param int $serviceid service id
* @param int $strictness IGNORE_MISSING, MUST_EXIST...
* @return stdClass external service
*/
public function get_external_service_by_id($serviceid, $strictness=IGNORE_MISSING) {
global $DB;
$service = $DB->get_record('external_services',
array('id' => $serviceid), '*', $strictness);
return $service;
}
/**
* Get an external service for a given shortname
*
* @param string $shortname service shortname
* @param int $strictness IGNORE_MISSING, MUST_EXIST...
* @return stdClass external service
*/
public function get_external_service_by_shortname($shortname, $strictness=IGNORE_MISSING) {
global $DB;
$service = $DB->get_record('external_services',
array('shortname' => $shortname), '*', $strictness);
return $service;
}
/**
* Get an external function for a given function id
*
* @param int $functionid function id
* @param int $strictness IGNORE_MISSING, MUST_EXIST...
* @return stdClass external function
*/
public function get_external_function_by_id($functionid, $strictness=IGNORE_MISSING) {
global $DB;
$function = $DB->get_record('external_functions',
array('id' => $functionid), '*', $strictness);
return $function;
}
/**
* Add a function to a service
*
* @param string $functionname function name
* @param int $serviceid service id
*/
public function add_external_function_to_service($functionname, $serviceid) {
global $DB;
$addedfunction = new stdClass();
$addedfunction->externalserviceid = $serviceid;
$addedfunction->functionname = $functionname;
$DB->insert_record('external_services_functions', $addedfunction);
}
/**
* Add a service
* It generates the timecreated field automatically.
*
* @param stdClass $service
* @return serviceid integer
*/
public function add_external_service($service) {
global $DB;
$service->timecreated = time();
$serviceid = $DB->insert_record('external_services', $service);
return $serviceid;
}
/**
* Update a service
* It modifies the timemodified automatically.
*
* @param stdClass $service
*/
public function update_external_service($service) {
global $DB;
$service->timemodified = time();
$DB->update_record('external_services', $service);
}
/**
* Test whether an external function is already linked to a service
*
* @param string $functionname function name
* @param int $serviceid service id
* @return bool true if a matching function exists for the service, else false.
* @throws dml_exception if error
*/
public function service_function_exists($functionname, $serviceid) {
global $DB;
return $DB->record_exists('external_services_functions',
array('externalserviceid' => $serviceid,
'functionname' => $functionname));
}
/**
* Remove a function from a service
*
* @param string $functionname function name
* @param int $serviceid service id
*/
public function remove_external_function_from_service($functionname, $serviceid) {
global $DB;
$DB->delete_records('external_services_functions',
array('externalserviceid' => $serviceid, 'functionname' => $functionname));
}
}
/**
* Exception indicating access control problem in web service call
* This exception should return general errors about web service setup.
* Errors related to the user like wrong username/password should not use it,
* you should not use this exception if you want to let the client implement
* some code logic against an access error.
*
* @package core_webservice
* @copyright 2009 Petr Skodak
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class webservice_access_exception extends moodle_exception {
/**
* Constructor
*
* @param string $debuginfo the debug info
*/
function __construct($debuginfo) {
parent::__construct('accessexception', 'webservice', '', null, $debuginfo);
}
}
/**
* Check if a protocol is enabled
*
* @param string $protocol name of WS protocol ('rest', 'soap', 'xmlrpc', 'amf'...)
* @return bool true if the protocol is enabled
*/
function webservice_protocol_is_enabled($protocol) {
global $CFG;
if (empty($CFG->enablewebservices)) {
return false;
}
$active = explode(',', $CFG->webserviceprotocols);
return(in_array($protocol, $active));
}
/**
* Mandatory interface for all test client classes.
*
* @package core_webservice
* @copyright 2009 Petr Skodak
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
interface webservice_test_client_interface {
/**
* Execute test client WS request
*
* @param string $serverurl server url (including the token param)
* @param string $function web service function name
* @param array $params parameters of the web service function
* @return mixed
*/
public function simpletest($serverurl, $function, $params);
}
/**
* Mandatory interface for all web service protocol classes
*
* @package core_webservice
* @copyright 2009 Petr Skodak
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
interface webservice_server_interface {
/**
* Process request from client.
*/
public function run();
}
/**
* Abstract web service base class.
*
* @package core_webservice
* @copyright 2009 Petr Skodak
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
abstract class webservice_server implements webservice_server_interface {
/** @var string Name of the web server plugin */
protected $wsname = null;
/** @var string Name of local user */
protected $username = null;
/** @var string Password of the local user */
protected $password = null;
/** @var int The local user */
protected $userid = null;
/** @var integer Authentication method one of WEBSERVICE_AUTHMETHOD_* */
protected $authmethod;
/** @var string Authentication token*/
protected $token = null;
/** @var stdClass Restricted context */
protected $restricted_context;
/** @var int Restrict call to one service id*/
protected $restricted_serviceid = null;
/**
* Constructor
*
* @param integer $authmethod authentication method one of WEBSERVICE_AUTHMETHOD_*
*/
public function __construct($authmethod) {
$this->authmethod = $authmethod;
}
/**
* Authenticate user using username+password or token.
* This function sets up $USER global.
* It is safe to use has_capability() after this.
* This method also verifies user is allowed to use this
* server.
*/
protected function authenticate_user() {
global $CFG, $DB;
if (!NO_MOODLE_COOKIES) {
throw new coding_exception('Cookies must be disabled in WS servers!');
}
$loginfaileddefaultparams = array(
'context' => context_system::instance(),
'other' => array(
'method' => $this->authmethod,
'reason' => null
)
);
if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
//we check that authentication plugin is enabled
//it is only required by simple authentication
if (!is_enabled_auth('webservice')) {
throw new webservice_access_exception('The web service authentication plugin is disabled.');
}
if (!$auth = get_auth_plugin('webservice')) {
throw new webservice_access_exception('The web service authentication plugin is missing.');
}
$this->restricted_context = context_system::instance();
if (!$this->username) {
throw new moodle_exception('missingusername', 'webservice');
}
if (!$this->password) {
throw new moodle_exception('missingpassword', 'webservice');
}
if (!$auth->user_login_webservice($this->username, $this->password)) {
// Log failed login attempts.
$params = $loginfaileddefaultparams;
$params['other']['reason'] = 'password';
$params['other']['username'] = $this->username;
$event = \core\event\webservice_login_failed::create($params);
$event->set_legacy_logdata(array(SITEID, 'webservice', get_string('simpleauthlog', 'webservice'), '' ,
get_string('failedtolog', 'webservice').": ".$this->username."/".$this->password." - ".getremoteaddr() , 0));
$event->trigger();
throw new moodle_exception('wrongusernamepassword', 'webservice');
}
$user = $DB->get_record('user', array('username'=>$this->username, 'mnethostid'=>$CFG->mnet_localhost_id), '*', MUST_EXIST);
} else if ($this->authmethod == WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN){
$user = $this->authenticate_by_token(EXTERNAL_TOKEN_PERMANENT);
} else {
$user = $this->authenticate_by_token(EXTERNAL_TOKEN_EMBEDDED);
}
//Non admin can not authenticate if maintenance mode
$hassiteconfig = has_capability('moodle/site:config', context_system::instance(), $user);
if (!empty($CFG->maintenance_enabled) and !$hassiteconfig) {
throw new moodle_exception('sitemaintenance', 'admin');
}
//only confirmed user should be able to call web service
if (!empty($user->deleted)) {
$params = $loginfaileddefaultparams;
$params['other']['reason'] = 'user_deleted';
$params['other']['username'] = $user->username;
$event = \core\event\webservice_login_failed::create($params);
$event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessuserdeleted', 'webservice',
$user->username) . " - ".getremoteaddr(), 0, $user->id));
$event->trigger();
throw new webservice_access_exception('Refused web service access for deleted username: ' . $user->username);
}
//only confirmed user should be able to call web service
if (empty($user->confirmed)) {
$params = $loginfaileddefaultparams;
$params['other']['reason'] = 'user_unconfirmed';
$params['other']['username'] = $user->username;
$event = \core\event\webservice_login_failed::create($params);
$event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessuserunconfirmed', 'webservice',
$user->username) . " - ".getremoteaddr(), 0, $user->id));
$event->trigger();
throw new moodle_exception('wsaccessuserunconfirmed', 'webservice', '', $user->username);
}
//check the user is suspended
if (!empty($user->suspended)) {
$params = $loginfaileddefaultparams;
$params['other']['reason'] = 'user_unconfirmed';
$params['other']['username'] = $user->username;
$event = \core\event\webservice_login_failed::create($params);
$event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessusersuspended', 'webservice',
$user->username) . " - ".getremoteaddr(), 0, $user->id));
$event->trigger();
throw new webservice_access_exception('Refused web service access for suspended username: ' . $user->username);
}
//retrieve the authentication plugin if no previously done
if (empty($auth)) {
$auth = get_auth_plugin($user->auth);
}
// check if credentials have expired
if (!empty($auth->config->expiration) and $auth->config->expiration == 1) {
$days2expire = $auth->password_expire($user->username);
if (intval($days2expire) < 0 ) {
$params = $loginfaileddefaultparams;
$params['other']['reason'] = 'password_expired';
$params['other']['username'] = $user->username;
$event = \core\event\webservice_login_failed::create($params);
$event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessuserexpired', 'webservice',
$user->username) . " - ".getremoteaddr(), 0, $user->id));
$event->trigger();
throw new webservice_access_exception('Refused web service access for password expired username: ' . $user->username);
}
}
//check if the auth method is nologin (in this case refuse connection)
if ($user->auth=='nologin') {
$params = $loginfaileddefaultparams;
$params['other']['reason'] = 'login';
$params['other']['username'] = $user->username;
$event = \core\event\webservice_login_failed::create($params);
$event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessusernologin', 'webservice',
$user->username) . " - ".getremoteaddr(), 0, $user->id));
$event->trigger();
throw new webservice_access_exception('Refused web service access for nologin authentication username: ' . $user->username);
}
// now fake user login, the session is completely empty too
enrol_check_plugins($user);
\core\session\manager::set_user($user);
$this->userid = $user->id;
if ($this->authmethod != WEBSERVICE_AUTHMETHOD_SESSION_TOKEN && !has_capability("webservice/$this->wsname:use", $this->restricted_context)) {
throw new webservice_access_exception('You are not allowed to use the {$a} protocol (missing capability: webservice/' . $this->wsname . ':use)');
}
external_api::set_context_restriction($this->restricted_context);