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 define('WEBSERVICE_AUTHMETHOD_USERNAME', 0);
29 define('WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN', 1);
30 define('WEBSERVICE_AUTHMETHOD_SESSION_TOKEN', 2);
33 * General web service library
38 * Add a user to the list of authorised user of a given service
41 public function add_ws_authorised_user($user) {
43 $serviceuser->timecreated = mktime();
44 $DB->insert_record('external_services_users', $user);
48 * Remove a user from a list of allowed user of a service
50 * @param int $serviceid
52 public function remove_ws_authorised_user($user, $serviceid) {
54 $DB->delete_records('external_services_users',
55 array('externalserviceid' => $serviceid, 'userid' => $user->id));
59 * Update service allowed user settings
62 public function update_ws_authorised_user($user) {
64 $DB->update_record('external_services_users', $user);
68 * Return list of allowed users with their options (ip/timecreated / validuntil...)
70 * @param int $serviceid
71 * @return array $users
73 public function get_ws_authorised_users($serviceid) {
75 $params = array($serviceid);
76 $sql = " SELECT u.id as id, esu.id as serviceuserid, u.email as email, u.firstname as firstname,
77 u.lastname as lastname,
78 esu.iprestriction as iprestriction, esu.validuntil as validuntil,
79 esu.timecreated as timecreated
80 FROM {user} u, {external_services_users} esu
81 WHERE username <> 'guest' AND deleted = 0 AND confirmed = 1
83 AND esu.externalserviceid = ?";
84 if (!empty($userid)) {
85 $sql .= ' AND u.id = ?';
89 $users = $DB->get_records_sql($sql, $params);
94 * Return a authorised user with his options (ip/timecreated / validuntil...)
95 * @param int $serviceid
99 public function get_ws_authorised_user($serviceid, $userid) {
101 $params = array($serviceid, $userid);
102 $sql = " SELECT u.id as id, esu.id as serviceuserid, u.email as email, u.firstname as firstname,
103 u.lastname as lastname,
104 esu.iprestriction as iprestriction, esu.validuntil as validuntil,
105 esu.timecreated as timecreated
106 FROM {user} u, {external_services_users} esu
107 WHERE username <> 'guest' AND deleted = 0 AND confirmed = 1
108 AND esu.userid = u.id
109 AND esu.externalserviceid = ?
111 $user = $DB->get_record_sql($sql, $params);
116 * Generate all ws token needed by a user
119 public function generate_user_ws_tokens($userid) {
122 /// generate a token for non admin if web service are enable and the user has the capability to create a token
123 if (!is_siteadmin() && has_capability('moodle/webservice:createtoken', get_context_instance(CONTEXT_SYSTEM), $userid) && !empty($CFG->enablewebservices)) {
124 /// for every service than the user is authorised on, create a token (if it doesn't already exist)
126 ///get all services which are set to all user (no restricted to specific users)
127 $norestrictedservices = $DB->get_records('external_services', array('restrictedusers' => 0));
128 $serviceidlist = array();
129 foreach ($norestrictedservices as $service) {
130 $serviceidlist[] = $service->id;
133 //get all services which are set to the current user (the current user is specified in the restricted user list)
134 $servicesusers = $DB->get_records('external_services_users', array('userid' => $userid));
135 foreach ($servicesusers as $serviceuser) {
136 if (!in_array($serviceuser->externalserviceid,$serviceidlist)) {
137 $serviceidlist[] = $serviceuser->externalserviceid;
141 //get all services which already have a token set for the current user
142 $usertokens = $DB->get_records('external_tokens', array('userid' => $userid, 'tokentype' => EXTERNAL_TOKEN_PERMANENT));
143 $tokenizedservice = array();
144 foreach ($usertokens as $token) {
145 $tokenizedservice[] = $token->externalserviceid;
148 //create a token for the service which have no token already
149 foreach ($serviceidlist as $serviceid) {
150 if (!in_array($serviceid, $tokenizedservice)) {
151 //create the token for this service
152 $newtoken = new object();
153 $newtoken->token = md5(uniqid(rand(),1));
154 //check that the user has capability on this service
155 $newtoken->tokentype = EXTERNAL_TOKEN_PERMANENT;
156 $newtoken->userid = $userid;
157 $newtoken->externalserviceid = $serviceid;
158 //TODO: find a way to get the context - UPDATE FOLLOWING LINE
159 $newtoken->contextid = get_context_instance(CONTEXT_SYSTEM)->id;
160 $newtoken->creatorid = $userid;
161 $newtoken->timecreated = time();
163 $DB->insert_record('external_tokens', $newtoken);
172 * Return all ws user token
173 * @param integer $userid
174 * @return array of token
176 public function get_user_ws_tokens($userid) {
178 //here retrieve token list (including linked users firstname/lastname and linked services name)
180 t.id, t.creatorid, t.token, u.firstname, u.lastname, s.name, t.validuntil
182 {external_tokens} t, {user} u, {external_services} s
184 t.userid=? AND t.tokentype = ".EXTERNAL_TOKEN_PERMANENT." AND s.id = t.externalserviceid AND t.userid = u.id";
185 $tokens = $DB->get_records_sql($sql, array( $userid));
190 * Return a user token that has been created by the user
191 * If doesn't exist a exception is thrown
192 * @param integer $userid
193 * @param integer $tokenid
196 public function get_created_by_user_ws_token($userid, $tokenid) {
199 t.id, t.token, u.firstname, u.lastname, s.name
201 {external_tokens} t, {user} u, {external_services} s
203 t.creatorid=? AND t.id=? AND t.tokentype = ".EXTERNAL_TOKEN_PERMANENT." AND s.id = t.externalserviceid AND t.userid = u.id";
204 $token = $DB->get_record_sql($sql, array($userid, $tokenid), MUST_EXIST); //must be the token creator
210 * Delete a user token
211 * @param int $tokenid
213 public function delete_user_ws_token($tokenid) {
215 $DB->delete_records('external_tokens', array('id'=>$tokenid));
219 * Get a user token by token
220 * @param string $token
221 * @throws moodle_exception if there is multiple result
223 public function get_user_ws_token($token) {
225 return $DB->get_record('external_tokens', array('token'=>$token), '*', MUST_EXIST);
231 * Exception indicating access control problem in web service call
232 * @author Petr Skoda (skodak)
234 class webservice_access_exception extends moodle_exception {
238 function __construct($debuginfo) {
239 parent::__construct('accessexception', 'webservice', '', null, $debuginfo);
244 * Is protocol enabled?
245 * @param string $protocol name of WS protocol
248 function webservice_protocol_is_enabled($protocol) {
251 if (empty($CFG->enablewebservices)) {
255 $active = explode(',', $CFG->webserviceprotocols);
257 return(in_array($protocol, $active));
263 * Mandatory interface for all test client classes.
264 * @author Petr Skoda (skodak)
266 interface webservice_test_client_interface {
268 * Execute test client WS request
269 * @param string $serverurl
270 * @param string $function
271 * @param array $params
274 public function simpletest($serverurl, $function, $params);
278 * Mandatory interface for all web service protocol classes
279 * @author Petr Skoda (skodak)
281 interface webservice_server_interface {
283 * Process request from client.
286 public function run();
290 * Abstract web service base class.
291 * @author Petr Skoda (skodak)
293 abstract class webservice_server implements webservice_server_interface {
295 /** @property string $wsname name of the web server plugin */
296 protected $wsname = null;
298 /** @property string $username name of local user */
299 protected $username = null;
301 /** @property string $password password of the local user */
302 protected $password = null;
304 /** @property int $userid the local user */
305 protected $userid = null;
307 /** @property integer $authmethod authentication method one of WEBSERVICE_AUTHMETHOD_* */
308 protected $authmethod;
310 /** @property string $token authentication token*/
311 protected $token = null;
313 /** @property object restricted context */
314 protected $restricted_context;
316 /** @property int restrict call to one service id*/
317 protected $restricted_serviceid = null;
321 * @param integer $authmethod authentication method one of WEBSERVICE_AUTHMETHOD_*
323 public function __construct($authmethod) {
324 $this->authmethod = $authmethod;
329 * Authenticate user using username+password or token.
330 * This function sets up $USER global.
331 * It is safe to use has_capability() after this.
332 * This method also verifies user is allowed to use this
336 protected function authenticate_user() {
339 if (!NO_MOODLE_COOKIES) {
340 throw new coding_exception('Cookies must be disabled in WS servers!');
343 if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
345 //we check that authentication plugin is enabled
346 //it is only required by simple authentication
347 if (!is_enabled_auth('webservice')) {
348 throw new webservice_access_exception(get_string('wsauthnotenabled', 'webservice'));
351 if (!$auth = get_auth_plugin('webservice')) {
352 throw new webservice_access_exception(get_string('wsauthmissing', 'webservice'));
355 $this->restricted_context = get_context_instance(CONTEXT_SYSTEM);
357 if (!$this->username) {
358 throw new webservice_access_exception(get_string('missingusername', 'webservice'));
361 if (!$this->password) {
362 throw new webservice_access_exception(get_string('missingpassword', 'webservice'));
365 if (!$auth->user_login_webservice($this->username, $this->password)) {
366 // log failed login attempts
367 add_to_log(1, 'webservice', get_string('simpleauthlog', 'webservice'), '' , get_string('failedtolog', 'webservice').": ".$this->username."/".$this->password." - ".getremoteaddr() , 0);
368 throw new webservice_access_exception(get_string('wrongusernamepassword', 'webservice'));
371 $user = $DB->get_record('user', array('username'=>$this->username, 'mnethostid'=>$CFG->mnet_localhost_id, 'deleted'=>0), '*', MUST_EXIST);
373 } else if ($this->authmethod == WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN){
374 $user = $this->authenticate_by_token(EXTERNAL_TOKEN_PERMANENT);
376 $user = $this->authenticate_by_token(EXTERNAL_TOKEN_EMBEDDED);
379 // now fake user login, the session is completely empty too
380 session_set_user($user);
381 $this->userid = $user->id;
383 if ($this->authmethod != WEBSERVICE_AUTHMETHOD_SESSION_TOKEN && !has_capability("webservice/$this->wsname:use", $this->restricted_context)) {
384 throw new webservice_access_exception(get_string('accessnotallowed', 'webservice'));
387 external_api::set_context_restriction($this->restricted_context);
390 protected function authenticate_by_token($tokentype){
392 if (!$token = $DB->get_record('external_tokens', array('token'=>$this->token, 'tokentype'=>$tokentype))) {
393 // log failed login attempts
394 add_to_log(1, 'webservice', get_string('tokenauthlog', 'webservice'), '' , get_string('failedtolog', 'webservice').": ".$this->token. " - ".getremoteaddr() , 0);
395 throw new webservice_access_exception(get_string('invalidtoken', 'webservice'));
398 if ($token->validuntil and $token->validuntil < time()) {
399 $DB->delete_records('external_tokens', array('token'=>$this->token, 'tokentype'=>$tokentype));
400 throw new webservice_access_exception(get_string('invalidtimedtoken', 'webservice'));
403 if ($token->sid){//assumes that if sid is set then there must be a valid associated session no matter the token type
404 $session = session_get_instance();
405 if (!$session->session_exists($token->sid)){
406 $DB->delete_records('external_tokens', array('sid'=>$token->sid));
407 throw new webservice_access_exception(get_string('invalidtokensession', 'webservice'));
411 if ($token->iprestriction and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
412 add_to_log(1, 'webservice', get_string('tokenauthlog', 'webservice'), '' , get_string('failedtolog', 'webservice').": ".getremoteaddr() , 0);
413 throw new webservice_access_exception(get_string('invalidiptoken', 'webservice'));
416 $this->restricted_context = get_context_instance_by_id($token->contextid);
417 $this->restricted_serviceid = $token->externalserviceid;
419 $user = $DB->get_record('user', array('id'=>$token->userid, 'deleted'=>0), '*', MUST_EXIST);
422 $DB->set_field('external_tokens', 'lastaccess', time(), array('id'=>$token->id));
430 * Special abstraction of our srvices that allows
431 * interaction with stock Zend ws servers.
432 * @author Petr Skoda (skodak)
434 abstract class webservice_zend_server extends webservice_server {
436 /** @property string name of the zend server class : Zend_XmlRpc_Server, Zend_Soap_Server, Zend_Soap_AutoDiscover, ...*/
437 protected $zend_class;
439 /** @property object Zend server instance */
440 protected $zend_server;
442 /** @property string $service_class virtual web service class with all functions user name execute, created on the fly */
443 protected $service_class;
447 * @param integer $authmethod authentication method - one of WEBSERVICE_AUTHMETHOD_*
449 public function __construct($authmethod, $zend_class) {
450 parent::__construct($authmethod);
451 $this->zend_class = $zend_class;
455 * Process request from client.
456 * @param bool $simple use simple authentication
459 public function run() {
460 // we will probably need a lot of memory in some functions
461 @raise_memory_limit('128M');
463 // set some longer timeout, this script is not sending any output,
464 // this means we need to manually extend the timeout operations
465 // that need longer time to finish
466 external_api::set_timeout();
468 // now create the instance of zend server
469 $this->init_zend_server();
471 // set up exception handler first, we want to sent them back in correct format that
472 // the other system understands
473 // we do not need to call the original default handler because this ws handler does everything
474 set_exception_handler(array($this, 'exception_handler'));
476 // init all properties from the request data
477 $this->parse_request();
479 // this sets up $USER and $SESSION and context restrictions
480 $this->authenticate_user();
482 // make a list of all functions user is allowed to excecute
483 $this->init_service_class();
485 // tell server what functions are available
486 $this->zend_server->setClass($this->service_class);
488 //log the web service request
489 add_to_log(1, 'webservice', '', '' , $this->zend_class." ".getremoteaddr() , 0, $this->userid);
491 // execute and return response, this sends some headers too
492 $response = $this->zend_server->handle();
495 $this->session_cleanup();
497 //finally send the result
498 $this->send_headers();
504 * Load virtual class needed for Zend api
507 protected function init_service_class() {
510 // first ofall get a complete list of services user is allowed to access
512 if ($this->restricted_serviceid) {
513 $params = array('sid1'=>$this->restricted_serviceid, 'sid2'=>$this->restricted_serviceid);
514 $wscond1 = 'AND s.id = :sid1';
515 $wscond2 = 'AND s.id = :sid2';
522 // now make sure the function is listed in at least one service user is allowed to use
523 // allow access only if:
524 // 1/ entry in the external_services_users table if required
525 // 2/ validuntil not reached
526 // 3/ has capability if specified in service desc
529 $sql = "SELECT s.*, NULL AS iprestriction
530 FROM {external_services} s
531 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0)
532 WHERE s.enabled = 1 $wscond1
536 SELECT s.*, su.iprestriction
537 FROM {external_services} s
538 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1)
539 JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)
540 WHERE s.enabled = 1 AND su.validuntil IS NULL OR su.validuntil < :now $wscond2";
542 $params = array_merge($params, array('userid'=>$USER->id, 'now'=>time()));
544 $serviceids = array();
545 $rs = $DB->get_recordset_sql($sql, $params);
547 // now make sure user may access at least one service
548 $remoteaddr = getremoteaddr();
550 foreach ($rs as $service) {
551 if (isset($serviceids[$service->id])) {
554 if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) {
555 continue; // cap required, sorry
557 if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) {
558 continue; // wrong request source ip, sorry
560 $serviceids[$service->id] = $service->id;
564 // now get the list of all functions
566 list($serviceids, $params) = $DB->get_in_or_equal($serviceids);
568 FROM {external_functions} f
569 WHERE f.name IN (SELECT sf.functionname
570 FROM {external_services_functions} sf
571 WHERE sf.externalserviceid $serviceids)";
572 $functions = $DB->get_records_sql($sql, $params);
574 $functions = array();
577 // now make the virtual WS class with all the fuctions for this particular user
579 foreach ($functions as $function) {
580 $methods .= $this->get_virtual_method_code($function);
583 // let's use unique class name, there might be problem in unit tests
584 $classname = 'webservices_virtual_class_000000';
585 while(class_exists($classname)) {
591 * Virtual class web services for user id '.$USER->id.' in context '.$this->restricted_context->id.'.
593 class '.$classname.' {
598 // load the virtual class definition into memory
600 $this->service_class = $classname;
604 * returns virtual method code
605 * @param object $function
606 * @return string PHP code
608 protected function get_virtual_method_code($function) {
611 $function = external_function_info($function);
614 $params_desc = array();
615 foreach ($function->parameters_desc->keys as $name=>$keydesc) {
617 //need to generate the default if there is any
618 if ($keydesc instanceof external_value) {
619 if ($keydesc->required == VALUE_DEFAULT) {
620 if ($keydesc->default===null) {
623 switch($keydesc->type) {
625 $param .= $keydesc->default; break;
627 $param .= $keydesc->default; break;
629 $param .= $keydesc->default; break;
631 $param .= '=\''.$keydesc->default.'\'';
634 } else if ($keydesc->required == VALUE_OPTIONAL) {
635 //it does make sens to declare a parameter VALUE_OPTIONAL
636 //VALUE_OPTIONAL is used only for array/object key
637 throw new moodle_exception('parametercannotbevalueoptional');
639 } else { //for the moment we do not support default for other structure types
640 if ($keydesc->required == VALUE_DEFAULT) {
641 //accept empty array as default
642 if (isset($keydesc->default) and is_array($keydesc->default)
643 and empty($keydesc->default)) {
644 $param .= '=array()';
646 throw new moodle_exception('errornotemptydefaultparamarray', 'webservice', '', $name);
649 if ($keydesc->required == VALUE_OPTIONAL) {
650 throw new moodle_exception('erroroptionalparamarray', 'webservice', '', $name);
655 if ($keydesc instanceof external_value) {
656 switch($keydesc->type) {
657 case PARAM_BOOL: // 0 or 1 only for now
659 $type = 'int'; break;
661 $type = 'double'; break;
665 } else if ($keydesc instanceof external_single_structure) {
666 $type = 'object|struct';
667 } else if ($keydesc instanceof external_multiple_structure) {
670 $params_desc[] = ' * @param '.$type.' $'.$name.' '.$keydesc->desc;
672 $params = implode(', ', $params);
673 $params_desc = implode("\n", $params_desc);
675 $serviceclassmethodbody = $this->service_class_method_body($function, $params);
677 if (is_null($function->returns_desc)) {
678 $return = ' * @return void';
681 if ($function->returns_desc instanceof external_value) {
682 switch($function->returns_desc->type) {
683 case PARAM_BOOL: // 0 or 1 only for now
685 $type = 'int'; break;
687 $type = 'double'; break;
691 } else if ($function->returns_desc instanceof external_single_structure) {
692 $type = 'object|struct'; //only 'object' is supported by SOAP, 'struct' by XML-RPC MDL-23083
693 } else if ($function->returns_desc instanceof external_multiple_structure) {
696 $return = ' * @return '.$type.' '.$function->returns_desc->desc;
699 // now crate the virtual method that calls the ext implementation
703 * '.$function->description.'
708 public function '.$function->name.'('.$params.') {
709 '.$serviceclassmethodbody.'
716 * You can override this function in your child class to add extra code into the dynamically
717 * created service class. For example it is used in the amf server to cast types of parameters and to
718 * cast the return value to the types as specified in the return value description.
719 * @param unknown_type $function
720 * @param unknown_type $params
721 * @return string body of the method for $function ie. everything within the {} of the method declaration.
723 protected function service_class_method_body($function, $params){
724 //cast the param from object to array (validate_parameters except array only)
727 $paramstocast = split(',', $params);
728 foreach ($paramstocast as $paramtocast) {
729 //clean the parameter from any white space
730 $paramtocast = trim($paramtocast);
731 $castingcode .= $paramtocast .
732 '=webservice_zend_server::cast_objects_to_array('.$paramtocast.');';
737 $descriptionmethod = $function->methodname.'_returns()';
738 $callforreturnvaluedesc = $function->classname.'::'.$descriptionmethod;
739 return $castingcode . ' if ('.$callforreturnvaluedesc.' == null) {'.
740 $function->classname.'::'.$function->methodname.'('.$params.');
743 return external_api::clean_returnvalue('.$callforreturnvaluedesc.', '.$function->classname.'::'.$function->methodname.'('.$params.'));';
747 * Recursive function to recurse down into a complex variable and convert all
749 * @param mixed $param value to cast
750 * @return mixed Cast value
752 public static function cast_objects_to_array($param){
753 if (is_object($param)){
754 $param = (array)$param;
756 if (is_array($param)){
758 foreach ($param as $key=> $param){
759 $toreturn[$key] = self::cast_objects_to_array($param);
768 * Set up zend service class
771 protected function init_zend_server() {
772 $this->zend_server = new $this->zend_class();
776 * This method parses the $_REQUEST superglobal and looks for
777 * the following information:
778 * 1/ user authentication - username+password or token (wsusername, wspassword and wstoken parameters)
782 protected function parse_request() {
783 if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
784 //note: some clients have problems with entity encoding :-(
785 if (isset($_REQUEST['wsusername'])) {
786 $this->username = $_REQUEST['wsusername'];
788 if (isset($_REQUEST['wspassword'])) {
789 $this->password = $_REQUEST['wspassword'];
792 if (isset($_REQUEST['wstoken'])) {
793 $this->token = $_REQUEST['wstoken'];
799 * Internal implementation - sending of page headers.
802 protected function send_headers() {
803 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
804 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
805 header('Pragma: no-cache');
806 header('Accept-Ranges: none');
810 * Specialised exception handler, we can not use the standard one because
811 * it can not just print html to output.
813 * @param exception $ex
814 * @return void does not return
816 public function exception_handler($ex) {
817 // detect active db transactions, rollback and log as error
818 abort_all_db_transactions();
820 // some hacks might need a cleanup hook
821 $this->session_cleanup($ex);
823 // now let the plugin send the exception to client
824 $this->send_error($ex);
826 // not much else we can do now, add some logging later
831 * Send the error information to the WS client
832 * formatted as XML document.
833 * @param exception $ex
836 protected function send_error($ex=null) {
837 $this->send_headers();
838 echo $this->zend_server->fault($ex);
842 * Future hook needed for emulated sessions.
843 * @param exception $exception null means normal termination, $exception received when WS call failed
846 protected function session_cleanup($exception=null) {
847 if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
848 // nothing needs to be done, there is no persistent session
850 // close emulated session if used
857 * Web Service server base class, this class handles both
858 * simple and token authentication.
859 * @author Petr Skoda (skodak)
861 abstract class webservice_base_server extends webservice_server {
863 /** @property array $parameters the function parameters - the real values submitted in the request */
864 protected $parameters = null;
866 /** @property string $functionname the name of the function that is executed */
867 protected $functionname = null;
869 /** @property object $function full function description */
870 protected $function = null;
872 /** @property mixed $returns function return value */
873 protected $returns = null;
876 * This method parses the request input, it needs to get:
877 * 1/ user authentication - username+password or token
879 * 3/ function parameters
883 abstract protected function parse_request();
886 * Send the result of function call to the WS client.
889 abstract protected function send_response();
892 * Send the error information to the WS client.
893 * @param exception $ex
896 abstract protected function send_error($ex=null);
899 * Process request from client.
902 public function run() {
903 // we will probably need a lot of memory in some functions
904 @raise_memory_limit('128M');
906 // set some longer timeout, this script is not sending any output,
907 // this means we need to manually extend the timeout operations
908 // that need longer time to finish
909 external_api::set_timeout();
911 // set up exception handler first, we want to sent them back in correct format that
912 // the other system understands
913 // we do not need to call the original default handler because this ws handler does everything
914 set_exception_handler(array($this, 'exception_handler'));
916 // init all properties from the request data
917 $this->parse_request();
919 // authenticate user, this has to be done after the request parsing
920 // this also sets up $USER and $SESSION
921 $this->authenticate_user();
923 // find all needed function info and make sure user may actually execute the function
924 $this->load_function_info();
926 //log the web service request
927 add_to_log(1, 'webservice', $this->functionname, '' , getremoteaddr() , 0, $this->userid);
929 // finally, execute the function - any errors are catched by the default exception handler
932 // send the results back in correct format
933 $this->send_response();
936 $this->session_cleanup();
942 * Specialised exception handler, we can not use the standard one because
943 * it can not just print html to output.
945 * @param exception $ex
946 * @return void does not return
948 public function exception_handler($ex) {
949 // detect active db transactions, rollback and log as error
950 abort_all_db_transactions();
952 // some hacks might need a cleanup hook
953 $this->session_cleanup($ex);
955 // now let the plugin send the exception to client
956 $this->send_error($ex);
958 // not much else we can do now, add some logging later
963 * Future hook needed for emulated sessions.
964 * @param exception $exception null means normal termination, $exception received when WS call failed
967 protected function session_cleanup($exception=null) {
968 if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
969 // nothing needs to be done, there is no persistent session
971 // close emulated session if used
976 * Fetches the function description from database,
977 * verifies user is allowed to use this function and
978 * loads all paremeters and return descriptions.
981 protected function load_function_info() {
982 global $DB, $USER, $CFG;
984 if (empty($this->functionname)) {
985 throw new invalid_parameter_exception('Missing function name');
988 // function must exist
989 $function = external_function_info($this->functionname);
991 if ($this->restricted_serviceid) {
992 $params = array('sid1'=>$this->restricted_serviceid, 'sid2'=>$this->restricted_serviceid);
993 $wscond1 = 'AND s.id = :sid1';
994 $wscond2 = 'AND s.id = :sid2';
1001 // now let's verify access control
1003 // now make sure the function is listed in at least one service user is allowed to use
1004 // allow access only if:
1005 // 1/ entry in the external_services_users table if required
1006 // 2/ validuntil not reached
1007 // 3/ has capability if specified in service desc
1010 $sql = "SELECT s.*, NULL AS iprestriction
1011 FROM {external_services} s
1012 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0 AND sf.functionname = :name1)
1013 WHERE s.enabled = 1 $wscond1
1017 SELECT s.*, su.iprestriction
1018 FROM {external_services} s
1019 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1 AND sf.functionname = :name2)
1020 JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)
1021 WHERE s.enabled = 1 AND su.validuntil IS NULL OR su.validuntil < :now $wscond2";
1022 $params = array_merge($params, array('userid'=>$USER->id, 'name1'=>$function->name, 'name2'=>$function->name, 'now'=>time()));
1024 $rs = $DB->get_recordset_sql($sql, $params);
1025 // now make sure user may access at least one service
1026 $remoteaddr = getremoteaddr();
1028 foreach ($rs as $service) {
1029 if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) {
1030 continue; // cap required, sorry
1032 if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) {
1033 continue; // wrong request source ip, sorry
1036 break; // one service is enough, no need to continue
1040 throw new webservice_access_exception('Access to external function not allowed');
1043 // we have all we need now
1044 $this->function = $function;
1048 * Execute previously loaded function using parameters parsed from the request data.
1051 protected function execute() {
1052 // validate params, this also sorts the params properly, we need the correct order in the next part
1053 $params = call_user_func(array($this->function->classname, 'validate_parameters'), $this->function->parameters_desc, $this->parameters);
1056 $this->returns = call_user_func_array(array($this->function->classname, $this->function->methodname), array_values($params));