MDL-28670 webservice : (review) changes improving performance
[moodle.git] / webservice / lib.php
blob188007dc8e06d902821e9231febd35e8e1c6a6da
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Web services utility functions and classes
21 * @package webservice
22 * @copyright 2009 Moodle Pty Ltd (http://moodle.com)
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 require_once($CFG->libdir.'/externallib.php');
28 define('WEBSERVICE_AUTHMETHOD_USERNAME', 0);
29 define('WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN', 1);
30 define('WEBSERVICE_AUTHMETHOD_SESSION_TOKEN', 2);
32 /**
33 * General web service library
35 class webservice {
37 /**
38 * Add a user to the list of authorised user of a given service
39 * @param object $user
41 public function add_ws_authorised_user($user) {
42 global $DB;
43 $user->timecreated = mktime();
44 $DB->insert_record('external_services_users', $user);
47 /**
48 * Remove a user from a list of allowed user of a service
49 * @param object $user
50 * @param int $serviceid
52 public function remove_ws_authorised_user($user, $serviceid) {
53 global $DB;
54 $DB->delete_records('external_services_users',
55 array('externalserviceid' => $serviceid, 'userid' => $user->id));
58 /**
59 * Update service allowed user settings
60 * @param object $user
62 public function update_ws_authorised_user($user) {
63 global $DB;
64 $DB->update_record('external_services_users', $user);
67 /**
68 * Return list of allowed users with their options (ip/timecreated / validuntil...)
69 * for a given service
70 * @param int $serviceid
71 * @return array $users
73 public function get_ws_authorised_users($serviceid) {
74 global $DB, $CFG;
75 $params = array($CFG->siteguest, $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 u.id <> ? AND u.deleted = 0 AND u.confirmed = 1
82 AND esu.userid = u.id
83 AND esu.externalserviceid = ?";
85 $users = $DB->get_records_sql($sql, $params);
86 return $users;
89 /**
90 * Return a authorised user with his options (ip/timecreated / validuntil...)
91 * @param int $serviceid
92 * @param int $userid
93 * @return object
95 public function get_ws_authorised_user($serviceid, $userid) {
96 global $DB, $CFG;
97 $params = array($CFG->siteguest, $serviceid, $userid);
98 $sql = " SELECT u.id as id, esu.id as serviceuserid, u.email as email, u.firstname as firstname,
99 u.lastname as lastname,
100 esu.iprestriction as iprestriction, esu.validuntil as validuntil,
101 esu.timecreated as timecreated
102 FROM {user} u, {external_services_users} esu
103 WHERE u.id <> ? AND u.deleted = 0 AND u.confirmed = 1
104 AND esu.userid = u.id
105 AND esu.externalserviceid = ?
106 AND u.id = ?";
107 $user = $DB->get_record_sql($sql, $params);
108 return $user;
112 * Generate all ws token needed by a user
113 * @param int $userid
115 public function generate_user_ws_tokens($userid) {
116 global $CFG, $DB;
118 /// generate a token for non admin if web service are enable and the user has the capability to create a token
119 if (!is_siteadmin() && has_capability('moodle/webservice:createtoken', get_context_instance(CONTEXT_SYSTEM), $userid) && !empty($CFG->enablewebservices)) {
120 /// for every service than the user is authorised on, create a token (if it doesn't already exist)
122 ///get all services which are set to all user (no restricted to specific users)
123 $norestrictedservices = $DB->get_records('external_services', array('restrictedusers' => 0));
124 $serviceidlist = array();
125 foreach ($norestrictedservices as $service) {
126 $serviceidlist[] = $service->id;
129 //get all services which are set to the current user (the current user is specified in the restricted user list)
130 $servicesusers = $DB->get_records('external_services_users', array('userid' => $userid));
131 foreach ($servicesusers as $serviceuser) {
132 if (!in_array($serviceuser->externalserviceid,$serviceidlist)) {
133 $serviceidlist[] = $serviceuser->externalserviceid;
137 //get all services which already have a token set for the current user
138 $usertokens = $DB->get_records('external_tokens', array('userid' => $userid, 'tokentype' => EXTERNAL_TOKEN_PERMANENT));
139 $tokenizedservice = array();
140 foreach ($usertokens as $token) {
141 $tokenizedservice[] = $token->externalserviceid;
144 //create a token for the service which have no token already
145 foreach ($serviceidlist as $serviceid) {
146 if (!in_array($serviceid, $tokenizedservice)) {
147 //create the token for this service
148 $newtoken = new stdClass();
149 $newtoken->token = md5(uniqid(rand(),1));
150 //check that the user has capability on this service
151 $newtoken->tokentype = EXTERNAL_TOKEN_PERMANENT;
152 $newtoken->userid = $userid;
153 $newtoken->externalserviceid = $serviceid;
154 //TODO: find a way to get the context - UPDATE FOLLOWING LINE
155 $newtoken->contextid = get_context_instance(CONTEXT_SYSTEM)->id;
156 $newtoken->creatorid = $userid;
157 $newtoken->timecreated = time();
159 $DB->insert_record('external_tokens', $newtoken);
168 * Return all ws user token with ws enabled/disabled and ws restricted users mode.
169 * @param integer $userid
170 * @return array of token
172 public function get_user_ws_tokens($userid) {
173 global $DB;
174 //here retrieve token list (including linked users firstname/lastname and linked services name)
175 $sql = "SELECT
176 t.id, t.creatorid, t.token, u.firstname, u.lastname, s.id as wsid, s.name, s.enabled, s.restrictedusers, t.validuntil
177 FROM
178 {external_tokens} t, {user} u, {external_services} s
179 WHERE
180 t.userid=? AND t.tokentype = ".EXTERNAL_TOKEN_PERMANENT." AND s.id = t.externalserviceid AND t.userid = u.id";
181 $tokens = $DB->get_records_sql($sql, array( $userid));
182 return $tokens;
186 * Return a user token that has been created by the user
187 * If doesn't exist a exception is thrown
188 * @param integer $userid
189 * @param integer $tokenid
190 * @return object token
191 * ->id token id
192 * ->token
193 * ->firstname user firstname
194 * ->lastname
195 * ->name service name
197 public function get_created_by_user_ws_token($userid, $tokenid) {
198 global $DB;
199 $sql = "SELECT
200 t.id, t.token, u.firstname, u.lastname, s.name
201 FROM
202 {external_tokens} t, {user} u, {external_services} s
203 WHERE
204 t.creatorid=? AND t.id=? AND t.tokentype = "
205 . EXTERNAL_TOKEN_PERMANENT
206 . " AND s.id = t.externalserviceid AND t.userid = u.id";
207 //must be the token creator
208 $token = $DB->get_record_sql($sql, array($userid, $tokenid), MUST_EXIST);
209 return $token;
213 * Return a token for a given id
214 * @param integer $tokenid
215 * @return object token
217 public function get_token_by_id($tokenid) {
218 global $DB;
219 return $DB->get_record('external_tokens', array('id' => $tokenid));
223 * Delete a user token
224 * @param int $tokenid
226 public function delete_user_ws_token($tokenid) {
227 global $DB;
228 $DB->delete_records('external_tokens', array('id'=>$tokenid));
232 * Delete a service - it also delete the functions and users references to this service
233 * @param int $serviceid
235 public function delete_service($serviceid) {
236 global $DB;
237 $DB->delete_records('external_services_users', array('externalserviceid' => $serviceid));
238 $DB->delete_records('external_services_functions', array('externalserviceid' => $serviceid));
239 $DB->delete_records('external_tokens', array('externalserviceid' => $serviceid));
240 $DB->delete_records('external_services', array('id' => $serviceid));
244 * Get a user token by token
245 * @param string $token
246 * @throws moodle_exception if there is multiple result
248 public function get_user_ws_token($token) {
249 global $DB;
250 return $DB->get_record('external_tokens', array('token'=>$token), '*', MUST_EXIST);
254 * Get the list of all functions for given service ids
255 * @param array $serviceids
256 * @return array functions
258 public function get_external_functions($serviceids) {
259 global $DB;
260 if (!empty($serviceids)) {
261 list($serviceids, $params) = $DB->get_in_or_equal($serviceids);
262 $sql = "SELECT f.*
263 FROM {external_functions} f
264 WHERE f.name IN (SELECT sf.functionname
265 FROM {external_services_functions} sf
266 WHERE sf.externalserviceid $serviceids)";
267 $functions = $DB->get_records_sql($sql, $params);
268 } else {
269 $functions = array();
271 return $functions;
275 * Get the list of all functions for given service shortnames
276 * @param array $serviceshortnames
277 * @param $enabledonly if true then only return function for the service that has been enabled
278 * @return array functions
280 public function get_external_functions_by_enabled_services($serviceshortnames, $enabledonly = true) {
281 global $DB;
282 if (!empty($serviceshortnames)) {
283 $enabledonlysql = $enabledonly?' AND s.enabled = 1 ':'';
284 list($serviceshortnames, $params) = $DB->get_in_or_equal($serviceshortnames);
285 $sql = "SELECT f.*
286 FROM {external_functions} f
287 WHERE f.name IN (SELECT sf.functionname
288 FROM {external_services_functions} sf, {external_services} s
289 WHERE s.shortname $serviceshortnames
290 AND sf.externalserviceid = s.id
291 " . $enabledonlysql . ")";
292 $functions = $DB->get_records_sql($sql, $params);
293 } else {
294 $functions = array();
296 return $functions;
300 * Get the list of all functions not in the given service id
301 * @param int $serviceid
302 * @return array functions
304 public function get_not_associated_external_functions($serviceid) {
305 global $DB;
306 $select = "name NOT IN (SELECT s.functionname
307 FROM {external_services_functions} s
308 WHERE s.externalserviceid = :sid
311 $functions = $DB->get_records_select('external_functions',
312 $select, array('sid' => $serviceid), 'name');
314 return $functions;
318 * Get list of required capabilities of a service, sorted by functions
319 * @param integer $serviceid
320 * @return array
321 * example of return value:
322 * Array
324 * [moodle_group_create_groups] => Array
326 * [0] => moodle/course:managegroups
329 * [moodle_enrol_get_enrolled_users] => Array
331 * [0] => moodle/site:viewparticipants
332 * [1] => moodle/course:viewparticipants
333 * [2] => moodle/role:review
334 * [3] => moodle/site:accessallgroups
335 * [4] => moodle/course:enrolreview
339 public function get_service_required_capabilities($serviceid) {
340 $functions = $this->get_external_functions(array($serviceid));
341 $requiredusercaps = array();
342 foreach ($functions as $function) {
343 $functioncaps = explode(',', $function->capabilities);
344 if (!empty($functioncaps) and !empty($functioncaps[0])) {
345 foreach ($functioncaps as $functioncap) {
346 $requiredusercaps[$function->name][] = trim($functioncap);
350 return $requiredusercaps;
354 * Get user capabilities (with context)
355 * Only usefull for documentation purpose
356 * @param integer $userid
357 * @return array
359 public function get_user_capabilities($userid) {
360 global $DB;
361 //retrieve the user capabilities
362 $sql = "SELECT rc.id, rc.capability FROM {role_capabilities} rc, {role_assignments} ra
363 WHERE rc.roleid=ra.roleid AND ra.userid= ?";
364 $dbusercaps = $DB->get_records_sql($sql, array($userid));
365 $usercaps = array();
366 foreach ($dbusercaps as $usercap) {
367 $usercaps[$usercap->capability] = true;
369 return $usercaps;
373 * Get users missing capabilities for a given service
374 * @param array $users
375 * @param integer $serviceid
376 * @return array of missing capabilities, the key being the user id
378 public function get_missing_capabilities_by_users($users, $serviceid) {
379 global $DB;
380 $usersmissingcaps = array();
382 //retrieve capabilities required by the service
383 $servicecaps = $this->get_service_required_capabilities($serviceid);
385 //retrieve users missing capabilities
386 foreach ($users as $user) {
387 //cast user array into object to be a bit more flexible
388 if (is_array($user)) {
389 $user = (object) $user;
391 $usercaps = $this->get_user_capabilities($user->id);
393 //detect the missing capabilities
394 foreach ($servicecaps as $functioname => $functioncaps) {
395 foreach ($functioncaps as $functioncap) {
396 if (!key_exists($functioncap, $usercaps)) {
397 if (!isset($usersmissingcaps[$user->id])
398 or array_search($functioncap, $usersmissingcaps[$user->id]) === false) {
399 $usersmissingcaps[$user->id][] = $functioncap;
406 return $usersmissingcaps;
410 * Get a external service for a given id
411 * @param service id $serviceid
412 * @param integer $strictness IGNORE_MISSING, MUST_EXIST...
413 * @return object external service
415 public function get_external_service_by_id($serviceid, $strictness=IGNORE_MISSING) {
416 global $DB;
417 $service = $DB->get_record('external_services',
418 array('id' => $serviceid), '*', $strictness);
419 return $service;
423 * Get a external service for a given shortname
424 * @param service shortname $shortname
425 * @param integer $strictness IGNORE_MISSING, MUST_EXIST...
426 * @return object external service
428 public function get_external_service_by_shortname($shortname, $strictness=IGNORE_MISSING) {
429 global $DB;
430 $service = $DB->get_record('external_services',
431 array('shortname' => $shortname), '*', $strictness);
432 return $service;
436 * Get a external function for a given id
437 * @param function id $functionid
438 * @param integer $strictness IGNORE_MISSING, MUST_EXIST...
439 * @return object external function
441 public function get_external_function_by_id($functionid, $strictness=IGNORE_MISSING) {
442 global $DB;
443 $function = $DB->get_record('external_functions',
444 array('id' => $functionid), '*', $strictness);
445 return $function;
449 * Add a function to a service
450 * @param string $functionname
451 * @param integer $serviceid
453 public function add_external_function_to_service($functionname, $serviceid) {
454 global $DB;
455 $addedfunction = new stdClass();
456 $addedfunction->externalserviceid = $serviceid;
457 $addedfunction->functionname = $functionname;
458 $DB->insert_record('external_services_functions', $addedfunction);
462 * Add a service
463 * @param object $service
464 * @return serviceid integer
466 public function add_external_service($service) {
467 global $DB;
468 $service->timecreated = mktime();
469 $serviceid = $DB->insert_record('external_services', $service);
470 return $serviceid;
474 * Update a service
475 * @param object $service
477 public function update_external_service($service) {
478 global $DB;
479 $service->timemodified = mktime();
480 $DB->update_record('external_services', $service);
484 * Test whether a external function is already linked to a service
485 * @param string $functionname
486 * @param integer $serviceid
487 * @return bool true if a matching function exists for the service, else false.
488 * @throws dml_exception if error
490 public function service_function_exists($functionname, $serviceid) {
491 global $DB;
492 return $DB->record_exists('external_services_functions',
493 array('externalserviceid' => $serviceid,
494 'functionname' => $functionname));
497 public function remove_external_function_from_service($functionname, $serviceid) {
498 global $DB;
499 $DB->delete_records('external_services_functions',
500 array('externalserviceid' => $serviceid, 'functionname' => $functionname));
508 * Exception indicating access control problem in web service call
509 * @author Petr Skoda (skodak)
511 class webservice_access_exception extends moodle_exception {
513 * Constructor
515 function __construct($debuginfo) {
516 parent::__construct('accessexception', 'webservice', '', null, $debuginfo);
521 * Is protocol enabled?
522 * @param string $protocol name of WS protocol
523 * @return bool
525 function webservice_protocol_is_enabled($protocol) {
526 global $CFG;
528 if (empty($CFG->enablewebservices)) {
529 return false;
532 $active = explode(',', $CFG->webserviceprotocols);
534 return(in_array($protocol, $active));
537 //=== WS classes ===
540 * Mandatory interface for all test client classes.
541 * @author Petr Skoda (skodak)
543 interface webservice_test_client_interface {
545 * Execute test client WS request
546 * @param string $serverurl
547 * @param string $function
548 * @param array $params
549 * @return mixed
551 public function simpletest($serverurl, $function, $params);
555 * Mandatory interface for all web service protocol classes
556 * @author Petr Skoda (skodak)
558 interface webservice_server_interface {
560 * Process request from client.
561 * @return void
563 public function run();
567 * Abstract web service base class.
568 * @author Petr Skoda (skodak)
570 abstract class webservice_server implements webservice_server_interface {
572 /** @property string $wsname name of the web server plugin */
573 protected $wsname = null;
575 /** @property string $username name of local user */
576 protected $username = null;
578 /** @property string $password password of the local user */
579 protected $password = null;
581 /** @property int $userid the local user */
582 protected $userid = null;
584 /** @property integer $authmethod authentication method one of WEBSERVICE_AUTHMETHOD_* */
585 protected $authmethod;
587 /** @property string $token authentication token*/
588 protected $token = null;
590 /** @property object restricted context */
591 protected $restricted_context;
593 /** @property int restrict call to one service id*/
594 protected $restricted_serviceid = null;
597 * Contructor
598 * @param integer $authmethod authentication method one of WEBSERVICE_AUTHMETHOD_*
600 public function __construct($authmethod) {
601 $this->authmethod = $authmethod;
606 * Authenticate user using username+password or token.
607 * This function sets up $USER global.
608 * It is safe to use has_capability() after this.
609 * This method also verifies user is allowed to use this
610 * server.
611 * @return void
613 protected function authenticate_user() {
614 global $CFG, $DB;
616 if (!NO_MOODLE_COOKIES) {
617 throw new coding_exception('Cookies must be disabled in WS servers!');
620 if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
622 //we check that authentication plugin is enabled
623 //it is only required by simple authentication
624 if (!is_enabled_auth('webservice')) {
625 throw new webservice_access_exception(get_string('wsauthnotenabled', 'webservice'));
628 if (!$auth = get_auth_plugin('webservice')) {
629 throw new webservice_access_exception(get_string('wsauthmissing', 'webservice'));
632 $this->restricted_context = get_context_instance(CONTEXT_SYSTEM);
634 if (!$this->username) {
635 throw new webservice_access_exception(get_string('missingusername', 'webservice'));
638 if (!$this->password) {
639 throw new webservice_access_exception(get_string('missingpassword', 'webservice'));
642 if (!$auth->user_login_webservice($this->username, $this->password)) {
643 // log failed login attempts
644 add_to_log(SITEID, 'webservice', get_string('simpleauthlog', 'webservice'), '' , get_string('failedtolog', 'webservice').": ".$this->username."/".$this->password." - ".getremoteaddr() , 0);
645 throw new webservice_access_exception(get_string('wrongusernamepassword', 'webservice'));
648 $user = $DB->get_record('user', array('username'=>$this->username, 'mnethostid'=>$CFG->mnet_localhost_id, 'deleted'=>0), '*', MUST_EXIST);
650 } else if ($this->authmethod == WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN){
651 $user = $this->authenticate_by_token(EXTERNAL_TOKEN_PERMANENT);
652 } else {
653 $user = $this->authenticate_by_token(EXTERNAL_TOKEN_EMBEDDED);
656 // now fake user login, the session is completely empty too
657 session_set_user($user);
658 $this->userid = $user->id;
660 if ($this->authmethod != WEBSERVICE_AUTHMETHOD_SESSION_TOKEN && !has_capability("webservice/$this->wsname:use", $this->restricted_context)) {
661 throw new webservice_access_exception(get_string('accessnotallowed', 'webservice'));
664 external_api::set_context_restriction($this->restricted_context);
667 protected function authenticate_by_token($tokentype){
668 global $DB;
669 if (!$token = $DB->get_record('external_tokens', array('token'=>$this->token, 'tokentype'=>$tokentype))) {
670 // log failed login attempts
671 add_to_log(SITEID, 'webservice', get_string('tokenauthlog', 'webservice'), '' , get_string('failedtolog', 'webservice').": ".$this->token. " - ".getremoteaddr() , 0);
672 throw new webservice_access_exception(get_string('invalidtoken', 'webservice'));
675 if ($token->validuntil and $token->validuntil < time()) {
676 $DB->delete_records('external_tokens', array('token'=>$this->token, 'tokentype'=>$tokentype));
677 throw new webservice_access_exception(get_string('invalidtimedtoken', 'webservice'));
680 if ($token->sid){//assumes that if sid is set then there must be a valid associated session no matter the token type
681 $session = session_get_instance();
682 if (!$session->session_exists($token->sid)){
683 $DB->delete_records('external_tokens', array('sid'=>$token->sid));
684 throw new webservice_access_exception(get_string('invalidtokensession', 'webservice'));
688 if ($token->iprestriction and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
689 add_to_log(SITEID, 'webservice', get_string('tokenauthlog', 'webservice'), '' , get_string('failedtolog', 'webservice').": ".getremoteaddr() , 0);
690 throw new webservice_access_exception(get_string('invalidiptoken', 'webservice'));
693 $this->restricted_context = get_context_instance_by_id($token->contextid);
694 $this->restricted_serviceid = $token->externalserviceid;
696 $user = $DB->get_record('user', array('id'=>$token->userid, 'deleted'=>0), '*', MUST_EXIST);
698 // log token access
699 $DB->set_field('external_tokens', 'lastaccess', time(), array('id'=>$token->id));
701 return $user;
707 * Special abstraction of our srvices that allows
708 * interaction with stock Zend ws servers.
709 * @author Petr Skoda (skodak)
711 abstract class webservice_zend_server extends webservice_server {
713 /** @property string name of the zend server class : Zend_XmlRpc_Server, Zend_Soap_Server, Zend_Soap_AutoDiscover, ...*/
714 protected $zend_class;
716 /** @property object Zend server instance */
717 protected $zend_server;
719 /** @property string $service_class virtual web service class with all functions user name execute, created on the fly */
720 protected $service_class;
723 * Contructor
724 * @param integer $authmethod authentication method - one of WEBSERVICE_AUTHMETHOD_*
726 public function __construct($authmethod, $zend_class) {
727 parent::__construct($authmethod);
728 $this->zend_class = $zend_class;
732 * Process request from client.
733 * @param bool $simple use simple authentication
734 * @return void
736 public function run() {
737 // we will probably need a lot of memory in some functions
738 raise_memory_limit(MEMORY_EXTRA);
740 // set some longer timeout, this script is not sending any output,
741 // this means we need to manually extend the timeout operations
742 // that need longer time to finish
743 external_api::set_timeout();
745 // now create the instance of zend server
746 $this->init_zend_server();
748 // set up exception handler first, we want to sent them back in correct format that
749 // the other system understands
750 // we do not need to call the original default handler because this ws handler does everything
751 set_exception_handler(array($this, 'exception_handler'));
753 // init all properties from the request data
754 $this->parse_request();
756 // this sets up $USER and $SESSION and context restrictions
757 $this->authenticate_user();
759 // make a list of all functions user is allowed to excecute
760 $this->init_service_class();
762 // tell server what functions are available
763 $this->zend_server->setClass($this->service_class);
765 //log the web service request
766 add_to_log(SITEID, 'webservice', '', '' , $this->zend_class." ".getremoteaddr() , 0, $this->userid);
768 //send headers
769 $this->send_headers();
771 // execute and return response, this sends some headers too
772 $response = $this->zend_server->handle();
774 // session cleanup
775 $this->session_cleanup();
777 //finally send the result
778 echo $response;
779 die;
783 * Load virtual class needed for Zend api
784 * @return void
786 protected function init_service_class() {
787 global $USER, $DB;
789 // first ofall get a complete list of services user is allowed to access
791 if ($this->restricted_serviceid) {
792 $params = array('sid1'=>$this->restricted_serviceid, 'sid2'=>$this->restricted_serviceid);
793 $wscond1 = 'AND s.id = :sid1';
794 $wscond2 = 'AND s.id = :sid2';
795 } else {
796 $params = array();
797 $wscond1 = '';
798 $wscond2 = '';
801 // now make sure the function is listed in at least one service user is allowed to use
802 // allow access only if:
803 // 1/ entry in the external_services_users table if required
804 // 2/ validuntil not reached
805 // 3/ has capability if specified in service desc
806 // 4/ iprestriction
808 $sql = "SELECT s.*, NULL AS iprestriction
809 FROM {external_services} s
810 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0)
811 WHERE s.enabled = 1 $wscond1
813 UNION
815 SELECT s.*, su.iprestriction
816 FROM {external_services} s
817 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1)
818 JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)
819 WHERE s.enabled = 1 AND su.validuntil IS NULL OR su.validuntil < :now $wscond2";
821 $params = array_merge($params, array('userid'=>$USER->id, 'now'=>time()));
823 $serviceids = array();
824 $rs = $DB->get_recordset_sql($sql, $params);
826 // now make sure user may access at least one service
827 $remoteaddr = getremoteaddr();
828 $allowed = false;
829 foreach ($rs as $service) {
830 if (isset($serviceids[$service->id])) {
831 continue;
833 if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) {
834 continue; // cap required, sorry
836 if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) {
837 continue; // wrong request source ip, sorry
839 $serviceids[$service->id] = $service->id;
841 $rs->close();
843 // now get the list of all functions
844 $wsmanager = new webservice();
845 $functions = $wsmanager->get_external_functions($serviceids);
847 // now make the virtual WS class with all the fuctions for this particular user
848 $methods = '';
849 foreach ($functions as $function) {
850 $methods .= $this->get_virtual_method_code($function);
853 // let's use unique class name, there might be problem in unit tests
854 $classname = 'webservices_virtual_class_000000';
855 while(class_exists($classname)) {
856 $classname++;
859 $code = '
861 * Virtual class web services for user id '.$USER->id.' in context '.$this->restricted_context->id.'.
863 class '.$classname.' {
864 '.$methods.'
868 // load the virtual class definition into memory
869 eval($code);
870 $this->service_class = $classname;
874 * returns virtual method code
875 * @param object $function
876 * @return string PHP code
878 protected function get_virtual_method_code($function) {
879 global $CFG;
881 $function = external_function_info($function);
883 //arguments in function declaration line with defaults.
884 $paramanddefaults = array();
885 //arguments used as parameters for external lib call.
886 $params = array();
887 $params_desc = array();
888 foreach ($function->parameters_desc->keys as $name=>$keydesc) {
889 $param = '$'.$name;
890 $paramanddefault = $param;
891 //need to generate the default if there is any
892 if ($keydesc instanceof external_value) {
893 if ($keydesc->required == VALUE_DEFAULT) {
894 if ($keydesc->default===null) {
895 $paramanddefault .= '=null';
896 } else {
897 switch($keydesc->type) {
898 case PARAM_BOOL:
899 $paramanddefault .= '='.$keydesc->default; break;
900 case PARAM_INT:
901 $paramanddefault .= '='.$keydesc->default; break;
902 case PARAM_FLOAT;
903 $paramanddefault .= '='.$keydesc->default; break;
904 default:
905 $paramanddefault .= '=\''.$keydesc->default.'\'';
908 } else if ($keydesc->required == VALUE_OPTIONAL) {
909 //it does make sens to declare a parameter VALUE_OPTIONAL
910 //VALUE_OPTIONAL is used only for array/object key
911 throw new moodle_exception('parametercannotbevalueoptional');
913 } else { //for the moment we do not support default for other structure types
914 if ($keydesc->required == VALUE_DEFAULT) {
915 //accept empty array as default
916 if (isset($keydesc->default) and is_array($keydesc->default)
917 and empty($keydesc->default)) {
918 $paramanddefault .= '=array()';
919 } else {
920 throw new moodle_exception('errornotemptydefaultparamarray', 'webservice', '', $name);
923 if ($keydesc->required == VALUE_OPTIONAL) {
924 throw new moodle_exception('erroroptionalparamarray', 'webservice', '', $name);
927 $params[] = $param;
928 $paramanddefaults[] = $paramanddefault;
929 $type = 'string';
930 if ($keydesc instanceof external_value) {
931 switch($keydesc->type) {
932 case PARAM_BOOL: // 0 or 1 only for now
933 case PARAM_INT:
934 $type = 'int'; break;
935 case PARAM_FLOAT;
936 $type = 'double'; break;
937 default:
938 $type = 'string';
940 } else if ($keydesc instanceof external_single_structure) {
941 $type = 'object|struct';
942 } else if ($keydesc instanceof external_multiple_structure) {
943 $type = 'array';
945 $params_desc[] = ' * @param '.$type.' $'.$name.' '.$keydesc->desc;
947 $params = implode(', ', $params);
948 $paramanddefaults = implode(', ', $paramanddefaults);
949 $params_desc = implode("\n", $params_desc);
951 $serviceclassmethodbody = $this->service_class_method_body($function, $params);
953 if (is_null($function->returns_desc)) {
954 $return = ' * @return void';
955 } else {
956 $type = 'string';
957 if ($function->returns_desc instanceof external_value) {
958 switch($function->returns_desc->type) {
959 case PARAM_BOOL: // 0 or 1 only for now
960 case PARAM_INT:
961 $type = 'int'; break;
962 case PARAM_FLOAT;
963 $type = 'double'; break;
964 default:
965 $type = 'string';
967 } else if ($function->returns_desc instanceof external_single_structure) {
968 $type = 'object|struct'; //only 'object' is supported by SOAP, 'struct' by XML-RPC MDL-23083
969 } else if ($function->returns_desc instanceof external_multiple_structure) {
970 $type = 'array';
972 $return = ' * @return '.$type.' '.$function->returns_desc->desc;
975 // now crate the virtual method that calls the ext implementation
977 $code = '
979 * '.$function->description.'
981 '.$params_desc.'
982 '.$return.'
984 public function '.$function->name.'('.$paramanddefaults.') {
985 '.$serviceclassmethodbody.'
988 return $code;
992 * You can override this function in your child class to add extra code into the dynamically
993 * created service class. For example it is used in the amf server to cast types of parameters and to
994 * cast the return value to the types as specified in the return value description.
995 * @param stdClass $function
996 * @param array $params
997 * @return string body of the method for $function ie. everything within the {} of the method declaration.
999 protected function service_class_method_body($function, $params){
1000 //cast the param from object to array (validate_parameters except array only)
1001 $castingcode = '';
1002 if ($params){
1003 $paramstocast = explode(',', $params);
1004 foreach ($paramstocast as $paramtocast) {
1005 //clean the parameter from any white space
1006 $paramtocast = trim($paramtocast);
1007 $castingcode .= $paramtocast .
1008 '=webservice_zend_server::cast_objects_to_array('.$paramtocast.');';
1013 $descriptionmethod = $function->methodname.'_returns()';
1014 $callforreturnvaluedesc = $function->classname.'::'.$descriptionmethod;
1015 return $castingcode . ' if ('.$callforreturnvaluedesc.' == null) {'.
1016 $function->classname.'::'.$function->methodname.'('.$params.');
1017 return null;
1019 return external_api::clean_returnvalue('.$callforreturnvaluedesc.', '.$function->classname.'::'.$function->methodname.'('.$params.'));';
1023 * Recursive function to recurse down into a complex variable and convert all
1024 * objects to arrays.
1025 * @param mixed $param value to cast
1026 * @return mixed Cast value
1028 public static function cast_objects_to_array($param){
1029 if (is_object($param)){
1030 $param = (array)$param;
1032 if (is_array($param)){
1033 $toreturn = array();
1034 foreach ($param as $key=> $param){
1035 $toreturn[$key] = self::cast_objects_to_array($param);
1037 return $toreturn;
1038 } else {
1039 return $param;
1044 * Set up zend service class
1045 * @return void
1047 protected function init_zend_server() {
1048 $this->zend_server = new $this->zend_class();
1052 * This method parses the $_REQUEST superglobal and looks for
1053 * the following information:
1054 * 1/ user authentication - username+password or token (wsusername, wspassword and wstoken parameters)
1056 * @return void
1058 protected function parse_request() {
1059 if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
1060 //note: some clients have problems with entity encoding :-(
1061 if (isset($_REQUEST['wsusername'])) {
1062 $this->username = $_REQUEST['wsusername'];
1064 if (isset($_REQUEST['wspassword'])) {
1065 $this->password = $_REQUEST['wspassword'];
1067 } else {
1068 if (isset($_REQUEST['wstoken'])) {
1069 $this->token = $_REQUEST['wstoken'];
1075 * Internal implementation - sending of page headers.
1076 * @return void
1078 protected function send_headers() {
1079 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
1080 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1081 header('Pragma: no-cache');
1082 header('Accept-Ranges: none');
1086 * Specialised exception handler, we can not use the standard one because
1087 * it can not just print html to output.
1089 * @param exception $ex
1090 * @return void does not return
1092 public function exception_handler($ex) {
1093 // detect active db transactions, rollback and log as error
1094 abort_all_db_transactions();
1096 // some hacks might need a cleanup hook
1097 $this->session_cleanup($ex);
1099 // now let the plugin send the exception to client
1100 $this->send_error($ex);
1102 // not much else we can do now, add some logging later
1103 exit(1);
1107 * Send the error information to the WS client
1108 * formatted as XML document.
1109 * @param exception $ex
1110 * @return void
1112 protected function send_error($ex=null) {
1113 $this->send_headers();
1114 echo $this->zend_server->fault($ex);
1118 * Future hook needed for emulated sessions.
1119 * @param exception $exception null means normal termination, $exception received when WS call failed
1120 * @return void
1122 protected function session_cleanup($exception=null) {
1123 if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
1124 // nothing needs to be done, there is no persistent session
1125 } else {
1126 // close emulated session if used
1133 * Web Service server base class, this class handles both
1134 * simple and token authentication.
1135 * @author Petr Skoda (skodak)
1137 abstract class webservice_base_server extends webservice_server {
1139 /** @property array $parameters the function parameters - the real values submitted in the request */
1140 protected $parameters = null;
1142 /** @property string $functionname the name of the function that is executed */
1143 protected $functionname = null;
1145 /** @property object $function full function description */
1146 protected $function = null;
1148 /** @property mixed $returns function return value */
1149 protected $returns = null;
1152 * This method parses the request input, it needs to get:
1153 * 1/ user authentication - username+password or token
1154 * 2/ function name
1155 * 3/ function parameters
1157 * @return void
1159 abstract protected function parse_request();
1162 * Send the result of function call to the WS client.
1163 * @return void
1165 abstract protected function send_response();
1168 * Send the error information to the WS client.
1169 * @param exception $ex
1170 * @return void
1172 abstract protected function send_error($ex=null);
1175 * Process request from client.
1176 * @return void
1178 public function run() {
1179 // we will probably need a lot of memory in some functions
1180 raise_memory_limit(MEMORY_EXTRA);
1182 // set some longer timeout, this script is not sending any output,
1183 // this means we need to manually extend the timeout operations
1184 // that need longer time to finish
1185 external_api::set_timeout();
1187 // set up exception handler first, we want to sent them back in correct format that
1188 // the other system understands
1189 // we do not need to call the original default handler because this ws handler does everything
1190 set_exception_handler(array($this, 'exception_handler'));
1192 // init all properties from the request data
1193 $this->parse_request();
1195 // authenticate user, this has to be done after the request parsing
1196 // this also sets up $USER and $SESSION
1197 $this->authenticate_user();
1199 // find all needed function info and make sure user may actually execute the function
1200 $this->load_function_info();
1202 //log the web service request
1203 add_to_log(SITEID, 'webservice', $this->functionname, '' , getremoteaddr() , 0, $this->userid);
1205 // finally, execute the function - any errors are catched by the default exception handler
1206 $this->execute();
1208 // send the results back in correct format
1209 $this->send_response();
1211 // session cleanup
1212 $this->session_cleanup();
1214 die;
1218 * Specialised exception handler, we can not use the standard one because
1219 * it can not just print html to output.
1221 * @param exception $ex
1222 * @return void does not return
1224 public function exception_handler($ex) {
1225 // detect active db transactions, rollback and log as error
1226 abort_all_db_transactions();
1228 // some hacks might need a cleanup hook
1229 $this->session_cleanup($ex);
1231 // now let the plugin send the exception to client
1232 $this->send_error($ex);
1234 // not much else we can do now, add some logging later
1235 exit(1);
1239 * Future hook needed for emulated sessions.
1240 * @param exception $exception null means normal termination, $exception received when WS call failed
1241 * @return void
1243 protected function session_cleanup($exception=null) {
1244 if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
1245 // nothing needs to be done, there is no persistent session
1246 } else {
1247 // close emulated session if used
1252 * Fetches the function description from database,
1253 * verifies user is allowed to use this function and
1254 * loads all paremeters and return descriptions.
1255 * @return void
1257 protected function load_function_info() {
1258 global $DB, $USER, $CFG;
1260 if (empty($this->functionname)) {
1261 throw new invalid_parameter_exception('Missing function name');
1264 // function must exist
1265 $function = external_function_info($this->functionname);
1267 if ($this->restricted_serviceid) {
1268 $params = array('sid1'=>$this->restricted_serviceid, 'sid2'=>$this->restricted_serviceid);
1269 $wscond1 = 'AND s.id = :sid1';
1270 $wscond2 = 'AND s.id = :sid2';
1271 } else {
1272 $params = array();
1273 $wscond1 = '';
1274 $wscond2 = '';
1277 // now let's verify access control
1279 // now make sure the function is listed in at least one service user is allowed to use
1280 // allow access only if:
1281 // 1/ entry in the external_services_users table if required
1282 // 2/ validuntil not reached
1283 // 3/ has capability if specified in service desc
1284 // 4/ iprestriction
1286 $sql = "SELECT s.*, NULL AS iprestriction
1287 FROM {external_services} s
1288 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0 AND sf.functionname = :name1)
1289 WHERE s.enabled = 1 $wscond1
1291 UNION
1293 SELECT s.*, su.iprestriction
1294 FROM {external_services} s
1295 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1 AND sf.functionname = :name2)
1296 JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)
1297 WHERE s.enabled = 1 AND su.validuntil IS NULL OR su.validuntil < :now $wscond2";
1298 $params = array_merge($params, array('userid'=>$USER->id, 'name1'=>$function->name, 'name2'=>$function->name, 'now'=>time()));
1300 $rs = $DB->get_recordset_sql($sql, $params);
1301 // now make sure user may access at least one service
1302 $remoteaddr = getremoteaddr();
1303 $allowed = false;
1304 foreach ($rs as $service) {
1305 if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) {
1306 continue; // cap required, sorry
1308 if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) {
1309 continue; // wrong request source ip, sorry
1311 $allowed = true;
1312 break; // one service is enough, no need to continue
1314 $rs->close();
1315 if (!$allowed) {
1316 throw new webservice_access_exception('Access to external function not allowed');
1319 // we have all we need now
1320 $this->function = $function;
1324 * Execute previously loaded function using parameters parsed from the request data.
1325 * @return void
1327 protected function execute() {
1328 // validate params, this also sorts the params properly, we need the correct order in the next part
1329 $params = call_user_func(array($this->function->classname, 'validate_parameters'), $this->function->parameters_desc, $this->parameters);
1331 // execute - yay!
1332 $this->returns = call_user_func_array(array($this->function->classname, $this->function->methodname), array_values($params));