2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * Web services utility functions and classes
21 * @package core_webservice
22 * @copyright 2009 Jerome Mouneyrac <jerome@moodle.com>
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 require_once($CFG->libdir.'/externallib.php');
29 * WEBSERVICE_AUTHMETHOD_USERNAME - username/password authentication (also called simple authentication)
31 define('WEBSERVICE_AUTHMETHOD_USERNAME', 0);
34 * WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN - most common token authentication (external app, mobile app...)
36 define('WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN', 1);
39 * WEBSERVICE_AUTHMETHOD_SESSION_TOKEN - token for embedded application (requires Moodle session)
41 define('WEBSERVICE_AUTHMETHOD_SESSION_TOKEN', 2);
44 * General web service library
46 * @package core_webservice
47 * @copyright 2010 Jerome Mouneyrac <jerome@moodle.com>
48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
53 * Authenticate user (used by download/upload file scripts)
55 * @param string $token
56 * @return array - contains the authenticated user, token and service objects
58 public function authenticate_user($token) {
61 // web service must be enabled to use this script
62 if (!$CFG->enablewebservices) {
63 throw new webservice_access_exception('Web services are not enabled in Advanced features.');
66 // Obtain token record
67 if (!$token = $DB->get_record('external_tokens', array('token' => $token))) {
68 //client may want to display login form => moodle_exception
69 throw new moodle_exception('invalidtoken', 'webservice');
72 $loginfaileddefaultparams = array(
74 'method' => WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN,
76 'tokenid' => $token->id
80 // Validate token date
81 if ($token->validuntil and $token->validuntil < time()) {
82 $params = $loginfaileddefaultparams;
83 $params['other']['reason'] = 'token_expired';
84 $event = \core\event\webservice_login_failed::create($params);
85 $event->add_record_snapshot('external_tokens', $token);
86 $event->set_legacy_logdata(array(SITEID, 'webservice', get_string('tokenauthlog', 'webservice'), '',
87 get_string('invalidtimedtoken', 'webservice'), 0));
89 $DB->delete_records('external_tokens', array('token' => $token->token));
90 throw new webservice_access_exception('Invalid token - token expired - check validuntil time for the token');
94 if ($token->iprestriction and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
95 $params = $loginfaileddefaultparams;
96 $params['other']['reason'] = 'ip_restricted';
97 $event = \core\event\webservice_login_failed::create($params);
98 $event->add_record_snapshot('external_tokens', $token);
99 $event->set_legacy_logdata(array(SITEID, 'webservice', get_string('tokenauthlog', 'webservice'), '',
100 get_string('failedtolog', 'webservice') . ": " . getremoteaddr(), 0));
102 throw new webservice_access_exception('Invalid token - IP:' . getremoteaddr()
103 . ' is not supported');
106 //retrieve user link to the token
107 $user = $DB->get_record('user', array('id' => $token->userid, 'deleted' => 0), '*', MUST_EXIST);
109 // let enrol plugins deal with new enrolments if necessary
110 enrol_check_plugins($user);
112 // setup user session to check capability
113 session_set_user($user);
115 //assumes that if sid is set then there must be a valid associated session no matter the token type
117 $session = session_get_instance();
118 if (!$session->session_exists($token->sid)) {
119 $DB->delete_records('external_tokens', array('sid' => $token->sid));
120 throw new webservice_access_exception('Invalid session based token - session not found or expired');
124 //Non admin can not authenticate if maintenance mode
125 $hassiteconfig = has_capability('moodle/site:config', context_system::instance(), $user);
126 if (!empty($CFG->maintenance_enabled) and !$hassiteconfig) {
127 //this is usually temporary, client want to implement code logic => moodle_exception
128 throw new moodle_exception('sitemaintenance', 'admin');
131 //retrieve web service record
132 $service = $DB->get_record('external_services', array('id' => $token->externalserviceid, 'enabled' => 1));
133 if (empty($service)) {
134 // will throw exception if no token found
135 throw new webservice_access_exception('Web service is not available (it doesn\'t exist or might be disabled)');
138 //check if there is any required system capability
139 if ($service->requiredcapability and !has_capability($service->requiredcapability, context_system::instance(), $user)) {
140 throw new webservice_access_exception('The capability ' . $service->requiredcapability . ' is required.');
143 //specific checks related to user restricted service
144 if ($service->restrictedusers) {
145 $authoriseduser = $DB->get_record('external_services_users', array('externalserviceid' => $service->id, 'userid' => $user->id));
147 if (empty($authoriseduser)) {
148 throw new webservice_access_exception(
149 'The user is not allowed for this service. First you need to allow this user on the '
150 . $service->name . '\'s allowed users administration page.');
153 if (!empty($authoriseduser->validuntil) and $authoriseduser->validuntil < time()) {
154 throw new webservice_access_exception('Invalid service - service expired - check validuntil time for this allowed user');
157 if (!empty($authoriseduser->iprestriction) and !address_in_subnet(getremoteaddr(), $authoriseduser->iprestriction)) {
158 throw new webservice_access_exception('Invalid service - IP:' . getremoteaddr()
159 . ' is not supported - check this allowed user');
163 //only confirmed user should be able to call web service
164 if (empty($user->confirmed)) {
165 $params = $loginfaileddefaultparams;
166 $params['other']['reason'] = 'user_unconfirmed';
167 $event = \core\event\webservice_login_failed::create($params);
168 $event->add_record_snapshot('external_tokens', $token);
169 $event->set_legacy_logdata(array(SITEID, 'webservice', 'user unconfirmed', '', $user->username));
171 throw new moodle_exception('usernotconfirmed', 'moodle', '', $user->username);
174 //check the user is suspended
175 if (!empty($user->suspended)) {
176 $params = $loginfaileddefaultparams;
177 $params['other']['reason'] = 'user_suspended';
178 $event = \core\event\webservice_login_failed::create($params);
179 $event->add_record_snapshot('external_tokens', $token);
180 $event->set_legacy_logdata(array(SITEID, 'webservice', 'user suspended', '', $user->username));
182 throw new webservice_access_exception('Refused web service access for suspended username: ' . $user->username);
185 //check if the auth method is nologin (in this case refuse connection)
186 if ($user->auth == 'nologin') {
187 $params = $loginfaileddefaultparams;
188 $params['other']['reason'] = 'nologin';
189 $event = \core\event\webservice_login_failed::create($params);
190 $event->add_record_snapshot('external_tokens', $token);
191 $event->set_legacy_logdata(array(SITEID, 'webservice', 'nologin auth attempt with web service', '', $user->username));
193 throw new webservice_access_exception('Refused web service access for nologin authentication username: ' . $user->username);
196 //Check if the user password is expired
197 $auth = get_auth_plugin($user->auth);
198 if (!empty($auth->config->expiration) and $auth->config->expiration == 1) {
199 $days2expire = $auth->password_expire($user->username);
200 if (intval($days2expire) < 0) {
201 $params = $loginfaileddefaultparams;
202 $params['other']['reason'] = 'password_expired';
203 $event = \core\event\webservice_login_failed::create($params);
204 $event->add_record_snapshot('external_tokens', $token);
205 $event->set_legacy_logdata(array(SITEID, 'webservice', 'expired password', '', $user->username));
207 throw new moodle_exception('passwordisexpired', 'webservice');
212 $DB->set_field('external_tokens', 'lastaccess', time(), array('id' => $token->id));
214 return array('user' => $user, 'token' => $token, 'service' => $service);
218 * Allow user to call a service
220 * @param stdClass $user a user
222 public function add_ws_authorised_user($user) {
224 $user->timecreated = time();
225 $DB->insert_record('external_services_users', $user);
229 * Disallow a user to call a service
231 * @param stdClass $user a user
232 * @param int $serviceid
234 public function remove_ws_authorised_user($user, $serviceid) {
236 $DB->delete_records('external_services_users',
237 array('externalserviceid' => $serviceid, 'userid' => $user->id));
241 * Update allowed user settings (ip restriction, valid until...)
243 * @param stdClass $user
245 public function update_ws_authorised_user($user) {
247 $DB->update_record('external_services_users', $user);
251 * Return list of allowed users with their options (ip/timecreated / validuntil...)
252 * for a given service
254 * @param int $serviceid the service id to search against
255 * @return array $users
257 public function get_ws_authorised_users($serviceid) {
259 $params = array($CFG->siteguest, $serviceid);
260 $sql = " SELECT u.id as id, esu.id as serviceuserid, u.email as email, u.firstname as firstname,
261 u.lastname as lastname,
262 esu.iprestriction as iprestriction, esu.validuntil as validuntil,
263 esu.timecreated as timecreated
264 FROM {user} u, {external_services_users} esu
265 WHERE u.id <> ? AND u.deleted = 0 AND u.confirmed = 1
266 AND esu.userid = u.id
267 AND esu.externalserviceid = ?";
269 $users = $DB->get_records_sql($sql, $params);
274 * Return an authorised user with their options (ip/timecreated / validuntil...)
276 * @param int $serviceid the service id to search against
277 * @param int $userid the user to search against
280 public function get_ws_authorised_user($serviceid, $userid) {
282 $params = array($CFG->siteguest, $serviceid, $userid);
283 $sql = " SELECT u.id as id, esu.id as serviceuserid, u.email as email, u.firstname as firstname,
284 u.lastname as lastname,
285 esu.iprestriction as iprestriction, esu.validuntil as validuntil,
286 esu.timecreated as timecreated
287 FROM {user} u, {external_services_users} esu
288 WHERE u.id <> ? AND u.deleted = 0 AND u.confirmed = 1
289 AND esu.userid = u.id
290 AND esu.externalserviceid = ?
292 $user = $DB->get_record_sql($sql, $params);
297 * Generate all tokens of a specific user
299 * @param int $userid user id
301 public function generate_user_ws_tokens($userid) {
304 // generate a token for non admin if web service are enable and the user has the capability to create a token
305 if (!is_siteadmin() && has_capability('moodle/webservice:createtoken', context_system::instance(), $userid) && !empty($CFG->enablewebservices)) {
306 // for every service than the user is authorised on, create a token (if it doesn't already exist)
308 // get all services which are set to all user (no restricted to specific users)
309 $norestrictedservices = $DB->get_records('external_services', array('restrictedusers' => 0));
310 $serviceidlist = array();
311 foreach ($norestrictedservices as $service) {
312 $serviceidlist[] = $service->id;
315 // get all services which are set to the current user (the current user is specified in the restricted user list)
316 $servicesusers = $DB->get_records('external_services_users', array('userid' => $userid));
317 foreach ($servicesusers as $serviceuser) {
318 if (!in_array($serviceuser->externalserviceid,$serviceidlist)) {
319 $serviceidlist[] = $serviceuser->externalserviceid;
323 // get all services which already have a token set for the current user
324 $usertokens = $DB->get_records('external_tokens', array('userid' => $userid, 'tokentype' => EXTERNAL_TOKEN_PERMANENT));
325 $tokenizedservice = array();
326 foreach ($usertokens as $token) {
327 $tokenizedservice[] = $token->externalserviceid;
330 // create a token for the service which have no token already
331 foreach ($serviceidlist as $serviceid) {
332 if (!in_array($serviceid, $tokenizedservice)) {
333 // create the token for this service
334 $newtoken = new stdClass();
335 $newtoken->token = md5(uniqid(rand(),1));
336 // check that the user has capability on this service
337 $newtoken->tokentype = EXTERNAL_TOKEN_PERMANENT;
338 $newtoken->userid = $userid;
339 $newtoken->externalserviceid = $serviceid;
340 // TODO MDL-31190 find a way to get the context - UPDATE FOLLOWING LINE
341 $newtoken->contextid = context_system::instance()->id;
342 $newtoken->creatorid = $userid;
343 $newtoken->timecreated = time();
345 $DB->insert_record('external_tokens', $newtoken);
354 * Return all tokens of a specific user
355 * + the service state (enabled/disabled)
356 * + the authorised user mode (restricted/not restricted)
358 * @param int $userid user id
361 public function get_user_ws_tokens($userid) {
363 //here retrieve token list (including linked users firstname/lastname and linked services name)
365 t.id, t.creatorid, t.token, u.firstname, u.lastname, s.id as wsid, s.name, s.enabled, s.restrictedusers, t.validuntil
367 {external_tokens} t, {user} u, {external_services} s
369 t.userid=? AND t.tokentype = ".EXTERNAL_TOKEN_PERMANENT." AND s.id = t.externalserviceid AND t.userid = u.id";
370 $tokens = $DB->get_records_sql($sql, array( $userid));
375 * Return a token that has been created by the user (i.e. to created by an admin)
376 * If no tokens exist an exception is thrown
378 * The returned value is a stdClass:
381 * ->firstname user firstname
383 * ->name service name
385 * @param int $userid user id
386 * @param int $tokenid token id
389 public function get_created_by_user_ws_token($userid, $tokenid) {
392 t.id, t.token, u.firstname, u.lastname, s.name
394 {external_tokens} t, {user} u, {external_services} s
396 t.creatorid=? AND t.id=? AND t.tokentype = "
397 . EXTERNAL_TOKEN_PERMANENT
398 . " AND s.id = t.externalserviceid AND t.userid = u.id";
399 //must be the token creator
400 $token = $DB->get_record_sql($sql, array($userid, $tokenid), MUST_EXIST);
405 * Return a database token record for a token id
407 * @param int $tokenid token id
408 * @return object token
410 public function get_token_by_id($tokenid) {
412 return $DB->get_record('external_tokens', array('id' => $tokenid));
418 * @param int $tokenid token id
420 public function delete_user_ws_token($tokenid) {
422 $DB->delete_records('external_tokens', array('id'=>$tokenid));
427 * Also delete function references and authorised user references.
429 * @param int $serviceid service id
431 public function delete_service($serviceid) {
433 $DB->delete_records('external_services_users', array('externalserviceid' => $serviceid));
434 $DB->delete_records('external_services_functions', array('externalserviceid' => $serviceid));
435 $DB->delete_records('external_tokens', array('externalserviceid' => $serviceid));
436 $DB->delete_records('external_services', array('id' => $serviceid));
440 * Get a full database token record for a given token value
442 * @param string $token
443 * @throws moodle_exception if there is multiple result
445 public function get_user_ws_token($token) {
447 return $DB->get_record('external_tokens', array('token'=>$token), '*', MUST_EXIST);
451 * Get the functions list of a service list (by id)
453 * @param array $serviceids service ids
454 * @return array of functions
456 public function get_external_functions($serviceids) {
458 if (!empty($serviceids)) {
459 list($serviceids, $params) = $DB->get_in_or_equal($serviceids);
461 FROM {external_functions} f
462 WHERE f.name IN (SELECT sf.functionname
463 FROM {external_services_functions} sf
464 WHERE sf.externalserviceid $serviceids)";
465 $functions = $DB->get_records_sql($sql, $params);
467 $functions = array();
473 * Get the functions of a service list (by shortname). It can return only enabled functions if required.
475 * @param array $serviceshortnames service shortnames
476 * @param bool $enabledonly if true then only return functions for services that have been enabled
477 * @return array functions
479 public function get_external_functions_by_enabled_services($serviceshortnames, $enabledonly = true) {
481 if (!empty($serviceshortnames)) {
482 $enabledonlysql = $enabledonly?' AND s.enabled = 1 ':'';
483 list($serviceshortnames, $params) = $DB->get_in_or_equal($serviceshortnames);
485 FROM {external_functions} f
486 WHERE f.name IN (SELECT sf.functionname
487 FROM {external_services_functions} sf, {external_services} s
488 WHERE s.shortname $serviceshortnames
489 AND sf.externalserviceid = s.id
490 " . $enabledonlysql . ")";
491 $functions = $DB->get_records_sql($sql, $params);
493 $functions = array();
499 * Get functions not included in a service
501 * @param int $serviceid service id
502 * @return array functions
504 public function get_not_associated_external_functions($serviceid) {
506 $select = "name NOT IN (SELECT s.functionname
507 FROM {external_services_functions} s
508 WHERE s.externalserviceid = :sid
511 $functions = $DB->get_records_select('external_functions',
512 $select, array('sid' => $serviceid), 'name');
518 * Get list of required capabilities of a service, sorted by functions
519 * Example of returned value:
522 * [moodle_group_create_groups] => Array
524 * [0] => moodle/course:managegroups
527 * [moodle_enrol_get_enrolled_users] => Array
529 * [0] => moodle/site:viewparticipants
530 * [1] => moodle/course:viewparticipants
531 * [2] => moodle/role:review
532 * [3] => moodle/site:accessallgroups
533 * [4] => moodle/course:enrolreview
537 * @param int $serviceid service id
540 public function get_service_required_capabilities($serviceid) {
541 $functions = $this->get_external_functions(array($serviceid));
542 $requiredusercaps = array();
543 foreach ($functions as $function) {
544 $functioncaps = explode(',', $function->capabilities);
545 if (!empty($functioncaps) and !empty($functioncaps[0])) {
546 foreach ($functioncaps as $functioncap) {
547 $requiredusercaps[$function->name][] = trim($functioncap);
551 return $requiredusercaps;
555 * Get user capabilities (with context)
556 * Only useful for documentation purpose
557 * WARNING: do not use this "broken" function. It was created in the goal to display some capabilities
558 * required by users. In theory we should not need to display this kind of information
559 * as the front end does not display it itself. In pratice,
560 * admins would like the info, for more info you can follow: MDL-29962
562 * @param int $userid user id
565 public function get_user_capabilities($userid) {
567 //retrieve the user capabilities
568 $sql = "SELECT DISTINCT rc.id, rc.capability FROM {role_capabilities} rc, {role_assignments} ra
569 WHERE rc.roleid=ra.roleid AND ra.userid= ? AND rc.permission = ?";
570 $dbusercaps = $DB->get_records_sql($sql, array($userid, CAP_ALLOW));
572 foreach ($dbusercaps as $usercap) {
573 $usercaps[$usercap->capability] = true;
579 * Get missing user capabilities for a given service
580 * WARNING: do not use this "broken" function. It was created in the goal to display some capabilities
581 * required by users. In theory we should not need to display this kind of information
582 * as the front end does not display it itself. In pratice,
583 * admins would like the info, for more info you can follow: MDL-29962
585 * @param array $users users
586 * @param int $serviceid service id
587 * @return array of missing capabilities, keys being the user ids
589 public function get_missing_capabilities_by_users($users, $serviceid) {
591 $usersmissingcaps = array();
593 //retrieve capabilities required by the service
594 $servicecaps = $this->get_service_required_capabilities($serviceid);
596 //retrieve users missing capabilities
597 foreach ($users as $user) {
598 //cast user array into object to be a bit more flexible
599 if (is_array($user)) {
600 $user = (object) $user;
602 $usercaps = $this->get_user_capabilities($user->id);
604 //detect the missing capabilities
605 foreach ($servicecaps as $functioname => $functioncaps) {
606 foreach ($functioncaps as $functioncap) {
607 if (!array_key_exists($functioncap, $usercaps)) {
608 if (!isset($usersmissingcaps[$user->id])
609 or array_search($functioncap, $usersmissingcaps[$user->id]) === false) {
610 $usersmissingcaps[$user->id][] = $functioncap;
617 return $usersmissingcaps;
621 * Get an external service for a given service id
623 * @param int $serviceid service id
624 * @param int $strictness IGNORE_MISSING, MUST_EXIST...
625 * @return stdClass external service
627 public function get_external_service_by_id($serviceid, $strictness=IGNORE_MISSING) {
629 $service = $DB->get_record('external_services',
630 array('id' => $serviceid), '*', $strictness);
635 * Get an external service for a given shortname
637 * @param string $shortname service shortname
638 * @param int $strictness IGNORE_MISSING, MUST_EXIST...
639 * @return stdClass external service
641 public function get_external_service_by_shortname($shortname, $strictness=IGNORE_MISSING) {
643 $service = $DB->get_record('external_services',
644 array('shortname' => $shortname), '*', $strictness);
649 * Get an external function for a given function id
651 * @param int $functionid function id
652 * @param int $strictness IGNORE_MISSING, MUST_EXIST...
653 * @return stdClass external function
655 public function get_external_function_by_id($functionid, $strictness=IGNORE_MISSING) {
657 $function = $DB->get_record('external_functions',
658 array('id' => $functionid), '*', $strictness);
663 * Add a function to a service
665 * @param string $functionname function name
666 * @param int $serviceid service id
668 public function add_external_function_to_service($functionname, $serviceid) {
670 $addedfunction = new stdClass();
671 $addedfunction->externalserviceid = $serviceid;
672 $addedfunction->functionname = $functionname;
673 $DB->insert_record('external_services_functions', $addedfunction);
678 * It generates the timecreated field automatically.
680 * @param stdClass $service
681 * @return serviceid integer
683 public function add_external_service($service) {
685 $service->timecreated = time();
686 $serviceid = $DB->insert_record('external_services', $service);
692 * It modifies the timemodified automatically.
694 * @param stdClass $service
696 public function update_external_service($service) {
698 $service->timemodified = time();
699 $DB->update_record('external_services', $service);
703 * Test whether an external function is already linked to a service
705 * @param string $functionname function name
706 * @param int $serviceid service id
707 * @return bool true if a matching function exists for the service, else false.
708 * @throws dml_exception if error
710 public function service_function_exists($functionname, $serviceid) {
712 return $DB->record_exists('external_services_functions',
713 array('externalserviceid' => $serviceid,
714 'functionname' => $functionname));
718 * Remove a function from a service
720 * @param string $functionname function name
721 * @param int $serviceid service id
723 public function remove_external_function_from_service($functionname, $serviceid) {
725 $DB->delete_records('external_services_functions',
726 array('externalserviceid' => $serviceid, 'functionname' => $functionname));
734 * Exception indicating access control problem in web service call
735 * This exception should return general errors about web service setup.
736 * Errors related to the user like wrong username/password should not use it,
737 * you should not use this exception if you want to let the client implement
738 * some code logic against an access error.
740 * @package core_webservice
741 * @copyright 2009 Petr Skodak
742 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
744 class webservice_access_exception extends moodle_exception {
749 * @param string $debuginfo the debug info
751 function __construct($debuginfo) {
752 parent::__construct('accessexception', 'webservice', '', null, $debuginfo);
757 * Check if a protocol is enabled
759 * @param string $protocol name of WS protocol ('rest', 'soap', 'xmlrpc', 'amf'...)
760 * @return bool true if the protocol is enabled
762 function webservice_protocol_is_enabled($protocol) {
765 if (empty($CFG->enablewebservices)) {
769 $active = explode(',', $CFG->webserviceprotocols);
771 return(in_array($protocol, $active));
775 * Mandatory interface for all test client classes.
777 * @package core_webservice
778 * @copyright 2009 Petr Skodak
779 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
781 interface webservice_test_client_interface {
784 * Execute test client WS request
786 * @param string $serverurl server url (including the token param)
787 * @param string $function web service function name
788 * @param array $params parameters of the web service function
791 public function simpletest($serverurl, $function, $params);
795 * Mandatory interface for all web service protocol classes
797 * @package core_webservice
798 * @copyright 2009 Petr Skodak
799 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
801 interface webservice_server_interface {
804 * Process request from client.
806 public function run();
810 * Abstract web service base class.
812 * @package core_webservice
813 * @copyright 2009 Petr Skodak
814 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
816 abstract class webservice_server implements webservice_server_interface {
818 /** @var string Name of the web server plugin */
819 protected $wsname = null;
821 /** @var string Name of local user */
822 protected $username = null;
824 /** @var string Password of the local user */
825 protected $password = null;
827 /** @var int The local user */
828 protected $userid = null;
830 /** @var integer Authentication method one of WEBSERVICE_AUTHMETHOD_* */
831 protected $authmethod;
833 /** @var string Authentication token*/
834 protected $token = null;
836 /** @var stdClass Restricted context */
837 protected $restricted_context;
839 /** @var int Restrict call to one service id*/
840 protected $restricted_serviceid = null;
845 * @param integer $authmethod authentication method one of WEBSERVICE_AUTHMETHOD_*
847 public function __construct($authmethod) {
848 $this->authmethod = $authmethod;
853 * Authenticate user using username+password or token.
854 * This function sets up $USER global.
855 * It is safe to use has_capability() after this.
856 * This method also verifies user is allowed to use this
859 protected function authenticate_user() {
862 if (!NO_MOODLE_COOKIES) {
863 throw new coding_exception('Cookies must be disabled in WS servers!');
866 $loginfaileddefaultparams = array(
867 'context' => context_system::instance(),
869 'method' => $this->authmethod,
871 'token' => $this->token
875 if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
877 //we check that authentication plugin is enabled
878 //it is only required by simple authentication
879 if (!is_enabled_auth('webservice')) {
880 throw new webservice_access_exception('The web service authentication plugin is disabled.');
883 if (!$auth = get_auth_plugin('webservice')) {
884 throw new webservice_access_exception('The web service authentication plugin is missing.');
887 $this->restricted_context = context_system::instance();
889 if (!$this->username) {
890 throw new moodle_exception('missingusername', 'webservice');
893 if (!$this->password) {
894 throw new moodle_exception('missingpassword', 'webservice');
897 if (!$auth->user_login_webservice($this->username, $this->password)) {
899 // Log failed login attempts.
900 $params = $loginfaileddefaultparams;
901 $params['other']['reason'] = 'password';
902 $params['other']['username'] = $this->username;
903 $event = \core\event\webservice_login_failed::create($params);
904 $event->set_legacy_logdata(array(SITEID, 'webservice', get_string('simpleauthlog', 'webservice'), '' ,
905 get_string('failedtolog', 'webservice').": ".$this->username."/".$this->password." - ".getremoteaddr() , 0));
908 throw new moodle_exception('wrongusernamepassword', 'webservice');
911 $user = $DB->get_record('user', array('username'=>$this->username, 'mnethostid'=>$CFG->mnet_localhost_id), '*', MUST_EXIST);
913 } else if ($this->authmethod == WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN){
914 $user = $this->authenticate_by_token(EXTERNAL_TOKEN_PERMANENT);
916 $user = $this->authenticate_by_token(EXTERNAL_TOKEN_EMBEDDED);
919 //Non admin can not authenticate if maintenance mode
920 $hassiteconfig = has_capability('moodle/site:config', context_system::instance(), $user);
921 if (!empty($CFG->maintenance_enabled) and !$hassiteconfig) {
922 throw new moodle_exception('sitemaintenance', 'admin');
925 //only confirmed user should be able to call web service
926 if (!empty($user->deleted)) {
927 $params = $loginfaileddefaultparams;
928 $params['other']['reason'] = 'user_deleted';
929 $params['other']['username'] = $user->username;
930 $event = \core\event\webservice_login_failed::create($params);
931 $event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessuserdeleted', 'webservice',
932 $user->username) . " - ".getremoteaddr(), 0, $user->id));
934 throw new webservice_access_exception('Refused web service access for deleted username: ' . $user->username);
937 //only confirmed user should be able to call web service
938 if (empty($user->confirmed)) {
939 $params = $loginfaileddefaultparams;
940 $params['other']['reason'] = 'user_unconfirmed';
941 $params['other']['username'] = $user->username;
942 $event = \core\event\webservice_login_failed::create($params);
943 $event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessuserunconfirmed', 'webservice',
944 $user->username) . " - ".getremoteaddr(), 0, $user->id));
946 throw new moodle_exception('wsaccessuserunconfirmed', 'webservice', '', $user->username);
949 //check the user is suspended
950 if (!empty($user->suspended)) {
951 $params = $loginfaileddefaultparams;
952 $params['other']['reason'] = 'user_unconfirmed';
953 $params['other']['username'] = $user->username;
954 $event = \core\event\webservice_login_failed::create($params);
955 $event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessusersuspended', 'webservice',
956 $user->username) . " - ".getremoteaddr(), 0, $user->id));
958 throw new webservice_access_exception('Refused web service access for suspended username: ' . $user->username);
961 //retrieve the authentication plugin if no previously done
963 $auth = get_auth_plugin($user->auth);
966 // check if credentials have expired
967 if (!empty($auth->config->expiration) and $auth->config->expiration == 1) {
968 $days2expire = $auth->password_expire($user->username);
969 if (intval($days2expire) < 0 ) {
970 $params = $loginfaileddefaultparams;
971 $params['other']['reason'] = 'password_expired';
972 $params['other']['username'] = $user->username;
973 $event = \core\event\webservice_login_failed::create($params);
974 $event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessuserexpired', 'webservice',
975 $user->username) . " - ".getremoteaddr(), 0, $user->id));
977 throw new webservice_access_exception('Refused web service access for password expired username: ' . $user->username);
981 //check if the auth method is nologin (in this case refuse connection)
982 if ($user->auth=='nologin') {
983 $params = $loginfaileddefaultparams;
984 $params['other']['reason'] = 'login';
985 $params['other']['username'] = $user->username;
986 $event = \core\event\webservice_login_failed::create($params);
987 $event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessusernologin', 'webservice',
988 $user->username) . " - ".getremoteaddr(), 0, $user->id));
990 throw new webservice_access_exception('Refused web service access for nologin authentication username: ' . $user->username);
993 // now fake user login, the session is completely empty too
994 enrol_check_plugins($user);
995 session_set_user($user);
996 $this->userid = $user->id;
998 if ($this->authmethod != WEBSERVICE_AUTHMETHOD_SESSION_TOKEN && !has_capability("webservice/$this->wsname:use", $this->restricted_context)) {
999 throw new webservice_access_exception('You are not allowed to use the {$a} protocol (missing capability: webservice/' . $this->wsname . ':use)');
1002 external_api::set_context_restriction($this->restricted_context);
1006 * User authentication by token
1008 * @param string $tokentype token type (EXTERNAL_TOKEN_EMBEDDED or EXTERNAL_TOKEN_PERMANENT)
1009 * @return stdClass the authenticated user
1010 * @throws webservice_access_exception
1012 protected function authenticate_by_token($tokentype){
1015 $loginfaileddefaultparams = array(
1016 'context' => context_system::instance(),
1018 'method' => $this->authmethod,
1020 'token' => $this->token
1024 if (!$token = $DB->get_record('external_tokens', array('token'=>$this->token, 'tokentype'=>$tokentype))) {
1025 // Log failed login attempts.
1026 $params = $loginfaileddefaultparams;
1027 $params['other']['reason'] = 'invalid_token';
1028 $event = \core\event\webservice_login_failed::create($params);
1029 $event->set_legacy_logdata(array(SITEID, 'webservice', get_string('tokenauthlog', 'webservice'), '' ,
1030 get_string('failedtolog', 'webservice').": ".$this->token. " - ".getremoteaddr() , 0));
1032 throw new moodle_exception('invalidtoken', 'webservice');
1035 if ($token->validuntil and $token->validuntil < time()) {
1036 $DB->delete_records('external_tokens', array('token'=>$this->token, 'tokentype'=>$tokentype));
1037 throw new webservice_access_exception('Invalid token - token expired - check validuntil time for the token');
1040 if ($token->sid){//assumes that if sid is set then there must be a valid associated session no matter the token type
1041 $session = session_get_instance();
1042 if (!$session->session_exists($token->sid)){
1043 $DB->delete_records('external_tokens', array('sid'=>$token->sid));
1044 throw new webservice_access_exception('Invalid session based token - session not found or expired');
1048 if ($token->iprestriction and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
1049 $params = $loginfaileddefaultparams;
1050 $params['other']['reason'] = 'ip_restricted';
1051 $params['other']['tokenid'] = $token->id;
1052 $event = \core\event\webservice_login_failed::create($params);
1053 $event->add_record_snapshot('external_tokens', $token);
1054 $event->set_legacy_logdata(array(SITEID, 'webservice', get_string('tokenauthlog', 'webservice'), '' ,
1055 get_string('failedtolog', 'webservice').": ".getremoteaddr() , 0));
1057 throw new webservice_access_exception('Invalid service - IP:' . getremoteaddr()
1058 . ' is not supported - check this allowed user');
1061 $this->restricted_context = context::instance_by_id($token->contextid);
1062 $this->restricted_serviceid = $token->externalserviceid;
1064 $user = $DB->get_record('user', array('id'=>$token->userid), '*', MUST_EXIST);
1067 $DB->set_field('external_tokens', 'lastaccess', time(), array('id'=>$token->id));
1074 * Intercept some moodlewssettingXXX $_GET and $_POST parameter
1075 * that are related to the web service call and are not the function parameters
1077 protected function set_web_service_call_settings() {
1080 // Default web service settings.
1081 // Must be the same XXX key name as the external_settings::set_XXX function.
1082 // Must be the same XXX ws parameter name as 'moodlewssettingXXX'.
1083 $externalsettings = array(
1088 // Load the external settings with the web service settings.
1089 $settings = external_settings::get_instance();
1090 foreach ($externalsettings as $name => $default) {
1092 $wsparamname = 'moodlewssetting' . $name;
1094 // Retrieve and remove the setting parameter from the request.
1095 $value = optional_param($wsparamname, $default, PARAM_BOOL);
1096 unset($_GET[$wsparamname]);
1097 unset($_POST[$wsparamname]);
1099 $functioname = 'set_' . $name;
1100 $settings->$functioname($value);
1107 * Special abstraction of our services that allows interaction with stock Zend ws servers.
1109 * @package core_webservice
1110 * @copyright 2009 Jerome Mouneyrac <jerome@moodle.com>
1111 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1113 abstract class webservice_zend_server extends webservice_server {
1115 /** @var string Name of the zend server class : Zend_Amf_Server, moodle_zend_soap_server, Zend_Soap_AutoDiscover, ...*/
1116 protected $zend_class;
1118 /** @var stdClass Zend server instance */
1119 protected $zend_server;
1121 /** @var string Virtual web service class with all functions user name execute, created on the fly */
1122 protected $service_class;
1127 * @param int $authmethod authentication method - one of WEBSERVICE_AUTHMETHOD_*
1128 * @param string $zend_class Name of the zend server class
1130 public function __construct($authmethod, $zend_class) {
1131 parent::__construct($authmethod);
1132 $this->zend_class = $zend_class;
1136 * Process request from client.
1140 public function run() {
1141 // we will probably need a lot of memory in some functions
1142 raise_memory_limit(MEMORY_EXTRA);
1144 // set some longer timeout, this script is not sending any output,
1145 // this means we need to manually extend the timeout operations
1146 // that need longer time to finish
1147 external_api::set_timeout();
1149 // now create the instance of zend server
1150 $this->init_zend_server();
1152 // set up exception handler first, we want to sent them back in correct format that
1153 // the other system understands
1154 // we do not need to call the original default handler because this ws handler does everything
1155 set_exception_handler(array($this, 'exception_handler'));
1157 // init all properties from the request data
1158 $this->parse_request();
1160 // this sets up $USER and $SESSION and context restrictions
1161 $this->authenticate_user();
1163 // make a list of all functions user is allowed to excecute
1164 $this->init_service_class();
1166 // tell server what functions are available
1167 $this->zend_server->setClass($this->service_class);
1169 // Log the web service request.
1172 'function' => 'unknown'
1175 $event = \core\event\webservice_function_called::create($params);
1176 $event->set_legacy_logdata(array(SITEID, 'webservice', '', '', $this->zend_class.' '.getremoteaddr(), 0, $this->userid));
1180 $this->send_headers();
1182 // execute and return response, this sends some headers too
1183 $response = $this->zend_server->handle();
1186 $this->session_cleanup();
1188 //finally send the result
1194 * Load virtual class needed for Zend api
1196 protected function init_service_class() {
1199 // first ofall get a complete list of services user is allowed to access
1201 if ($this->restricted_serviceid) {
1202 $params = array('sid1'=>$this->restricted_serviceid, 'sid2'=>$this->restricted_serviceid);
1203 $wscond1 = 'AND s.id = :sid1';
1204 $wscond2 = 'AND s.id = :sid2';
1211 // now make sure the function is listed in at least one service user is allowed to use
1212 // allow access only if:
1213 // 1/ entry in the external_services_users table if required
1214 // 2/ validuntil not reached
1215 // 3/ has capability if specified in service desc
1218 $sql = "SELECT s.*, NULL AS iprestriction
1219 FROM {external_services} s
1220 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0)
1221 WHERE s.enabled = 1 $wscond1
1225 SELECT s.*, su.iprestriction
1226 FROM {external_services} s
1227 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1)
1228 JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)
1229 WHERE s.enabled = 1 AND (su.validuntil IS NULL OR su.validuntil < :now) $wscond2";
1231 $params = array_merge($params, array('userid'=>$USER->id, 'now'=>time()));
1233 $serviceids = array();
1234 $rs = $DB->get_recordset_sql($sql, $params);
1236 // now make sure user may access at least one service
1237 $remoteaddr = getremoteaddr();
1239 foreach ($rs as $service) {
1240 if (isset($serviceids[$service->id])) {
1243 if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) {
1244 continue; // cap required, sorry
1246 if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) {
1247 continue; // wrong request source ip, sorry
1249 $serviceids[$service->id] = $service->id;
1253 // now get the list of all functions
1254 $wsmanager = new webservice();
1255 $functions = $wsmanager->get_external_functions($serviceids);
1257 // now make the virtual WS class with all the fuctions for this particular user
1259 foreach ($functions as $function) {
1260 $methods .= $this->get_virtual_method_code($function);
1263 // let's use unique class name, there might be problem in unit tests
1264 $classname = 'webservices_virtual_class_000000';
1265 while(class_exists($classname)) {
1271 * Virtual class web services for user id '.$USER->id.' in context '.$this->restricted_context->id.'.
1273 class '.$classname.' {
1278 // load the virtual class definition into memory
1280 $this->service_class = $classname;
1284 * returns virtual method code
1286 * @param stdClass $function a record from external_function
1287 * @return string PHP code
1289 protected function get_virtual_method_code($function) {
1292 $function = external_function_info($function);
1294 //arguments in function declaration line with defaults.
1295 $paramanddefaults = array();
1296 //arguments used as parameters for external lib call.
1298 $params_desc = array();
1299 foreach ($function->parameters_desc->keys as $name=>$keydesc) {
1301 $paramanddefault = $param;
1302 //need to generate the default if there is any
1303 if ($keydesc instanceof external_value) {
1304 if ($keydesc->required == VALUE_DEFAULT) {
1305 if ($keydesc->default===null) {
1306 $paramanddefault .= '=null';
1308 switch($keydesc->type) {
1310 $paramanddefault .= '='. (int) $keydesc->default; break;
1312 $paramanddefault .= '='.$keydesc->default; break;
1314 $paramanddefault .= '='.$keydesc->default; break;
1316 $paramanddefault .= '=\''.$keydesc->default.'\'';
1319 } else if ($keydesc->required == VALUE_OPTIONAL) {
1320 //it does make sens to declare a parameter VALUE_OPTIONAL
1321 //VALUE_OPTIONAL is used only for array/object key
1322 throw new moodle_exception('parametercannotbevalueoptional');
1324 } else { //for the moment we do not support default for other structure types
1325 if ($keydesc->required == VALUE_DEFAULT) {
1326 //accept empty array as default
1327 if (isset($keydesc->default) and is_array($keydesc->default)
1328 and empty($keydesc->default)) {
1329 $paramanddefault .= '=array()';
1331 throw new moodle_exception('errornotemptydefaultparamarray', 'webservice', '', $name);
1334 if ($keydesc->required == VALUE_OPTIONAL) {
1335 throw new moodle_exception('erroroptionalparamarray', 'webservice', '', $name);
1339 $paramanddefaults[] = $paramanddefault;
1340 $type = $this->get_phpdoc_type($keydesc);
1341 $params_desc[] = ' * @param '.$type.' $'.$name.' '.$keydesc->desc;
1343 $params = implode(', ', $params);
1344 $paramanddefaults = implode(', ', $paramanddefaults);
1345 $params_desc = implode("\n", $params_desc);
1347 $serviceclassmethodbody = $this->service_class_method_body($function, $params);
1349 if (is_null($function->returns_desc)) {
1350 $return = ' * @return void';
1352 $type = $this->get_phpdoc_type($function->returns_desc);
1353 $return = ' * @return '.$type.' '.$function->returns_desc->desc;
1356 // now crate the virtual method that calls the ext implementation
1360 * '.$function->description.'
1365 public function '.$function->name.'('.$paramanddefaults.') {
1366 '.$serviceclassmethodbody.'
1373 * Get the phpdoc type for an external_description
1374 * external_value => int, double or string
1375 * external_single_structure => object|struct, on-fly generated stdClass name, ...
1376 * external_multiple_structure => array
1378 * @param string $keydesc any of PARAM_*
1379 * @return string phpdoc type (string, double, int, array...)
1381 protected function get_phpdoc_type($keydesc) {
1382 if ($keydesc instanceof external_value) {
1383 switch($keydesc->type) {
1384 case PARAM_BOOL: // 0 or 1 only for now
1386 $type = 'int'; break;
1388 $type = 'double'; break;
1393 } else if ($keydesc instanceof external_single_structure) {
1394 $classname = $this->generate_simple_struct_class($keydesc);
1397 } else if ($keydesc instanceof external_multiple_structure) {
1405 * Generate 'struct'/'object' type name
1406 * Some servers (our Zend ones) parse the phpdoc to know the parameter types.
1407 * The purpose to this function is to be overwritten when the common object|struct type are not understood by the server.
1408 * See webservice/soap/locallib.php - the SOAP server requires detailed structure)
1410 * @param external_single_structure $structdesc the structure for which we generate the phpdoc type
1411 * @return string the phpdoc type
1413 protected function generate_simple_struct_class(external_single_structure $structdesc) {
1414 return 'object|struct'; //only 'object' is supported by SOAP, 'struct' by XML-RPC MDL-23083
1418 * You can override this function in your child class to add extra code into the dynamically
1419 * created service class. For example it is used in the amf server to cast types of parameters and to
1420 * cast the return value to the types as specified in the return value description.
1422 * @param stdClass $function a record from external_function
1423 * @param array $params web service function parameters
1424 * @return string body of the method for $function ie. everything within the {} of the method declaration.
1426 protected function service_class_method_body($function, $params){
1427 //cast the param from object to array (validate_parameters except array only)
1430 $paramstocast = explode(',', $params);
1431 foreach ($paramstocast as $paramtocast) {
1432 //clean the parameter from any white space
1433 $paramtocast = trim($paramtocast);
1434 $castingcode .= $paramtocast .
1435 '=webservice_zend_server::cast_objects_to_array('.$paramtocast.');';
1440 $descriptionmethod = $function->methodname.'_returns()';
1441 $callforreturnvaluedesc = $function->classname.'::'.$descriptionmethod;
1442 return $castingcode . ' if ('.$callforreturnvaluedesc.' == null) {'.
1443 $function->classname.'::'.$function->methodname.'('.$params.');
1446 return external_api::clean_returnvalue('.$callforreturnvaluedesc.', '.$function->classname.'::'.$function->methodname.'('.$params.'));';
1450 * Recursive function to recurse down into a complex variable and convert all
1451 * objects to arrays.
1453 * @param mixed $param value to cast
1454 * @return mixed Cast value
1456 public static function cast_objects_to_array($param){
1457 if (is_object($param)){
1458 $param = (array)$param;
1460 if (is_array($param)){
1461 $toreturn = array();
1462 foreach ($param as $key=> $param){
1463 $toreturn[$key] = self::cast_objects_to_array($param);
1472 * Set up zend service class
1474 protected function init_zend_server() {
1475 $this->zend_server = new $this->zend_class();
1479 * This method parses the $_POST and $_GET superglobals and looks for
1480 * the following information:
1481 * 1/ user authentication - username+password or token (wsusername, wspassword and wstoken parameters)
1485 protected function parse_request() {
1487 // We are going to clean the POST/GET parameters from the parameters specific to the server.
1488 parent::set_web_service_call_settings();
1490 // Get GET and POST paramters.
1491 $methodvariables = array_merge($_GET,$_POST);
1493 if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
1494 //note: some clients have problems with entity encoding :-(
1495 if (isset($methodvariables['wsusername'])) {
1496 $this->username = $methodvariables['wsusername'];
1498 if (isset($methodvariables['wspassword'])) {
1499 $this->password = $methodvariables['wspassword'];
1502 if (isset($methodvariables['wstoken'])) {
1503 $this->token = $methodvariables['wstoken'];
1509 * Internal implementation - sending of page headers.
1511 protected function send_headers() {
1512 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
1513 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1514 header('Pragma: no-cache');
1515 header('Accept-Ranges: none');
1519 * Specialised exception handler, we can not use the standard one because
1520 * it can not just print html to output.
1522 * @param exception $ex
1525 public function exception_handler($ex) {
1526 // detect active db transactions, rollback and log as error
1527 abort_all_db_transactions();
1529 // some hacks might need a cleanup hook
1530 $this->session_cleanup($ex);
1532 // now let the plugin send the exception to client
1533 $this->send_error($ex);
1535 // not much else we can do now, add some logging later
1540 * Send the error information to the WS client
1541 * formatted as XML document.
1543 * @param exception $ex
1545 protected function send_error($ex=null) {
1546 $this->send_headers();
1547 echo $this->zend_server->fault($ex);
1551 * Future hook needed for emulated sessions.
1553 * @param exception $exception null means normal termination, $exception received when WS call failed
1555 protected function session_cleanup($exception=null) {
1556 if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
1557 // nothing needs to be done, there is no persistent session
1559 // close emulated session if used
1566 * Web Service server base class.
1568 * This class handles both simple and token authentication.
1570 * @package core_webservice
1571 * @copyright 2009 Petr Skodak
1572 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1574 abstract class webservice_base_server extends webservice_server {
1576 /** @var array The function parameters - the real values submitted in the request */
1577 protected $parameters = null;
1579 /** @var string The name of the function that is executed */
1580 protected $functionname = null;
1582 /** @var stdClass Full function description */
1583 protected $function = null;
1585 /** @var mixed Function return value */
1586 protected $returns = null;
1589 * This method parses the request input, it needs to get:
1590 * 1/ user authentication - username+password or token
1592 * 3/ function parameters
1594 abstract protected function parse_request();
1597 * Send the result of function call to the WS client.
1599 abstract protected function send_response();
1602 * Send the error information to the WS client.
1604 * @param exception $ex
1606 abstract protected function send_error($ex=null);
1609 * Process request from client.
1613 public function run() {
1614 // we will probably need a lot of memory in some functions
1615 raise_memory_limit(MEMORY_EXTRA);
1617 // set some longer timeout, this script is not sending any output,
1618 // this means we need to manually extend the timeout operations
1619 // that need longer time to finish
1620 external_api::set_timeout();
1622 // set up exception handler first, we want to sent them back in correct format that
1623 // the other system understands
1624 // we do not need to call the original default handler because this ws handler does everything
1625 set_exception_handler(array($this, 'exception_handler'));
1627 // init all properties from the request data
1628 $this->parse_request();
1630 // authenticate user, this has to be done after the request parsing
1631 // this also sets up $USER and $SESSION
1632 $this->authenticate_user();
1634 // find all needed function info and make sure user may actually execute the function
1635 $this->load_function_info();
1637 // Log the web service request.
1640 'function' => $this->functionname
1643 $event = \core\event\webservice_function_called::create($params);
1644 $event->set_legacy_logdata(array(SITEID, 'webservice', $this->functionname, '' , getremoteaddr() , 0, $this->userid));
1647 // finally, execute the function - any errors are catched by the default exception handler
1650 // send the results back in correct format
1651 $this->send_response();
1654 $this->session_cleanup();
1660 * Specialised exception handler, we can not use the standard one because
1661 * it can not just print html to output.
1663 * @param exception $ex
1666 public function exception_handler($ex) {
1667 // detect active db transactions, rollback and log as error
1668 abort_all_db_transactions();
1670 // some hacks might need a cleanup hook
1671 $this->session_cleanup($ex);
1673 // now let the plugin send the exception to client
1674 $this->send_error($ex);
1676 // not much else we can do now, add some logging later
1681 * Future hook needed for emulated sessions.
1683 * @param exception $exception null means normal termination, $exception received when WS call failed
1685 protected function session_cleanup($exception=null) {
1686 if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
1687 // nothing needs to be done, there is no persistent session
1689 // close emulated session if used
1694 * Fetches the function description from database,
1695 * verifies user is allowed to use this function and
1696 * loads all paremeters and return descriptions.
1698 protected function load_function_info() {
1699 global $DB, $USER, $CFG;
1701 if (empty($this->functionname)) {
1702 throw new invalid_parameter_exception('Missing function name');
1705 // function must exist
1706 $function = external_function_info($this->functionname);
1708 if ($this->restricted_serviceid) {
1709 $params = array('sid1'=>$this->restricted_serviceid, 'sid2'=>$this->restricted_serviceid);
1710 $wscond1 = 'AND s.id = :sid1';
1711 $wscond2 = 'AND s.id = :sid2';
1718 // now let's verify access control
1720 // now make sure the function is listed in at least one service user is allowed to use
1721 // allow access only if:
1722 // 1/ entry in the external_services_users table if required
1723 // 2/ validuntil not reached
1724 // 3/ has capability if specified in service desc
1727 $sql = "SELECT s.*, NULL AS iprestriction
1728 FROM {external_services} s
1729 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0 AND sf.functionname = :name1)
1730 WHERE s.enabled = 1 $wscond1
1734 SELECT s.*, su.iprestriction
1735 FROM {external_services} s
1736 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1 AND sf.functionname = :name2)
1737 JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)
1738 WHERE s.enabled = 1 AND (su.validuntil IS NULL OR su.validuntil < :now) $wscond2";
1739 $params = array_merge($params, array('userid'=>$USER->id, 'name1'=>$function->name, 'name2'=>$function->name, 'now'=>time()));
1741 $rs = $DB->get_recordset_sql($sql, $params);
1742 // now make sure user may access at least one service
1743 $remoteaddr = getremoteaddr();
1745 foreach ($rs as $service) {
1746 if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) {
1747 continue; // cap required, sorry
1749 if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) {
1750 continue; // wrong request source ip, sorry
1753 break; // one service is enough, no need to continue
1757 throw new webservice_access_exception(
1758 'Access to the function '.$this->functionname.'() is not allowed.
1759 There could be multiple reasons for this:
1760 1. The service linked to the user token does not contain the function.
1761 2. The service is user-restricted and the user is not listed.
1762 3. The service is IP-restricted and the user IP is not listed.
1763 4. The service is time-restricted and the time has expired.
1764 5. The token is time-restricted and the time has expired.
1765 6. The service requires a specific capability which the user does not have.
1766 7. The function is called with username/password (no user token is sent)
1767 and none of the services has the function to allow the user.
1768 These settings can be found in Administration > Site administration
1769 > Plugins > Web services > External services and Manage tokens.');
1772 // we have all we need now
1773 $this->function = $function;
1777 * Execute previously loaded function using parameters parsed from the request data.
1779 protected function execute() {
1780 // validate params, this also sorts the params properly, we need the correct order in the next part
1781 $params = call_user_func(array($this->function->classname, 'validate_parameters'), $this->function->parameters_desc, $this->parameters);
1784 $this->returns = call_user_func_array(array($this->function->classname, $this->function->methodname), array_values($params));