gradebook MDL-22428 fixed a JS problem that prevented the user from changing a course...
[moodle.git] / webservice / lib.php
CommitLineData
06e7fadc 1<?php
cc93c7da 2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
06e7fadc 18/**
cc93c7da 19 * Web services utility functions and classes
06e7fadc 20 *
06e7fadc 21 * @package webservice
551f4420 22 * @copyright 2009 Moodle Pty Ltd (http://moodle.com)
cc93c7da 23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
06e7fadc 24 */
25
cc93c7da 26require_once($CFG->libdir.'/externallib.php');
893d7f0f 27
2d0acbd5
JP
28define('WEBSERVICE_AUTHMETHOD_USERNAME', 0);
29define('WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN', 1);
30define('WEBSERVICE_AUTHMETHOD_SESSION_TOKEN', 2);
31
5593d2dc 32/**
33 * Exception indicating access control problem in web service call
01482a4a 34 * @author Petr Skoda (skodak)
5593d2dc 35 */
36class webservice_access_exception extends moodle_exception {
37 /**
38 * Constructor
39 */
40 function __construct($debuginfo) {
e8b21670 41 parent::__construct('accessexception', 'webservice', '', null, $debuginfo);
5593d2dc 42 }
43}
44
f0dafb3c 45/**
46 * Is protocol enabled?
47 * @param string $protocol name of WS protocol
48 * @return bool
49 */
cc93c7da 50function webservice_protocol_is_enabled($protocol) {
51 global $CFG;
893d7f0f 52
cc93c7da 53 if (empty($CFG->enablewebservices)) {
54 return false;
893d7f0f 55 }
56
cc93c7da 57 $active = explode(',', $CFG->webserviceprotocols);
893d7f0f 58
cc93c7da 59 return(in_array($protocol, $active));
60}
893d7f0f 61
01482a4a 62//=== WS classes ===
893d7f0f 63
f0dafb3c 64/**
3f599588 65 * Mandatory interface for all test client classes.
01482a4a 66 * @author Petr Skoda (skodak)
f0dafb3c 67 */
68interface webservice_test_client_interface {
69 /**
70 * Execute test client WS request
71 * @param string $serverurl
72 * @param string $function
73 * @param array $params
74 * @return mixed
75 */
76 public function simpletest($serverurl, $function, $params);
77}
78
06e7fadc 79/**
3f599588 80 * Mandatory interface for all web service protocol classes
01482a4a 81 * @author Petr Skoda (skodak)
06e7fadc 82 */
01482a4a
PS
83interface webservice_server_interface {
84 /**
85 * Process request from client.
86 * @return void
87 */
88 public function run();
89}
88098133 90
01482a4a
PS
91/**
92 * Abstract web service base class.
93 * @author Petr Skoda (skodak)
94 */
95abstract class webservice_server implements webservice_server_interface {
88098133 96
97 /** @property string $wsname name of the web server plugin */
98 protected $wsname = null;
99
c187722c
PS
100 /** @property string $username name of local user */
101 protected $username = null;
102
103 /** @property string $password password of the local user */
104 protected $password = null;
b107e647 105
c3517f05 106 /** @property int $userid the local user */
107 protected $userid = null;
108
2d0acbd5
JP
109 /** @property integer $authmethod authentication method one of WEBSERVICE_AUTHMETHOD_* */
110 protected $authmethod;
88098133 111
01482a4a
PS
112 /** @property string $token authentication token*/
113 protected $token = null;
88098133 114
115 /** @property object restricted context */
116 protected $restricted_context;
117
01482a4a
PS
118 /** @property int restrict call to one service id*/
119 protected $restricted_serviceid = null;
120
2d0acbd5
JP
121 /**
122 * Contructor
123 * @param integer $authmethod authentication method one of WEBSERVICE_AUTHMETHOD_*
124 */
125 public function __construct($authmethod) {
126 $this->authmethod = $authmethod;
127 }
128
129
01482a4a
PS
130 /**
131 * Authenticate user using username+password or token.
132 * This function sets up $USER global.
133 * It is safe to use has_capability() after this.
134 * This method also verifies user is allowed to use this
135 * server.
136 * @return void
137 */
138 protected function authenticate_user() {
139 global $CFG, $DB;
140
141 if (!NO_MOODLE_COOKIES) {
142 throw new coding_exception('Cookies must be disabled in WS servers!');
143 }
144
2d0acbd5 145 if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
01482a4a 146
1839e2f0 147 //we check that authentication plugin is enabled
148 //it is only required by simple authentication
149 if (!is_enabled_auth('webservice')) {
150 throw new webservice_access_exception(get_string('wsauthnotenabled', 'webservice'));
151 }
01482a4a 152
1839e2f0 153 if (!$auth = get_auth_plugin('webservice')) {
154 throw new webservice_access_exception(get_string('wsauthmissing', 'webservice'));
155 }
01482a4a 156
01482a4a
PS
157 $this->restricted_context = get_context_instance(CONTEXT_SYSTEM);
158
159 if (!$this->username) {
b0a9a0cd 160 throw new webservice_access_exception(get_string('missingusername', 'webservice'));
01482a4a
PS
161 }
162
163 if (!$this->password) {
b0a9a0cd 164 throw new webservice_access_exception(get_string('missingpassword', 'webservice'));
01482a4a
PS
165 }
166
167 if (!$auth->user_login_webservice($this->username, $this->password)) {
1e29fe3f 168 // log failed login attempts
7e0eac79 169 add_to_log(1, 'webservice', get_string('simpleauthlog', 'webservice'), '' , get_string('failedtolog', 'webservice').": ".$this->username."/".$this->password." - ".getremoteaddr() , 0);
b0a9a0cd 170 throw new webservice_access_exception(get_string('wrongusernamepassword', 'webservice'));
01482a4a
PS
171 }
172
173 $user = $DB->get_record('user', array('username'=>$this->username, 'mnethostid'=>$CFG->mnet_localhost_id, 'deleted'=>0), '*', MUST_EXIST);
174
2d0acbd5
JP
175 } else if ($this->authmethod == WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN){
176 $user = $this->authenticate_by_token(EXTERNAL_TOKEN_PERMANENT);
01482a4a 177 } else {
2d0acbd5 178 $user = $this->authenticate_by_token(EXTERNAL_TOKEN_EMBEDDED);
01482a4a 179 }
2d0acbd5 180
01482a4a
PS
181 // now fake user login, the session is completely empty too
182 session_set_user($user);
c3517f05 183 $this->userid = $user->id;
01482a4a 184
0f1e3914 185 if ($this->authmethod != WEBSERVICE_AUTHMETHOD_SESSION_TOKEN && !has_capability("webservice/$this->wsname:use", $this->restricted_context)) {
b0a9a0cd 186 throw new webservice_access_exception(get_string('accessnotallowed', 'webservice'));
01482a4a
PS
187 }
188
189 external_api::set_context_restriction($this->restricted_context);
190 }
2d0acbd5
JP
191
192 protected function authenticate_by_token($tokentype){
193 global $DB;
194 if (!$token = $DB->get_record('external_tokens', array('token'=>$this->token, 'tokentype'=>$tokentype))) {
195 // log failed login attempts
196 add_to_log(1, 'webservice', get_string('tokenauthlog', 'webservice'), '' , get_string('failedtolog', 'webservice').": ".$this->token. " - ".getremoteaddr() , 0);
197 throw new webservice_access_exception(get_string('invalidtoken', 'webservice'));
198 }
199
200 if ($token->validuntil and $token->validuntil < time()) {
201 $DB->delete_records('external_tokens', array('token'=>$this->token, 'tokentype'=>$tokentype));
202 throw new webservice_access_exception(get_string('invalidtimedtoken', 'webservice'));
203 }
204
205 if ($token->sid){//assumes that if sid is set then there must be a valid associated session no matter the token type
206 $session = session_get_instance();
207 if (!$session->session_exists($token->sid)){
208 $DB->delete_records('external_tokens', array('sid'=>$token->sid));
209 throw new webservice_access_exception(get_string('invalidtokensession', 'webservice'));
210 }
211 }
212
213 if ($token->iprestriction and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
214 add_to_log(1, 'webservice', get_string('tokenauthlog', 'webservice'), '' , get_string('failedtolog', 'webservice').": ".getremoteaddr() , 0);
215 throw new webservice_access_exception(get_string('invalidiptoken', 'webservice'));
216 }
217
218 $this->restricted_context = get_context_instance_by_id($token->contextid);
219 $this->restricted_serviceid = $token->externalserviceid;
220
221 $user = $DB->get_record('user', array('id'=>$token->userid, 'deleted'=>0), '*', MUST_EXIST);
222
223 // log token access
224 $DB->set_field('external_tokens', 'lastaccess', time(), array('id'=>$token->id));
225
226 return $user;
227
228 }
01482a4a
PS
229}
230
231/**
232 * Special abstraction of our srvices that allows
233 * interaction with stock Zend ws servers.
234 * @author Petr Skoda (skodak)
235 */
236abstract class webservice_zend_server extends webservice_server {
237
abf7dc44 238 /** @property string name of the zend server class : Zend_XmlRpc_Server, Zend_Soap_Server, Zend_Soap_AutoDiscover, ...*/
01482a4a
PS
239 protected $zend_class;
240
241 /** @property object Zend server instance */
242 protected $zend_server;
243
244 /** @property string $service_class virtual web service class with all functions user name execute, created on the fly */
245 protected $service_class;
246
88098133 247 /**
248 * Contructor
2d0acbd5 249 * @param integer $authmethod authentication method - one of WEBSERVICE_AUTHMETHOD_*
88098133 250 */
2d0acbd5
JP
251 public function __construct($authmethod, $zend_class) {
252 parent::__construct($authmethod);
88098133 253 $this->zend_class = $zend_class;
254 }
255
256 /**
257 * Process request from client.
258 * @param bool $simple use simple authentication
259 * @return void
260 */
2458e30a 261 public function run() {
88098133 262 // we will probably need a lot of memory in some functions
263 @raise_memory_limit('128M');
264
265 // set some longer timeout, this script is not sending any output,
266 // this means we need to manually extend the timeout operations
267 // that need longer time to finish
268 external_api::set_timeout();
269
e8b21670 270 // now create the instance of zend server
271 $this->init_zend_server();
272
88098133 273 // set up exception handler first, we want to sent them back in correct format that
274 // the other system understands
275 // we do not need to call the original default handler because this ws handler does everything
276 set_exception_handler(array($this, 'exception_handler'));
277
c187722c
PS
278 // init all properties from the request data
279 $this->parse_request();
280
88098133 281 // this sets up $USER and $SESSION and context restrictions
282 $this->authenticate_user();
283
284 // make a list of all functions user is allowed to excecute
285 $this->init_service_class();
286
2458e30a 287 // tell server what functions are available
88098133 288 $this->zend_server->setClass($this->service_class);
eae18ab6 289
1e29fe3f 290 //log the web service request
7e0eac79 291 add_to_log(1, 'webservice', '', '' , $this->zend_class." ".getremoteaddr() , 0, $this->userid);
1e29fe3f 292
2458e30a 293 // execute and return response, this sends some headers too
88098133 294 $response = $this->zend_server->handle();
2458e30a 295
88098133 296 // session cleanup
297 $this->session_cleanup();
298
ca6340bf 299 //finally send the result
300 $this->send_headers();
88098133 301 echo $response;
302 die;
303 }
304
305 /**
306 * Load virtual class needed for Zend api
307 * @return void
308 */
309 protected function init_service_class() {
310 global $USER, $DB;
311
312 // first ofall get a complete list of services user is allowed to access
88098133 313
01482a4a
PS
314 if ($this->restricted_serviceid) {
315 $params = array('sid1'=>$this->restricted_serviceid, 'sid2'=>$this->restricted_serviceid);
316 $wscond1 = 'AND s.id = :sid1';
317 $wscond2 = 'AND s.id = :sid2';
318 } else {
319 $params = array();
320 $wscond1 = '';
321 $wscond2 = '';
322 }
88098133 323
01482a4a
PS
324 // now make sure the function is listed in at least one service user is allowed to use
325 // allow access only if:
326 // 1/ entry in the external_services_users table if required
327 // 2/ validuntil not reached
328 // 3/ has capability if specified in service desc
329 // 4/ iprestriction
88098133 330
01482a4a
PS
331 $sql = "SELECT s.*, NULL AS iprestriction
332 FROM {external_services} s
333 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0)
334 WHERE s.enabled = 1 $wscond1
88098133 335
01482a4a
PS
336 UNION
337
338 SELECT s.*, su.iprestriction
339 FROM {external_services} s
340 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1)
341 JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)
342 WHERE s.enabled = 1 AND su.validuntil IS NULL OR su.validuntil < :now $wscond2";
343
344 $params = array_merge($params, array('userid'=>$USER->id, 'now'=>time()));
88098133 345
346 $serviceids = array();
347 $rs = $DB->get_recordset_sql($sql, $params);
348
349 // now make sure user may access at least one service
350 $remoteaddr = getremoteaddr();
351 $allowed = false;
352 foreach ($rs as $service) {
353 if (isset($serviceids[$service->id])) {
354 continue;
355 }
356 if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) {
357 continue; // cap required, sorry
358 }
359 if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) {
360 continue; // wrong request source ip, sorry
361 }
362 $serviceids[$service->id] = $service->id;
363 }
364 $rs->close();
365
366 // now get the list of all functions
367 if ($serviceids) {
368 list($serviceids, $params) = $DB->get_in_or_equal($serviceids);
369 $sql = "SELECT f.*
370 FROM {external_functions} f
371 WHERE f.name IN (SELECT sf.functionname
372 FROM {external_services_functions} sf
373 WHERE sf.externalserviceid $serviceids)";
374 $functions = $DB->get_records_sql($sql, $params);
375 } else {
376 $functions = array();
377 }
378
379 // now make the virtual WS class with all the fuctions for this particular user
380 $methods = '';
381 foreach ($functions as $function) {
382 $methods .= $this->get_virtual_method_code($function);
383 }
384
5593d2dc 385 // let's use unique class name, there might be problem in unit tests
88098133 386 $classname = 'webservices_virtual_class_000000';
387 while(class_exists($classname)) {
388 $classname++;
389 }
390
391 $code = '
392/**
393 * Virtual class web services for user id '.$USER->id.' in context '.$this->restricted_context->id.'.
394 */
395class '.$classname.' {
396'.$methods.'
397}
398';
f0dafb3c 399
88098133 400 // load the virtual class definition into memory
401 eval($code);
88098133 402 $this->service_class = $classname;
403 }
404
405 /**
406 * returns virtual method code
407 * @param object $function
408 * @return string PHP code
409 */
410 protected function get_virtual_method_code($function) {
411 global $CFG;
412
5593d2dc 413 $function = external_function_info($function);
88098133 414
415 $params = array();
416 $params_desc = array();
453a7a85 417 foreach ($function->parameters_desc->keys as $name=>$keydesc) {
a8dd0325 418 $param = '$'.$name;
419 //need to generate the default if there is any
420 if ($keydesc instanceof external_value) {
421 if ($keydesc->required == VALUE_DEFAULT) {
422 if ($keydesc->default===null) {
423 $param .= '=null';
424 } else {
425 switch($keydesc->type) {
426 case PARAM_BOOL:
427 $param .= $keydesc->default; break;
428 case PARAM_INT:
429 $param .= $keydesc->default; break;
430 case PARAM_FLOAT;
431 $param .= $keydesc->default; break;
432 default:
433 $param .= '=\''.$keydesc->default.'\'';
434 }
435 }
436 } else if ($keydesc->required == VALUE_OPTIONAL) {
437 //it does make sens to declare a parameter VALUE_OPTIONAL
438 //VALUE_OPTIONAL is used only for array/object key
439 throw new moodle_exception('parametercannotbevalueoptional');
440 }
441 } else { //for the moment we do not support default for other structure types
442 if ($keydesc->required == VALUE_OPTIONAL or $keydesc->required == VALUE_DEFAULT) {
443 throw new moodle_exception('paramdefaultarraynotsupported');
444 }
445 }
446 $params[] = $param;
453a7a85 447 $type = 'string';
448 if ($keydesc instanceof external_value) {
449 switch($keydesc->type) {
450 case PARAM_BOOL: // 0 or 1 only for now
451 case PARAM_INT:
452 $type = 'int'; break;
453 case PARAM_FLOAT;
454 $type = 'double'; break;
455 default:
456 $type = 'string';
457 }
458 } else if ($keydesc instanceof external_single_structure) {
459 $type = 'struct';
460 } else if ($keydesc instanceof external_multiple_structure) {
461 $type = 'array';
462 }
463 $params_desc[] = ' * @param '.$type.' $'.$name.' '.$keydesc->desc;
88098133 464 }
465 $params = implode(', ', $params);
466 $params_desc = implode("\n", $params_desc);
94a9b9e7
JP
467
468 $serviceclassmethodbody = $this->service_class_method_body($function, $params);
88098133 469
453a7a85 470 if (is_null($function->returns_desc)) {
471 $return = ' * @return void';
472 } else {
473 $type = 'string';
474 if ($function->returns_desc instanceof external_value) {
475 switch($function->returns_desc->type) {
476 case PARAM_BOOL: // 0 or 1 only for now
477 case PARAM_INT:
478 $type = 'int'; break;
479 case PARAM_FLOAT;
480 $type = 'double'; break;
481 default:
482 $type = 'string';
483 }
484 } else if ($function->returns_desc instanceof external_single_structure) {
485 $type = 'struct';
486 } else if ($function->returns_desc instanceof external_multiple_structure) {
487 $type = 'array';
488 }
489 $return = ' * @return '.$type.' '.$function->returns_desc->desc;
490 }
d4e764ab 491
01482a4a 492 // now crate the virtual method that calls the ext implementation
88098133 493
494 $code = '
495 /**
5593d2dc 496 * '.$function->description.'
497 *
88098133 498'.$params_desc.'
453a7a85 499'.$return.'
88098133 500 */
501 public function '.$function->name.'('.$params.') {
c77e75a3 502'.$serviceclassmethodbody.'
88098133 503 }
504';
505 return $code;
506 }
94a9b9e7
JP
507
508 /**
509 * You can override this function in your child class to add extra code into the dynamically
510 * created service class. For example it is used in the amf server to cast types of parameters and to
511 * cast the return value to the types as specified in the return value description.
512 * @param unknown_type $function
513 * @param unknown_type $params
514 * @return string body of the method for $function ie. everything within the {} of the method declaration.
515 */
516 protected function service_class_method_body($function, $params){
d07ff72d 517 $descriptionmethod = $function->methodname.'_returns()';
2d0acbd5 518 $callforreturnvaluedesc = $function->classname.'::'.$descriptionmethod;
99152d09 519 return ' if ('.$callforreturnvaluedesc.' == null) {
520 return null;
521 }
522 return external_api::clean_returnvalue('.$callforreturnvaluedesc.', '.$function->classname.'::'.$function->methodname.'('.$params.'));';
94a9b9e7 523 }
d07ff72d 524
88098133 525 /**
b107e647 526 * Set up zend service class
88098133 527 * @return void
528 */
529 protected function init_zend_server() {
88098133 530 $this->zend_server = new $this->zend_class();
88098133 531 }
532
c187722c
PS
533 /**
534 * This method parses the $_REQUEST superglobal and looks for
535 * the following information:
536 * 1/ user authentication - username+password or token (wsusername, wspassword and wstoken parameters)
537 *
538 * @return void
539 */
540 protected function parse_request() {
2d0acbd5 541 if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
01482a4a 542 //note: some clients have problems with entity encoding :-(
c187722c
PS
543 if (isset($_REQUEST['wsusername'])) {
544 $this->username = $_REQUEST['wsusername'];
c187722c
PS
545 }
546 if (isset($_REQUEST['wspassword'])) {
547 $this->password = $_REQUEST['wspassword'];
c187722c
PS
548 }
549 } else {
01482a4a
PS
550 if (isset($_REQUEST['wstoken'])) {
551 $this->token = $_REQUEST['wstoken'];
88098133 552 }
88098133 553 }
88098133 554 }
555
ca6340bf 556 /**
557 * Internal implementation - sending of page headers.
558 * @return void
559 */
560 protected function send_headers() {
561 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
562 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
563 header('Pragma: no-cache');
564 header('Accept-Ranges: none');
565 }
566
88098133 567 /**
568 * Specialised exception handler, we can not use the standard one because
569 * it can not just print html to output.
570 *
571 * @param exception $ex
572 * @return void does not return
573 */
574 public function exception_handler($ex) {
88098133 575 // detect active db transactions, rollback and log as error
3086dd59 576 abort_all_db_transactions();
88098133 577
88098133 578 // some hacks might need a cleanup hook
579 $this->session_cleanup($ex);
580
ca6340bf 581 // now let the plugin send the exception to client
b107e647 582 $this->send_error($ex);
ca6340bf 583
88098133 584 // not much else we can do now, add some logging later
585 exit(1);
586 }
587
b107e647
PS
588 /**
589 * Send the error information to the WS client
590 * formatted as XML document.
591 * @param exception $ex
592 * @return void
593 */
594 protected function send_error($ex=null) {
595 $this->send_headers();
596 echo $this->zend_server->fault($ex);
597 }
01482a4a 598
88098133 599 /**
600 * Future hook needed for emulated sessions.
601 * @param exception $exception null means normal termination, $exception received when WS call failed
602 * @return void
603 */
604 protected function session_cleanup($exception=null) {
2d0acbd5 605 if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
88098133 606 // nothing needs to be done, there is no persistent session
607 } else {
608 // close emulated session if used
609 }
610 }
611
cc93c7da 612}
613
886d7556 614/**
cc93c7da 615 * Web Service server base class, this class handles both
616 * simple and token authentication.
617 * @author Petr Skoda (skodak)
886d7556 618 */
01482a4a 619abstract class webservice_base_server extends webservice_server {
88098133 620
cc93c7da 621 /** @property array $parameters the function parameters - the real values submitted in the request */
622 protected $parameters = null;
623
624 /** @property string $functionname the name of the function that is executed */
625 protected $functionname = null;
626
627 /** @property object $function full function description */
628 protected $function = null;
629
630 /** @property mixed $returns function return value */
631 protected $returns = null;
06e7fadc 632
24350e06 633 /**
cc93c7da 634 * This method parses the request input, it needs to get:
635 * 1/ user authentication - username+password or token
636 * 2/ function name
637 * 3/ function parameters
638 *
639 * @return void
24350e06 640 */
cc93c7da 641 abstract protected function parse_request();
24350e06 642
cc93c7da 643 /**
644 * Send the result of function call to the WS client.
645 * @return void
646 */
647 abstract protected function send_response();
24350e06 648
fa0797ec 649 /**
cc93c7da 650 * Send the error information to the WS client.
651 * @param exception $ex
652 * @return void
fa0797ec 653 */
cc93c7da 654 abstract protected function send_error($ex=null);
fa0797ec 655
cc93c7da 656 /**
657 * Process request from client.
cc93c7da 658 * @return void
659 */
2458e30a 660 public function run() {
cc93c7da 661 // we will probably need a lot of memory in some functions
662 @raise_memory_limit('128M');
fa0797ec 663
cc93c7da 664 // set some longer timeout, this script is not sending any output,
665 // this means we need to manually extend the timeout operations
666 // that need longer time to finish
667 external_api::set_timeout();
fa0797ec 668
cc93c7da 669 // set up exception handler first, we want to sent them back in correct format that
670 // the other system understands
671 // we do not need to call the original default handler because this ws handler does everything
672 set_exception_handler(array($this, 'exception_handler'));
06e7fadc 673
cc93c7da 674 // init all properties from the request data
675 $this->parse_request();
06e7fadc 676
cc93c7da 677 // authenticate user, this has to be done after the request parsing
678 // this also sets up $USER and $SESSION
679 $this->authenticate_user();
06e7fadc 680
cc93c7da 681 // find all needed function info and make sure user may actually execute the function
682 $this->load_function_info();
c3517f05 683
684 //log the web service request
7e0eac79 685 add_to_log(1, 'webservice', $this->functionname, '' , getremoteaddr() , 0, $this->userid);
f7631e73 686
cc93c7da 687 // finally, execute the function - any errors are catched by the default exception handler
688 $this->execute();
06e7fadc 689
cc93c7da 690 // send the results back in correct format
691 $this->send_response();
06e7fadc 692
cc93c7da 693 // session cleanup
694 $this->session_cleanup();
06e7fadc 695
cc93c7da 696 die;
f7631e73 697 }
698
cc93c7da 699 /**
700 * Specialised exception handler, we can not use the standard one because
701 * it can not just print html to output.
702 *
703 * @param exception $ex
704 * @return void does not return
705 */
706 public function exception_handler($ex) {
cc93c7da 707 // detect active db transactions, rollback and log as error
3086dd59 708 abort_all_db_transactions();
06e7fadc 709
cc93c7da 710 // some hacks might need a cleanup hook
711 $this->session_cleanup($ex);
06e7fadc 712
ca6340bf 713 // now let the plugin send the exception to client
714 $this->send_error($ex);
715
cc93c7da 716 // not much else we can do now, add some logging later
717 exit(1);
f7631e73 718 }
719
720 /**
cc93c7da 721 * Future hook needed for emulated sessions.
722 * @param exception $exception null means normal termination, $exception received when WS call failed
723 * @return void
f7631e73 724 */
cc93c7da 725 protected function session_cleanup($exception=null) {
726 if ($this->simple) {
727 // nothing needs to be done, there is no persistent session
728 } else {
729 // close emulated session if used
730 }
f7631e73 731 }
732
24350e06 733 /**
cc93c7da 734 * Fetches the function description from database,
735 * verifies user is allowed to use this function and
736 * loads all paremeters and return descriptions.
737 * @return void
24350e06 738 */
cc93c7da 739 protected function load_function_info() {
740 global $DB, $USER, $CFG;
40f024c9 741
cc93c7da 742 if (empty($this->functionname)) {
743 throw new invalid_parameter_exception('Missing function name');
744 }
24350e06 745
cc93c7da 746 // function must exist
5593d2dc 747 $function = external_function_info($this->functionname);
cc93c7da 748
01482a4a
PS
749 if ($this->restricted_serviceid) {
750 $params = array('sid1'=>$this->restricted_serviceid, 'sid2'=>$this->restricted_serviceid);
751 $wscond1 = 'AND s.id = :sid1';
752 $wscond2 = 'AND s.id = :sid2';
753 } else {
754 $params = array();
755 $wscond1 = '';
756 $wscond2 = '';
757 }
758
cc93c7da 759 // now let's verify access control
b8c5309e 760
761 // now make sure the function is listed in at least one service user is allowed to use
762 // allow access only if:
763 // 1/ entry in the external_services_users table if required
764 // 2/ validuntil not reached
765 // 3/ has capability if specified in service desc
766 // 4/ iprestriction
767
768 $sql = "SELECT s.*, NULL AS iprestriction
769 FROM {external_services} s
770 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0 AND sf.functionname = :name1)
771 WHERE s.enabled = 1 $wscond1
772
773 UNION
774
775 SELECT s.*, su.iprestriction
776 FROM {external_services} s
777 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1 AND sf.functionname = :name2)
778 JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)
779 WHERE s.enabled = 1 AND su.validuntil IS NULL OR su.validuntil < :now $wscond2";
780 $params = array_merge($params, array('userid'=>$USER->id, 'name1'=>$function->name, 'name2'=>$function->name, 'now'=>time()));
88098133 781
782 $rs = $DB->get_recordset_sql($sql, $params);
783 // now make sure user may access at least one service
784 $remoteaddr = getremoteaddr();
785 $allowed = false;
786 foreach ($rs as $service) {
787 if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) {
788 continue; // cap required, sorry
cc93c7da 789 }
88098133 790 if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) {
791 continue; // wrong request source ip, sorry
cc93c7da 792 }
88098133 793 $allowed = true;
794 break; // one service is enough, no need to continue
795 }
796 $rs->close();
797 if (!$allowed) {
c91cc5ef 798 throw new webservice_access_exception('Access to external function not allowed');
cc93c7da 799 }
9baf6825 800
cc93c7da 801 // we have all we need now
802 $this->function = $function;
803 }
804
805 /**
806 * Execute previously loaded function using parameters parsed from the request data.
807 * @return void
808 */
809 protected function execute() {
810 // validate params, this also sorts the params properly, we need the correct order in the next part
811 $params = call_user_func(array($this->function->classname, 'validate_parameters'), $this->function->parameters_desc, $this->parameters);
9baf6825 812
cc93c7da 813 // execute - yay!
814 $this->returns = call_user_func_array(array($this->function->classname, $this->function->methodname), array_values($params));
9baf6825 815 }
816}
817
818