Merge branch 'MDL-31101_21' of git://github.com/timhunt/moodle into MOODLE_21_STABLE
[moodle.git] / webservice / lib.php
blobfe5ec3dd3ddb48af81670d097983bda339c2d3b6
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Web services utility functions and classes
21 * @package webservice
22 * @copyright 2009 Moodle Pty Ltd (http://moodle.com)
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 require_once($CFG->libdir.'/externallib.php');
28 define('WEBSERVICE_AUTHMETHOD_USERNAME', 0);
29 define('WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN', 1);
30 define('WEBSERVICE_AUTHMETHOD_SESSION_TOKEN', 2);
32 /**
33 * General web service library
35 class webservice {
37 /**
38 * Authenticate user (used by download/upload file scripts)
39 * @param string $token
40 * @return array - contains the authenticated user, token and service objects
42 public function authenticate_user($token) {
43 global $DB, $CFG;
45 // web service must be enabled to use this script
46 if (!$CFG->enablewebservices) {
47 throw new webservice_access_exception(get_string('enablewsdescription', 'webservice'));
50 // Obtain token record
51 if (!$token = $DB->get_record('external_tokens', array('token' => $token))) {
52 throw new webservice_access_exception(get_string('invalidtoken', 'webservice'));
55 // Validate token date
56 if ($token->validuntil and $token->validuntil < time()) {
57 add_to_log(SITEID, 'webservice', get_string('tokenauthlog', 'webservice'), '', get_string('invalidtimedtoken', 'webservice'), 0);
58 $DB->delete_records('external_tokens', array('token' => $token->token));
59 throw new webservice_access_exception(get_string('invalidtimedtoken', 'webservice'));
62 // Check ip
63 if ($token->iprestriction and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
64 add_to_log(SITEID, 'webservice', get_string('tokenauthlog', 'webservice'), '', get_string('failedtolog', 'webservice') . ": " . getremoteaddr(), 0);
65 throw new webservice_access_exception(get_string('invalidiptoken', 'webservice'));
68 //retrieve the user info from the token
69 $user = $DB->get_record('user', array('id' => $token->userid, 'deleted' => 0), '*', MUST_EXIST);
71 // setup user session to check capability
72 session_set_user($user);
74 //assumes that if sid is set then there must be a valid associated session no matter the token type
75 if ($token->sid) {
76 $session = session_get_instance();
77 if (!$session->session_exists($token->sid)) {
78 $DB->delete_records('external_tokens', array('sid' => $token->sid));
79 throw new webservice_access_exception(get_string('invalidtokensession', 'webservice'));
83 //Refuse non-admin authentication in maintenance mode
84 $hassiteconfig = has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM), $user);
85 if (!empty($CFG->maintenance_enabled) and !$hassiteconfig) {
86 throw new webservice_access_exception(get_string('sitemaintenance', 'admin'));
89 //retrieve web service record
90 $service = $DB->get_record('external_services', array('id' => $token->externalserviceid, 'enabled' => 1));
91 if (empty($service)) {
92 // will throw exception if no token found
93 throw new webservice_access_exception(get_string('servicenotavailable', 'webservice'));
96 //check if there is any required system capability
97 if ($service->requiredcapability and !has_capability($service->requiredcapability, get_context_instance(CONTEXT_SYSTEM), $user)) {
98 throw new webservice_access_exception(get_string('missingrequiredcapability', 'webservice', $service->requiredcapability));
101 //specific checks related to user restricted service
102 if ($service->restrictedusers) {
103 $authoriseduser = $DB->get_record('external_services_users', array('externalserviceid' => $service->id, 'userid' => $user->id));
105 if (empty($authoriseduser)) {
106 throw new webservice_access_exception(get_string('usernotallowed', 'webservice', $service->name));
109 if (!empty($authoriseduser->validuntil) and $authoriseduser->validuntil < time()) {
110 throw new webservice_access_exception(get_string('invalidtimedtoken', 'webservice'));
113 if (!empty($authoriseduser->iprestriction) and !address_in_subnet(getremoteaddr(), $authoriseduser->iprestriction)) {
114 throw new webservice_access_exception(get_string('invalidiptoken', 'webservice'));
118 //only confirmed user should be able to call web service
119 if (empty($user->confirmed)) {
120 add_to_log(SITEID, 'webservice', 'user unconfirmed', '', $user->username);
121 throw new webservice_access_exception(get_string('usernotconfirmed', 'moodle', $user->username));
124 //check the user is suspended
125 if (!empty($user->suspended)) {
126 add_to_log(SITEID, 'webservice', 'user suspended', '', $user->username);
127 throw new webservice_access_exception(get_string('usersuspended', 'webservice'));
130 //check if the auth method is nologin (in this case refuse connection)
131 if ($user->auth == 'nologin') {
132 add_to_log(SITEID, 'webservice', 'nologin auth attempt with web service', '', $user->username);
133 throw new webservice_access_exception(get_string('nologinauth', 'webservice'));
136 //Check if the user password is expired
137 $auth = get_auth_plugin($user->auth);
138 if (!empty($auth->config->expiration) and $auth->config->expiration == 1) {
139 $days2expire = $auth->password_expire($user->username);
140 if (intval($days2expire) < 0) {
141 add_to_log(SITEID, 'webservice', 'expired password', '', $user->username);
142 throw new webservice_access_exception(get_string('passwordisexpired', 'webservice'));
146 // log token access
147 $DB->set_field('external_tokens', 'lastaccess', time(), array('id' => $token->id));
149 return array('user' => $user, 'token' => $token, 'service' => $service);
154 * Add a user to the list of authorised user of a given service
155 * @param object $user
157 public function add_ws_authorised_user($user) {
158 global $DB;
159 $user->timecreated = mktime();
160 $DB->insert_record('external_services_users', $user);
164 * Remove a user from a list of allowed user of a service
165 * @param object $user
166 * @param int $serviceid
168 public function remove_ws_authorised_user($user, $serviceid) {
169 global $DB;
170 $DB->delete_records('external_services_users',
171 array('externalserviceid' => $serviceid, 'userid' => $user->id));
175 * Update service allowed user settings
176 * @param object $user
178 public function update_ws_authorised_user($user) {
179 global $DB;
180 $DB->update_record('external_services_users', $user);
184 * Return list of allowed users with their options (ip/timecreated / validuntil...)
185 * for a given service
186 * @param int $serviceid
187 * @return array $users
189 public function get_ws_authorised_users($serviceid) {
190 global $DB, $CFG;
191 $params = array($CFG->siteguest, $serviceid);
192 $sql = " SELECT u.id as id, esu.id as serviceuserid, u.email as email, u.firstname as firstname,
193 u.lastname as lastname,
194 esu.iprestriction as iprestriction, esu.validuntil as validuntil,
195 esu.timecreated as timecreated
196 FROM {user} u, {external_services_users} esu
197 WHERE u.id <> ? AND u.deleted = 0 AND u.confirmed = 1
198 AND esu.userid = u.id
199 AND esu.externalserviceid = ?";
201 $users = $DB->get_records_sql($sql, $params);
202 return $users;
206 * Return a authorised user with his options (ip/timecreated / validuntil...)
207 * @param int $serviceid
208 * @param int $userid
209 * @return object
211 public function get_ws_authorised_user($serviceid, $userid) {
212 global $DB, $CFG;
213 $params = array($CFG->siteguest, $serviceid, $userid);
214 $sql = " SELECT u.id as id, esu.id as serviceuserid, u.email as email, u.firstname as firstname,
215 u.lastname as lastname,
216 esu.iprestriction as iprestriction, esu.validuntil as validuntil,
217 esu.timecreated as timecreated
218 FROM {user} u, {external_services_users} esu
219 WHERE u.id <> ? AND u.deleted = 0 AND u.confirmed = 1
220 AND esu.userid = u.id
221 AND esu.externalserviceid = ?
222 AND u.id = ?";
223 $user = $DB->get_record_sql($sql, $params);
224 return $user;
228 * Generate all ws token needed by a user
229 * @param int $userid
231 public function generate_user_ws_tokens($userid) {
232 global $CFG, $DB;
234 /// generate a token for non admin if web service are enable and the user has the capability to create a token
235 if (!is_siteadmin() && has_capability('moodle/webservice:createtoken', get_context_instance(CONTEXT_SYSTEM), $userid) && !empty($CFG->enablewebservices)) {
236 /// for every service than the user is authorised on, create a token (if it doesn't already exist)
238 ///get all services which are set to all user (no restricted to specific users)
239 $norestrictedservices = $DB->get_records('external_services', array('restrictedusers' => 0));
240 $serviceidlist = array();
241 foreach ($norestrictedservices as $service) {
242 $serviceidlist[] = $service->id;
245 //get all services which are set to the current user (the current user is specified in the restricted user list)
246 $servicesusers = $DB->get_records('external_services_users', array('userid' => $userid));
247 foreach ($servicesusers as $serviceuser) {
248 if (!in_array($serviceuser->externalserviceid,$serviceidlist)) {
249 $serviceidlist[] = $serviceuser->externalserviceid;
253 //get all services which already have a token set for the current user
254 $usertokens = $DB->get_records('external_tokens', array('userid' => $userid, 'tokentype' => EXTERNAL_TOKEN_PERMANENT));
255 $tokenizedservice = array();
256 foreach ($usertokens as $token) {
257 $tokenizedservice[] = $token->externalserviceid;
260 //create a token for the service which have no token already
261 foreach ($serviceidlist as $serviceid) {
262 if (!in_array($serviceid, $tokenizedservice)) {
263 //create the token for this service
264 $newtoken = new stdClass();
265 $newtoken->token = md5(uniqid(rand(),1));
266 //check that the user has capability on this service
267 $newtoken->tokentype = EXTERNAL_TOKEN_PERMANENT;
268 $newtoken->userid = $userid;
269 $newtoken->externalserviceid = $serviceid;
270 //TODO: find a way to get the context - UPDATE FOLLOWING LINE
271 $newtoken->contextid = get_context_instance(CONTEXT_SYSTEM)->id;
272 $newtoken->creatorid = $userid;
273 $newtoken->timecreated = time();
275 $DB->insert_record('external_tokens', $newtoken);
284 * Return all ws user token with ws enabled/disabled and ws restricted users mode.
285 * @param integer $userid
286 * @return array of token
288 public function get_user_ws_tokens($userid) {
289 global $DB;
290 //here retrieve token list (including linked users firstname/lastname and linked services name)
291 $sql = "SELECT
292 t.id, t.creatorid, t.token, u.firstname, u.lastname, s.id as wsid, s.name, s.enabled, s.restrictedusers, t.validuntil
293 FROM
294 {external_tokens} t, {user} u, {external_services} s
295 WHERE
296 t.userid=? AND t.tokentype = ".EXTERNAL_TOKEN_PERMANENT." AND s.id = t.externalserviceid AND t.userid = u.id";
297 $tokens = $DB->get_records_sql($sql, array( $userid));
298 return $tokens;
302 * Return a user token that has been created by the user
303 * If doesn't exist a exception is thrown
304 * @param integer $userid
305 * @param integer $tokenid
306 * @return object token
307 * ->id token id
308 * ->token
309 * ->firstname user firstname
310 * ->lastname
311 * ->name service name
313 public function get_created_by_user_ws_token($userid, $tokenid) {
314 global $DB;
315 $sql = "SELECT
316 t.id, t.token, u.firstname, u.lastname, s.name
317 FROM
318 {external_tokens} t, {user} u, {external_services} s
319 WHERE
320 t.creatorid=? AND t.id=? AND t.tokentype = "
321 . EXTERNAL_TOKEN_PERMANENT
322 . " AND s.id = t.externalserviceid AND t.userid = u.id";
323 //must be the token creator
324 $token = $DB->get_record_sql($sql, array($userid, $tokenid), MUST_EXIST);
325 return $token;
329 * Return a token for a given id
330 * @param integer $tokenid
331 * @return object token
333 public function get_token_by_id($tokenid) {
334 global $DB;
335 return $DB->get_record('external_tokens', array('id' => $tokenid));
339 * Delete a user token
340 * @param int $tokenid
342 public function delete_user_ws_token($tokenid) {
343 global $DB;
344 $DB->delete_records('external_tokens', array('id'=>$tokenid));
348 * Delete a service - it also delete the functions and users references to this service
349 * @param int $serviceid
351 public function delete_service($serviceid) {
352 global $DB;
353 $DB->delete_records('external_services_users', array('externalserviceid' => $serviceid));
354 $DB->delete_records('external_services_functions', array('externalserviceid' => $serviceid));
355 $DB->delete_records('external_tokens', array('externalserviceid' => $serviceid));
356 $DB->delete_records('external_services', array('id' => $serviceid));
360 * Get a user token by token
361 * @param string $token
362 * @throws moodle_exception if there is multiple result
364 public function get_user_ws_token($token) {
365 global $DB;
366 return $DB->get_record('external_tokens', array('token'=>$token), '*', MUST_EXIST);
370 * Get the list of all functions for given service ids
371 * @param array $serviceids
372 * @return array functions
374 public function get_external_functions($serviceids) {
375 global $DB;
376 if (!empty($serviceids)) {
377 list($serviceids, $params) = $DB->get_in_or_equal($serviceids);
378 $sql = "SELECT f.*
379 FROM {external_functions} f
380 WHERE f.name IN (SELECT sf.functionname
381 FROM {external_services_functions} sf
382 WHERE sf.externalserviceid $serviceids)";
383 $functions = $DB->get_records_sql($sql, $params);
384 } else {
385 $functions = array();
387 return $functions;
391 * Get the list of all functions for given service shortnames
392 * @param array $serviceshortnames
393 * @param $enabledonly if true then only return function for the service that has been enabled
394 * @return array functions
396 public function get_external_functions_by_enabled_services($serviceshortnames, $enabledonly = true) {
397 global $DB;
398 if (!empty($serviceshortnames)) {
399 $enabledonlysql = $enabledonly?' AND s.enabled = 1 ':'';
400 list($serviceshortnames, $params) = $DB->get_in_or_equal($serviceshortnames);
401 $sql = "SELECT f.*
402 FROM {external_functions} f
403 WHERE f.name IN (SELECT sf.functionname
404 FROM {external_services_functions} sf, {external_services} s
405 WHERE s.shortname $serviceshortnames
406 AND sf.externalserviceid = s.id
407 " . $enabledonlysql . ")";
408 $functions = $DB->get_records_sql($sql, $params);
409 } else {
410 $functions = array();
412 return $functions;
416 * Get the list of all functions not in the given service id
417 * @param int $serviceid
418 * @return array functions
420 public function get_not_associated_external_functions($serviceid) {
421 global $DB;
422 $select = "name NOT IN (SELECT s.functionname
423 FROM {external_services_functions} s
424 WHERE s.externalserviceid = :sid
427 $functions = $DB->get_records_select('external_functions',
428 $select, array('sid' => $serviceid), 'name');
430 return $functions;
434 * Get list of required capabilities of a service, sorted by functions
435 * @param integer $serviceid
436 * @return array
437 * example of return value:
438 * Array
440 * [moodle_group_create_groups] => Array
442 * [0] => moodle/course:managegroups
445 * [moodle_enrol_get_enrolled_users] => Array
447 * [0] => moodle/site:viewparticipants
448 * [1] => moodle/course:viewparticipants
449 * [2] => moodle/role:review
450 * [3] => moodle/site:accessallgroups
451 * [4] => moodle/course:enrolreview
455 public function get_service_required_capabilities($serviceid) {
456 $functions = $this->get_external_functions(array($serviceid));
457 $requiredusercaps = array();
458 foreach ($functions as $function) {
459 $functioncaps = explode(',', $function->capabilities);
460 if (!empty($functioncaps) and !empty($functioncaps[0])) {
461 foreach ($functioncaps as $functioncap) {
462 $requiredusercaps[$function->name][] = trim($functioncap);
466 return $requiredusercaps;
470 * Get user capabilities (with context)
471 * Only usefull for documentation purpose
472 * @param integer $userid
473 * @return array
475 public function get_user_capabilities($userid) {
476 global $DB;
477 //retrieve the user capabilities
478 $sql = "SELECT rc.id, rc.capability FROM {role_capabilities} rc, {role_assignments} ra
479 WHERE rc.roleid=ra.roleid AND ra.userid= ?";
480 $dbusercaps = $DB->get_records_sql($sql, array($userid));
481 $usercaps = array();
482 foreach ($dbusercaps as $usercap) {
483 $usercaps[$usercap->capability] = true;
485 return $usercaps;
489 * Get users missing capabilities for a given service
490 * @param array $users
491 * @param integer $serviceid
492 * @return array of missing capabilities, the key being the user id
494 public function get_missing_capabilities_by_users($users, $serviceid) {
495 global $DB;
496 $usersmissingcaps = array();
498 //retrieve capabilities required by the service
499 $servicecaps = $this->get_service_required_capabilities($serviceid);
501 //retrieve users missing capabilities
502 foreach ($users as $user) {
503 //cast user array into object to be a bit more flexible
504 if (is_array($user)) {
505 $user = (object) $user;
507 $usercaps = $this->get_user_capabilities($user->id);
509 //detect the missing capabilities
510 foreach ($servicecaps as $functioname => $functioncaps) {
511 foreach ($functioncaps as $functioncap) {
512 if (!key_exists($functioncap, $usercaps)) {
513 if (!isset($usersmissingcaps[$user->id])
514 or array_search($functioncap, $usersmissingcaps[$user->id]) === false) {
515 $usersmissingcaps[$user->id][] = $functioncap;
522 return $usersmissingcaps;
526 * Get a external service for a given id
527 * @param service id $serviceid
528 * @param integer $strictness IGNORE_MISSING, MUST_EXIST...
529 * @return object external service
531 public function get_external_service_by_id($serviceid, $strictness=IGNORE_MISSING) {
532 global $DB;
533 $service = $DB->get_record('external_services',
534 array('id' => $serviceid), '*', $strictness);
535 return $service;
539 * Get a external service for a given shortname
540 * @param service shortname $shortname
541 * @param integer $strictness IGNORE_MISSING, MUST_EXIST...
542 * @return object external service
544 public function get_external_service_by_shortname($shortname, $strictness=IGNORE_MISSING) {
545 global $DB;
546 $service = $DB->get_record('external_services',
547 array('shortname' => $shortname), '*', $strictness);
548 return $service;
552 * Get a external function for a given id
553 * @param function id $functionid
554 * @param integer $strictness IGNORE_MISSING, MUST_EXIST...
555 * @return object external function
557 public function get_external_function_by_id($functionid, $strictness=IGNORE_MISSING) {
558 global $DB;
559 $function = $DB->get_record('external_functions',
560 array('id' => $functionid), '*', $strictness);
561 return $function;
565 * Add a function to a service
566 * @param string $functionname
567 * @param integer $serviceid
569 public function add_external_function_to_service($functionname, $serviceid) {
570 global $DB;
571 $addedfunction = new stdClass();
572 $addedfunction->externalserviceid = $serviceid;
573 $addedfunction->functionname = $functionname;
574 $DB->insert_record('external_services_functions', $addedfunction);
578 * Add a service
579 * @param object $service
580 * @return serviceid integer
582 public function add_external_service($service) {
583 global $DB;
584 $service->timecreated = mktime();
585 $serviceid = $DB->insert_record('external_services', $service);
586 return $serviceid;
590 * Update a service
591 * @param object $service
593 public function update_external_service($service) {
594 global $DB;
595 $service->timemodified = mktime();
596 $DB->update_record('external_services', $service);
600 * Test whether a external function is already linked to a service
601 * @param string $functionname
602 * @param integer $serviceid
603 * @return bool true if a matching function exists for the service, else false.
604 * @throws dml_exception if error
606 public function service_function_exists($functionname, $serviceid) {
607 global $DB;
608 return $DB->record_exists('external_services_functions',
609 array('externalserviceid' => $serviceid,
610 'functionname' => $functionname));
613 public function remove_external_function_from_service($functionname, $serviceid) {
614 global $DB;
615 $DB->delete_records('external_services_functions',
616 array('externalserviceid' => $serviceid, 'functionname' => $functionname));
624 * Exception indicating access control problem in web service call
625 * @author Petr Skoda (skodak)
627 class webservice_access_exception extends moodle_exception {
629 * Constructor
631 function __construct($debuginfo) {
632 parent::__construct('accessexception', 'webservice', '', null, $debuginfo);
637 * Is protocol enabled?
638 * @param string $protocol name of WS protocol
639 * @return bool
641 function webservice_protocol_is_enabled($protocol) {
642 global $CFG;
644 if (empty($CFG->enablewebservices)) {
645 return false;
648 $active = explode(',', $CFG->webserviceprotocols);
650 return(in_array($protocol, $active));
653 //=== WS classes ===
656 * Mandatory interface for all test client classes.
657 * @author Petr Skoda (skodak)
659 interface webservice_test_client_interface {
661 * Execute test client WS request
662 * @param string $serverurl
663 * @param string $function
664 * @param array $params
665 * @return mixed
667 public function simpletest($serverurl, $function, $params);
671 * Mandatory interface for all web service protocol classes
672 * @author Petr Skoda (skodak)
674 interface webservice_server_interface {
676 * Process request from client.
677 * @return void
679 public function run();
683 * Abstract web service base class.
684 * @author Petr Skoda (skodak)
686 abstract class webservice_server implements webservice_server_interface {
688 /** @property string $wsname name of the web server plugin */
689 protected $wsname = null;
691 /** @property string $username name of local user */
692 protected $username = null;
694 /** @property string $password password of the local user */
695 protected $password = null;
697 /** @property int $userid the local user */
698 protected $userid = null;
700 /** @property integer $authmethod authentication method one of WEBSERVICE_AUTHMETHOD_* */
701 protected $authmethod;
703 /** @property string $token authentication token*/
704 protected $token = null;
706 /** @property object restricted context */
707 protected $restricted_context;
709 /** @property int restrict call to one service id*/
710 protected $restricted_serviceid = null;
713 * Contructor
714 * @param integer $authmethod authentication method one of WEBSERVICE_AUTHMETHOD_*
716 public function __construct($authmethod) {
717 $this->authmethod = $authmethod;
722 * Authenticate user using username+password or token.
723 * This function sets up $USER global.
724 * It is safe to use has_capability() after this.
725 * This method also verifies user is allowed to use this
726 * server.
727 * @return void
729 protected function authenticate_user() {
730 global $CFG, $DB;
732 if (!NO_MOODLE_COOKIES) {
733 throw new coding_exception('Cookies must be disabled in WS servers!');
736 if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
738 //we check that authentication plugin is enabled
739 //it is only required by simple authentication
740 if (!is_enabled_auth('webservice')) {
741 throw new webservice_access_exception(get_string('wsauthnotenabled', 'webservice'));
744 if (!$auth = get_auth_plugin('webservice')) {
745 throw new webservice_access_exception(get_string('wsauthmissing', 'webservice'));
748 $this->restricted_context = get_context_instance(CONTEXT_SYSTEM);
750 if (!$this->username) {
751 throw new webservice_access_exception(get_string('missingusername', 'webservice'));
754 if (!$this->password) {
755 throw new webservice_access_exception(get_string('missingpassword', 'webservice'));
758 if (!$auth->user_login_webservice($this->username, $this->password)) {
759 // log failed login attempts
760 add_to_log(SITEID, 'webservice', get_string('simpleauthlog', 'webservice'), '' , get_string('failedtolog', 'webservice').": ".$this->username."/".$this->password." - ".getremoteaddr() , 0);
761 throw new webservice_access_exception(get_string('wrongusernamepassword', 'webservice'));
764 $user = $DB->get_record('user', array('username'=>$this->username, 'mnethostid'=>$CFG->mnet_localhost_id), '*', MUST_EXIST);
766 } else if ($this->authmethod == WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN){
767 $user = $this->authenticate_by_token(EXTERNAL_TOKEN_PERMANENT);
768 } else {
769 $user = $this->authenticate_by_token(EXTERNAL_TOKEN_EMBEDDED);
772 //Non admin can not authenticate if maintenance mode
773 $hassiteconfig = has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM), $user);
774 if (!empty($CFG->maintenance_enabled) and !$hassiteconfig) {
775 throw new webservice_access_exception(get_string('sitemaintenance', 'admin'));
778 //only confirmed user should be able to call web service
779 if (!empty($user->deleted)) {
780 add_to_log(SITEID, '', '', '', get_string('wsaccessuserdeleted', 'webservice', $user->username) . " - ".getremoteaddr(), 0, $user->id);
781 throw new webservice_access_exception(get_string('wsaccessuserdeleted', 'webservice', $user->username));
784 //only confirmed user should be able to call web service
785 if (empty($user->confirmed)) {
786 add_to_log(SITEID, '', '', '', get_string('wsaccessuserunconfirmed', 'webservice', $user->username) . " - ".getremoteaddr(), 0, $user->id);
787 throw new webservice_access_exception(get_string('wsaccessuserunconfirmed', 'webservice', $user->username));
790 //check the user is suspended
791 if (!empty($user->suspended)) {
792 add_to_log(SITEID, '', '', '', get_string('wsaccessusersuspended', 'webservice', $user->username) . " - ".getremoteaddr(), 0, $user->id);
793 throw new webservice_access_exception(get_string('wsaccessusersuspended', 'webservice', $user->username));
796 //retrieve the authentication plugin if no previously done
797 if (empty($auth)) {
798 $auth = get_auth_plugin($user->auth);
801 // check if credentials have expired
802 if (!empty($auth->config->expiration) and $auth->config->expiration == 1) {
803 $days2expire = $auth->password_expire($user->username);
804 if (intval($days2expire) < 0 ) {
805 add_to_log(SITEID, '', '', '', get_string('wsaccessuserexpired', 'webservice', $user->username) . " - ".getremoteaddr(), 0, $user->id);
806 throw new webservice_access_exception(get_string('wsaccessuserexpired', 'webservice', $user->username));
810 //check if the auth method is nologin (in this case refuse connection)
811 if ($user->auth=='nologin') {
812 add_to_log(SITEID, '', '', '', get_string('wsaccessusernologin', 'webservice', $user->username) . " - ".getremoteaddr(), 0, $user->id);
813 throw new webservice_access_exception(get_string('wsaccessusernologin', 'webservice', $user->username));
816 // now fake user login, the session is completely empty too
817 session_set_user($user);
818 $this->userid = $user->id;
820 if ($this->authmethod != WEBSERVICE_AUTHMETHOD_SESSION_TOKEN && !has_capability("webservice/$this->wsname:use", $this->restricted_context)) {
821 throw new webservice_access_exception(get_string('accessnotallowed', 'webservice'));
824 external_api::set_context_restriction($this->restricted_context);
827 protected function authenticate_by_token($tokentype){
828 global $DB;
829 if (!$token = $DB->get_record('external_tokens', array('token'=>$this->token, 'tokentype'=>$tokentype))) {
830 // log failed login attempts
831 add_to_log(SITEID, 'webservice', get_string('tokenauthlog', 'webservice'), '' , get_string('failedtolog', 'webservice').": ".$this->token. " - ".getremoteaddr() , 0);
832 throw new webservice_access_exception(get_string('invalidtoken', 'webservice'));
835 if ($token->validuntil and $token->validuntil < time()) {
836 $DB->delete_records('external_tokens', array('token'=>$this->token, 'tokentype'=>$tokentype));
837 throw new webservice_access_exception(get_string('invalidtimedtoken', 'webservice'));
840 if ($token->sid){//assumes that if sid is set then there must be a valid associated session no matter the token type
841 $session = session_get_instance();
842 if (!$session->session_exists($token->sid)){
843 $DB->delete_records('external_tokens', array('sid'=>$token->sid));
844 throw new webservice_access_exception(get_string('invalidtokensession', 'webservice'));
848 if ($token->iprestriction and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
849 add_to_log(SITEID, 'webservice', get_string('tokenauthlog', 'webservice'), '' , get_string('failedtolog', 'webservice').": ".getremoteaddr() , 0);
850 throw new webservice_access_exception(get_string('invalidiptoken', 'webservice'));
853 $this->restricted_context = get_context_instance_by_id($token->contextid);
854 $this->restricted_serviceid = $token->externalserviceid;
856 $user = $DB->get_record('user', array('id'=>$token->userid), '*', MUST_EXIST);
858 // log token access
859 $DB->set_field('external_tokens', 'lastaccess', time(), array('id'=>$token->id));
861 return $user;
867 * Special abstraction of our srvices that allows
868 * interaction with stock Zend ws servers.
869 * @author Petr Skoda (skodak)
871 abstract class webservice_zend_server extends webservice_server {
873 /** @property string name of the zend server class : Zend_XmlRpc_Server, Zend_Soap_Server, Zend_Soap_AutoDiscover, ...*/
874 protected $zend_class;
876 /** @property object Zend server instance */
877 protected $zend_server;
879 /** @property string $service_class virtual web service class with all functions user name execute, created on the fly */
880 protected $service_class;
883 * Contructor
884 * @param integer $authmethod authentication method - one of WEBSERVICE_AUTHMETHOD_*
886 public function __construct($authmethod, $zend_class) {
887 parent::__construct($authmethod);
888 $this->zend_class = $zend_class;
892 * Process request from client.
893 * @param bool $simple use simple authentication
894 * @return void
896 public function run() {
897 // we will probably need a lot of memory in some functions
898 raise_memory_limit(MEMORY_EXTRA);
900 // set some longer timeout, this script is not sending any output,
901 // this means we need to manually extend the timeout operations
902 // that need longer time to finish
903 external_api::set_timeout();
905 // now create the instance of zend server
906 $this->init_zend_server();
908 // set up exception handler first, we want to sent them back in correct format that
909 // the other system understands
910 // we do not need to call the original default handler because this ws handler does everything
911 set_exception_handler(array($this, 'exception_handler'));
913 // init all properties from the request data
914 $this->parse_request();
916 // this sets up $USER and $SESSION and context restrictions
917 $this->authenticate_user();
919 // make a list of all functions user is allowed to excecute
920 $this->init_service_class();
922 // tell server what functions are available
923 $this->zend_server->setClass($this->service_class);
925 //log the web service request
926 add_to_log(SITEID, 'webservice', '', '' , $this->zend_class." ".getremoteaddr() , 0, $this->userid);
928 //send headers
929 $this->send_headers();
931 // execute and return response, this sends some headers too
932 $response = $this->zend_server->handle();
934 // session cleanup
935 $this->session_cleanup();
937 //finally send the result
938 echo $response;
939 die;
943 * Load virtual class needed for Zend api
944 * @return void
946 protected function init_service_class() {
947 global $USER, $DB;
949 // first ofall get a complete list of services user is allowed to access
951 if ($this->restricted_serviceid) {
952 $params = array('sid1'=>$this->restricted_serviceid, 'sid2'=>$this->restricted_serviceid);
953 $wscond1 = 'AND s.id = :sid1';
954 $wscond2 = 'AND s.id = :sid2';
955 } else {
956 $params = array();
957 $wscond1 = '';
958 $wscond2 = '';
961 // now make sure the function is listed in at least one service user is allowed to use
962 // allow access only if:
963 // 1/ entry in the external_services_users table if required
964 // 2/ validuntil not reached
965 // 3/ has capability if specified in service desc
966 // 4/ iprestriction
968 $sql = "SELECT s.*, NULL AS iprestriction
969 FROM {external_services} s
970 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0)
971 WHERE s.enabled = 1 $wscond1
973 UNION
975 SELECT s.*, su.iprestriction
976 FROM {external_services} s
977 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1)
978 JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)
979 WHERE s.enabled = 1 AND su.validuntil IS NULL OR su.validuntil < :now $wscond2";
981 $params = array_merge($params, array('userid'=>$USER->id, 'now'=>time()));
983 $serviceids = array();
984 $rs = $DB->get_recordset_sql($sql, $params);
986 // now make sure user may access at least one service
987 $remoteaddr = getremoteaddr();
988 $allowed = false;
989 foreach ($rs as $service) {
990 if (isset($serviceids[$service->id])) {
991 continue;
993 if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) {
994 continue; // cap required, sorry
996 if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) {
997 continue; // wrong request source ip, sorry
999 $serviceids[$service->id] = $service->id;
1001 $rs->close();
1003 // now get the list of all functions
1004 $wsmanager = new webservice();
1005 $functions = $wsmanager->get_external_functions($serviceids);
1007 // now make the virtual WS class with all the fuctions for this particular user
1008 $methods = '';
1009 foreach ($functions as $function) {
1010 $methods .= $this->get_virtual_method_code($function);
1013 // let's use unique class name, there might be problem in unit tests
1014 $classname = 'webservices_virtual_class_000000';
1015 while(class_exists($classname)) {
1016 $classname++;
1019 $code = '
1021 * Virtual class web services for user id '.$USER->id.' in context '.$this->restricted_context->id.'.
1023 class '.$classname.' {
1024 '.$methods.'
1028 // load the virtual class definition into memory
1029 eval($code);
1030 $this->service_class = $classname;
1034 * returns virtual method code
1035 * @param object $function
1036 * @return string PHP code
1038 protected function get_virtual_method_code($function) {
1039 global $CFG;
1041 $function = external_function_info($function);
1043 //arguments in function declaration line with defaults.
1044 $paramanddefaults = array();
1045 //arguments used as parameters for external lib call.
1046 $params = array();
1047 $params_desc = array();
1048 foreach ($function->parameters_desc->keys as $name=>$keydesc) {
1049 $param = '$'.$name;
1050 $paramanddefault = $param;
1051 //need to generate the default if there is any
1052 if ($keydesc instanceof external_value) {
1053 if ($keydesc->required == VALUE_DEFAULT) {
1054 if ($keydesc->default===null) {
1055 $paramanddefault .= '=null';
1056 } else {
1057 switch($keydesc->type) {
1058 case PARAM_BOOL:
1059 $paramanddefault .= '='.$keydesc->default; break;
1060 case PARAM_INT:
1061 $paramanddefault .= '='.$keydesc->default; break;
1062 case PARAM_FLOAT;
1063 $paramanddefault .= '='.$keydesc->default; break;
1064 default:
1065 $paramanddefault .= '=\''.$keydesc->default.'\'';
1068 } else if ($keydesc->required == VALUE_OPTIONAL) {
1069 //it does make sens to declare a parameter VALUE_OPTIONAL
1070 //VALUE_OPTIONAL is used only for array/object key
1071 throw new moodle_exception('parametercannotbevalueoptional');
1073 } else { //for the moment we do not support default for other structure types
1074 if ($keydesc->required == VALUE_DEFAULT) {
1075 //accept empty array as default
1076 if (isset($keydesc->default) and is_array($keydesc->default)
1077 and empty($keydesc->default)) {
1078 $paramanddefault .= '=array()';
1079 } else {
1080 throw new moodle_exception('errornotemptydefaultparamarray', 'webservice', '', $name);
1083 if ($keydesc->required == VALUE_OPTIONAL) {
1084 throw new moodle_exception('erroroptionalparamarray', 'webservice', '', $name);
1087 $params[] = $param;
1088 $paramanddefaults[] = $paramanddefault;
1089 $type = 'string';
1090 if ($keydesc instanceof external_value) {
1091 switch($keydesc->type) {
1092 case PARAM_BOOL: // 0 or 1 only for now
1093 case PARAM_INT:
1094 $type = 'int'; break;
1095 case PARAM_FLOAT;
1096 $type = 'double'; break;
1097 default:
1098 $type = 'string';
1100 } else if ($keydesc instanceof external_single_structure) {
1101 $type = 'object|struct';
1102 } else if ($keydesc instanceof external_multiple_structure) {
1103 $type = 'array';
1105 $params_desc[] = ' * @param '.$type.' $'.$name.' '.$keydesc->desc;
1107 $params = implode(', ', $params);
1108 $paramanddefaults = implode(', ', $paramanddefaults);
1109 $params_desc = implode("\n", $params_desc);
1111 $serviceclassmethodbody = $this->service_class_method_body($function, $params);
1113 if (is_null($function->returns_desc)) {
1114 $return = ' * @return void';
1115 } else {
1116 $type = 'string';
1117 if ($function->returns_desc instanceof external_value) {
1118 switch($function->returns_desc->type) {
1119 case PARAM_BOOL: // 0 or 1 only for now
1120 case PARAM_INT:
1121 $type = 'int'; break;
1122 case PARAM_FLOAT;
1123 $type = 'double'; break;
1124 default:
1125 $type = 'string';
1127 } else if ($function->returns_desc instanceof external_single_structure) {
1128 $type = 'object|struct'; //only 'object' is supported by SOAP, 'struct' by XML-RPC MDL-23083
1129 } else if ($function->returns_desc instanceof external_multiple_structure) {
1130 $type = 'array';
1132 $return = ' * @return '.$type.' '.$function->returns_desc->desc;
1135 // now crate the virtual method that calls the ext implementation
1137 $code = '
1139 * '.$function->description.'
1141 '.$params_desc.'
1142 '.$return.'
1144 public function '.$function->name.'('.$paramanddefaults.') {
1145 '.$serviceclassmethodbody.'
1148 return $code;
1152 * You can override this function in your child class to add extra code into the dynamically
1153 * created service class. For example it is used in the amf server to cast types of parameters and to
1154 * cast the return value to the types as specified in the return value description.
1155 * @param stdClass $function
1156 * @param array $params
1157 * @return string body of the method for $function ie. everything within the {} of the method declaration.
1159 protected function service_class_method_body($function, $params){
1160 //cast the param from object to array (validate_parameters except array only)
1161 $castingcode = '';
1162 if ($params){
1163 $paramstocast = explode(',', $params);
1164 foreach ($paramstocast as $paramtocast) {
1165 //clean the parameter from any white space
1166 $paramtocast = trim($paramtocast);
1167 $castingcode .= $paramtocast .
1168 '=webservice_zend_server::cast_objects_to_array('.$paramtocast.');';
1173 $descriptionmethod = $function->methodname.'_returns()';
1174 $callforreturnvaluedesc = $function->classname.'::'.$descriptionmethod;
1175 return $castingcode . ' if ('.$callforreturnvaluedesc.' == null) {'.
1176 $function->classname.'::'.$function->methodname.'('.$params.');
1177 return null;
1179 return external_api::clean_returnvalue('.$callforreturnvaluedesc.', '.$function->classname.'::'.$function->methodname.'('.$params.'));';
1183 * Recursive function to recurse down into a complex variable and convert all
1184 * objects to arrays.
1185 * @param mixed $param value to cast
1186 * @return mixed Cast value
1188 public static function cast_objects_to_array($param){
1189 if (is_object($param)){
1190 $param = (array)$param;
1192 if (is_array($param)){
1193 $toreturn = array();
1194 foreach ($param as $key=> $param){
1195 $toreturn[$key] = self::cast_objects_to_array($param);
1197 return $toreturn;
1198 } else {
1199 return $param;
1204 * Set up zend service class
1205 * @return void
1207 protected function init_zend_server() {
1208 $this->zend_server = new $this->zend_class();
1212 * This method parses the $_REQUEST superglobal and looks for
1213 * the following information:
1214 * 1/ user authentication - username+password or token (wsusername, wspassword and wstoken parameters)
1216 * @return void
1218 protected function parse_request() {
1219 if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
1220 //note: some clients have problems with entity encoding :-(
1221 if (isset($_REQUEST['wsusername'])) {
1222 $this->username = $_REQUEST['wsusername'];
1224 if (isset($_REQUEST['wspassword'])) {
1225 $this->password = $_REQUEST['wspassword'];
1227 } else {
1228 if (isset($_REQUEST['wstoken'])) {
1229 $this->token = $_REQUEST['wstoken'];
1235 * Internal implementation - sending of page headers.
1236 * @return void
1238 protected function send_headers() {
1239 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
1240 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1241 header('Pragma: no-cache');
1242 header('Accept-Ranges: none');
1246 * Specialised exception handler, we can not use the standard one because
1247 * it can not just print html to output.
1249 * @param exception $ex
1250 * @return void does not return
1252 public function exception_handler($ex) {
1253 // detect active db transactions, rollback and log as error
1254 abort_all_db_transactions();
1256 // some hacks might need a cleanup hook
1257 $this->session_cleanup($ex);
1259 // now let the plugin send the exception to client
1260 $this->send_error($ex);
1262 // not much else we can do now, add some logging later
1263 exit(1);
1267 * Send the error information to the WS client
1268 * formatted as XML document.
1269 * @param exception $ex
1270 * @return void
1272 protected function send_error($ex=null) {
1273 $this->send_headers();
1274 echo $this->zend_server->fault($ex);
1278 * Future hook needed for emulated sessions.
1279 * @param exception $exception null means normal termination, $exception received when WS call failed
1280 * @return void
1282 protected function session_cleanup($exception=null) {
1283 if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
1284 // nothing needs to be done, there is no persistent session
1285 } else {
1286 // close emulated session if used
1293 * Web Service server base class, this class handles both
1294 * simple and token authentication.
1295 * @author Petr Skoda (skodak)
1297 abstract class webservice_base_server extends webservice_server {
1299 /** @property array $parameters the function parameters - the real values submitted in the request */
1300 protected $parameters = null;
1302 /** @property string $functionname the name of the function that is executed */
1303 protected $functionname = null;
1305 /** @property object $function full function description */
1306 protected $function = null;
1308 /** @property mixed $returns function return value */
1309 protected $returns = null;
1312 * This method parses the request input, it needs to get:
1313 * 1/ user authentication - username+password or token
1314 * 2/ function name
1315 * 3/ function parameters
1317 * @return void
1319 abstract protected function parse_request();
1322 * Send the result of function call to the WS client.
1323 * @return void
1325 abstract protected function send_response();
1328 * Send the error information to the WS client.
1329 * @param exception $ex
1330 * @return void
1332 abstract protected function send_error($ex=null);
1335 * Process request from client.
1336 * @return void
1338 public function run() {
1339 // we will probably need a lot of memory in some functions
1340 raise_memory_limit(MEMORY_EXTRA);
1342 // set some longer timeout, this script is not sending any output,
1343 // this means we need to manually extend the timeout operations
1344 // that need longer time to finish
1345 external_api::set_timeout();
1347 // set up exception handler first, we want to sent them back in correct format that
1348 // the other system understands
1349 // we do not need to call the original default handler because this ws handler does everything
1350 set_exception_handler(array($this, 'exception_handler'));
1352 // init all properties from the request data
1353 $this->parse_request();
1355 // authenticate user, this has to be done after the request parsing
1356 // this also sets up $USER and $SESSION
1357 $this->authenticate_user();
1359 // find all needed function info and make sure user may actually execute the function
1360 $this->load_function_info();
1362 //log the web service request
1363 add_to_log(SITEID, 'webservice', $this->functionname, '' , getremoteaddr() , 0, $this->userid);
1365 // finally, execute the function - any errors are catched by the default exception handler
1366 $this->execute();
1368 // send the results back in correct format
1369 $this->send_response();
1371 // session cleanup
1372 $this->session_cleanup();
1374 die;
1378 * Specialised exception handler, we can not use the standard one because
1379 * it can not just print html to output.
1381 * @param exception $ex
1382 * @return void does not return
1384 public function exception_handler($ex) {
1385 // detect active db transactions, rollback and log as error
1386 abort_all_db_transactions();
1388 // some hacks might need a cleanup hook
1389 $this->session_cleanup($ex);
1391 // now let the plugin send the exception to client
1392 $this->send_error($ex);
1394 // not much else we can do now, add some logging later
1395 exit(1);
1399 * Future hook needed for emulated sessions.
1400 * @param exception $exception null means normal termination, $exception received when WS call failed
1401 * @return void
1403 protected function session_cleanup($exception=null) {
1404 if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
1405 // nothing needs to be done, there is no persistent session
1406 } else {
1407 // close emulated session if used
1412 * Fetches the function description from database,
1413 * verifies user is allowed to use this function and
1414 * loads all paremeters and return descriptions.
1415 * @return void
1417 protected function load_function_info() {
1418 global $DB, $USER, $CFG;
1420 if (empty($this->functionname)) {
1421 throw new invalid_parameter_exception('Missing function name');
1424 // function must exist
1425 $function = external_function_info($this->functionname);
1427 if ($this->restricted_serviceid) {
1428 $params = array('sid1'=>$this->restricted_serviceid, 'sid2'=>$this->restricted_serviceid);
1429 $wscond1 = 'AND s.id = :sid1';
1430 $wscond2 = 'AND s.id = :sid2';
1431 } else {
1432 $params = array();
1433 $wscond1 = '';
1434 $wscond2 = '';
1437 // now let's verify access control
1439 // now make sure the function is listed in at least one service user is allowed to use
1440 // allow access only if:
1441 // 1/ entry in the external_services_users table if required
1442 // 2/ validuntil not reached
1443 // 3/ has capability if specified in service desc
1444 // 4/ iprestriction
1446 $sql = "SELECT s.*, NULL AS iprestriction
1447 FROM {external_services} s
1448 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0 AND sf.functionname = :name1)
1449 WHERE s.enabled = 1 $wscond1
1451 UNION
1453 SELECT s.*, su.iprestriction
1454 FROM {external_services} s
1455 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1 AND sf.functionname = :name2)
1456 JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)
1457 WHERE s.enabled = 1 AND su.validuntil IS NULL OR su.validuntil < :now $wscond2";
1458 $params = array_merge($params, array('userid'=>$USER->id, 'name1'=>$function->name, 'name2'=>$function->name, 'now'=>time()));
1460 $rs = $DB->get_recordset_sql($sql, $params);
1461 // now make sure user may access at least one service
1462 $remoteaddr = getremoteaddr();
1463 $allowed = false;
1464 foreach ($rs as $service) {
1465 if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) {
1466 continue; // cap required, sorry
1468 if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) {
1469 continue; // wrong request source ip, sorry
1471 $allowed = true;
1472 break; // one service is enough, no need to continue
1474 $rs->close();
1475 if (!$allowed) {
1476 throw new webservice_access_exception('Access to external function not allowed');
1479 // we have all we need now
1480 $this->function = $function;
1484 * Execute previously loaded function using parameters parsed from the request data.
1485 * @return void
1487 protected function execute() {
1488 // validate params, this also sorts the params properly, we need the correct order in the next part
1489 $params = call_user_func(array($this->function->classname, 'validate_parameters'), $this->function->parameters_desc, $this->parameters);
1491 // execute - yay!
1492 $this->returns = call_user_func_array(array($this->function->classname, $this->function->methodname), array_values($params));