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 error_log(ob_get_clean());
266 error_log($response);
269 $this->session_cleanup();
271 //finally send the result
272 $this->send_headers();
278 * Load virtual class needed for Zend api
281 protected function init_service_class() {
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';
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
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
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();
324 foreach ($rs as $service) {
325 if (isset($serviceids[$service->id
])) {
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
;
338 // now get the list of all functions
340 list($serviceids, $params) = $DB->get_in_or_equal($serviceids);
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);
348 $functions = array();
351 // now make the virtual WS class with all the fuctions for this particular user
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)) {
365 * Virtual class web services for user id '.$USER->id
.' in context '.$this->restricted_context
->id
.'.
367 class '.$classname.' {
372 // load the virtual class definition into memory
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) {
385 $function = external_function_info($function);
388 $params_desc = array();
389 foreach ($function->parameters_desc
->keys
as $name=>$keydesc) {
390 $params[] = '$'.$name;
392 if ($keydesc instanceof external_value
) {
393 switch($keydesc->type
) {
394 case PARAM_BOOL
: // 0 or 1 only for now
396 $type = 'int'; break;
398 $type = 'double'; break;
402 } else if ($keydesc instanceof external_single_structure
) {
404 } else if ($keydesc instanceof external_multiple_structure
) {
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';
418 if ($function->returns_desc
instanceof external_value
) {
419 switch($function->returns_desc
->type
) {
420 case PARAM_BOOL
: // 0 or 1 only for now
422 $type = 'int'; break;
424 $type = 'double'; break;
428 } else if ($function->returns_desc
instanceof external_single_structure
) {
430 } else if ($function->returns_desc
instanceof external_multiple_structure
) {
433 $return = ' * @return '.$type.' '.$function->returns_desc
->desc
;
436 // now crate the virtual method that calls the ext implementation
440 * '.$function->description
.'
445 public function '.$function->name
.'('.$params.') {
446 '.$serviceclassmethodbody.'
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
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)
479 protected function parse_request() {
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'];
489 if (isset($_REQUEST['wstoken'])) {
490 $this->token
= $_REQUEST['wstoken'];
496 * Internal implementation - sending of page headers.
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
528 * Send the error information to the WS client
529 * formatted as XML document.
530 * @param exception $ex
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
543 protected function session_cleanup($exception=null) {
545 // nothing needs to be done, there is no persistent session
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;
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
584 * 3/ function parameters
588 abstract protected function parse_request();
591 * Send the result of function call to the WS client.
594 abstract protected function send_response();
597 * Send the error information to the WS client.
598 * @param exception $ex
601 abstract protected function send_error($ex=null);
604 * Process request from client.
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
637 // send the results back in correct format
638 $this->send_response();
641 $this->session_cleanup();
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
668 * Future hook needed for emulated sessions.
669 * @param exception $exception null means normal termination, $exception received when WS call failed
672 protected function session_cleanup($exception=null) {
674 // nothing needs to be done, there is no persistent session
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.
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';
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
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
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();
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
741 break; // one service is enough, no need to continue
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.
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
);
761 $this->returns
= call_user_func_array(array($this->function->classname
, $this->function->methodname
), array_values($params));