Merge branch 'MDL-74154-master' of https://github.com/peterRd/moodle
[moodle.git] / webservice / lib.php
blobe0c5d8054e3cd67808630ddec08c82195ed87618
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
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.
8 //
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/>.
18 /**
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');
28 /**
29 * WEBSERVICE_AUTHMETHOD_USERNAME - username/password authentication (also called simple authentication)
31 define('WEBSERVICE_AUTHMETHOD_USERNAME', 0);
33 /**
34 * WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN - most common token authentication (external app, mobile app...)
36 define('WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN', 1);
38 /**
39 * WEBSERVICE_AUTHMETHOD_SESSION_TOKEN - token for embedded application (requires Moodle session)
41 define('WEBSERVICE_AUTHMETHOD_SESSION_TOKEN', 2);
43 /**
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
50 class webservice {
51 /**
52 * Only update token last access once per this many seconds. (This constant controls update of
53 * the external tokens last access field. There is a similar define LASTACCESS_UPDATE_SECS
54 * which controls update of the web site last access fields.)
56 * @var int
58 const TOKEN_LASTACCESS_UPDATE_SECS = 60;
60 /**
61 * Authenticate user (used by download/upload file scripts)
63 * @param string $token
64 * @return array - contains the authenticated user, token and service objects
66 public function authenticate_user($token) {
67 global $DB, $CFG;
69 // web service must be enabled to use this script
70 if (!$CFG->enablewebservices) {
71 throw new webservice_access_exception('Web services are not enabled in Advanced features.');
74 // Obtain token record
75 if (!$token = $DB->get_record('external_tokens', array('token' => $token))) {
76 //client may want to display login form => moodle_exception
77 throw new moodle_exception('invalidtoken', 'webservice');
80 $loginfaileddefaultparams = array(
81 'other' => array(
82 'method' => WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN,
83 'reason' => null,
84 'tokenid' => $token->id
88 // Validate token date
89 if ($token->validuntil and $token->validuntil < time()) {
90 $params = $loginfaileddefaultparams;
91 $params['other']['reason'] = 'token_expired';
92 $event = \core\event\webservice_login_failed::create($params);
93 $event->add_record_snapshot('external_tokens', $token);
94 $event->set_legacy_logdata(array(SITEID, 'webservice', get_string('tokenauthlog', 'webservice'), '',
95 get_string('invalidtimedtoken', 'webservice'), 0));
96 $event->trigger();
97 $DB->delete_records('external_tokens', array('token' => $token->token));
98 throw new webservice_access_exception('Invalid token - token expired - check validuntil time for the token');
101 // Check ip
102 if ($token->iprestriction and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
103 $params = $loginfaileddefaultparams;
104 $params['other']['reason'] = 'ip_restricted';
105 $event = \core\event\webservice_login_failed::create($params);
106 $event->add_record_snapshot('external_tokens', $token);
107 $event->set_legacy_logdata(array(SITEID, 'webservice', get_string('tokenauthlog', 'webservice'), '',
108 get_string('failedtolog', 'webservice') . ": " . getremoteaddr(), 0));
109 $event->trigger();
110 throw new webservice_access_exception('Invalid token - IP:' . getremoteaddr()
111 . ' is not supported');
114 //retrieve user link to the token
115 $user = $DB->get_record('user', array('id' => $token->userid, 'deleted' => 0), '*', MUST_EXIST);
117 // let enrol plugins deal with new enrolments if necessary
118 enrol_check_plugins($user);
120 // setup user session to check capability
121 \core\session\manager::set_user($user);
122 set_login_session_preferences();
124 //assumes that if sid is set then there must be a valid associated session no matter the token type
125 if ($token->sid) {
126 if (!\core\session\manager::session_exists($token->sid)) {
127 $DB->delete_records('external_tokens', array('sid' => $token->sid));
128 throw new webservice_access_exception('Invalid session based token - session not found or expired');
132 // Cannot authenticate unless maintenance access is granted.
133 $hasmaintenanceaccess = has_capability('moodle/site:maintenanceaccess', context_system::instance(), $user);
134 if (!empty($CFG->maintenance_enabled) and !$hasmaintenanceaccess) {
135 //this is usually temporary, client want to implement code logic => moodle_exception
136 throw new moodle_exception('sitemaintenance', 'admin');
139 //retrieve web service record
140 $service = $DB->get_record('external_services', array('id' => $token->externalserviceid, 'enabled' => 1));
141 if (empty($service)) {
142 // will throw exception if no token found
143 throw new webservice_access_exception('Web service is not available (it doesn\'t exist or might be disabled)');
146 //check if there is any required system capability
147 if ($service->requiredcapability and !has_capability($service->requiredcapability, context_system::instance(), $user)) {
148 throw new webservice_access_exception('The capability ' . $service->requiredcapability . ' is required.');
151 //specific checks related to user restricted service
152 if ($service->restrictedusers) {
153 $authoriseduser = $DB->get_record('external_services_users', array('externalserviceid' => $service->id, 'userid' => $user->id));
155 if (empty($authoriseduser)) {
156 throw new webservice_access_exception(
157 'The user is not allowed for this service. First you need to allow this user on the '
158 . $service->name . '\'s allowed users administration page.');
161 if (!empty($authoriseduser->validuntil) and $authoriseduser->validuntil < time()) {
162 throw new webservice_access_exception('Invalid service - service expired - check validuntil time for this allowed user');
165 if (!empty($authoriseduser->iprestriction) and !address_in_subnet(getremoteaddr(), $authoriseduser->iprestriction)) {
166 throw new webservice_access_exception('Invalid service - IP:' . getremoteaddr()
167 . ' is not supported - check this allowed user');
171 //only confirmed user should be able to call web service
172 if (empty($user->confirmed)) {
173 $params = $loginfaileddefaultparams;
174 $params['other']['reason'] = 'user_unconfirmed';
175 $event = \core\event\webservice_login_failed::create($params);
176 $event->add_record_snapshot('external_tokens', $token);
177 $event->set_legacy_logdata(array(SITEID, 'webservice', 'user unconfirmed', '', $user->username));
178 $event->trigger();
179 throw new moodle_exception('usernotconfirmed', 'moodle', '', $user->username);
182 //check the user is suspended
183 if (!empty($user->suspended)) {
184 $params = $loginfaileddefaultparams;
185 $params['other']['reason'] = 'user_suspended';
186 $event = \core\event\webservice_login_failed::create($params);
187 $event->add_record_snapshot('external_tokens', $token);
188 $event->set_legacy_logdata(array(SITEID, 'webservice', 'user suspended', '', $user->username));
189 $event->trigger();
190 throw new moodle_exception('wsaccessusersuspended', 'moodle', '', $user->username);
193 //check if the auth method is nologin (in this case refuse connection)
194 if ($user->auth == 'nologin') {
195 $params = $loginfaileddefaultparams;
196 $params['other']['reason'] = 'nologin';
197 $event = \core\event\webservice_login_failed::create($params);
198 $event->add_record_snapshot('external_tokens', $token);
199 $event->set_legacy_logdata(array(SITEID, 'webservice', 'nologin auth attempt with web service', '', $user->username));
200 $event->trigger();
201 throw new moodle_exception('wsaccessusernologin', 'moodle', '', $user->username);
204 //Check if the user password is expired
205 $auth = get_auth_plugin($user->auth);
206 if (!empty($auth->config->expiration) and $auth->config->expiration == 1) {
207 $days2expire = $auth->password_expire($user->username);
208 if (intval($days2expire) < 0) {
209 $params = $loginfaileddefaultparams;
210 $params['other']['reason'] = 'password_expired';
211 $event = \core\event\webservice_login_failed::create($params);
212 $event->add_record_snapshot('external_tokens', $token);
213 $event->set_legacy_logdata(array(SITEID, 'webservice', 'expired password', '', $user->username));
214 $event->trigger();
215 throw new moodle_exception('passwordisexpired', 'webservice');
219 // log token access
220 self::update_token_lastaccess($token);
222 return array('user' => $user, 'token' => $token, 'service' => $service);
226 * Updates the last access time for a token.
228 * @param \stdClass $token Token object (must include id, lastaccess fields)
229 * @param int $time Time of access (0 = use current time)
230 * @throws dml_exception If database error
232 public static function update_token_lastaccess($token, int $time = 0) {
233 global $DB;
235 if (!$time) {
236 $time = time();
239 // Only update the field if it is a different time from previous request,
240 // so as not to waste database effort.
241 if ($time >= $token->lastaccess + self::TOKEN_LASTACCESS_UPDATE_SECS) {
242 $DB->set_field('external_tokens', 'lastaccess', $time, array('id' => $token->id));
247 * Allow user to call a service
249 * @param stdClass $user a user
251 public function add_ws_authorised_user($user) {
252 global $DB;
253 $user->timecreated = time();
254 $DB->insert_record('external_services_users', $user);
258 * Disallow a user to call a service
260 * @param stdClass $user a user
261 * @param int $serviceid
263 public function remove_ws_authorised_user($user, $serviceid) {
264 global $DB;
265 $DB->delete_records('external_services_users',
266 array('externalserviceid' => $serviceid, 'userid' => $user->id));
270 * Update allowed user settings (ip restriction, valid until...)
272 * @param stdClass $user
274 public function update_ws_authorised_user($user) {
275 global $DB;
276 $DB->update_record('external_services_users', $user);
280 * Return list of allowed users with their options (ip/timecreated / validuntil...)
281 * for a given service
283 * @param int $serviceid the service id to search against
284 * @return array $users
286 public function get_ws_authorised_users($serviceid) {
287 global $DB, $CFG;
289 $params = array($CFG->siteguest, $serviceid);
291 $userfields = \core_user\fields::for_identity(context_system::instance())->with_name()->excluding('id');
292 $fieldsql = $userfields->get_sql('u');
294 $sql = " SELECT u.id as id, esu.id as serviceuserid {$fieldsql->selects},
295 esu.iprestriction as iprestriction, esu.validuntil as validuntil,
296 esu.timecreated as timecreated
297 FROM {user} u
298 JOIN {external_services_users} esu ON esu.userid = u.id
299 {$fieldsql->joins}
300 WHERE u.id <> ? AND u.deleted = 0 AND u.confirmed = 1
301 AND esu.externalserviceid = ?";
303 $users = $DB->get_records_sql($sql, array_merge($fieldsql->params, $params));
305 return $users;
309 * Return an authorised user with their options (ip/timecreated / validuntil...)
311 * @param int $serviceid the service id to search against
312 * @param int $userid the user to search against
313 * @return stdClass
315 public function get_ws_authorised_user($serviceid, $userid) {
316 global $DB, $CFG;
317 $params = array($CFG->siteguest, $serviceid, $userid);
318 $sql = " SELECT u.id as id, esu.id as serviceuserid, u.email as email, u.firstname as firstname,
319 u.lastname as lastname,
320 esu.iprestriction as iprestriction, esu.validuntil as validuntil,
321 esu.timecreated as timecreated
322 FROM {user} u, {external_services_users} esu
323 WHERE u.id <> ? AND u.deleted = 0 AND u.confirmed = 1
324 AND esu.userid = u.id
325 AND esu.externalserviceid = ?
326 AND u.id = ?";
327 $user = $DB->get_record_sql($sql, $params);
328 return $user;
332 * Generate all tokens of a specific user
334 * @param int $userid user id
336 public function generate_user_ws_tokens($userid) {
337 global $CFG, $DB;
339 // generate a token for non admin if web service are enable and the user has the capability to create a token
340 if (!is_siteadmin() && has_capability('moodle/webservice:createtoken', context_system::instance(), $userid) && !empty($CFG->enablewebservices)) {
341 // for every service than the user is authorised on, create a token (if it doesn't already exist)
343 // get all services which are set to all user (no restricted to specific users)
344 $norestrictedservices = $DB->get_records('external_services', array('restrictedusers' => 0));
345 $serviceidlist = array();
346 foreach ($norestrictedservices as $service) {
347 $serviceidlist[] = $service->id;
350 // get all services which are set to the current user (the current user is specified in the restricted user list)
351 $servicesusers = $DB->get_records('external_services_users', array('userid' => $userid));
352 foreach ($servicesusers as $serviceuser) {
353 if (!in_array($serviceuser->externalserviceid,$serviceidlist)) {
354 $serviceidlist[] = $serviceuser->externalserviceid;
358 // get all services which already have a token set for the current user
359 $usertokens = $DB->get_records('external_tokens', array('userid' => $userid, 'tokentype' => EXTERNAL_TOKEN_PERMANENT));
360 $tokenizedservice = array();
361 foreach ($usertokens as $token) {
362 $tokenizedservice[] = $token->externalserviceid;
365 // create a token for the service which have no token already
366 foreach ($serviceidlist as $serviceid) {
367 if (!in_array($serviceid, $tokenizedservice)) {
368 // create the token for this service
369 $newtoken = new stdClass();
370 $newtoken->token = md5(uniqid(rand(),1));
371 // check that the user has capability on this service
372 $newtoken->tokentype = EXTERNAL_TOKEN_PERMANENT;
373 $newtoken->userid = $userid;
374 $newtoken->externalserviceid = $serviceid;
375 // TODO MDL-31190 find a way to get the context - UPDATE FOLLOWING LINE
376 $newtoken->contextid = context_system::instance()->id;
377 $newtoken->creatorid = $userid;
378 $newtoken->timecreated = time();
379 // Generate the private token, it must be transmitted only via https.
380 $newtoken->privatetoken = random_string(64);
382 $DB->insert_record('external_tokens', $newtoken);
391 * Return all tokens of a specific user
392 * + the service state (enabled/disabled)
393 * + the authorised user mode (restricted/not restricted)
395 * @param int $userid user id
396 * @return array
398 public function get_user_ws_tokens($userid) {
399 global $DB;
400 //here retrieve token list (including linked users firstname/lastname and linked services name)
401 $sql = "SELECT
402 t.id, t.creatorid, t.token, u.firstname, u.lastname, s.id as wsid, s.name, s.enabled, s.restrictedusers, t.validuntil
403 FROM
404 {external_tokens} t, {user} u, {external_services} s
405 WHERE
406 t.userid=? AND t.tokentype = ".EXTERNAL_TOKEN_PERMANENT." AND s.id = t.externalserviceid AND t.userid = u.id";
407 $tokens = $DB->get_records_sql($sql, array( $userid));
408 return $tokens;
412 * Return a token that has been created by the user (i.e. to created by an admin)
413 * If no tokens exist an exception is thrown
415 * The returned value is a stdClass:
416 * ->id token id
417 * ->token
418 * ->firstname user firstname
419 * ->lastname
420 * ->name service name
422 * @param int $userid user id
423 * @param int $tokenid token id
424 * @return stdClass
426 public function get_created_by_user_ws_token($userid, $tokenid) {
427 global $DB;
428 $sql = "SELECT
429 t.id, t.token, u.firstname, u.lastname, s.name
430 FROM
431 {external_tokens} t, {user} u, {external_services} s
432 WHERE
433 t.creatorid=? AND t.id=? AND t.tokentype = "
434 . EXTERNAL_TOKEN_PERMANENT
435 . " AND s.id = t.externalserviceid AND t.userid = u.id";
436 //must be the token creator
437 $token = $DB->get_record_sql($sql, array($userid, $tokenid), MUST_EXIST);
438 return $token;
442 * Return a token of an arbitrary user by tokenid, including details of the associated user and the service name.
443 * If no tokens exist an exception is thrown
445 * The returned value is a stdClass:
446 * ->id token id
447 * ->token
448 * ->firstname user firstname
449 * ->lastname
450 * ->name service name
452 * @param int $tokenid token id
453 * @return stdClass
455 public function get_token_by_id_with_details($tokenid) {
456 global $DB;
457 $sql = "SELECT t.id, t.token, u.id AS userid, u.firstname, u.lastname, s.name, t.creatorid
458 FROM {external_tokens} t, {user} u, {external_services} s
459 WHERE t.id=? AND t.tokentype = ? AND s.id = t.externalserviceid AND t.userid = u.id";
460 $token = $DB->get_record_sql($sql, array($tokenid, EXTERNAL_TOKEN_PERMANENT), MUST_EXIST);
461 return $token;
465 * Return a database token record for a token id
467 * @param int $tokenid token id
468 * @return object token
470 public function get_token_by_id($tokenid) {
471 global $DB;
472 return $DB->get_record('external_tokens', array('id' => $tokenid));
476 * Delete a token
478 * @param int $tokenid token id
480 public function delete_user_ws_token($tokenid) {
481 global $DB;
482 $DB->delete_records('external_tokens', array('id'=>$tokenid));
486 * Delete all the tokens belonging to a user.
488 * @param int $userid the user id whose tokens must be deleted
490 public static function delete_user_ws_tokens($userid) {
491 global $DB;
492 $DB->delete_records('external_tokens', array('userid' => $userid));
496 * Delete a service
497 * Also delete function references and authorised user references.
499 * @param int $serviceid service id
501 public function delete_service($serviceid) {
502 global $DB;
503 $DB->delete_records('external_services_users', array('externalserviceid' => $serviceid));
504 $DB->delete_records('external_services_functions', array('externalserviceid' => $serviceid));
505 $DB->delete_records('external_tokens', array('externalserviceid' => $serviceid));
506 $DB->delete_records('external_services', array('id' => $serviceid));
510 * Get a full database token record for a given token value
512 * @param string $token
513 * @throws moodle_exception if there is multiple result
515 public function get_user_ws_token($token) {
516 global $DB;
517 return $DB->get_record('external_tokens', array('token'=>$token), '*', MUST_EXIST);
521 * Get the functions list of a service list (by id)
523 * @param array $serviceids service ids
524 * @return array of functions
526 public function get_external_functions($serviceids) {
527 global $DB;
528 if (!empty($serviceids)) {
529 list($serviceids, $params) = $DB->get_in_or_equal($serviceids);
530 $sql = "SELECT f.*
531 FROM {external_functions} f
532 WHERE f.name IN (SELECT sf.functionname
533 FROM {external_services_functions} sf
534 WHERE sf.externalserviceid $serviceids)
535 ORDER BY f.name ASC";
536 $functions = $DB->get_records_sql($sql, $params);
537 } else {
538 $functions = array();
540 return $functions;
544 * Get the functions of a service list (by shortname). It can return only enabled functions if required.
546 * @param array $serviceshortnames service shortnames
547 * @param bool $enabledonly if true then only return functions for services that have been enabled
548 * @return array functions
550 public function get_external_functions_by_enabled_services($serviceshortnames, $enabledonly = true) {
551 global $DB;
552 if (!empty($serviceshortnames)) {
553 $enabledonlysql = $enabledonly?' AND s.enabled = 1 ':'';
554 list($serviceshortnames, $params) = $DB->get_in_or_equal($serviceshortnames);
555 $sql = "SELECT f.*
556 FROM {external_functions} f
557 WHERE f.name IN (SELECT sf.functionname
558 FROM {external_services_functions} sf, {external_services} s
559 WHERE s.shortname $serviceshortnames
560 AND sf.externalserviceid = s.id
561 " . $enabledonlysql . ")";
562 $functions = $DB->get_records_sql($sql, $params);
563 } else {
564 $functions = array();
566 return $functions;
570 * Get functions not included in a service
572 * @param int $serviceid service id
573 * @return array functions
575 public function get_not_associated_external_functions($serviceid) {
576 global $DB;
577 $select = "name NOT IN (SELECT s.functionname
578 FROM {external_services_functions} s
579 WHERE s.externalserviceid = :sid
582 $functions = $DB->get_records_select('external_functions',
583 $select, array('sid' => $serviceid), 'name');
585 return $functions;
589 * Get list of required capabilities of a service, sorted by functions
590 * Example of returned value:
591 * Array
593 * [core_group_create_groups] => Array
595 * [0] => moodle/course:managegroups
598 * [core_enrol_get_enrolled_users] => Array
600 * [0] => moodle/user:viewdetails
601 * [1] => moodle/user:viewhiddendetails
602 * [2] => moodle/course:useremail
603 * [3] => moodle/user:update
604 * [4] => moodle/site:accessallgroups
607 * @param int $serviceid service id
608 * @return array
610 public function get_service_required_capabilities($serviceid) {
611 $functions = $this->get_external_functions(array($serviceid));
612 $requiredusercaps = array();
613 foreach ($functions as $function) {
614 $functioncaps = explode(',', $function->capabilities);
615 if (!empty($functioncaps) and !empty($functioncaps[0])) {
616 foreach ($functioncaps as $functioncap) {
617 $requiredusercaps[$function->name][] = trim($functioncap);
621 return $requiredusercaps;
625 * Get user capabilities (with context)
626 * Only useful for documentation purpose
627 * WARNING: do not use this "broken" function. It was created in the goal to display some capabilities
628 * required by users. In theory we should not need to display this kind of information
629 * as the front end does not display it itself. In pratice,
630 * admins would like the info, for more info you can follow: MDL-29962
632 * @deprecated since Moodle 3.11 in MDL-67748 without a replacement.
633 * @todo MDL-70187 Please delete this method completely in Moodle 4.3, thank you.
634 * @param int $userid user id
635 * @return array
637 public function get_user_capabilities($userid) {
638 global $DB;
640 debugging('webservice::get_user_capabilities() has been deprecated.', DEBUG_DEVELOPER);
642 //retrieve the user capabilities
643 $sql = "SELECT DISTINCT rc.id, rc.capability FROM {role_capabilities} rc, {role_assignments} ra
644 WHERE rc.roleid=ra.roleid AND ra.userid= ? AND rc.permission = ?";
645 $dbusercaps = $DB->get_records_sql($sql, array($userid, CAP_ALLOW));
646 $usercaps = array();
647 foreach ($dbusercaps as $usercap) {
648 $usercaps[$usercap->capability] = true;
650 return $usercaps;
654 * Get missing user capabilities for the given service's functions.
656 * Every external function can declare some required capabilities to allow for easier setup of the web services.
657 * However, that is supposed to be used for informational admin report only. There is no automatic evaluation of
658 * the declared capabilities and the context of the capability evaluation is ignored. Also, actual capability
659 * evaluation is much more complex as it allows for overrides etc.
661 * Returned are capabilities that the given users do not seem to have assigned anywhere at the site and that should
662 * be checked by the admin.
664 * Do not use this method for anything else, particularly not for any security related checks. See MDL-29962 for the
665 * background of why we have this - there are arguments for dropping this feature completely.
667 * @param array $users List of users to check, consisting of objects, arrays or integer ids.
668 * @param int $serviceid The id of the external service to check.
669 * @return array List of missing capabilities: (int)userid => array of (string)capabilitynames
671 public function get_missing_capabilities_by_users(array $users, int $serviceid): array {
672 global $DB;
674 // The following are default capabilities for all authenticated users and we will assume them granted.
675 $commoncaps = get_default_capabilities('user');
677 // Get the list of additional capabilities required by the service.
678 $servicecaps = [];
679 foreach ($this->get_service_required_capabilities($serviceid) as $service => $caps) {
680 foreach ($caps as $cap) {
681 if (empty($commoncaps[$cap])) {
682 $servicecaps[$cap] = true;
687 if (empty($servicecaps)) {
688 return [];
691 // Prepare a list of user ids we want to check.
692 $userids = [];
693 foreach ($users as $user) {
694 if (is_object($user) && isset($user->id)) {
695 $userids[$user->id] = true;
696 } else if (is_array($user) && isset($user['id'])) {
697 $userids[$user['id']] = true;
698 } else {
699 throw new coding_exception('Unexpected format of users list in webservice::get_missing_capabilities_by_users().');
703 // Prepare a matrix of missing capabilities x users - consider them all missing by default.
704 foreach (array_keys($userids) as $userid) {
705 foreach (array_keys($servicecaps) as $capname) {
706 $matrix[$userid][$capname] = true;
710 list($capsql, $capparams) = $DB->get_in_or_equal(array_keys($servicecaps), SQL_PARAMS_NAMED, 'paramcap');
711 list($usersql, $userparams) = $DB->get_in_or_equal(array_keys($userids), SQL_PARAMS_NAMED, 'paramuser');
713 $sql = "SELECT c.name AS capability, u.id AS userid
714 FROM {capabilities} c
715 JOIN {role_capabilities} rc ON c.name = rc.capability
716 JOIN {role_assignments} ra ON ra.roleid = rc.roleid
717 JOIN {user} u ON ra.userid = u.id
718 WHERE rc.permission = :capallow
719 AND c.name {$capsql}
720 AND u.id {$usersql}";
722 $params = $capparams + $userparams + [
723 'capallow' => CAP_ALLOW,
726 $rs = $DB->get_recordset_sql($sql, $params);
728 foreach ($rs as $record) {
729 // If there was a potential role assignment found that might grant the user the given capability,
730 // remove it from the matrix. Again, we ignore all the contexts, prohibits, prevents and other details
731 // of the permissions evaluations. See the function docblock for details.
732 unset($matrix[$record->userid][$record->capability]);
735 $rs->close();
737 foreach ($matrix as $userid => $caps) {
738 $matrix[$userid] = array_keys($caps);
739 if (empty($matrix[$userid])) {
740 unset($matrix[$userid]);
744 return $matrix;
748 * Get an external service for a given service id
750 * @param int $serviceid service id
751 * @param int $strictness IGNORE_MISSING, MUST_EXIST...
752 * @return stdClass external service
754 public function get_external_service_by_id($serviceid, $strictness=IGNORE_MISSING) {
755 global $DB;
756 $service = $DB->get_record('external_services',
757 array('id' => $serviceid), '*', $strictness);
758 return $service;
762 * Get an external service for a given shortname
764 * @param string $shortname service shortname
765 * @param int $strictness IGNORE_MISSING, MUST_EXIST...
766 * @return stdClass external service
768 public function get_external_service_by_shortname($shortname, $strictness=IGNORE_MISSING) {
769 global $DB;
770 $service = $DB->get_record('external_services',
771 array('shortname' => $shortname), '*', $strictness);
772 return $service;
776 * Get an external function for a given function id
778 * @param int $functionid function id
779 * @param int $strictness IGNORE_MISSING, MUST_EXIST...
780 * @return stdClass external function
782 public function get_external_function_by_id($functionid, $strictness=IGNORE_MISSING) {
783 global $DB;
784 $function = $DB->get_record('external_functions',
785 array('id' => $functionid), '*', $strictness);
786 return $function;
790 * Add a function to a service
792 * @param string $functionname function name
793 * @param int $serviceid service id
795 public function add_external_function_to_service($functionname, $serviceid) {
796 global $DB;
797 $addedfunction = new stdClass();
798 $addedfunction->externalserviceid = $serviceid;
799 $addedfunction->functionname = $functionname;
800 $DB->insert_record('external_services_functions', $addedfunction);
804 * Add a service
805 * It generates the timecreated field automatically.
807 * @param stdClass $service
808 * @return serviceid integer
810 public function add_external_service($service) {
811 global $DB;
812 $service->timecreated = time();
813 $serviceid = $DB->insert_record('external_services', $service);
814 return $serviceid;
818 * Update a service
819 * It modifies the timemodified automatically.
821 * @param stdClass $service
823 public function update_external_service($service) {
824 global $DB;
825 $service->timemodified = time();
826 $DB->update_record('external_services', $service);
830 * Test whether an external function is already linked to a service
832 * @param string $functionname function name
833 * @param int $serviceid service id
834 * @return bool true if a matching function exists for the service, else false.
835 * @throws dml_exception if error
837 public function service_function_exists($functionname, $serviceid) {
838 global $DB;
839 return $DB->record_exists('external_services_functions',
840 array('externalserviceid' => $serviceid,
841 'functionname' => $functionname));
845 * Remove a function from a service
847 * @param string $functionname function name
848 * @param int $serviceid service id
850 public function remove_external_function_from_service($functionname, $serviceid) {
851 global $DB;
852 $DB->delete_records('external_services_functions',
853 array('externalserviceid' => $serviceid, 'functionname' => $functionname));
858 * Return a list with all the valid user tokens for the given user, it only excludes expired tokens.
860 * @param string $userid user id to retrieve tokens from
861 * @return array array of token entries
862 * @since Moodle 3.2
864 public static function get_active_tokens($userid) {
865 global $DB;
867 $sql = 'SELECT t.*, s.name as servicename FROM {external_tokens} t JOIN
868 {external_services} s ON t.externalserviceid = s.id WHERE
869 t.userid = :userid AND (COALESCE(t.validuntil, 0) = 0 OR t.validuntil > :now)';
870 $params = array('userid' => $userid, 'now' => time());
871 return $DB->get_records_sql($sql, $params);
876 * Exception indicating access control problem in web service call
877 * This exception should return general errors about web service setup.
878 * Errors related to the user like wrong username/password should not use it,
879 * you should not use this exception if you want to let the client implement
880 * some code logic against an access error.
882 * @package core_webservice
883 * @copyright 2009 Petr Skodak
884 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
886 class webservice_access_exception extends moodle_exception {
889 * Constructor
891 * @param string $debuginfo the debug info
893 function __construct($debuginfo) {
894 parent::__construct('accessexception', 'webservice', '', null, $debuginfo);
899 * Check if a protocol is enabled
901 * @param string $protocol name of WS protocol ('rest', 'soap', 'xmlrpc'...)
902 * @return bool true if the protocol is enabled
904 function webservice_protocol_is_enabled($protocol) {
905 global $CFG;
907 if (empty($CFG->enablewebservices) || empty($CFG->webserviceprotocols)) {
908 return false;
911 $active = explode(',', $CFG->webserviceprotocols);
913 return(in_array($protocol, $active));
917 * Mandatory interface for all test client classes.
919 * @package core_webservice
920 * @copyright 2009 Petr Skodak
921 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
923 interface webservice_test_client_interface {
926 * Execute test client WS request
928 * @param string $serverurl server url (including the token param)
929 * @param string $function web service function name
930 * @param array $params parameters of the web service function
931 * @return mixed
933 public function simpletest($serverurl, $function, $params);
937 * Mandatory interface for all web service protocol classes
939 * @package core_webservice
940 * @copyright 2009 Petr Skodak
941 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
943 interface webservice_server_interface {
946 * Process request from client.
948 public function run();
952 * Abstract web service base class.
954 * @package core_webservice
955 * @copyright 2009 Petr Skodak
956 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
958 abstract class webservice_server implements webservice_server_interface {
960 /** @var string Name of the web server plugin */
961 protected $wsname = null;
963 /** @var string Name of local user */
964 protected $username = null;
966 /** @var string Password of the local user */
967 protected $password = null;
969 /** @var int The local user */
970 protected $userid = null;
972 /** @var integer Authentication method one of WEBSERVICE_AUTHMETHOD_* */
973 protected $authmethod;
975 /** @var string Authentication token*/
976 protected $token = null;
978 /** @var stdClass Restricted context */
979 protected $restricted_context;
981 /** @var int Restrict call to one service id*/
982 protected $restricted_serviceid = null;
985 * Constructor
987 * @param integer $authmethod authentication method one of WEBSERVICE_AUTHMETHOD_*
989 public function __construct($authmethod) {
990 $this->authmethod = $authmethod;
995 * Authenticate user using username+password or token.
996 * This function sets up $USER global.
997 * It is safe to use has_capability() after this.
998 * This method also verifies user is allowed to use this
999 * server.
1001 protected function authenticate_user() {
1002 global $CFG, $DB;
1004 if (!NO_MOODLE_COOKIES) {
1005 throw new coding_exception('Cookies must be disabled in WS servers!');
1008 $loginfaileddefaultparams = array(
1009 'other' => array(
1010 'method' => $this->authmethod,
1011 'reason' => null
1015 if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
1017 //we check that authentication plugin is enabled
1018 //it is only required by simple authentication
1019 if (!is_enabled_auth('webservice')) {
1020 throw new webservice_access_exception('The web service authentication plugin is disabled.');
1023 if (!$auth = get_auth_plugin('webservice')) {
1024 throw new webservice_access_exception('The web service authentication plugin is missing.');
1027 $this->restricted_context = context_system::instance();
1029 if (!$this->username) {
1030 throw new moodle_exception('missingusername', 'webservice');
1033 if (!$this->password) {
1034 throw new moodle_exception('missingpassword', 'webservice');
1037 if (!$auth->user_login_webservice($this->username, $this->password)) {
1039 // Log failed login attempts.
1040 $params = $loginfaileddefaultparams;
1041 $params['other']['reason'] = 'password';
1042 $params['other']['username'] = $this->username;
1043 $event = \core\event\webservice_login_failed::create($params);
1044 $event->set_legacy_logdata(array(SITEID, 'webservice', get_string('simpleauthlog', 'webservice'), '' ,
1045 get_string('failedtolog', 'webservice').": ".$this->username."/".$this->password." - ".getremoteaddr() , 0));
1046 $event->trigger();
1048 throw new moodle_exception('wrongusernamepassword', 'webservice');
1051 $user = $DB->get_record('user', array('username'=>$this->username, 'mnethostid'=>$CFG->mnet_localhost_id), '*', MUST_EXIST);
1053 } else if ($this->authmethod == WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN){
1054 $user = $this->authenticate_by_token(EXTERNAL_TOKEN_PERMANENT);
1055 } else {
1056 $user = $this->authenticate_by_token(EXTERNAL_TOKEN_EMBEDDED);
1059 // Cannot authenticate unless maintenance access is granted.
1060 $hasmaintenanceaccess = has_capability('moodle/site:maintenanceaccess', context_system::instance(), $user);
1061 if (!empty($CFG->maintenance_enabled) and !$hasmaintenanceaccess) {
1062 throw new moodle_exception('sitemaintenance', 'admin');
1065 //only confirmed user should be able to call web service
1066 if (!empty($user->deleted)) {
1067 $params = $loginfaileddefaultparams;
1068 $params['other']['reason'] = 'user_deleted';
1069 $params['other']['username'] = $user->username;
1070 $event = \core\event\webservice_login_failed::create($params);
1071 $event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessuserdeleted', 'webservice',
1072 $user->username) . " - ".getremoteaddr(), 0, $user->id));
1073 $event->trigger();
1074 throw new moodle_exception('wsaccessuserdeleted', 'webservice', '', $user->username);
1077 //only confirmed user should be able to call web service
1078 if (empty($user->confirmed)) {
1079 $params = $loginfaileddefaultparams;
1080 $params['other']['reason'] = 'user_unconfirmed';
1081 $params['other']['username'] = $user->username;
1082 $event = \core\event\webservice_login_failed::create($params);
1083 $event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessuserunconfirmed', 'webservice',
1084 $user->username) . " - ".getremoteaddr(), 0, $user->id));
1085 $event->trigger();
1086 throw new moodle_exception('wsaccessuserunconfirmed', 'webservice', '', $user->username);
1089 //check the user is suspended
1090 if (!empty($user->suspended)) {
1091 $params = $loginfaileddefaultparams;
1092 $params['other']['reason'] = 'user_unconfirmed';
1093 $params['other']['username'] = $user->username;
1094 $event = \core\event\webservice_login_failed::create($params);
1095 $event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessusersuspended', 'webservice',
1096 $user->username) . " - ".getremoteaddr(), 0, $user->id));
1097 $event->trigger();
1098 throw new moodle_exception('wsaccessusersuspended', 'webservice', '', $user->username);
1101 //retrieve the authentication plugin if no previously done
1102 if (empty($auth)) {
1103 $auth = get_auth_plugin($user->auth);
1106 // check if credentials have expired
1107 if (!empty($auth->config->expiration) and $auth->config->expiration == 1) {
1108 $days2expire = $auth->password_expire($user->username);
1109 if (intval($days2expire) < 0 ) {
1110 $params = $loginfaileddefaultparams;
1111 $params['other']['reason'] = 'password_expired';
1112 $params['other']['username'] = $user->username;
1113 $event = \core\event\webservice_login_failed::create($params);
1114 $event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessuserexpired', 'webservice',
1115 $user->username) . " - ".getremoteaddr(), 0, $user->id));
1116 $event->trigger();
1117 throw new moodle_exception('wsaccessuserexpired', 'webservice', '', $user->username);
1121 //check if the auth method is nologin (in this case refuse connection)
1122 if ($user->auth=='nologin') {
1123 $params = $loginfaileddefaultparams;
1124 $params['other']['reason'] = 'login';
1125 $params['other']['username'] = $user->username;
1126 $event = \core\event\webservice_login_failed::create($params);
1127 $event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessusernologin', 'webservice',
1128 $user->username) . " - ".getremoteaddr(), 0, $user->id));
1129 $event->trigger();
1130 throw new moodle_exception('wsaccessusernologin', 'webservice', '', $user->username);
1133 // now fake user login, the session is completely empty too
1134 enrol_check_plugins($user);
1135 \core\session\manager::set_user($user);
1136 set_login_session_preferences();
1137 $this->userid = $user->id;
1139 if ($this->authmethod != WEBSERVICE_AUTHMETHOD_SESSION_TOKEN && !has_capability("webservice/$this->wsname:use", $this->restricted_context)) {
1140 throw new webservice_access_exception('You are not allowed to use the {$a} protocol (missing capability: webservice/' . $this->wsname . ':use)');
1143 external_api::set_context_restriction($this->restricted_context);
1147 * User authentication by token
1149 * @param string $tokentype token type (EXTERNAL_TOKEN_EMBEDDED or EXTERNAL_TOKEN_PERMANENT)
1150 * @return stdClass the authenticated user
1151 * @throws webservice_access_exception
1153 protected function authenticate_by_token($tokentype){
1154 global $DB;
1156 $loginfaileddefaultparams = array(
1157 'other' => array(
1158 'method' => $this->authmethod,
1159 'reason' => null
1163 if (!$token = $DB->get_record('external_tokens', array('token'=>$this->token, 'tokentype'=>$tokentype))) {
1164 // Log failed login attempts.
1165 $params = $loginfaileddefaultparams;
1166 $params['other']['reason'] = 'invalid_token';
1167 $event = \core\event\webservice_login_failed::create($params);
1168 $event->set_legacy_logdata(array(SITEID, 'webservice', get_string('tokenauthlog', 'webservice'), '' ,
1169 get_string('failedtolog', 'webservice').": ".$this->token. " - ".getremoteaddr() , 0));
1170 $event->trigger();
1171 throw new moodle_exception('invalidtoken', 'webservice');
1174 if ($token->validuntil and $token->validuntil < time()) {
1175 $DB->delete_records('external_tokens', array('token'=>$this->token, 'tokentype'=>$tokentype));
1176 throw new webservice_access_exception('Invalid token - token expired - check validuntil time for the token');
1179 if ($token->sid){//assumes that if sid is set then there must be a valid associated session no matter the token type
1180 if (!\core\session\manager::session_exists($token->sid)){
1181 $DB->delete_records('external_tokens', array('sid'=>$token->sid));
1182 throw new webservice_access_exception('Invalid session based token - session not found or expired');
1186 if ($token->iprestriction and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
1187 $params = $loginfaileddefaultparams;
1188 $params['other']['reason'] = 'ip_restricted';
1189 $params['other']['tokenid'] = $token->id;
1190 $event = \core\event\webservice_login_failed::create($params);
1191 $event->add_record_snapshot('external_tokens', $token);
1192 $event->set_legacy_logdata(array(SITEID, 'webservice', get_string('tokenauthlog', 'webservice'), '' ,
1193 get_string('failedtolog', 'webservice').": ".getremoteaddr() , 0));
1194 $event->trigger();
1195 throw new webservice_access_exception('Invalid service - IP:' . getremoteaddr()
1196 . ' is not supported - check this allowed user');
1199 $this->restricted_context = context::instance_by_id($token->contextid);
1200 $this->restricted_serviceid = $token->externalserviceid;
1202 $user = $DB->get_record('user', array('id'=>$token->userid), '*', MUST_EXIST);
1204 // log token access
1205 webservice::update_token_lastaccess($token);
1207 return $user;
1212 * Intercept some moodlewssettingXXX $_GET and $_POST parameter
1213 * that are related to the web service call and are not the function parameters
1215 protected function set_web_service_call_settings() {
1216 global $CFG;
1218 // Default web service settings.
1219 // Must be the same XXX key name as the external_settings::set_XXX function.
1220 // Must be the same XXX ws parameter name as 'moodlewssettingXXX'.
1221 $externalsettings = array(
1222 'raw' => array('default' => false, 'type' => PARAM_BOOL),
1223 'fileurl' => array('default' => true, 'type' => PARAM_BOOL),
1224 'filter' => array('default' => false, 'type' => PARAM_BOOL),
1225 'lang' => array('default' => '', 'type' => PARAM_LANG),
1226 'timezone' => array('default' => '', 'type' => PARAM_TIMEZONE),
1229 // Load the external settings with the web service settings.
1230 $settings = external_settings::get_instance();
1231 foreach ($externalsettings as $name => $settingdata) {
1233 $wsparamname = 'moodlewssetting' . $name;
1235 // Retrieve and remove the setting parameter from the request.
1236 $value = optional_param($wsparamname, $settingdata['default'], $settingdata['type']);
1237 unset($_GET[$wsparamname]);
1238 unset($_POST[$wsparamname]);
1240 $functioname = 'set_' . $name;
1241 $settings->$functioname($value);
1248 * Web Service server base class.
1250 * This class handles both simple and token authentication.
1252 * @package core_webservice
1253 * @copyright 2009 Petr Skodak
1254 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1256 abstract class webservice_base_server extends webservice_server {
1258 /** @var array The function parameters - the real values submitted in the request */
1259 protected $parameters = null;
1261 /** @var string The name of the function that is executed */
1262 protected $functionname = null;
1264 /** @var stdClass Full function description */
1265 protected $function = null;
1267 /** @var mixed Function return value */
1268 protected $returns = null;
1270 /** @var array List of methods and their information provided by the web service. */
1271 protected $servicemethods;
1273 /** @var array List of struct classes generated for the web service methods. */
1274 protected $servicestructs;
1277 * This method parses the request input, it needs to get:
1278 * 1/ user authentication - username+password or token
1279 * 2/ function name
1280 * 3/ function parameters
1282 abstract protected function parse_request();
1285 * Send the result of function call to the WS client.
1287 abstract protected function send_response();
1290 * Send the error information to the WS client.
1292 * @param exception $ex
1294 abstract protected function send_error($ex=null);
1297 * Process request from client.
1299 * @uses die
1301 public function run() {
1302 global $CFG, $USER, $SESSION;
1304 // we will probably need a lot of memory in some functions
1305 raise_memory_limit(MEMORY_EXTRA);
1307 // set some longer timeout, this script is not sending any output,
1308 // this means we need to manually extend the timeout operations
1309 // that need longer time to finish
1310 external_api::set_timeout();
1312 // set up exception handler first, we want to sent them back in correct format that
1313 // the other system understands
1314 // we do not need to call the original default handler because this ws handler does everything
1315 set_exception_handler(array($this, 'exception_handler'));
1317 // init all properties from the request data
1318 $this->parse_request();
1320 // authenticate user, this has to be done after the request parsing
1321 // this also sets up $USER and $SESSION
1322 $this->authenticate_user();
1324 // find all needed function info and make sure user may actually execute the function
1325 $this->load_function_info();
1327 // Log the web service request.
1328 $params = array(
1329 'other' => array(
1330 'function' => $this->functionname
1333 $event = \core\event\webservice_function_called::create($params);
1334 $event->set_legacy_logdata(array(SITEID, 'webservice', $this->functionname, '' , getremoteaddr() , 0, $this->userid));
1335 $event->trigger();
1337 // Do additional setup stuff.
1338 $settings = external_settings::get_instance();
1339 $sessionlang = $settings->get_lang();
1340 if (!empty($sessionlang)) {
1341 $SESSION->lang = $sessionlang;
1344 setup_lang_from_browser();
1346 if (empty($CFG->lang)) {
1347 if (empty($SESSION->lang)) {
1348 $CFG->lang = 'en';
1349 } else {
1350 $CFG->lang = $SESSION->lang;
1354 // Change timezone only in sites where it isn't forced.
1355 $newtimezone = $settings->get_timezone();
1356 if (!empty($newtimezone) && (!isset($CFG->forcetimezone) || $CFG->forcetimezone == 99)) {
1357 $USER->timezone = $newtimezone;
1360 // finally, execute the function - any errors are catched by the default exception handler
1361 $this->execute();
1363 // send the results back in correct format
1364 $this->send_response();
1366 // session cleanup
1367 $this->session_cleanup();
1369 die;
1373 * Specialised exception handler, we can not use the standard one because
1374 * it can not just print html to output.
1376 * @param exception $ex
1377 * $uses exit
1379 public function exception_handler($ex) {
1380 // detect active db transactions, rollback and log as error
1381 abort_all_db_transactions();
1383 // some hacks might need a cleanup hook
1384 $this->session_cleanup($ex);
1386 // now let the plugin send the exception to client
1387 $this->send_error($ex);
1389 // not much else we can do now, add some logging later
1390 exit(1);
1394 * Future hook needed for emulated sessions.
1396 * @param exception $exception null means normal termination, $exception received when WS call failed
1398 protected function session_cleanup($exception=null) {
1399 if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
1400 // nothing needs to be done, there is no persistent session
1401 } else {
1402 // close emulated session if used
1407 * Fetches the function description from database,
1408 * verifies user is allowed to use this function and
1409 * loads all paremeters and return descriptions.
1411 protected function load_function_info() {
1412 global $DB, $USER, $CFG;
1414 if (empty($this->functionname)) {
1415 throw new invalid_parameter_exception('Missing function name');
1418 // function must exist
1419 $function = external_api::external_function_info($this->functionname);
1421 if ($this->restricted_serviceid) {
1422 $params = array('sid1'=>$this->restricted_serviceid, 'sid2'=>$this->restricted_serviceid);
1423 $wscond1 = 'AND s.id = :sid1';
1424 $wscond2 = 'AND s.id = :sid2';
1425 } else {
1426 $params = array();
1427 $wscond1 = '';
1428 $wscond2 = '';
1431 // now let's verify access control
1433 // now make sure the function is listed in at least one service user is allowed to use
1434 // allow access only if:
1435 // 1/ entry in the external_services_users table if required
1436 // 2/ validuntil not reached
1437 // 3/ has capability if specified in service desc
1438 // 4/ iprestriction
1440 $sql = "SELECT s.*, NULL AS iprestriction
1441 FROM {external_services} s
1442 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0 AND sf.functionname = :name1)
1443 WHERE s.enabled = 1 $wscond1
1445 UNION
1447 SELECT s.*, su.iprestriction
1448 FROM {external_services} s
1449 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1 AND sf.functionname = :name2)
1450 JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)
1451 WHERE s.enabled = 1 AND (su.validuntil IS NULL OR su.validuntil < :now) $wscond2";
1452 $params = array_merge($params, array('userid'=>$USER->id, 'name1'=>$function->name, 'name2'=>$function->name, 'now'=>time()));
1454 $rs = $DB->get_recordset_sql($sql, $params);
1455 // now make sure user may access at least one service
1456 $remoteaddr = getremoteaddr();
1457 $allowed = false;
1458 foreach ($rs as $service) {
1459 if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) {
1460 continue; // cap required, sorry
1462 if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) {
1463 continue; // wrong request source ip, sorry
1465 $allowed = true;
1466 break; // one service is enough, no need to continue
1468 $rs->close();
1469 if (!$allowed) {
1470 throw new webservice_access_exception(
1471 'Access to the function '.$this->functionname.'() is not allowed.
1472 There could be multiple reasons for this:
1473 1. The service linked to the user token does not contain the function.
1474 2. The service is user-restricted and the user is not listed.
1475 3. The service is IP-restricted and the user IP is not listed.
1476 4. The service is time-restricted and the time has expired.
1477 5. The token is time-restricted and the time has expired.
1478 6. The service requires a specific capability which the user does not have.
1479 7. The function is called with username/password (no user token is sent)
1480 and none of the services has the function to allow the user.
1481 These settings can be found in Administration > Site administration
1482 > Server > Web services > External services and Manage tokens.');
1485 // we have all we need now
1486 $this->function = $function;
1490 * Execute previously loaded function using parameters parsed from the request data.
1492 protected function execute() {
1493 // validate params, this also sorts the params properly, we need the correct order in the next part
1494 $params = call_user_func(array($this->function->classname, 'validate_parameters'), $this->function->parameters_desc, $this->parameters);
1495 $params = array_values($params);
1497 // Allow any Moodle plugin a chance to override this call. This is a convenient spot to
1498 // make arbitrary behaviour customisations, for example to affect the mobile app behaviour.
1499 // The overriding plugin could call the 'real' function first and then modify the results,
1500 // or it could do a completely separate thing.
1501 $callbacks = get_plugins_with_function('override_webservice_execution');
1502 foreach ($callbacks as $plugintype => $plugins) {
1503 foreach ($plugins as $plugin => $callback) {
1504 $result = $callback($this->function, $params);
1505 if ($result !== false) {
1506 // If the callback returns anything other than false, we assume it replaces the
1507 // real function.
1508 $this->returns = $result;
1509 return;
1514 // execute - yay!
1515 $this->returns = call_user_func_array(array($this->function->classname, $this->function->methodname), $params);
1519 * Load the virtual class needed for the web service.
1521 * Initialises the virtual class that contains the web service functions that the user is allowed to use.
1522 * The web service function will be available if the user:
1523 * - is validly registered in the external_services_users table.
1524 * - has the required capability.
1525 * - meets the IP restriction requirement.
1526 * This virtual class can be used by web service protocols such as SOAP, especially when generating WSDL.
1528 protected function init_service_class() {
1529 global $USER, $DB;
1531 // Initialise service methods and struct classes.
1532 $this->servicemethods = array();
1533 $this->servicestructs = array();
1535 $params = array();
1536 $wscond1 = '';
1537 $wscond2 = '';
1538 if ($this->restricted_serviceid) {
1539 $params = array('sid1' => $this->restricted_serviceid, 'sid2' => $this->restricted_serviceid);
1540 $wscond1 = 'AND s.id = :sid1';
1541 $wscond2 = 'AND s.id = :sid2';
1544 $sql = "SELECT s.*, NULL AS iprestriction
1545 FROM {external_services} s
1546 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0)
1547 WHERE s.enabled = 1 $wscond1
1549 UNION
1551 SELECT s.*, su.iprestriction
1552 FROM {external_services} s
1553 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1)
1554 JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)
1555 WHERE s.enabled = 1 AND (su.validuntil IS NULL OR su.validuntil < :now) $wscond2";
1556 $params = array_merge($params, array('userid' => $USER->id, 'now' => time()));
1558 $serviceids = array();
1559 $remoteaddr = getremoteaddr();
1561 // Query list of external services for the user.
1562 $rs = $DB->get_recordset_sql($sql, $params);
1564 // Check which service ID to include.
1565 foreach ($rs as $service) {
1566 if (isset($serviceids[$service->id])) {
1567 continue; // Service already added.
1569 if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) {
1570 continue; // Cap required, sorry.
1572 if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) {
1573 continue; // Wrong request source ip, sorry.
1575 $serviceids[$service->id] = $service->id;
1577 $rs->close();
1579 // Generate the virtual class name.
1580 $classname = 'webservices_virtual_class_000000';
1581 while (class_exists($classname)) {
1582 $classname++;
1584 $this->serviceclass = $classname;
1586 // Get the list of all available external functions.
1587 $wsmanager = new webservice();
1588 $functions = $wsmanager->get_external_functions($serviceids);
1590 // Generate code for the virtual methods for this web service.
1591 $methods = '';
1592 foreach ($functions as $function) {
1593 $methods .= $this->get_virtual_method_code($function);
1596 $code = <<<EOD
1598 * Virtual class web services for user id $USER->id in context {$this->restricted_context->id}.
1600 class $classname {
1601 $methods
1603 EOD;
1604 // Load the virtual class definition into memory.
1605 eval($code);
1609 * Generates a struct class.
1611 * @param external_single_structure $structdesc The basis of the struct class to be generated.
1612 * @return string The class name of the generated struct class.
1614 protected function generate_simple_struct_class(external_single_structure $structdesc) {
1615 global $USER;
1617 $propeties = array();
1618 $fields = array();
1619 foreach ($structdesc->keys as $name => $fieldsdesc) {
1620 $type = $this->get_phpdoc_type($fieldsdesc);
1621 $propertytype = array('type' => $type);
1622 if (empty($fieldsdesc->allownull) || $fieldsdesc->allownull == NULL_ALLOWED) {
1623 $propertytype['nillable'] = true;
1625 $propeties[$name] = $propertytype;
1626 $fields[] = ' /** @var ' . $type . ' $' . $name . '*/';
1627 $fields[] = ' public $' . $name .';';
1629 $fieldsstr = implode("\n", $fields);
1631 // We do this after the call to get_phpdoc_type() to avoid duplicate class creation.
1632 $classname = 'webservices_struct_class_000000';
1633 while (class_exists($classname)) {
1634 $classname++;
1636 $code = <<<EOD
1638 * Virtual struct class for web services for user id $USER->id in context {$this->restricted_context->id}.
1640 class $classname {
1641 $fieldsstr
1643 EOD;
1644 // Load into memory.
1645 eval($code);
1647 // Prepare struct info.
1648 $structinfo = new stdClass();
1649 $structinfo->classname = $classname;
1650 $structinfo->properties = $propeties;
1651 // Add the struct info the the list of service struct classes.
1652 $this->servicestructs[] = $structinfo;
1654 return $classname;
1658 * Returns a virtual method code for a web service function.
1660 * @param stdClass $function a record from external_function
1661 * @return string The PHP code of the virtual method.
1662 * @throws coding_exception
1663 * @throws moodle_exception
1665 protected function get_virtual_method_code($function) {
1666 $function = external_api::external_function_info($function);
1668 // Parameters and their defaults for the method signature.
1669 $paramanddefaults = array();
1670 // Parameters for external lib call.
1671 $params = array();
1672 $paramdesc = array();
1673 // The method's input parameters and their respective types.
1674 $inputparams = array();
1675 // The method's output parameters and their respective types.
1676 $outputparams = array();
1678 foreach ($function->parameters_desc->keys as $name => $keydesc) {
1679 $param = '$' . $name;
1680 $paramanddefault = $param;
1681 if ($keydesc->required == VALUE_OPTIONAL) {
1682 // It does not make sense to declare a parameter VALUE_OPTIONAL. VALUE_OPTIONAL is used only for array/object key.
1683 throw new moodle_exception('erroroptionalparamarray', 'webservice', '', $name);
1684 } else if ($keydesc->required == VALUE_DEFAULT) {
1685 // Need to generate the default, if there is any.
1686 if ($keydesc instanceof external_value) {
1687 if ($keydesc->default === null) {
1688 $paramanddefault .= ' = null';
1689 } else {
1690 switch ($keydesc->type) {
1691 case PARAM_BOOL:
1692 $default = (int)$keydesc->default;
1693 break;
1694 case PARAM_INT:
1695 $default = $keydesc->default;
1696 break;
1697 case PARAM_FLOAT;
1698 $default = $keydesc->default;
1699 break;
1700 default:
1701 $default = "'$keydesc->default'";
1703 $paramanddefault .= " = $default";
1705 } else {
1706 // Accept empty array as default.
1707 if (isset($keydesc->default) && is_array($keydesc->default) && empty($keydesc->default)) {
1708 $paramanddefault .= ' = array()';
1709 } else {
1710 // For the moment we do not support default for other structure types.
1711 throw new moodle_exception('errornotemptydefaultparamarray', 'webservice', '', $name);
1716 $params[] = $param;
1717 $paramanddefaults[] = $paramanddefault;
1718 $type = $this->get_phpdoc_type($keydesc);
1719 $inputparams[$name]['type'] = $type;
1721 $paramdesc[] = '* @param ' . $type . ' $' . $name . ' ' . $keydesc->desc;
1723 $paramanddefaults = implode(', ', $paramanddefaults);
1724 $paramdescstr = implode("\n ", $paramdesc);
1726 $serviceclassmethodbody = $this->service_class_method_body($function, $params);
1728 if (empty($function->returns_desc)) {
1729 $return = '* @return void';
1730 } else {
1731 $type = $this->get_phpdoc_type($function->returns_desc);
1732 $outputparams['return']['type'] = $type;
1733 $return = '* @return ' . $type . ' ' . $function->returns_desc->desc;
1736 // Now create the virtual method that calls the ext implementation.
1737 $code = <<<EOD
1739 * $function->description.
1741 $paramdescstr
1742 $return
1744 public function $function->name($paramanddefaults) {
1745 $serviceclassmethodbody
1747 EOD;
1749 // Prepare the method information.
1750 $methodinfo = new stdClass();
1751 $methodinfo->name = $function->name;
1752 $methodinfo->inputparams = $inputparams;
1753 $methodinfo->outputparams = $outputparams;
1754 $methodinfo->description = $function->description;
1755 // Add the method information into the list of service methods.
1756 $this->servicemethods[] = $methodinfo;
1758 return $code;
1762 * Get the phpdoc type for an external_description object.
1763 * external_value => int, double or string
1764 * external_single_structure => object|struct, on-fly generated stdClass name.
1765 * external_multiple_structure => array
1767 * @param mixed $keydesc The type description.
1768 * @return string The PHP doc type of the external_description object.
1770 protected function get_phpdoc_type($keydesc) {
1771 $type = null;
1772 if ($keydesc instanceof external_value) {
1773 switch ($keydesc->type) {
1774 case PARAM_BOOL: // 0 or 1 only for now.
1775 case PARAM_INT:
1776 $type = 'int';
1777 break;
1778 case PARAM_FLOAT;
1779 $type = 'double';
1780 break;
1781 default:
1782 $type = 'string';
1784 } else if ($keydesc instanceof external_single_structure) {
1785 $type = $this->generate_simple_struct_class($keydesc);
1786 } else if ($keydesc instanceof external_multiple_structure) {
1787 $type = 'array';
1790 return $type;
1794 * Generates the method body of the virtual external function.
1796 * @param stdClass $function a record from external_function.
1797 * @param array $params web service function parameters.
1798 * @return string body of the method for $function ie. everything within the {} of the method declaration.
1800 protected function service_class_method_body($function, $params) {
1801 // Cast the param from object to array (validate_parameters except array only).
1802 $castingcode = '';
1803 $paramsstr = '';
1804 if (!empty($params)) {
1805 foreach ($params as $paramtocast) {
1806 // Clean the parameter from any white space.
1807 $paramtocast = trim($paramtocast);
1808 $castingcode .= " $paramtocast = json_decode(json_encode($paramtocast), true);\n";
1810 $paramsstr = implode(', ', $params);
1813 $descriptionmethod = $function->methodname . '_returns()';
1814 $callforreturnvaluedesc = $function->classname . '::' . $descriptionmethod;
1816 $methodbody = <<<EOD
1817 $castingcode
1818 if ($callforreturnvaluedesc == null) {
1819 $function->classname::$function->methodname($paramsstr);
1820 return null;
1822 return external_api::clean_returnvalue($callforreturnvaluedesc, $function->classname::$function->methodname($paramsstr));
1823 EOD;
1824 return $methodbody;
1829 * Early WS exception handler.
1830 * It handles exceptions during setup and returns the Exception text in the WS format.
1831 * If a raise function is found nothing is returned. Throws Exception otherwise.
1833 * @param Exception $ex Raised exception.
1834 * @throws Exception
1836 function early_ws_exception_handler(Exception $ex): void {
1837 if (function_exists('raise_early_ws_exception')) {
1838 raise_early_ws_exception($ex);
1839 die;
1842 throw $ex;