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');
28 function webservice_protocol_is_enabled($protocol) {
31 if (empty($CFG->enablewebservices)) {
35 $active = explode(',', $CFG->webserviceprotocols);
37 return(in_array($protocol, $active));
41 * Mandatory web service server interface
42 * @author Petr Skoda (skodak)
44 interface webservice_server {
46 * Process request from client.
47 * @param bool $simple use simple authentication
50 public function run($simple);
54 * Special abstraction of our srvices that allows
55 * interaction with stock Zend ws servers.
58 abstract class webservice_zend_server implements webservice_server {
60 /** @property string name of the zend server class */
61 protected $zend_class;
63 /** @property object Zend server instance */
64 protected $zend_server;
66 /** @property string $wsname name of the web server plugin */
67 protected $wsname = null;
69 /** @property bool $simple true if simple auth used */
72 /** @property string $service_class virtual web service class with all functions user name execute, created on the fly */
73 protected $service_class;
75 /** @property object restricted context */
76 protected $restricted_context;
81 public function __construct($zend_class) {
82 $this->zend_class = $zend_class;
86 * Process request from client.
87 * @param bool $simple use simple authentication
90 public function run($simple) {
91 $this->simple = $simple;
93 // we will probably need a lot of memory in some functions
94 @raise_memory_limit('128M');
96 // set some longer timeout, this script is not sending any output,
97 // this means we need to manually extend the timeout operations
98 // that need longer time to finish
99 external_api::set_timeout();
101 // set up exception handler first, we want to sent them back in correct format that
102 // the other system understands
103 // we do not need to call the original default handler because this ws handler does everything
104 set_exception_handler(array($this, 'exception_handler'));
106 // now create the instance of zend server
107 $this->init_zend_server();
109 // this sets up $USER and $SESSION and context restrictions
110 $this->authenticate_user();
112 // make a list of all functions user is allowed to excecute
113 $this->init_service_class();
115 // TODO: solve debugging level somehow
116 Zend_XmlRpc_Server_Fault::attachFaultException('moodle_exception');
119 $this->zend_server->setClass($this->service_class);
120 $response = $this->zend_server->handle();
122 //$grrr = ob_get_clean();
126 $this->session_cleanup();
128 //TODO: we need to send some headers too I guess
134 * Load virtual class needed for Zend api
137 protected function init_service_class() {
140 // first ofall get a complete list of services user is allowed to access
142 // now make sure the function is listed in at least one service user is allowed to use
143 // allow access only if:
144 // 1/ entry in the external_services_users table if required
145 // 2/ validuntil not reached
146 // 3/ has capability if specified in service desc
149 $sql = "SELECT s.*, NULL AS iprestriction
150 FROM {external_services} s
151 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0)
156 SELECT s.*, su.iprestriction
157 FROM {external_services} s
158 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1)
159 JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)
160 WHERE s.enabled = 1 AND su.validuntil IS NULL OR su.validuntil < :now";
161 $params = array('userid'=>$USER->id, 'now'=>time());
164 //TODO: token may restrict access to one service only
165 die('not implemented yet');
168 $serviceids = array();
169 $rs = $DB->get_recordset_sql($sql, $params);
171 // now make sure user may access at least one service
172 $remoteaddr = getremoteaddr();
174 foreach ($rs as $service) {
175 if (isset($serviceids[$service->id])) {
178 if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) {
179 continue; // cap required, sorry
181 if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) {
182 continue; // wrong request source ip, sorry
184 $serviceids[$service->id] = $service->id;
188 // now get the list of all functions
190 list($serviceids, $params) = $DB->get_in_or_equal($serviceids);
192 FROM {external_functions} f
193 WHERE f.name IN (SELECT sf.functionname
194 FROM {external_services_functions} sf
195 WHERE sf.externalserviceid $serviceids)";
196 $functions = $DB->get_records_sql($sql, $params);
198 $functions = array();
201 // now make the virtual WS class with all the fuctions for this particular user
203 foreach ($functions as $function) {
204 $methods .= $this->get_virtual_method_code($function);
207 $classname = 'webservices_virtual_class_000000';
208 while(class_exists($classname)) {
214 * Virtual class web services for user id '.$USER->id.' in context '.$this->restricted_context->id.'.
216 class '.$classname.' {
220 // load the virtual class definition into memory
222 $this->service_class = $classname;
226 * returns virtual method code
227 * @param object $function
228 * @return string PHP code
230 protected function get_virtual_method_code($function) {
233 //first find and include the ext implementation class
234 $function->classpath = empty($function->classpath) ? get_component_directory($function->component).'/externallib.php' : $CFG->dirroot.'/'.$function->classpath;
235 if (!file_exists($function->classpath)) {
236 throw new coding_exception('Can not find file with external function implementation');
238 require_once($function->classpath);
240 $function->parameters_method = $function->methodname.'_parameters';
241 $function->returns_method = $function->methodname.'_returns';
243 // make sure the implementaion class is ok
244 if (!method_exists($function->classname, $function->methodname)) {
245 throw new coding_exception('Missing implementation method');
247 if (!method_exists($function->classname, $function->parameters_method)) {
248 throw new coding_exception('Missing parameters description');
250 if (!method_exists($function->classname, $function->returns_method)) {
251 throw new coding_exception('Missing returned values description');
254 // fetch the parameters description
255 $function->parameters_desc = call_user_func(array($function->classname, $function->parameters_method));
256 if (!($function->parameters_desc instanceof external_function_parameters)) {
257 throw new coding_exception('Invalid parameters description');
260 // fetch the return values description
261 $function->returns_desc = call_user_func(array($function->classname, $function->returns_method));
262 // null means void result or result is ignored
263 if (!is_null($function->returns_desc) and !($function->returns_desc instanceof external_description)) {
264 throw new coding_exception('Invalid return description');
268 $params_desc = array();
269 foreach ($function->parameters_desc->keys as $name=>$keydesc) {
270 $params[] = '$'.$name;
272 if ($keydesc instanceof external_value) {
273 switch($keydesc->type) {
274 case PARAM_BOOL: // 0 or 1 only for now
276 $type = 'int'; break;
278 $type = 'double'; break;
282 } else if ($keydesc instanceof external_single_structure) {
284 } else if ($keydesc instanceof external_multiple_structure) {
287 $params_desc[] = ' * @param '.$type.' $'.$name.' '.$keydesc->desc;
289 $params = implode(', ', $params);
290 $params_desc = implode("\n", $params_desc);
292 if (is_null($function->returns_desc)) {
293 $return = ' * @return void';
296 if ($function->returns_desc instanceof external_value) {
297 switch($function->returns_desc->type) {
298 case PARAM_BOOL: // 0 or 1 only for now
300 $type = 'int'; break;
302 $type = 'double'; break;
306 } else if ($function->returns_desc instanceof external_single_structure) {
308 } else if ($function->returns_desc instanceof external_multiple_structure) {
311 $return = ' * @return '.$type.' '.$function->returns_desc->desc;
314 // now crate a virtual method that calls the ext implemenation
315 // TODO: add PHP docs and all missing info here
319 * External function: '.$function->name.'
320 * TODO: add function description
324 public function '.$function->name.'('.$params.') {
325 return '.$function->classname.'::'.$function->methodname.'('.$params.');
332 * Set up zend serice class
335 protected function init_zend_server() {
336 include "Zend/Loader.php";
337 Zend_Loader::registerAutoload();
338 //TODO: set up some server options and debugging too - maybe a new method
339 //TODO: add some zend exeption handler too
340 $this->zend_server = new $this->zend_class();
344 * Send the error information to the WS client.
345 * @param exception $ex
348 protected function send_error($ex=null) {
351 // TODO: find some way to send the error back through the Zend
355 * Authenticate user using username+password or token.
356 * This function sets up $USER global.
357 * It is safe to use has_capability() after this.
358 * This method also verifies user is allowed to use this
362 protected function authenticate_user() {
365 if (!NO_MOODLE_COOKIES) {
366 throw new coding_exception('Cookies must be disabled in WS servers!');
370 $this->restricted_context = get_context_instance(CONTEXT_SYSTEM);
372 if (!is_enabled_auth('webservice')) {
373 error_log('WS auth not enabled');
374 die('WS auth not enabled');
377 if (!$auth = get_auth_plugin('webservice')) {
378 error_log('WS auth missing');
379 die('WS auth missing');
382 // the username is hardcoded as URL parameter because we can not easily parse the request data :-(
383 if (!$username = optional_param('wsusername', '', PARAM_RAW)) {
384 throw new invalid_parameter_exception('Missing username');
387 // the password is hardcoded as URL parameter because we can not easily parse the request data :-(
388 if (!$password = optional_param('wspassword', '', PARAM_RAW)) {
389 throw new invalid_parameter_exception('Missing password');
392 if (!$auth->user_login_webservice($username, $password)) {
393 throw new invalid_parameter_exception('Wrong username or password');
396 $user = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id, 'deleted'=>0), '*', MUST_EXIST);
398 // now fake user login, the session is completely empty too
399 session_set_user($user);
403 //TODO: not implemented yet
404 die('token login not implemented yet');
405 //TODO: $this->restricted_context is derived from the token context
408 if (!has_capability("webservice/$this->wsname:use", $this->restricted_context)) {
409 throw new invalid_parameter_exception('Access to web service not allowed');
412 external_api::set_context_restriction($this->restricted_context);
416 * Specialised exception handler, we can not use the standard one because
417 * it can not just print html to output.
419 * @param exception $ex
420 * @return void does not return
422 public function exception_handler($ex) {
423 global $CFG, $DB, $SCRIPT;
425 // detect active db transactions, rollback and log as error
426 if ($DB->is_transaction_started()) {
427 error_log('Database transaction aborted by exception in ' . $CFG->dirroot . $SCRIPT);
429 // note: transaction blocks should never change current $_SESSION
431 } catch (Exception $ignored) {
435 // now let the plugin send the exception to client
436 $this->send_error($ex);
438 // some hacks might need a cleanup hook
439 $this->session_cleanup($ex);
441 // not much else we can do now, add some logging later
446 * Future hook needed for emulated sessions.
447 * @param exception $exception null means normal termination, $exception received when WS call failed
450 protected function session_cleanup($exception=null) {
452 // nothing needs to be done, there is no persistent session
454 // close emulated session if used
462 * Web Service server base class, this class handles both
463 * simple and token authentication.
464 * @author Petr Skoda (skodak)
466 abstract class webservice_base_server implements webservice_server {
468 /** @property string $wsname name of the web server plugin */
469 protected $wsname = null;
471 /** @property bool $simple true if simple auth used */
474 /** @property string $username name of local user */
475 protected $username = null;
477 /** @property string $password password of the local user */
478 protected $password = null;
480 /** @property string $token authentication token*/
481 protected $token = null;
483 /** @property object restricted context */
484 protected $restricted_context;
486 /** @property array $parameters the function parameters - the real values submitted in the request */
487 protected $parameters = null;
489 /** @property string $functionname the name of the function that is executed */
490 protected $functionname = null;
492 /** @property object $function full function description */
493 protected $function = null;
495 /** @property mixed $returns function return value */
496 protected $returns = null;
501 public function __construct() {
505 * This method parses the request input, it needs to get:
506 * 1/ user authentication - username+password or token
508 * 3/ function parameters
512 abstract protected function parse_request();
515 * Send the result of function call to the WS client.
518 abstract protected function send_response();
521 * Send the error information to the WS client.
522 * @param exception $ex
525 abstract protected function send_error($ex=null);
529 * Process request from client.
530 * @param bool $simple use simple authentication
533 public function run($simple) {
534 $this->simple = $simple;
536 // we will probably need a lot of memory in some functions
537 @raise_memory_limit('128M');
539 // set some longer timeout, this script is not sending any output,
540 // this means we need to manually extend the timeout operations
541 // that need longer time to finish
542 external_api::set_timeout();
544 // set up exception handler first, we want to sent them back in correct format that
545 // the other system understands
546 // we do not need to call the original default handler because this ws handler does everything
547 set_exception_handler(array($this, 'exception_handler'));
549 // init all properties from the request data
550 $this->parse_request();
552 // authenticate user, this has to be done after the request parsing
553 // this also sets up $USER and $SESSION
554 $this->authenticate_user();
556 // find all needed function info and make sure user may actually execute the function
557 $this->load_function_info();
559 // finally, execute the function - any errors are catched by the default exception handler
562 // send the results back in correct format
563 $this->send_response();
566 $this->session_cleanup();
572 * Specialised exception handler, we can not use the standard one because
573 * it can not just print html to output.
575 * @param exception $ex
576 * @return void does not return
578 public function exception_handler($ex) {
579 global $CFG, $DB, $SCRIPT;
581 // detect active db transactions, rollback and log as error
582 if ($DB->is_transaction_started()) {
583 error_log('Database transaction aborted by exception in ' . $CFG->dirroot . $SCRIPT);
585 // note: transaction blocks should never change current $_SESSION
587 } catch (Exception $ignored) {
591 // now let the plugin send the exception to client
592 $this->send_error($ex);
594 // some hacks might need a cleanup hook
595 $this->session_cleanup($ex);
597 // not much else we can do now, add some logging later
602 * Future hook needed for emulated sessions.
603 * @param exception $exception null means normal termination, $exception received when WS call failed
606 protected function session_cleanup($exception=null) {
608 // nothing needs to be done, there is no persistent session
610 // close emulated session if used
615 * Authenticate user using username+password or token.
616 * This function sets up $USER global.
617 * It is safe to use has_capability() after this.
618 * This method also verifies user is allowed to use this
622 protected function authenticate_user() {
625 if (!NO_MOODLE_COOKIES) {
626 throw new coding_exception('Cookies must be disabled in WS servers!');
630 $this->restricted_context = get_context_instance(CONTEXT_SYSTEM);
632 if (!is_enabled_auth('webservice')) {
633 die('WS auth not enabled');
636 if (!$auth = get_auth_plugin('webservice')) {
637 die('WS auth missing');
640 if (!$this->username) {
641 throw new invalid_parameter_exception('Missing username');
644 if (!$this->password) {
645 throw new invalid_parameter_exception('Missing password');
648 if (!$auth->user_login_webservice($this->username, $this->password)) {
649 throw new invalid_parameter_exception('Wrong username or password');
652 $user = $DB->get_record('user', array('username'=>$this->username, 'mnethostid'=>$CFG->mnet_localhost_id, 'deleted'=>0), '*', MUST_EXIST);
654 // now fake user login, the session is completely empty too
655 session_set_user($user);
658 //TODO: not implemented yet
659 die('token login not implemented yet');
660 //TODO: $this->restricted_context is derived from the token context
663 if (!has_capability("webservice/$this->wsname:use", $this->restricted_context)) {
664 throw new invalid_parameter_exception('Access to web service not allowed');
667 external_api::set_context_restriction($this->restricted_context);
671 * Fetches the function description from database,
672 * verifies user is allowed to use this function and
673 * loads all paremeters and return descriptions.
676 protected function load_function_info() {
677 global $DB, $USER, $CFG;
679 if (empty($this->functionname)) {
680 throw new invalid_parameter_exception('Missing function name');
683 // function must exist
684 $function = $DB->get_record('external_functions', array('name'=>$this->functionname), '*', MUST_EXIST);
687 // now let's verify access control
689 // now make sure the function is listed in at least one service user is allowed to use
690 // allow access only if:
691 // 1/ entry in the external_services_users table if required
692 // 2/ validuntil not reached
693 // 3/ has capability if specified in service desc
696 $sql = "SELECT s.*, NULL AS iprestriction
697 FROM {external_services} s
698 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0 AND sf.functionname = :name1)
703 SELECT s.*, su.iprestriction
704 FROM {external_services} s
705 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1 AND sf.functionname = :name2)
706 JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)
707 WHERE s.enabled = 1 AND su.validuntil IS NULL OR su.validuntil < :now";
708 $params = array('userid'=>$USER->id, 'name1'=>$function->name, 'name2'=>$function->name, 'now'=>time());
711 //TODO: token may restrict access to one service only
712 die('not implemented yet');
715 $rs = $DB->get_recordset_sql($sql, $params);
716 // now make sure user may access at least one service
717 $remoteaddr = getremoteaddr();
719 foreach ($rs as $service) {
720 if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) {
721 continue; // cap required, sorry
723 if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) {
724 continue; // wrong request source ip, sorry
727 break; // one service is enough, no need to continue
731 throw new invalid_parameter_exception('Access to external function not allowed');
733 // now we finally know the user may execute this function,
734 // the last step is to set context restriction - in this simple case
735 // we use system context because each external system has different user account
736 // and we can manage everything through normal permissions.
738 // get the params and return descriptions of the function
739 unset($function->id); // we want to prevent any accidental db updates ;-)
741 $function->classpath = empty($function->classpath) ? get_component_directory($function->component).'/externallib.php' : $CFG->dirroot.'/'.$function->classpath;
742 if (!file_exists($function->classpath)) {
743 throw new coding_exception('Can not find file with external function implementation');
745 require_once($function->classpath);
747 $function->parameters_method = $function->methodname.'_parameters';
748 $function->returns_method = $function->methodname.'_returns';
750 // make sure the implementaion class is ok
751 if (!method_exists($function->classname, $function->methodname)) {
752 throw new coding_exception('Missing implementation method');
754 if (!method_exists($function->classname, $function->parameters_method)) {
755 throw new coding_exception('Missing parameters description');
757 if (!method_exists($function->classname, $function->returns_method)) {
758 throw new coding_exception('Missing returned values description');
761 // fetch the parameters description
762 $function->parameters_desc = call_user_func(array($function->classname, $function->parameters_method));
763 if (!($function->parameters_desc instanceof external_function_parameters)) {
764 throw new coding_exception('Invalid parameters description');
767 // fetch the return values description
768 $function->returns_desc = call_user_func(array($function->classname, $function->returns_method));
769 // null means void result or result is ignored
770 if (!is_null($function->returns_desc) and !($function->returns_desc instanceof external_description)) {
771 throw new coding_exception('Invalid return description');
774 // we have all we need now
775 $this->function = $function;
779 * Execute previously loaded function using parameters parsed from the request data.
782 protected function execute() {
783 // validate params, this also sorts the params properly, we need the correct order in the next part
784 $params = call_user_func(array($this->function->classname, 'validate_parameters'), $this->function->parameters_desc, $this->parameters);
787 $this->returns = call_user_func_array(array($this->function->classname, $this->function->methodname), array_values($params));