MDL-20808 Fixes for amf web services and test client - a web service browser.
[moodle.git] / webservice / lib.php
blobf8f6d13b6f79fc478e39d52d8b0196fd7c2e8a37
1 <?php
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.
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/>.
18 /**
19 * Web services utility functions and classes
21 * @package webservice
22 * @copyright 2009 Moodle Pty Ltd (http://moodle.com)
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 require_once($CFG->libdir.'/externallib.php');
28 /**
29 * Exception indicating access control problem in web service call
30 * @author Petr Skoda (skodak)
32 class webservice_access_exception extends moodle_exception {
33 /**
34 * Constructor
36 function __construct($debuginfo) {
37 parent::__construct('accessexception', 'webservice', '', null, $debuginfo);
41 /**
42 * Is protocol enabled?
43 * @param string $protocol name of WS protocol
44 * @return bool
46 function webservice_protocol_is_enabled($protocol) {
47 global $CFG;
49 if (empty($CFG->enablewebservices)) {
50 return false;
53 $active = explode(',', $CFG->webserviceprotocols);
55 return(in_array($protocol, $active));
58 //=== WS classes ===
60 /**
61 * Mandatory interface for all test client classes.
62 * @author Petr Skoda (skodak)
64 interface webservice_test_client_interface {
65 /**
66 * Execute test client WS request
67 * @param string $serverurl
68 * @param string $function
69 * @param array $params
70 * @return mixed
72 public function simpletest($serverurl, $function, $params);
75 /**
76 * Mandatory interface for all web service protocol classes
77 * @author Petr Skoda (skodak)
79 interface webservice_server_interface {
80 /**
81 * Process request from client.
82 * @return void
84 public function run();
87 /**
88 * Abstract web service base class.
89 * @author Petr Skoda (skodak)
91 abstract class webservice_server implements webservice_server_interface {
93 /** @property string $wsname name of the web server plugin */
94 protected $wsname = null;
96 /** @property string $username name of local user */
97 protected $username = null;
99 /** @property string $password password of the local user */
100 protected $password = null;
102 /** @property int $userid the local user */
103 protected $userid = null;
105 /** @property bool $simple true if simple auth used */
106 protected $simple;
108 /** @property string $token authentication token*/
109 protected $token = null;
111 /** @property object restricted context */
112 protected $restricted_context;
114 /** @property int restrict call to one service id*/
115 protected $restricted_serviceid = null;
118 * Authenticate user using username+password or token.
119 * This function sets up $USER global.
120 * It is safe to use has_capability() after this.
121 * This method also verifies user is allowed to use this
122 * server.
123 * @return void
125 protected function authenticate_user() {
126 global $CFG, $DB;
128 if (!NO_MOODLE_COOKIES) {
129 throw new coding_exception('Cookies must be disabled in WS servers!');
132 if ($this->simple) {
134 //we check that authentication plugin is enabled
135 //it is only required by simple authentication
136 if (!is_enabled_auth('webservice')) {
137 throw new webservice_access_exception(get_string('wsauthnotenabled', 'webservice'));
140 if (!$auth = get_auth_plugin('webservice')) {
141 throw new webservice_access_exception(get_string('wsauthmissing', 'webservice'));
144 $this->restricted_context = get_context_instance(CONTEXT_SYSTEM);
146 if (!$this->username) {
147 throw new webservice_access_exception(get_string('missingusername', 'webservice'));
150 if (!$this->password) {
151 throw new webservice_access_exception(get_string('missingpassword', 'webservice'));
154 if (!$auth->user_login_webservice($this->username, $this->password)) {
155 // log failed login attempts
156 add_to_log(1, 'webservice', get_string('simpleauthlog', 'webservice'), '' , get_string('failedtolog', 'webservice').": ".$this->username."/".$this->password." - ".getremoteaddr() , 0);
157 throw new webservice_access_exception(get_string('wrongusernamepassword', 'webservice'));
160 $user = $DB->get_record('user', array('username'=>$this->username, 'mnethostid'=>$CFG->mnet_localhost_id, 'deleted'=>0), '*', MUST_EXIST);
162 } else {
163 if (!$token = $DB->get_record('external_tokens', array('token'=>$this->token, 'tokentype'=>EXTERNAL_TOKEN_PERMANENT))) {
164 // log failed login attempts
165 add_to_log(1, 'webservice', get_string('tokenauthlog', 'webservice'), '' , get_string('failedtolog', 'webservice').": ".$this->token. " - ".getremoteaddr() , 0);
166 throw new webservice_access_exception(get_string('invalidtoken', 'webservice'));
169 if ($token->validuntil and $token->validuntil < time()) {
170 throw new webservice_access_exception(get_string('invalidtimedtoken', 'webservice'));
173 if ($token->iprestriction and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
174 add_to_log(1, 'webservice', get_string('tokenauthlog', 'webservice'), '' , get_string('failedtolog', 'webservice').": ".getremoteaddr() , 0);
175 throw new webservice_access_exception(get_string('invalidiptoken', 'webservice'));
178 $this->restricted_context = get_context_instance_by_id($token->contextid);
179 $this->restricted_serviceid = $token->externalserviceid;
181 $user = $DB->get_record('user', array('id'=>$token->userid, 'deleted'=>0), '*', MUST_EXIST);
183 // log token access
184 $DB->set_field('external_tokens', 'lastaccess', time(), array('id'=>$token->id));
187 // now fake user login, the session is completely empty too
188 session_set_user($user);
189 $this->userid = $user->id;
191 if (!has_capability("webservice/$this->wsname:use", $this->restricted_context)) {
192 throw new webservice_access_exception(get_string('accessnotallowed', 'webservice'));
195 external_api::set_context_restriction($this->restricted_context);
200 * Special abstraction of our srvices that allows
201 * interaction with stock Zend ws servers.
202 * @author Petr Skoda (skodak)
204 abstract class webservice_zend_server extends webservice_server {
206 /** @property string name of the zend server class : Zend_XmlRpc_Server, Zend_Soap_Server, Zend_Soap_AutoDiscover, ...*/
207 protected $zend_class;
209 /** @property object Zend server instance */
210 protected $zend_server;
212 /** @property string $service_class virtual web service class with all functions user name execute, created on the fly */
213 protected $service_class;
216 * Contructor
217 * @param bool $simple use simple authentication
219 public function __construct($simple, $zend_class) {
220 $this->simple = $simple;
221 $this->zend_class = $zend_class;
225 * Process request from client.
226 * @param bool $simple use simple authentication
227 * @return void
229 public function run() {
230 // we will probably need a lot of memory in some functions
231 @raise_memory_limit('128M');
233 // set some longer timeout, this script is not sending any output,
234 // this means we need to manually extend the timeout operations
235 // that need longer time to finish
236 external_api::set_timeout();
238 // now create the instance of zend server
239 $this->init_zend_server();
241 // set up exception handler first, we want to sent them back in correct format that
242 // the other system understands
243 // we do not need to call the original default handler because this ws handler does everything
244 set_exception_handler(array($this, 'exception_handler'));
246 // init all properties from the request data
247 $this->parse_request();
249 // this sets up $USER and $SESSION and context restrictions
250 $this->authenticate_user();
252 // make a list of all functions user is allowed to excecute
253 $this->init_service_class();
255 // tell server what functions are available
256 $this->zend_server->setClass($this->service_class);
258 //log the web service request
259 add_to_log(1, 'webservice', '', '' , $this->zend_class." ".getremoteaddr() , 0, $this->userid);
261 // execute and return response, this sends some headers too
262 $response = $this->zend_server->handle();
265 error_log(ob_get_clean());
266 error_log($response);
268 // session cleanup
269 $this->session_cleanup();
271 //finally send the result
272 $this->send_headers();
273 echo $response;
274 die;
278 * Load virtual class needed for Zend api
279 * @return void
281 protected function init_service_class() {
282 global $USER, $DB;
284 // first ofall get a complete list of services user is allowed to access
286 if ($this->restricted_serviceid) {
287 $params = array('sid1'=>$this->restricted_serviceid, 'sid2'=>$this->restricted_serviceid);
288 $wscond1 = 'AND s.id = :sid1';
289 $wscond2 = 'AND s.id = :sid2';
290 } else {
291 $params = array();
292 $wscond1 = '';
293 $wscond2 = '';
296 // now make sure the function is listed in at least one service user is allowed to use
297 // allow access only if:
298 // 1/ entry in the external_services_users table if required
299 // 2/ validuntil not reached
300 // 3/ has capability if specified in service desc
301 // 4/ iprestriction
303 $sql = "SELECT s.*, NULL AS iprestriction
304 FROM {external_services} s
305 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0)
306 WHERE s.enabled = 1 $wscond1
308 UNION
310 SELECT s.*, su.iprestriction
311 FROM {external_services} s
312 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1)
313 JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)
314 WHERE s.enabled = 1 AND su.validuntil IS NULL OR su.validuntil < :now $wscond2";
316 $params = array_merge($params, array('userid'=>$USER->id, 'now'=>time()));
318 $serviceids = array();
319 $rs = $DB->get_recordset_sql($sql, $params);
321 // now make sure user may access at least one service
322 $remoteaddr = getremoteaddr();
323 $allowed = false;
324 foreach ($rs as $service) {
325 if (isset($serviceids[$service->id])) {
326 continue;
328 if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) {
329 continue; // cap required, sorry
331 if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) {
332 continue; // wrong request source ip, sorry
334 $serviceids[$service->id] = $service->id;
336 $rs->close();
338 // now get the list of all functions
339 if ($serviceids) {
340 list($serviceids, $params) = $DB->get_in_or_equal($serviceids);
341 $sql = "SELECT f.*
342 FROM {external_functions} f
343 WHERE f.name IN (SELECT sf.functionname
344 FROM {external_services_functions} sf
345 WHERE sf.externalserviceid $serviceids)";
346 $functions = $DB->get_records_sql($sql, $params);
347 } else {
348 $functions = array();
351 // now make the virtual WS class with all the fuctions for this particular user
352 $methods = '';
353 foreach ($functions as $function) {
354 $methods .= $this->get_virtual_method_code($function);
357 // let's use unique class name, there might be problem in unit tests
358 $classname = 'webservices_virtual_class_000000';
359 while(class_exists($classname)) {
360 $classname++;
363 $code = '
365 * Virtual class web services for user id '.$USER->id.' in context '.$this->restricted_context->id.'.
367 class '.$classname.' {
368 '.$methods.'
372 // load the virtual class definition into memory
373 eval($code);
374 $this->service_class = $classname;
378 * returns virtual method code
379 * @param object $function
380 * @return string PHP code
382 protected function get_virtual_method_code($function) {
383 global $CFG;
385 $function = external_function_info($function);
387 $params = array();
388 $params_desc = array();
389 foreach ($function->parameters_desc->keys as $name=>$keydesc) {
390 $params[] = '$'.$name;
391 $type = 'string';
392 if ($keydesc instanceof external_value) {
393 switch($keydesc->type) {
394 case PARAM_BOOL: // 0 or 1 only for now
395 case PARAM_INT:
396 $type = 'int'; break;
397 case PARAM_FLOAT;
398 $type = 'double'; break;
399 default:
400 $type = 'string';
402 } else if ($keydesc instanceof external_single_structure) {
403 $type = 'struct';
404 } else if ($keydesc instanceof external_multiple_structure) {
405 $type = 'array';
407 $params_desc[] = ' * @param '.$type.' $'.$name.' '.$keydesc->desc;
409 $params = implode(', ', $params);
410 $params_desc = implode("\n", $params_desc);
412 $serviceclassmethodbody = $this->service_class_method_body($function, $params);
414 if (is_null($function->returns_desc)) {
415 $return = ' * @return void';
416 } else {
417 $type = 'string';
418 if ($function->returns_desc instanceof external_value) {
419 switch($function->returns_desc->type) {
420 case PARAM_BOOL: // 0 or 1 only for now
421 case PARAM_INT:
422 $type = 'int'; break;
423 case PARAM_FLOAT;
424 $type = 'double'; break;
425 default:
426 $type = 'string';
428 } else if ($function->returns_desc instanceof external_single_structure) {
429 $type = 'struct';
430 } else if ($function->returns_desc instanceof external_multiple_structure) {
431 $type = 'array';
433 $return = ' * @return '.$type.' '.$function->returns_desc->desc;
436 // now crate the virtual method that calls the ext implementation
438 $code = '
440 * '.$function->description.'
442 '.$params_desc.'
443 '.$return.'
445 public function '.$function->name.'('.$params.') {
446 '.$serviceclassmethodbody.'
449 return $code;
453 * You can override this function in your child class to add extra code into the dynamically
454 * created service class. For example it is used in the amf server to cast types of parameters and to
455 * cast the return value to the types as specified in the return value description.
456 * @param unknown_type $function
457 * @param unknown_type $params
458 * @return string body of the method for $function ie. everything within the {} of the method declaration.
460 protected function service_class_method_body($function, $params){
461 return ' return '.$function->classname.'::'.$function->methodname.'('.$params.');';
465 * Set up zend service class
466 * @return void
468 protected function init_zend_server() {
469 $this->zend_server = new $this->zend_class();
473 * This method parses the $_REQUEST superglobal and looks for
474 * the following information:
475 * 1/ user authentication - username+password or token (wsusername, wspassword and wstoken parameters)
477 * @return void
479 protected function parse_request() {
480 if ($this->simple) {
481 //note: some clients have problems with entity encoding :-(
482 if (isset($_REQUEST['wsusername'])) {
483 $this->username = $_REQUEST['wsusername'];
485 if (isset($_REQUEST['wspassword'])) {
486 $this->password = $_REQUEST['wspassword'];
488 } else {
489 if (isset($_REQUEST['wstoken'])) {
490 $this->token = $_REQUEST['wstoken'];
496 * Internal implementation - sending of page headers.
497 * @return void
499 protected function send_headers() {
500 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
501 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
502 header('Pragma: no-cache');
503 header('Accept-Ranges: none');
507 * Specialised exception handler, we can not use the standard one because
508 * it can not just print html to output.
510 * @param exception $ex
511 * @return void does not return
513 public function exception_handler($ex) {
514 // detect active db transactions, rollback and log as error
515 abort_all_db_transactions();
517 // some hacks might need a cleanup hook
518 $this->session_cleanup($ex);
520 // now let the plugin send the exception to client
521 $this->send_error($ex);
523 // not much else we can do now, add some logging later
524 exit(1);
528 * Send the error information to the WS client
529 * formatted as XML document.
530 * @param exception $ex
531 * @return void
533 protected function send_error($ex=null) {
534 $this->send_headers();
535 echo $this->zend_server->fault($ex);
539 * Future hook needed for emulated sessions.
540 * @param exception $exception null means normal termination, $exception received when WS call failed
541 * @return void
543 protected function session_cleanup($exception=null) {
544 if ($this->simple) {
545 // nothing needs to be done, there is no persistent session
546 } else {
547 // close emulated session if used
554 * Web Service server base class, this class handles both
555 * simple and token authentication.
556 * @author Petr Skoda (skodak)
558 abstract class webservice_base_server extends webservice_server {
560 /** @property array $parameters the function parameters - the real values submitted in the request */
561 protected $parameters = null;
563 /** @property string $functionname the name of the function that is executed */
564 protected $functionname = null;
566 /** @property object $function full function description */
567 protected $function = null;
569 /** @property mixed $returns function return value */
570 protected $returns = null;
573 * Contructor
574 * @param bool $simple use simple authentication
576 public function __construct($simple) {
577 $this->simple = $simple;
581 * This method parses the request input, it needs to get:
582 * 1/ user authentication - username+password or token
583 * 2/ function name
584 * 3/ function parameters
586 * @return void
588 abstract protected function parse_request();
591 * Send the result of function call to the WS client.
592 * @return void
594 abstract protected function send_response();
597 * Send the error information to the WS client.
598 * @param exception $ex
599 * @return void
601 abstract protected function send_error($ex=null);
604 * Process request from client.
605 * @return void
607 public function run() {
608 // we will probably need a lot of memory in some functions
609 @raise_memory_limit('128M');
611 // set some longer timeout, this script is not sending any output,
612 // this means we need to manually extend the timeout operations
613 // that need longer time to finish
614 external_api::set_timeout();
616 // set up exception handler first, we want to sent them back in correct format that
617 // the other system understands
618 // we do not need to call the original default handler because this ws handler does everything
619 set_exception_handler(array($this, 'exception_handler'));
621 // init all properties from the request data
622 $this->parse_request();
624 // authenticate user, this has to be done after the request parsing
625 // this also sets up $USER and $SESSION
626 $this->authenticate_user();
628 // find all needed function info and make sure user may actually execute the function
629 $this->load_function_info();
631 //log the web service request
632 add_to_log(1, 'webservice', $this->functionname, '' , getremoteaddr() , 0, $this->userid);
634 // finally, execute the function - any errors are catched by the default exception handler
635 $this->execute();
637 // send the results back in correct format
638 $this->send_response();
640 // session cleanup
641 $this->session_cleanup();
643 die;
647 * Specialised exception handler, we can not use the standard one because
648 * it can not just print html to output.
650 * @param exception $ex
651 * @return void does not return
653 public function exception_handler($ex) {
654 // detect active db transactions, rollback and log as error
655 abort_all_db_transactions();
657 // some hacks might need a cleanup hook
658 $this->session_cleanup($ex);
660 // now let the plugin send the exception to client
661 $this->send_error($ex);
663 // not much else we can do now, add some logging later
664 exit(1);
668 * Future hook needed for emulated sessions.
669 * @param exception $exception null means normal termination, $exception received when WS call failed
670 * @return void
672 protected function session_cleanup($exception=null) {
673 if ($this->simple) {
674 // nothing needs to be done, there is no persistent session
675 } else {
676 // close emulated session if used
681 * Fetches the function description from database,
682 * verifies user is allowed to use this function and
683 * loads all paremeters and return descriptions.
684 * @return void
686 protected function load_function_info() {
687 global $DB, $USER, $CFG;
689 if (empty($this->functionname)) {
690 throw new invalid_parameter_exception('Missing function name');
693 // function must exist
694 $function = external_function_info($this->functionname);
696 if ($this->restricted_serviceid) {
697 $params = array('sid1'=>$this->restricted_serviceid, 'sid2'=>$this->restricted_serviceid);
698 $wscond1 = 'AND s.id = :sid1';
699 $wscond2 = 'AND s.id = :sid2';
700 } else {
701 $params = array();
702 $wscond1 = '';
703 $wscond2 = '';
706 // now let's verify access control
708 // now make sure the function is listed in at least one service user is allowed to use
709 // allow access only if:
710 // 1/ entry in the external_services_users table if required
711 // 2/ validuntil not reached
712 // 3/ has capability if specified in service desc
713 // 4/ iprestriction
715 $sql = "SELECT s.*, NULL AS iprestriction
716 FROM {external_services} s
717 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0 AND sf.functionname = :name1)
718 WHERE s.enabled = 1 $wscond1
720 UNION
722 SELECT s.*, su.iprestriction
723 FROM {external_services} s
724 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1 AND sf.functionname = :name2)
725 JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)
726 WHERE s.enabled = 1 AND su.validuntil IS NULL OR su.validuntil < :now $wscond2";
727 $params = array_merge($params, array('userid'=>$USER->id, 'name1'=>$function->name, 'name2'=>$function->name, 'now'=>time()));
729 $rs = $DB->get_recordset_sql($sql, $params);
730 // now make sure user may access at least one service
731 $remoteaddr = getremoteaddr();
732 $allowed = false;
733 foreach ($rs as $service) {
734 if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) {
735 continue; // cap required, sorry
737 if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) {
738 continue; // wrong request source ip, sorry
740 $allowed = true;
741 break; // one service is enough, no need to continue
743 $rs->close();
744 if (!$allowed) {
745 throw new webservice_access_exception('Access to external function not allowed');
748 // we have all we need now
749 $this->function = $function;
753 * Execute previously loaded function using parameters parsed from the request data.
754 * @return void
756 protected function execute() {
757 // validate params, this also sorts the params properly, we need the correct order in the next part
758 $params = call_user_func(array($this->function->classname, 'validate_parameters'), $this->function->parameters_desc, $this->parameters);
760 // execute - yay!
761 $this->returns = call_user_func_array(array($this->function->classname, $this->function->methodname), array_values($params));