forked from MaharaProject/mahara
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.php
2067 lines (1812 loc) · 77.3 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
/**
*
* @package mahara
* @subpackage auth-webservice
* @author Catalyst IT Ltd
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later
* @copyright For copyright information on Mahara, please see the README file distributed with this software.
*
*/
defined('INTERNAL') || die();
$path = get_config('docroot') . 'webservice/libs/zend';
set_include_path($path . PATH_SEPARATOR . get_include_path());
require_once(get_config('docroot') . 'webservice/locallib.php');
require_once(get_config('docroot') . 'artefact/lib.php');
require_once(get_config('docroot') . 'webservice/libs/net.php');
require_once(get_config('docroot') . 'api/xmlrpc/lib.php');
/**
* The directory within a component that contains the web service files
*/
define('WEBSERVICE_DIRECTORY', 'webservice');
/**
* Security token used for allowing access
* from external application such as web services.
* Scripts do not use any session, performance is relatively
* low because we need to load access info in each request.
* Scripts are executed in parallel.
*/
define('EXTERNAL_TOKEN_PERMANENT', 0);
/**
* Security token used for allowing access
* of embedded applications, the code is executed in the
* active user session. Token is invalidated after user logs out.
* Scripts are executed serially - normal session locking is used.
*/
define('EXTERNAL_TOKEN_EMBEDDED', 1);
/**
* OAuth Token type for registered applications oauth v1
*/
define('EXTERNAL_TOKEN_OAUTH1', 2);
/**
* OAuth Token type for registered applications oauth v1
*/
define('EXTERNAL_TOKEN_USER', 3);
/**
* Personal User Tokens expiry time
*/
define('EXTERNAL_TOKEN_USER_EXPIRES', (30 * 24 * 60 * 60));
define('WEBSERVICE_AUTHMETHOD_USERNAME', 0);
define('WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN', 1);
define('WEBSERVICE_AUTHMETHOD_SESSION_TOKEN', 2);
define('WEBSERVICE_AUTHMETHOD_OAUTH_TOKEN', 3);
define('WEBSERVICE_AUTHMETHOD_USER_TOKEN', 4);
// strictness check
define('MUST_EXIST', 2);
/** Get remote addr constant */
define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
/** Get remote addr constant */
define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
/**
* What debugging state is Web Services in
*
* @return boolean true on yes
*/
function ws_debugging() {
// must be set in config.php
if (get_config('enablewsdebugging')) {
return true;
}
else {
return false;
}
}
/**
* Check that a user is in the institution
*
* @param array $user array('id' => .., 'username' => ..)
* @param string $institution
* @return boolean true on yes
*/
function mahara_external_in_institution($user, $institution) {
$institutions = array_keys(load_user_institutions($user->id));
$auth_instance = get_record('auth_instance', 'id', $user->authinstance);
$institutions[]= $auth_instance->institution;
if (!in_array($institution, $institutions)) {
return false;
}
return true;
}
/**
* parameter definition for output of any Atom generator
*
* Returns description of method result value
* @return external_description
*/
function mahara_external_atom_returns() {
return new external_single_structure(
array(
'id' => new external_value(PARAM_RAW, 'Atom document Id'),
'title' => new external_value(PARAM_RAW, 'Atom document Title'),
'link' => new external_value(PARAM_RAW, 'Atom document Link'),
'email' => new external_value(PARAM_RAW, 'Atom document Author Email'),
'name' => new external_value(PARAM_RAW, 'Atom document Author Name'),
'updated' => new external_value(PARAM_RAW, 'Atom document Updated date'),
'uri' => new external_value(PARAM_RAW, 'Atom document URI'),
'entries' => new external_multiple_structure(
new external_single_structure(
array(
'id' => new external_value(PARAM_RAW, 'Atom entry Id'),
'link' => new external_value(PARAM_RAW, 'Atom entry Link'),
'email' => new external_value(PARAM_RAW, 'Atom entry Author Link'),
'name' => new external_value(PARAM_RAW, 'Atom entry Author Name'),
'updated' => new external_value(PARAM_RAW, 'Atom entry updated date'),
'published' => new external_value(PARAM_RAW, 'Atom entry published date'),
'title' => new external_value(PARAM_RAW, 'Atom entry Title'),
'summary' => new external_value(PARAM_RAW, 'Atom entry Summary', VALUE_OPTIONAL),
'content' => new external_value(PARAM_RAW, 'Atom entry Content', VALUE_OPTIONAL),
), 'Atom entry', VALUE_OPTIONAL)
, 'Entries', VALUE_OPTIONAL),
)
);
}
/**
* validate the user for webservices access
* the account must use the webservice auth plugin
* the account must have membership for the selected auth_instance
*
* @param object $dbuser
* @return object $auth_instance or null if $dbuser is empty
*/
function webservice_validate_user($dbuser) {
global $SESSION;
if (!empty($dbuser)) {
$auth_instance = get_record('auth_instance', 'id', $dbuser->authinstance);
if ($auth_instance->authname == 'webservice') {
$memberships = count_records('usr_institution', 'usr', $dbuser->id);
if ($memberships == 0) {
// auth instance should be a mahara one
if ($auth_instance->institution == 'mahara') {
return $auth_instance;
}
}
else {
$membership = get_record('usr_institution', 'usr', $dbuser->id, 'institution', $auth_instance->institution);
if (!empty($membership)) {
return $auth_instance;
}
}
}
}
return NULL;
}
/**
* List all installed component web service directories
*
* @return array of web service plugin directories
*/
function get_ws_subsystems() {
static $plugindirs = null;
if (!$plugindirs) {
// add the root webservice first which is empty because it is docroot, and local
$plugindirs = array(WEBSERVICE_DIRECTORY, 'local/' . WEBSERVICE_DIRECTORY);
foreach (plugin_types_installed() as $t) {
foreach (plugins_installed($t) as $name => $plugindata) {
$plugindir = $t . '/' . $name;
if (!empty($plugindata->authplugin)) {
$plugindir = 'auth/' . $plugindata->authplugin . '/' . $plugindir;
}
$plugindirs[] = $plugindir . '/' . WEBSERVICE_DIRECTORY;
}
}
}
return $plugindirs;
}
/**
* Generate a web services token
* @param string $tokentype
* @param integer $serviceorid
* @param integer $userid
* @param string $institution
* @param integer $validuntil
* @param string $iprestriction
* @throws WebserviceException
* @return string token
*/
function webservice_generate_token($tokentype, $serviceorid, $userid, $institution = 'mahara', $validuntil=0, $iprestriction='') {
global $USER;
// make sure the token doesn't exist (even if it should be almost impossible with the random generation)
$numtries = 0;
do {
$numtries ++;
$generatedtoken = md5(uniqid(rand(),1));
if ($numtries > 5) {
throw new WebserviceException('tokengenerationfailed');
}
} while (record_exists('external_tokens', 'token', $generatedtoken));
$newtoken = new stdClass();
$newtoken->token = $generatedtoken;
if (!is_object($serviceorid)) {
$service = get_record('external_services', 'id', $serviceorid);
}
else {
$service = $serviceorid;
}
$newtoken->externalserviceid = $service->id;
$newtoken->tokentype = $tokentype;
$newtoken->userid = $userid;
if ($tokentype == EXTERNAL_TOKEN_EMBEDDED) {
$newtoken->sid = session_id();
}
$newtoken->institution = $institution;
$newtoken->creatorid = $USER->get('id');
$newtoken->ctime = db_format_timestamp(time());
$newtoken->publickeyexpires = time();
$newtoken->wssigenc = 0;
$newtoken->publickey = '';
$newtoken->validuntil = $validuntil;
if (!empty($iprestriction)) {
$newtoken->iprestriction = $iprestriction;
}
insert_record('external_tokens', $newtoken);
return $newtoken->token;
}
/**
* Create and return a session linked token. Token to be used for html embedded client apps that want to communicate
* with the Moodle server through web services. The token is linked to the current session for the current page request.
* It is expected this will be called in the script generating the html page that is embedding the client app and that the
* returned token will be somehow passed into the client app being embedded in the page.
* @param string $servicename name of the web service. Service name as defined in db/services.php
* @param integer $userid
* @param string $institution
* @param integer $validuntil
* @param string $iprestriction
* @return int returns token id.
*/
function webservice_create_service_token($servicename, $userid, $institution = 'mahara', $validuntil=0, $iprestriction='') {
$service = get_record('external_services', 'name', $servicename, '*');
return webservice_generate_token(EXTERNAL_TOKEN_EMBEDDED, $service, $userid, $institution, $validuntil, $iprestriction);
}
/**
* Returns detailed function information
* @param string|object $function name of external function or record from external_function
* @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
* MUST_EXIST means throw exception if no record or multiple records found
* @return object description or false if not found or exception thrown
*/
function webservice_function_info($function, $strictness=MUST_EXIST) {
if (!is_object($function)) {
if (!$function = get_record('external_functions', 'name', $function, NULL, NULL, NULL, NULL, '*')) {
return false;
}
}
//first find and include the ext implementation class
$function->classpath = empty($function->classpath) ? get_config('docroot') . $function->component : get_config('docroot') . $function->classpath;
if (!file_exists($function->classpath . '/functions/' . $function->classname . '.php')) {
throw new WebserviceCodingException(get_string('cannotfindimplfile', 'auth.webservice'));
}
require_once($function->classpath . '/functions/' . $function->classname . '.php');
$function->parameters_method = $function->methodname . '_parameters';
$function->returns_method = $function->methodname . '_returns';
// make sure the implementaion class is ok
if (!method_exists($function->classname, $function->methodname)) {
throw new WebserviceCodingException(get_string('missingimplofmeth', 'auth.webservice', $function->classname . '::' . $function->methodname));
}
if (!method_exists($function->classname, $function->parameters_method)) {
throw new WebserviceCodingException(get_string('missingparamdesc', 'auth.webservice'));
}
if (!method_exists($function->classname, $function->returns_method)) {
throw new WebserviceCodingException(get_string('missingretvaldesc', 'auth.webservice'));
}
// fetch the parameters description
$function->parameters_desc = call_user_func(array($function->classname, $function->parameters_method));
if (!($function->parameters_desc instanceof external_function_parameters)) {
throw new WebserviceCodingException(get_string('invalidparamdesc', 'auth.webservice'));
}
// fetch the return values description
$function->returns_desc = call_user_func(array($function->classname, $function->returns_method));
// null means void result or result is ignored
if (!is_null($function->returns_desc) and !($function->returns_desc instanceof external_description)) {
throw new WebserviceCodingException(get_string('invalidretdesc', 'auth.webservice'));
}
//now get the function description
//TODO: use localised lang pack descriptions, it would be nice to have
// easy to understand descriptions in admin UI,
// on the other hand this is still a bit in a flux and we need to find some new naming
// conventions for these descriptions in lang packs
$function->description = null;
$servicesfile = $function->classpath . '/services.php';
if (file_exists($servicesfile)) {
$functions = null;
include($servicesfile);
if (isset($functions[$function->name]['description'])) {
$function->description = $functions[$function->name]['description'];
}
}
return $function;
}
/**
* General web service library
*/
class webservice {
/**
* Get the list of all functions for given service ids
* @param array $serviceids
* @return array functions
*/
public function get_external_functions($serviceids) {
global $WS_FUNCTIONS;
if (!empty($serviceids)) {
$where = (count($serviceids) == 1 ? ' = '.array_shift($serviceids) : ' IN (' . implode(',', $serviceids) . ')');
$sql = "SELECT f.*
FROM {external_functions} f
WHERE f.name IN (SELECT sf.functionname
FROM {external_services_functions} sf
WHERE sf.externalserviceid $where)";
$functions = get_records_sql_array($sql, array());
}
else {
$functions = array();
}
// stash functions for intro spective RPC calls later
$WS_FUNCTIONS = array();
foreach ($functions as $function) {
$WS_FUNCTIONS[$function->name] = array('id' => $function->id);
}
return $functions;
}
}
/**
* Base class for external api methods.
*/
class external_api {
private static $contextrestriction;
/**
* Set context restriction for all following subsequent function calls.
* @param stdClass $contex
* @return void
*/
public static function set_context_restriction($context) {
self::$contextrestriction = $context;
}
/**
* This method has to be called before every operation
* that takes a longer time to finish!
*
* @param int $seconds max expected time the next operation needs
* @return void
*/
public static function set_timeout($seconds=360) {
$seconds = ($seconds < 300) ? 300 : $seconds;
set_time_limit($seconds);
}
/**
* Validates submitted function parameters, if anything is incorrect
* WebserviceInvalidParameterException is thrown.
* This is a simple recursive method which is intended to be called from
* each implementation method of external API.
* @param external_description $description description of parameters
* @param mixed $params the actual parameters
* @return mixed params with added defaults for optional items, invalid_parameters_exception thrown if any problem found
*/
public static function validate_parameters(external_description $description, $params) {
if ($description instanceof external_value) {
if (is_array($params) or is_object($params)) {
throw new WebserviceInvalidParameterException(get_string('errorscalartype', 'auth.webservice'));
}
if ($description->type == PARAM_BOOL) {
// special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
if (is_bool($params) or $params === 0 or $params === 1 or $params === '0' or $params === '1') {
return (bool)$params;
}
}
return validate_param($params, $description->type, $description->allownull, get_string('errorinvalidparamsapi', 'auth.webservice'));
}
else if ($description instanceof external_single_structure) {
if (!is_array($params)) {
throw new WebserviceInvalidParameterException(get_string('erroronlyarray', 'auth.webservice'));
}
$result = array();
foreach ($description->keys as $key=>$subdesc) {
if (!array_key_exists($key, $params)) {
if ($subdesc->required == VALUE_REQUIRED) {
throw new WebserviceInvalidParameterException(get_string('errormissingkey', 'auth.webservice', $key));
}
if ($subdesc->required == VALUE_DEFAULT) {
try {
$result[$key] = self::validate_parameters($subdesc, $subdesc->default);
} catch (WebserviceInvalidParameterException $e) {
throw new WebserviceParameterException('invalidextparam', $key);
}
}
}
else {
try {
$result[$key] = self::validate_parameters($subdesc, $params[$key]);
} catch (WebserviceInvalidParameterException $e) {
//it's ok to display debug info as here the information is useful for ws client/dev
throw new WebserviceParameterException('invalidextparam',"key: $key (debuginfo: " . $e->debuginfo.") ");
}
}
unset($params[$key]);
}
if (!empty($params)) {
//list all unexpected keys
$keys = '';
foreach ($params as $key => $value) {
$keys .= $key . ',';
}
throw new WebserviceInvalidParameterException(get_string('errorunexpectedkey', 'auth.webservice', $keys));
}
return $result;
}
else if ($description instanceof external_multiple_structure) {
if (!is_array($params)) {
throw new WebserviceInvalidParameterException(get_string('erroronlyarray', 'auth.webservice'));
}
$result = array();
foreach ($params as $param) {
$result[] = self::validate_parameters($description->content, $param);
}
return $result;
}
else {
throw new WebserviceInvalidParameterException(get_string('errorinvalidparamsdesc', 'auth.webservice'));
}
}
/**
* Clean response
* If a response attribute is unknown from the description, we just ignore the attribute.
* If a response attribute is incorrect, WebserviceInvalidResponseException is thrown.
* Note: this function is similar to validate parameters, however it is distinct because
* parameters validation must be distinct from cleaning return values.
* @param external_description $description description of the return values
* @param mixed $response the actual response
* @return mixed response with added defaults for optional items, WebserviceInvalidResponseException thrown if any problem found
*/
public static function clean_returnvalue(external_description $description, $response) {
if ($description instanceof external_value) {
if (is_array($response) or is_object($response)) {
throw new WebserviceInvalidResponseException(get_string('errorscalartype', 'auth.webservice'));
}
if ($description->type == PARAM_BOOL) {
// special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
if (is_bool($response) or $response === 0 or $response === 1 or $response === '0' or $response === '1') {
return (bool)$response;
}
}
return validate_param($response, $description->type, $description->allownull, get_string('errorinvalidresponseapi', 'auth.webservice'));
}
else if ($description instanceof external_single_structure) {
if (!is_array($response)) {
throw new WebserviceInvalidResponseException(get_string('erroronlyarray', 'auth.webservice'));
}
$result = array();
foreach ($description->keys as $key=>$subdesc) {
if (!array_key_exists($key, $response)) {
if ($subdesc->required == VALUE_REQUIRED) {
throw new WebserviceParameterException('errorresponsemissingkey', $key);
}
if ($subdesc instanceof external_value) {
if ($subdesc->required == VALUE_DEFAULT) {
try {
$result[$key] = self::clean_returnvalue($subdesc, $subdesc->default);
} catch (Exception $e) {
throw new WebserviceParameterException('invalidextresponse',$key . " (" . $e->getMessage() . ")");
}
}
}
}
else {
try {
$result[$key] = self::clean_returnvalue($subdesc, $response[$key]);
} catch (Exception $e) {
//it's ok to display debug info as here the information is useful for ws client/dev
throw new WebserviceParameterException('invalidextresponse', $key . " (" . $e->getMessage() . ")");
}
}
unset($response[$key]);
}
return $result;
}
else if ($description instanceof external_multiple_structure) {
if (!is_array($response)) {
throw new WebserviceInvalidResponseException(get_string('erroronlyarray', 'auth.webservice'));
}
$result = array();
foreach ($response as $param) {
$result[] = self::clean_returnvalue($description->content, $param);
}
return $result;
}
else {
throw new WebserviceInvalidResponseException(get_string('errorinvalidresponsedesc', 'auth.webservice'));
}
}
}
/**
* Common ancestor of all parameter description classes
*/
abstract class external_description {
/** @property string $description description of element */
public $desc;
/** @property bool $required element value required, null not allowed */
public $required;
/** @property mixed $default default value */
public $default;
/**
* Contructor
* @param string $desc
* @param bool $required
* @param mixed $default
*/
public function __construct($desc, $required, $default) {
$this->desc = $desc;
$this->required = $required;
$this->default = $default;
}
}
/**
* Scalar alue description class
*/
class external_value extends external_description {
/** @property mixed $type value type PARAM_XX */
public $type;
/** @property bool $allownull allow null values */
public $allownull;
/**
* Constructor
* @param mixed $type
* @param string $desc
* @param bool $required
* @param mixed $default
* @param bool $allownull
*/
public function __construct($type, $desc='', $required=VALUE_REQUIRED,
$default=null, $allownull=NULL_ALLOWED) {
parent::__construct($desc, $required, $default);
$this->type = $type;
$this->allownull = $allownull;
}
}
/**
* Associative array description class
*/
class external_single_structure extends external_description {
/** @property array $keys description of array keys key=>external_description */
public $keys;
/**
* Constructor
* @param array $keys
* @param string $desc
* @param bool $required
* @param array $default
*/
public function __construct(array $keys, $desc='',
$required=VALUE_REQUIRED, $default=null) {
parent::__construct($desc, $required, $default);
$this->keys = $keys;
}
}
/**
* Bulk array description class.
*/
class external_multiple_structure extends external_description {
/** @property external_description $content */
public $content;
/**
* Constructor
* @param external_description $content
* @param string $desc
* @param bool $required
* @param array $default
*/
public function __construct(external_description $content, $desc='',
$required=VALUE_REQUIRED, $default=null) {
parent::__construct($desc, $required, $default);
$this->content = $content;
}
}
/**
* Description of top level - PHP function parameters.
* @author skodak
*
*/
class external_function_parameters extends external_single_structure {
}
/**
* Is protocol enabled?
* @param string $protocol name of WS protocol
* @return bool
*/
function webservice_protocol_is_enabled($protocol) {
if (!get_config('webservice_enabled')) {
return false;
}
return get_config('webservice_'.$protocol.'_enabled');
}
//=== WS classes ===
/**
* Mandatory interface for all test client classes.
* @author Petr Skoda (skodak)
*/
interface webservice_test_client_interface {
/**
* Execute test client WS request
* @param string $serverurl
* @param string $function
* @param array $params
* @return mixed
*/
public function simpletest($serverurl, $function, $params);
}
/**
* Mandatory interface for all web service protocol classes
* @author Petr Skoda (skodak)
*/
interface webservice_server_interface {
/**
* Process request from client.
* @return void
*/
public function run();
}
/**
* Abstract web service base class.
* @author Petr Skoda (skodak)
*/
abstract class webservice_server implements webservice_server_interface {
/** @property string $wsname name of the web server plugin */
protected $wsname = null;
/** @property string $username name of local user */
protected $username = null;
/** @property string $password password of the local user */
protected $password = null;
/** @property string $service service for wsdl look up */
protected $service = null;
/** @property int $userid the local user */
protected $userid = null;
/** @property integer $authmethod authentication method one of WEBSERVICE_AUTHMETHOD_* */
protected $authmethod;
/** @property string $token authentication token*/
protected $token = null;
/** @property int restrict call to one service id*/
protected $restricted_serviceid = null;
/** @property string info to add to logging*/
protected $info = null;
/**
* Contructor
* @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.
* @return void
*/
protected function authenticate_user() {
global $USER, $SESSION, $WEBSERVICE_INSTITUTION, $WEBSERVICE_OAUTH_USER;
if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
$this->auth = 'USER';
//we check that authentication plugin is enabled
//it is only required by simple authentication
$plugin = get_record('auth_installed', 'name', 'webservice');
if (empty($plugin) || $plugin->active != 1) {
throw new WebserviceAccessException(get_string('wsauthnotenabled', 'auth.webservice'));
}
if (!$this->username) {
throw new WebserviceAccessException(get_string('missingusername', 'auth.webservice'));
}
if (!$this->password) {
throw new WebserviceAccessException(get_string('missingpassword', 'auth.webservice'));
}
// special web service login
safe_require('auth', 'webservice');
// get the user
$user = get_record('usr', 'username', $this->username);
if (empty($user)) {
throw new WebserviceAccessException(get_string('wrongusernamepassword', 'auth.webservice'));
}
// user account is nolonger validly configured
if (!$auth_instance = webservice_validate_user($user)) {
throw new WebserviceAccessException(get_string('invalidaccount', 'auth.webservice'));
}
// set the global for the web service users defined institution
$WEBSERVICE_INSTITUTION = $auth_instance->institution;
// get the institution from the external user
$ext_user = get_record('external_services_users', 'userid', $user->id);
if (empty($ext_user)) {
throw new WebserviceAccessException(get_string('wrongusernamepassword', 'auth.webservice'));
}
// determine the internal auth instance
$auth_instance = get_record('auth_instance', 'institution', $ext_user->institution, 'authname', 'webservice');
if (empty($auth_instance)) {
throw new WebserviceAccessException(get_string('wrongusernamepassword', 'auth.webservice'));
}
// authenticate the user
$auth = new AuthWebservice($auth_instance->id);
if (!$auth->authenticate_user_account($user, $this->password, 'webservice')) {
// log failed login attempts
throw new WebserviceAccessException(get_string('wrongusernamepassword', 'auth.webservice'));
}
}
else if ($this->authmethod == WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN) {
$this->auth = 'TOKEN';
$user = $this->authenticate_by_token(EXTERNAL_TOKEN_PERMANENT);
}
else if ($this->authmethod == WEBSERVICE_AUTHMETHOD_OAUTH_TOKEN) {
//OAuth
$this->auth = 'OAUTH';
// special web service login
safe_require('auth', 'webservice');
// get the user - the user that authorised the token
$user = get_record('usr', 'id', $this->oauth_token_details['user_id']);
if (empty($user)) {
throw new WebserviceAccessException(get_string('wrongusernamepassword', 'auth.webservice'));
}
// check user is member of configured OAuth institution
$institutions = array_keys(load_user_institutions($this->oauth_token_details['user_id']));
$auth_instance = get_record('auth_instance', 'id', $user->authinstance);
$institutions[]= $auth_instance->institution;
if (!in_array($this->oauth_token_details['institution'], $institutions)) {
throw new WebserviceAccessException(get_string('institutiondenied', 'auth.webservice'));
}
// set the global for the web service users defined institution
$WEBSERVICE_INSTITUTION = $this->oauth_token_details['institution'];
// set the note of the OAuth service owner
$WEBSERVICE_OAUTH_USER = $this->oauth_token_details['service_user'];
}
else {
$this->auth = 'OTHER';
$user = $this->authenticate_by_token(EXTERNAL_TOKEN_USER);
}
// now fake user login, the session is completely empty too
$USER->reanimate($user->id, $user->authinstance);
}
/**
* Authenticate by token type
*
* @param $tokentype string tokentype constant
* @return $user object
*/
protected function authenticate_by_token($tokentype) {
global $WEBSERVICE_INSTITUTION;
if ($tokentype == EXTERNAL_TOKEN_PERMANENT || $tokentype == EXTERNAL_TOKEN_USER) {
$token = get_record('external_tokens', 'token', $this->token);
// trap personal tokens with no valid until time set
if ($token && $token->tokentype == EXTERNAL_TOKEN_USER && $token->validuntil == 0 && ((strtotime($token->ctime) - time()) > EXTERNAL_TOKEN_USER_EXPIRES)) {
delete_records('external_tokens', 'token', $this->token);
throw new WebserviceAccessException(get_string('invalidtimedtoken', 'auth.webservice'));
}
}
else {
$token = get_record('external_tokens', 'token', $this->token, 'tokentype', $tokentype);
}
if (!$token) {
// log failed login attempts
throw new WebserviceAccessException(get_string('invalidtoken', 'auth.webservice'));
}
// tidy up the uath method - this could be user token or session token
if ($token->tokentype != EXTERNAL_TOKEN_PERMANENT) {
$this->auth = 'OTHER';
}
/**
* check the valid until date
*/
if ($token->validuntil and $token->validuntil < time()) {
delete_records('external_tokens', 'token', $this->token, 'tokentype', $tokentype);
throw new WebserviceAccessException(get_string('invalidtimedtoken', 'auth.webservice'));
}
//assumes that if sid is set then there must be a valid associated session no matter the token type
if ($token->sid) {
$session = session_get_instance();
if (!$session->session_exists($token->sid)) {
delete_records('external_tokens', 'sid', $token->sid);
throw new WebserviceAccessException(get_string('invalidtokensession', 'auth.webservice'));
}
}
if ($token->iprestriction and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
throw new WebserviceAccessException(get_string('invalidiptoken', 'auth.webservice'));
}
$this->restricted_serviceid = $token->externalserviceid;
$user = get_record('usr', 'id', $token->userid, 'deleted', 0);
// log token access
set_field('external_tokens', 'mtime', db_format_timestamp(time()), 'id', $token->id);
// set the global for the web service users defined institution
$WEBSERVICE_INSTITUTION = $token->institution;
return $user;
}
/**
* Intercept some maharawssettingXXX $_GET and $_POST parameter
* that are related to the web service call and are not the function parameters
*/
protected function set_web_service_call_settings() {
global $CFG;
// Default web service settings.
// Must be the same XXX key name as the external_settings::set_XXX function.
// Must be the same XXX ws parameter name as 'maharawssettingXXX'.
$externalsettings = array(
'raw' => false,
'fileurl' => true,
'filter' => false);
// Load the external settings with the web service settings.
$settings = external_settings::get_instance();
foreach ($externalsettings as $name => $default) {
$wsparamname = 'maharawssetting' . $name;
// Retrieve and remove the setting parameter from the request.
// $value = optional_param($wsparamname, $default, PARAM_BOOL);
$value = param_variable($wsparamname, $default);
unset($_GET[$wsparamname]);
unset($_POST[$wsparamname]);
$functioname = 'set_' . $name;
$settings->$functioname($value);
}
}
}
/**
* Special abstraction of our srvices that allows
* interaction with stock Zend ws servers.
* @author Petr Skoda (skodak)
*/
abstract class webservice_zend_server extends webservice_server {
/** @property string name of the zend server class : Zend_XmlRpc_Server, Zend_Soap_Server, Zend_Soap_AutoDiscover, ...*/
protected $zend_class;
/** @property object Zend server instance */
protected $zend_server;
/** @property string $service_class virtual web service class with all functions user name execute, created on the fly */
protected $service_class;
/** @property string $functionname the name of the function that is executed */
protected $functionname = null;
/**
* Contructor
* @param integer $authmethod authentication method - one of WEBSERVICE_AUTHMETHOD_*
*/
public function __construct($authmethod, $zend_class) {
parent::__construct($authmethod);
$this->zend_class = $zend_class;
}
/**
* Process request from client.
* @param bool $simple use simple authentication
* @return void
*/
public function run() {
global $WEBSERVICE_FUNCTION_RUN, $USER, $WEBSERVICE_INSTITUTION, $WEBSERVICE_START;
$WEBSERVICE_START = microtime(true);
// we will probably need a lot of memory in some functions
raise_memory_limit('128M');
// set some longer timeout, this script is not sending any output,
// this means we need to manually extend the timeout operations
// that need longer time to finish
external_api::set_timeout();
// now create the instance of zend server
$this->init_zend_server();
// set up exception handler first, we want to sent them back in correct format that
// the other system understands
// we do not need to call the original default handler because this ws handler does everything
set_exception_handler(array($this, 'exception_handler'));
// init all properties from the request data
$this->parse_request();
// process wsdl only, and without a user
$xml = null;
if ($this->service && isset($_REQUEST['wsdl'])) {
$dbservice = get_record('external_services', 'name', $this->service);
if (empty($dbservice)) {
// throw error
throw new WebserviceAccessException(get_string('invalidservice', 'auth.webservice'));
}
$serviceids = array($dbservice->id);
$this->load_services($serviceids);
}
else {
// Manipulate the payload if necessary
$xml = $this->modify_payload();
// this sets up $USER and $SESSION and context restrictions
$this->authenticate_user();
}