3 // This file is part of Moodle - http://moodle.org/
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.
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/>.
19 * Web services utility functions and classes
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');
29 * Exception indicating access control problem in web service call
30 * @author Petr Skoda (skodak)
32 class webservice_access_exception extends moodle_exception {
36 function __construct($debuginfo) {
37 parent::__construct('accessexception', 'webservice', '', null, $debuginfo);
42 * Is protocol enabled?
43 * @param string $protocol name of WS protocol
46 function webservice_protocol_is_enabled($protocol) {
49 if (empty($CFG->enablewebservices)) {
53 $active = explode(',', $CFG->webserviceprotocols);
55 return(in_array($protocol, $active));
61 * Mandatory interface for all test client classes.
62 * @author Petr Skoda (skodak)
64 interface webservice_test_client_interface {
66 * Execute test client WS request
67 * @param string $serverurl
68 * @param string $function
69 * @param array $params
72 public function simpletest($serverurl, $function, $params);
76 * Mandatory interface for all web service protocol classes
77 * @author Petr Skoda (skodak)
79 interface webservice_server_interface {
81 * Process request from client.
84 public function run();
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 */
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
125 protected function authenticate_user() {
128 if (!NO_MOODLE_COOKIES) {
129 throw new coding_exception('Cookies must be disabled in WS servers!');
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);
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);
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;
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
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 $this->session_cleanup();
267 //finally send the result
268 $this->send_headers();
274 * Load virtual class needed for Zend api
277 protected function init_service_class() {
280 // first ofall get a complete list of services user is allowed to access
282 if ($this->restricted_serviceid) {
283 $params = array('sid1'=>$this->restricted_serviceid, 'sid2'=>$this->restricted_serviceid);
284 $wscond1 = 'AND s.id = :sid1';
285 $wscond2 = 'AND s.id = :sid2';
292 // now make sure the function is listed in at least one service user is allowed to use
293 // allow access only if:
294 // 1/ entry in the external_services_users table if required
295 // 2/ validuntil not reached
296 // 3/ has capability if specified in service desc
299 $sql = "SELECT s.*, NULL AS iprestriction
300 FROM {external_services} s
301 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0)
302 WHERE s.enabled = 1 $wscond1
306 SELECT s.*, su.iprestriction
307 FROM {external_services} s
308 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1)
309 JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)
310 WHERE s.enabled = 1 AND su.validuntil IS NULL OR su.validuntil < :now $wscond2";
312 $params = array_merge($params, array('userid'=>$USER->id, 'now'=>time()));
314 $serviceids = array();
315 $rs = $DB->get_recordset_sql($sql, $params);
317 // now make sure user may access at least one service
318 $remoteaddr = getremoteaddr();
320 foreach ($rs as $service) {
321 if (isset($serviceids[$service->id])) {
324 if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) {
325 continue; // cap required, sorry
327 if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) {
328 continue; // wrong request source ip, sorry
330 $serviceids[$service->id] = $service->id;
334 // now get the list of all functions
336 list($serviceids, $params) = $DB->get_in_or_equal($serviceids);
338 FROM {external_functions} f
339 WHERE f.name IN (SELECT sf.functionname
340 FROM {external_services_functions} sf
341 WHERE sf.externalserviceid $serviceids)";
342 $functions = $DB->get_records_sql($sql, $params);
344 $functions = array();
347 // now make the virtual WS class with all the fuctions for this particular user
349 foreach ($functions as $function) {
350 $methods .= $this->get_virtual_method_code($function);
353 // let's use unique class name, there might be problem in unit tests
354 $classname = 'webservices_virtual_class_000000';
355 while(class_exists($classname)) {
361 * Virtual class web services for user id '.$USER->id.' in context '.$this->restricted_context->id.'.
363 class '.$classname.' {
368 // load the virtual class definition into memory
370 $this->service_class = $classname;
374 * returns virtual method code
375 * @param object $function
376 * @return string PHP code
378 protected function get_virtual_method_code($function) {
381 $function = external_function_info($function);
384 $params_desc = array();
385 foreach ($function->parameters_desc->keys as $name=>$keydesc) {
387 //need to generate the default if there is any
388 if ($keydesc instanceof external_value) {
389 if ($keydesc->required == VALUE_DEFAULT) {
390 if ($keydesc->default===null) {
393 switch($keydesc->type) {
395 $param .= $keydesc->default; break;
397 $param .= $keydesc->default; break;
399 $param .= $keydesc->default; break;
401 $param .= '=\''.$keydesc->default.'\'';
404 } else if ($keydesc->required == VALUE_OPTIONAL) {
405 //it does make sens to declare a parameter VALUE_OPTIONAL
406 //VALUE_OPTIONAL is used only for array/object key
407 throw new moodle_exception('parametercannotbevalueoptional');
409 } else { //for the moment we do not support default for other structure types
410 if ($keydesc->required == VALUE_OPTIONAL or $keydesc->required == VALUE_DEFAULT) {
411 throw new moodle_exception('paramdefaultarraynotsupported');
416 if ($keydesc instanceof external_value) {
417 switch($keydesc->type) {
418 case PARAM_BOOL: // 0 or 1 only for now
420 $type = 'int'; break;
422 $type = 'double'; break;
426 } else if ($keydesc instanceof external_single_structure) {
428 } else if ($keydesc instanceof external_multiple_structure) {
431 $params_desc[] = ' * @param '.$type.' $'.$name.' '.$keydesc->desc;
433 $params = implode(', ', $params);
434 $params_desc = implode("\n", $params_desc);
436 $serviceclassmethodbody = $this->service_class_method_body($function, $params);
438 if (is_null($function->returns_desc)) {
439 $return = ' * @return void';
442 if ($function->returns_desc instanceof external_value) {
443 switch($function->returns_desc->type) {
444 case PARAM_BOOL: // 0 or 1 only for now
446 $type = 'int'; break;
448 $type = 'double'; break;
452 } else if ($function->returns_desc instanceof external_single_structure) {
454 } else if ($function->returns_desc instanceof external_multiple_structure) {
457 $return = ' * @return '.$type.' '.$function->returns_desc->desc;
460 // now crate the virtual method that calls the ext implementation
464 * '.$function->description.'
469 public function '.$function->name.'('.$params.') {
470 '.$serviceclassmethodbody.'
477 * You can override this function in your child class to add extra code into the dynamically
478 * created service class. For example it is used in the amf server to cast types of parameters and to
479 * cast the return value to the types as specified in the return value description.
480 * @param unknown_type $function
481 * @param unknown_type $params
482 * @return string body of the method for $function ie. everything within the {} of the method declaration.
484 protected function service_class_method_body($function, $params){
485 $descriptionmethod = $function->methodname.'_returns()';
486 $callforreturnvaluedesc = $function->classname.'::'.$descriptionmethod;
487 return ' if ('.$callforreturnvaluedesc.' == null) {
490 return external_api::clean_returnvalue('.$callforreturnvaluedesc.', '.$function->classname.'::'.$function->methodname.'('.$params.'));';
494 * Set up zend service class
497 protected function init_zend_server() {
498 $this->zend_server = new $this->zend_class();
502 * This method parses the $_REQUEST superglobal and looks for
503 * the following information:
504 * 1/ user authentication - username+password or token (wsusername, wspassword and wstoken parameters)
508 protected function parse_request() {
510 //note: some clients have problems with entity encoding :-(
511 if (isset($_REQUEST['wsusername'])) {
512 $this->username = $_REQUEST['wsusername'];
514 if (isset($_REQUEST['wspassword'])) {
515 $this->password = $_REQUEST['wspassword'];
518 if (isset($_REQUEST['wstoken'])) {
519 $this->token = $_REQUEST['wstoken'];
525 * Internal implementation - sending of page headers.
528 protected function send_headers() {
529 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
530 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
531 header('Pragma: no-cache');
532 header('Accept-Ranges: none');
536 * Specialised exception handler, we can not use the standard one because
537 * it can not just print html to output.
539 * @param exception $ex
540 * @return void does not return
542 public function exception_handler($ex) {
543 // detect active db transactions, rollback and log as error
544 abort_all_db_transactions();
546 // some hacks might need a cleanup hook
547 $this->session_cleanup($ex);
549 // now let the plugin send the exception to client
550 $this->send_error($ex);
552 // not much else we can do now, add some logging later
557 * Send the error information to the WS client
558 * formatted as XML document.
559 * @param exception $ex
562 protected function send_error($ex=null) {
563 $this->send_headers();
564 echo $this->zend_server->fault($ex);
568 * Future hook needed for emulated sessions.
569 * @param exception $exception null means normal termination, $exception received when WS call failed
572 protected function session_cleanup($exception=null) {
574 // nothing needs to be done, there is no persistent session
576 // close emulated session if used
583 * Web Service server base class, this class handles both
584 * simple and token authentication.
585 * @author Petr Skoda (skodak)
587 abstract class webservice_base_server extends webservice_server {
589 /** @property array $parameters the function parameters - the real values submitted in the request */
590 protected $parameters = null;
592 /** @property string $functionname the name of the function that is executed */
593 protected $functionname = null;
595 /** @property object $function full function description */
596 protected $function = null;
598 /** @property mixed $returns function return value */
599 protected $returns = null;
603 * @param bool $simple use simple authentication
605 public function __construct($simple) {
606 $this->simple = $simple;
610 * This method parses the request input, it needs to get:
611 * 1/ user authentication - username+password or token
613 * 3/ function parameters
617 abstract protected function parse_request();
620 * Send the result of function call to the WS client.
623 abstract protected function send_response();
626 * Send the error information to the WS client.
627 * @param exception $ex
630 abstract protected function send_error($ex=null);
633 * Process request from client.
636 public function run() {
637 // we will probably need a lot of memory in some functions
638 @raise_memory_limit('128M');
640 // set some longer timeout, this script is not sending any output,
641 // this means we need to manually extend the timeout operations
642 // that need longer time to finish
643 external_api::set_timeout();
645 // set up exception handler first, we want to sent them back in correct format that
646 // the other system understands
647 // we do not need to call the original default handler because this ws handler does everything
648 set_exception_handler(array($this, 'exception_handler'));
650 // init all properties from the request data
651 $this->parse_request();
653 // authenticate user, this has to be done after the request parsing
654 // this also sets up $USER and $SESSION
655 $this->authenticate_user();
657 // find all needed function info and make sure user may actually execute the function
658 $this->load_function_info();
660 //log the web service request
661 add_to_log(1, 'webservice', $this->functionname, '' , getremoteaddr() , 0, $this->userid);
663 // finally, execute the function - any errors are catched by the default exception handler
666 // send the results back in correct format
667 $this->send_response();
670 $this->session_cleanup();
676 * Specialised exception handler, we can not use the standard one because
677 * it can not just print html to output.
679 * @param exception $ex
680 * @return void does not return
682 public function exception_handler($ex) {
683 // detect active db transactions, rollback and log as error
684 abort_all_db_transactions();
686 // some hacks might need a cleanup hook
687 $this->session_cleanup($ex);
689 // now let the plugin send the exception to client
690 $this->send_error($ex);
692 // not much else we can do now, add some logging later
697 * Future hook needed for emulated sessions.
698 * @param exception $exception null means normal termination, $exception received when WS call failed
701 protected function session_cleanup($exception=null) {
703 // nothing needs to be done, there is no persistent session
705 // close emulated session if used
710 * Fetches the function description from database,
711 * verifies user is allowed to use this function and
712 * loads all paremeters and return descriptions.
715 protected function load_function_info() {
716 global $DB, $USER, $CFG;
718 if (empty($this->functionname)) {
719 throw new invalid_parameter_exception('Missing function name');
722 // function must exist
723 $function = external_function_info($this->functionname);
725 if ($this->restricted_serviceid) {
726 $params = array('sid1'=>$this->restricted_serviceid, 'sid2'=>$this->restricted_serviceid);
727 $wscond1 = 'AND s.id = :sid1';
728 $wscond2 = 'AND s.id = :sid2';
735 // now let's verify access control
737 // now make sure the function is listed in at least one service user is allowed to use
738 // allow access only if:
739 // 1/ entry in the external_services_users table if required
740 // 2/ validuntil not reached
741 // 3/ has capability if specified in service desc
744 $sql = "SELECT s.*, NULL AS iprestriction
745 FROM {external_services} s
746 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0 AND sf.functionname = :name1)
747 WHERE s.enabled = 1 $wscond1
751 SELECT s.*, su.iprestriction
752 FROM {external_services} s
753 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1 AND sf.functionname = :name2)
754 JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)
755 WHERE s.enabled = 1 AND su.validuntil IS NULL OR su.validuntil < :now $wscond2";
756 $params = array_merge($params, array('userid'=>$USER->id, 'name1'=>$function->name, 'name2'=>$function->name, 'now'=>time()));
758 $rs = $DB->get_recordset_sql($sql, $params);
759 // now make sure user may access at least one service
760 $remoteaddr = getremoteaddr();
762 foreach ($rs as $service) {
763 if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) {
764 continue; // cap required, sorry
766 if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) {
767 continue; // wrong request source ip, sorry
770 break; // one service is enough, no need to continue
774 throw new webservice_access_exception('Access to external function not allowed');
777 // we have all we need now
778 $this->function = $function;
782 * Execute previously loaded function using parameters parsed from the request data.
785 protected function execute() {
786 // validate params, this also sorts the params properly, we need the correct order in the next part
787 $params = call_user_func(array($this->function->classname, 'validate_parameters'), $this->function->parameters_desc, $this->parameters);
790 $this->returns = call_user_func_array(array($this->function->classname, $this->function->methodname), array_values($params));