2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * Web services utility functions and classes
21 * @package core_webservice
22 * @copyright 2009 Jerome Mouneyrac <jerome@moodle.com>
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 require_once($CFG->libdir
.'/externallib.php');
29 * WEBSERVICE_AUTHMETHOD_USERNAME - username/password authentication (also called simple authentication)
31 define('WEBSERVICE_AUTHMETHOD_USERNAME', 0);
34 * WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN - most common token authentication (external app, mobile app...)
36 define('WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN', 1);
39 * WEBSERVICE_AUTHMETHOD_SESSION_TOKEN - token for embedded application (requires Moodle session)
41 define('WEBSERVICE_AUTHMETHOD_SESSION_TOKEN', 2);
44 * General web service library
46 * @package core_webservice
47 * @copyright 2010 Jerome Mouneyrac <jerome@moodle.com>
48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
53 * Authenticate user (used by download/upload file scripts)
55 * @param string $token
56 * @return array - contains the authenticated user, token and service objects
58 public function authenticate_user($token) {
61 // web service must be enabled to use this script
62 if (!$CFG->enablewebservices
) {
63 throw new webservice_access_exception('Web services are not enabled in Advanced features.');
66 // Obtain token record
67 if (!$token = $DB->get_record('external_tokens', array('token' => $token))) {
68 //client may want to display login form => moodle_exception
69 throw new moodle_exception('invalidtoken', 'webservice');
72 // Validate token date
73 if ($token->validuntil
and $token->validuntil
< time()) {
74 add_to_log(SITEID
, 'webservice', get_string('tokenauthlog', 'webservice'), '', get_string('invalidtimedtoken', 'webservice'), 0);
75 $DB->delete_records('external_tokens', array('token' => $token->token
));
76 throw new webservice_access_exception('Invalid token - token expired - check validuntil time for the token');
80 if ($token->iprestriction
and !address_in_subnet(getremoteaddr(), $token->iprestriction
)) {
81 add_to_log(SITEID
, 'webservice', get_string('tokenauthlog', 'webservice'), '', get_string('failedtolog', 'webservice') . ": " . getremoteaddr(), 0);
82 throw new webservice_access_exception('Invalid token - IP:' . getremoteaddr()
83 . ' is not supported');
86 //retrieve user link to the token
87 $user = $DB->get_record('user', array('id' => $token->userid
, 'deleted' => 0), '*', MUST_EXIST
);
89 // let enrol plugins deal with new enrolments if necessary
90 enrol_check_plugins($user);
92 // setup user session to check capability
93 session_set_user($user);
95 //assumes that if sid is set then there must be a valid associated session no matter the token type
97 $session = session_get_instance();
98 if (!$session->session_exists($token->sid
)) {
99 $DB->delete_records('external_tokens', array('sid' => $token->sid
));
100 throw new webservice_access_exception('Invalid session based token - session not found or expired');
104 //Non admin can not authenticate if maintenance mode
105 $hassiteconfig = has_capability('moodle/site:config', context_system
::instance(), $user);
106 if (!empty($CFG->maintenance_enabled
) and !$hassiteconfig) {
107 //this is usually temporary, client want to implement code logic => moodle_exception
108 throw new moodle_exception('sitemaintenance', 'admin');
111 //retrieve web service record
112 $service = $DB->get_record('external_services', array('id' => $token->externalserviceid
, 'enabled' => 1));
113 if (empty($service)) {
114 // will throw exception if no token found
115 throw new webservice_access_exception('Web service is not available (it doesn\'t exist or might be disabled)');
118 //check if there is any required system capability
119 if ($service->requiredcapability
and !has_capability($service->requiredcapability
, context_system
::instance(), $user)) {
120 throw new webservice_access_exception('The capability ' . $service->requiredcapability
. ' is required.');
123 //specific checks related to user restricted service
124 if ($service->restrictedusers
) {
125 $authoriseduser = $DB->get_record('external_services_users', array('externalserviceid' => $service->id
, 'userid' => $user->id
));
127 if (empty($authoriseduser)) {
128 throw new webservice_access_exception(
129 'The user is not allowed for this service. First you need to allow this user on the '
130 . $service->name
. '\'s allowed users administration page.');
133 if (!empty($authoriseduser->validuntil
) and $authoriseduser->validuntil
< time()) {
134 throw new webservice_access_exception('Invalid service - service expired - check validuntil time for this allowed user');
137 if (!empty($authoriseduser->iprestriction
) and !address_in_subnet(getremoteaddr(), $authoriseduser->iprestriction
)) {
138 throw new webservice_access_exception('Invalid service - IP:' . getremoteaddr()
139 . ' is not supported - check this allowed user');
143 //only confirmed user should be able to call web service
144 if (empty($user->confirmed
)) {
145 add_to_log(SITEID
, 'webservice', 'user unconfirmed', '', $user->username
);
146 throw new moodle_exception('usernotconfirmed', 'moodle', '', $user->username
);
149 //check the user is suspended
150 if (!empty($user->suspended
)) {
151 add_to_log(SITEID
, 'webservice', 'user suspended', '', $user->username
);
152 throw new webservice_access_exception('Refused web service access for suspended username: ' . $user->username
);
155 //check if the auth method is nologin (in this case refuse connection)
156 if ($user->auth
== 'nologin') {
157 add_to_log(SITEID
, 'webservice', 'nologin auth attempt with web service', '', $user->username
);
158 throw new webservice_access_exception('Refused web service access for nologin authentication username: ' . $user->username
);
161 //Check if the user password is expired
162 $auth = get_auth_plugin($user->auth
);
163 if (!empty($auth->config
->expiration
) and $auth->config
->expiration
== 1) {
164 $days2expire = $auth->password_expire($user->username
);
165 if (intval($days2expire) < 0) {
166 add_to_log(SITEID
, 'webservice', 'expired password', '', $user->username
);
167 throw new moodle_exception('passwordisexpired', 'webservice');
172 $DB->set_field('external_tokens', 'lastaccess', time(), array('id' => $token->id
));
174 return array('user' => $user, 'token' => $token, 'service' => $service);
178 * Allow user to call a service
180 * @param stdClass $user a user
182 public function add_ws_authorised_user($user) {
184 $user->timecreated
= time();
185 $DB->insert_record('external_services_users', $user);
189 * Disallow a user to call a service
191 * @param stdClass $user a user
192 * @param int $serviceid
194 public function remove_ws_authorised_user($user, $serviceid) {
196 $DB->delete_records('external_services_users',
197 array('externalserviceid' => $serviceid, 'userid' => $user->id
));
201 * Update allowed user settings (ip restriction, valid until...)
203 * @param stdClass $user
205 public function update_ws_authorised_user($user) {
207 $DB->update_record('external_services_users', $user);
211 * Return list of allowed users with their options (ip/timecreated / validuntil...)
212 * for a given service
214 * @param int $serviceid the service id to search against
215 * @return array $users
217 public function get_ws_authorised_users($serviceid) {
219 $params = array($CFG->siteguest
, $serviceid);
220 $sql = " SELECT u.id as id, esu.id as serviceuserid, u.email as email, u.firstname as firstname,
221 u.lastname as lastname,
222 esu.iprestriction as iprestriction, esu.validuntil as validuntil,
223 esu.timecreated as timecreated
224 FROM {user} u, {external_services_users} esu
225 WHERE u.id <> ? AND u.deleted = 0 AND u.confirmed = 1
226 AND esu.userid = u.id
227 AND esu.externalserviceid = ?";
229 $users = $DB->get_records_sql($sql, $params);
234 * Return an authorised user with their options (ip/timecreated / validuntil...)
236 * @param int $serviceid the service id to search against
237 * @param int $userid the user to search against
240 public function get_ws_authorised_user($serviceid, $userid) {
242 $params = array($CFG->siteguest
, $serviceid, $userid);
243 $sql = " SELECT u.id as id, esu.id as serviceuserid, u.email as email, u.firstname as firstname,
244 u.lastname as lastname,
245 esu.iprestriction as iprestriction, esu.validuntil as validuntil,
246 esu.timecreated as timecreated
247 FROM {user} u, {external_services_users} esu
248 WHERE u.id <> ? AND u.deleted = 0 AND u.confirmed = 1
249 AND esu.userid = u.id
250 AND esu.externalserviceid = ?
252 $user = $DB->get_record_sql($sql, $params);
257 * Generate all tokens of a specific user
259 * @param int $userid user id
261 public function generate_user_ws_tokens($userid) {
264 // generate a token for non admin if web service are enable and the user has the capability to create a token
265 if (!is_siteadmin() && has_capability('moodle/webservice:createtoken', context_system
::instance(), $userid) && !empty($CFG->enablewebservices
)) {
266 // for every service than the user is authorised on, create a token (if it doesn't already exist)
268 // get all services which are set to all user (no restricted to specific users)
269 $norestrictedservices = $DB->get_records('external_services', array('restrictedusers' => 0));
270 $serviceidlist = array();
271 foreach ($norestrictedservices as $service) {
272 $serviceidlist[] = $service->id
;
275 // get all services which are set to the current user (the current user is specified in the restricted user list)
276 $servicesusers = $DB->get_records('external_services_users', array('userid' => $userid));
277 foreach ($servicesusers as $serviceuser) {
278 if (!in_array($serviceuser->externalserviceid
,$serviceidlist)) {
279 $serviceidlist[] = $serviceuser->externalserviceid
;
283 // get all services which already have a token set for the current user
284 $usertokens = $DB->get_records('external_tokens', array('userid' => $userid, 'tokentype' => EXTERNAL_TOKEN_PERMANENT
));
285 $tokenizedservice = array();
286 foreach ($usertokens as $token) {
287 $tokenizedservice[] = $token->externalserviceid
;
290 // create a token for the service which have no token already
291 foreach ($serviceidlist as $serviceid) {
292 if (!in_array($serviceid, $tokenizedservice)) {
293 // create the token for this service
294 $newtoken = new stdClass();
295 $newtoken->token
= md5(uniqid(rand(),1));
296 // check that the user has capability on this service
297 $newtoken->tokentype
= EXTERNAL_TOKEN_PERMANENT
;
298 $newtoken->userid
= $userid;
299 $newtoken->externalserviceid
= $serviceid;
300 // TODO MDL-31190 find a way to get the context - UPDATE FOLLOWING LINE
301 $newtoken->contextid
= context_system
::instance()->id
;
302 $newtoken->creatorid
= $userid;
303 $newtoken->timecreated
= time();
305 $DB->insert_record('external_tokens', $newtoken);
314 * Return all tokens of a specific user
315 * + the service state (enabled/disabled)
316 * + the authorised user mode (restricted/not restricted)
318 * @param int $userid user id
321 public function get_user_ws_tokens($userid) {
323 //here retrieve token list (including linked users firstname/lastname and linked services name)
325 t.id, t.creatorid, t.token, u.firstname, u.lastname, s.id as wsid, s.name, s.enabled, s.restrictedusers, t.validuntil
327 {external_tokens} t, {user} u, {external_services} s
329 t.userid=? AND t.tokentype = ".EXTERNAL_TOKEN_PERMANENT
." AND s.id = t.externalserviceid AND t.userid = u.id";
330 $tokens = $DB->get_records_sql($sql, array( $userid));
335 * Return a token that has been created by the user (i.e. to created by an admin)
336 * If no tokens exist an exception is thrown
338 * The returned value is a stdClass:
341 * ->firstname user firstname
343 * ->name service name
345 * @param int $userid user id
346 * @param int $tokenid token id
349 public function get_created_by_user_ws_token($userid, $tokenid) {
352 t.id, t.token, u.firstname, u.lastname, s.name
354 {external_tokens} t, {user} u, {external_services} s
356 t.creatorid=? AND t.id=? AND t.tokentype = "
357 . EXTERNAL_TOKEN_PERMANENT
358 . " AND s.id = t.externalserviceid AND t.userid = u.id";
359 //must be the token creator
360 $token = $DB->get_record_sql($sql, array($userid, $tokenid), MUST_EXIST
);
365 * Return a database token record for a token id
367 * @param int $tokenid token id
368 * @return object token
370 public function get_token_by_id($tokenid) {
372 return $DB->get_record('external_tokens', array('id' => $tokenid));
378 * @param int $tokenid token id
380 public function delete_user_ws_token($tokenid) {
382 $DB->delete_records('external_tokens', array('id'=>$tokenid));
387 * Also delete function references and authorised user references.
389 * @param int $serviceid service id
391 public function delete_service($serviceid) {
393 $DB->delete_records('external_services_users', array('externalserviceid' => $serviceid));
394 $DB->delete_records('external_services_functions', array('externalserviceid' => $serviceid));
395 $DB->delete_records('external_tokens', array('externalserviceid' => $serviceid));
396 $DB->delete_records('external_services', array('id' => $serviceid));
400 * Get a full database token record for a given token value
402 * @param string $token
403 * @throws moodle_exception if there is multiple result
405 public function get_user_ws_token($token) {
407 return $DB->get_record('external_tokens', array('token'=>$token), '*', MUST_EXIST
);
411 * Get the functions list of a service list (by id)
413 * @param array $serviceids service ids
414 * @return array of functions
416 public function get_external_functions($serviceids) {
418 if (!empty($serviceids)) {
419 list($serviceids, $params) = $DB->get_in_or_equal($serviceids);
421 FROM {external_functions} f
422 WHERE f.name IN (SELECT sf.functionname
423 FROM {external_services_functions} sf
424 WHERE sf.externalserviceid $serviceids)";
425 $functions = $DB->get_records_sql($sql, $params);
427 $functions = array();
433 * Get the functions of a service list (by shortname). It can return only enabled functions if required.
435 * @param array $serviceshortnames service shortnames
436 * @param bool $enabledonly if true then only return functions for services that have been enabled
437 * @return array functions
439 public function get_external_functions_by_enabled_services($serviceshortnames, $enabledonly = true) {
441 if (!empty($serviceshortnames)) {
442 $enabledonlysql = $enabledonly?
' AND s.enabled = 1 ':'';
443 list($serviceshortnames, $params) = $DB->get_in_or_equal($serviceshortnames);
445 FROM {external_functions} f
446 WHERE f.name IN (SELECT sf.functionname
447 FROM {external_services_functions} sf, {external_services} s
448 WHERE s.shortname $serviceshortnames
449 AND sf.externalserviceid = s.id
450 " . $enabledonlysql . ")";
451 $functions = $DB->get_records_sql($sql, $params);
453 $functions = array();
459 * Get functions not included in a service
461 * @param int $serviceid service id
462 * @return array functions
464 public function get_not_associated_external_functions($serviceid) {
466 $select = "name NOT IN (SELECT s.functionname
467 FROM {external_services_functions} s
468 WHERE s.externalserviceid = :sid
471 $functions = $DB->get_records_select('external_functions',
472 $select, array('sid' => $serviceid), 'name');
478 * Get list of required capabilities of a service, sorted by functions
479 * Example of returned value:
482 * [moodle_group_create_groups] => Array
484 * [0] => moodle/course:managegroups
487 * [moodle_enrol_get_enrolled_users] => Array
489 * [0] => moodle/site:viewparticipants
490 * [1] => moodle/course:viewparticipants
491 * [2] => moodle/role:review
492 * [3] => moodle/site:accessallgroups
493 * [4] => moodle/course:enrolreview
497 * @param int $serviceid service id
500 public function get_service_required_capabilities($serviceid) {
501 $functions = $this->get_external_functions(array($serviceid));
502 $requiredusercaps = array();
503 foreach ($functions as $function) {
504 $functioncaps = explode(',', $function->capabilities
);
505 if (!empty($functioncaps) and !empty($functioncaps[0])) {
506 foreach ($functioncaps as $functioncap) {
507 $requiredusercaps[$function->name
][] = trim($functioncap);
511 return $requiredusercaps;
515 * Get user capabilities (with context)
516 * Only useful for documentation purpose
517 * WARNING: do not use this "broken" function. It was created in the goal to display some capabilities
518 * required by users. In theory we should not need to display this kind of information
519 * as the front end does not display it itself. In pratice,
520 * admins would like the info, for more info you can follow: MDL-29962
522 * @param int $userid user id
525 public function get_user_capabilities($userid) {
527 //retrieve the user capabilities
528 $sql = "SELECT DISTINCT rc.id, rc.capability FROM {role_capabilities} rc, {role_assignments} ra
529 WHERE rc.roleid=ra.roleid AND ra.userid= ? AND rc.permission = ?";
530 $dbusercaps = $DB->get_records_sql($sql, array($userid, CAP_ALLOW
));
532 foreach ($dbusercaps as $usercap) {
533 $usercaps[$usercap->capability
] = true;
539 * Get missing user capabilities for a given service
540 * WARNING: do not use this "broken" function. It was created in the goal to display some capabilities
541 * required by users. In theory we should not need to display this kind of information
542 * as the front end does not display it itself. In pratice,
543 * admins would like the info, for more info you can follow: MDL-29962
545 * @param array $users users
546 * @param int $serviceid service id
547 * @return array of missing capabilities, keys being the user ids
549 public function get_missing_capabilities_by_users($users, $serviceid) {
551 $usersmissingcaps = array();
553 //retrieve capabilities required by the service
554 $servicecaps = $this->get_service_required_capabilities($serviceid);
556 //retrieve users missing capabilities
557 foreach ($users as $user) {
558 //cast user array into object to be a bit more flexible
559 if (is_array($user)) {
560 $user = (object) $user;
562 $usercaps = $this->get_user_capabilities($user->id
);
564 //detect the missing capabilities
565 foreach ($servicecaps as $functioname => $functioncaps) {
566 foreach ($functioncaps as $functioncap) {
567 if (!array_key_exists($functioncap, $usercaps)) {
568 if (!isset($usersmissingcaps[$user->id
])
569 or array_search($functioncap, $usersmissingcaps[$user->id
]) === false) {
570 $usersmissingcaps[$user->id
][] = $functioncap;
577 return $usersmissingcaps;
581 * Get an external service for a given service id
583 * @param int $serviceid service id
584 * @param int $strictness IGNORE_MISSING, MUST_EXIST...
585 * @return stdClass external service
587 public function get_external_service_by_id($serviceid, $strictness=IGNORE_MISSING
) {
589 $service = $DB->get_record('external_services',
590 array('id' => $serviceid), '*', $strictness);
595 * Get an external service for a given shortname
597 * @param string $shortname service shortname
598 * @param int $strictness IGNORE_MISSING, MUST_EXIST...
599 * @return stdClass external service
601 public function get_external_service_by_shortname($shortname, $strictness=IGNORE_MISSING
) {
603 $service = $DB->get_record('external_services',
604 array('shortname' => $shortname), '*', $strictness);
609 * Get an external function for a given function id
611 * @param int $functionid function id
612 * @param int $strictness IGNORE_MISSING, MUST_EXIST...
613 * @return stdClass external function
615 public function get_external_function_by_id($functionid, $strictness=IGNORE_MISSING
) {
617 $function = $DB->get_record('external_functions',
618 array('id' => $functionid), '*', $strictness);
623 * Add a function to a service
625 * @param string $functionname function name
626 * @param int $serviceid service id
628 public function add_external_function_to_service($functionname, $serviceid) {
630 $addedfunction = new stdClass();
631 $addedfunction->externalserviceid
= $serviceid;
632 $addedfunction->functionname
= $functionname;
633 $DB->insert_record('external_services_functions', $addedfunction);
638 * It generates the timecreated field automatically.
640 * @param stdClass $service
641 * @return serviceid integer
643 public function add_external_service($service) {
645 $service->timecreated
= time();
646 $serviceid = $DB->insert_record('external_services', $service);
652 * It modifies the timemodified automatically.
654 * @param stdClass $service
656 public function update_external_service($service) {
658 $service->timemodified
= time();
659 $DB->update_record('external_services', $service);
663 * Test whether an external function is already linked to a service
665 * @param string $functionname function name
666 * @param int $serviceid service id
667 * @return bool true if a matching function exists for the service, else false.
668 * @throws dml_exception if error
670 public function service_function_exists($functionname, $serviceid) {
672 return $DB->record_exists('external_services_functions',
673 array('externalserviceid' => $serviceid,
674 'functionname' => $functionname));
678 * Remove a function from a service
680 * @param string $functionname function name
681 * @param int $serviceid service id
683 public function remove_external_function_from_service($functionname, $serviceid) {
685 $DB->delete_records('external_services_functions',
686 array('externalserviceid' => $serviceid, 'functionname' => $functionname));
694 * Exception indicating access control problem in web service call
695 * This exception should return general errors about web service setup.
696 * Errors related to the user like wrong username/password should not use it,
697 * you should not use this exception if you want to let the client implement
698 * some code logic against an access error.
700 * @package core_webservice
701 * @copyright 2009 Petr Skodak
702 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
704 class webservice_access_exception
extends moodle_exception
{
709 * @param string $debuginfo the debug info
711 function __construct($debuginfo) {
712 parent
::__construct('accessexception', 'webservice', '', null, $debuginfo);
717 * Check if a protocol is enabled
719 * @param string $protocol name of WS protocol ('rest', 'soap', 'xmlrpc', 'amf'...)
720 * @return bool true if the protocol is enabled
722 function webservice_protocol_is_enabled($protocol) {
725 if (empty($CFG->enablewebservices
)) {
729 $active = explode(',', $CFG->webserviceprotocols
);
731 return(in_array($protocol, $active));
735 * Mandatory interface for all test client classes.
737 * @package core_webservice
738 * @copyright 2009 Petr Skodak
739 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
741 interface webservice_test_client_interface
{
744 * Execute test client WS request
746 * @param string $serverurl server url (including the token param)
747 * @param string $function web service function name
748 * @param array $params parameters of the web service function
751 public function simpletest($serverurl, $function, $params);
755 * Mandatory interface for all web service protocol classes
757 * @package core_webservice
758 * @copyright 2009 Petr Skodak
759 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
761 interface webservice_server_interface
{
764 * Process request from client.
766 public function run();
770 * Abstract web service base class.
772 * @package core_webservice
773 * @copyright 2009 Petr Skodak
774 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
776 abstract class webservice_server
implements webservice_server_interface
{
778 /** @var string Name of the web server plugin */
779 protected $wsname = null;
781 /** @var string Name of local user */
782 protected $username = null;
784 /** @var string Password of the local user */
785 protected $password = null;
787 /** @var int The local user */
788 protected $userid = null;
790 /** @var integer Authentication method one of WEBSERVICE_AUTHMETHOD_* */
791 protected $authmethod;
793 /** @var string Authentication token*/
794 protected $token = null;
796 /** @var stdClass Restricted context */
797 protected $restricted_context;
799 /** @var int Restrict call to one service id*/
800 protected $restricted_serviceid = null;
805 * @param integer $authmethod authentication method one of WEBSERVICE_AUTHMETHOD_*
807 public function __construct($authmethod) {
808 $this->authmethod
= $authmethod;
813 * Authenticate user using username+password or token.
814 * This function sets up $USER global.
815 * It is safe to use has_capability() after this.
816 * This method also verifies user is allowed to use this
819 protected function authenticate_user() {
822 if (!NO_MOODLE_COOKIES
) {
823 throw new coding_exception('Cookies must be disabled in WS servers!');
826 if ($this->authmethod
== WEBSERVICE_AUTHMETHOD_USERNAME
) {
828 //we check that authentication plugin is enabled
829 //it is only required by simple authentication
830 if (!is_enabled_auth('webservice')) {
831 throw new webservice_access_exception('The web service authentication plugin is disabled.');
834 if (!$auth = get_auth_plugin('webservice')) {
835 throw new webservice_access_exception('The web service authentication plugin is missing.');
838 $this->restricted_context
= context_system
::instance();
840 if (!$this->username
) {
841 throw new moodle_exception('missingusername', 'webservice');
844 if (!$this->password
) {
845 throw new moodle_exception('missingpassword', 'webservice');
848 if (!$auth->user_login_webservice($this->username
, $this->password
)) {
849 // log failed login attempts
850 add_to_log(SITEID
, 'webservice', get_string('simpleauthlog', 'webservice'), '' , get_string('failedtolog', 'webservice').": ".$this->username
."/".$this->password
." - ".getremoteaddr() , 0);
851 throw new moodle_exception('wrongusernamepassword', 'webservice');
854 $user = $DB->get_record('user', array('username'=>$this->username
, 'mnethostid'=>$CFG->mnet_localhost_id
), '*', MUST_EXIST
);
856 } else if ($this->authmethod
== WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN
){
857 $user = $this->authenticate_by_token(EXTERNAL_TOKEN_PERMANENT
);
859 $user = $this->authenticate_by_token(EXTERNAL_TOKEN_EMBEDDED
);
862 //Non admin can not authenticate if maintenance mode
863 $hassiteconfig = has_capability('moodle/site:config', context_system
::instance(), $user);
864 if (!empty($CFG->maintenance_enabled
) and !$hassiteconfig) {
865 throw new moodle_exception('sitemaintenance', 'admin');
868 //only confirmed user should be able to call web service
869 if (!empty($user->deleted
)) {
870 add_to_log(SITEID
, '', '', '', get_string('wsaccessuserdeleted', 'webservice', $user->username
) . " - ".getremoteaddr(), 0, $user->id
);
871 throw new webservice_access_exception('Refused web service access for deleted username: ' . $user->username
);
874 //only confirmed user should be able to call web service
875 if (empty($user->confirmed
)) {
876 add_to_log(SITEID
, '', '', '', get_string('wsaccessuserunconfirmed', 'webservice', $user->username
) . " - ".getremoteaddr(), 0, $user->id
);
877 throw new moodle_exception('wsaccessuserunconfirmed', 'webservice', '', $user->username
);
880 //check the user is suspended
881 if (!empty($user->suspended
)) {
882 add_to_log(SITEID
, '', '', '', get_string('wsaccessusersuspended', 'webservice', $user->username
) . " - ".getremoteaddr(), 0, $user->id
);
883 throw new webservice_access_exception('Refused web service access for suspended username: ' . $user->username
);
886 //retrieve the authentication plugin if no previously done
888 $auth = get_auth_plugin($user->auth
);
891 // check if credentials have expired
892 if (!empty($auth->config
->expiration
) and $auth->config
->expiration
== 1) {
893 $days2expire = $auth->password_expire($user->username
);
894 if (intval($days2expire) < 0 ) {
895 add_to_log(SITEID
, '', '', '', get_string('wsaccessuserexpired', 'webservice', $user->username
) . " - ".getremoteaddr(), 0, $user->id
);
896 throw new webservice_access_exception('Refused web service access for password expired username: ' . $user->username
);
900 //check if the auth method is nologin (in this case refuse connection)
901 if ($user->auth
=='nologin') {
902 add_to_log(SITEID
, '', '', '', get_string('wsaccessusernologin', 'webservice', $user->username
) . " - ".getremoteaddr(), 0, $user->id
);
903 throw new webservice_access_exception('Refused web service access for nologin authentication username: ' . $user->username
);
906 // now fake user login, the session is completely empty too
907 enrol_check_plugins($user);
908 session_set_user($user);
909 $this->userid
= $user->id
;
911 if ($this->authmethod
!= WEBSERVICE_AUTHMETHOD_SESSION_TOKEN
&& !has_capability("webservice/$this->wsname:use", $this->restricted_context
)) {
912 throw new webservice_access_exception('You are not allowed to use the {$a} protocol (missing capability: webservice/' . $this->wsname
. ':use)');
915 external_api
::set_context_restriction($this->restricted_context
);
919 * User authentication by token
921 * @param string $tokentype token type (EXTERNAL_TOKEN_EMBEDDED or EXTERNAL_TOKEN_PERMANENT)
922 * @return stdClass the authenticated user
923 * @throws webservice_access_exception
925 protected function authenticate_by_token($tokentype){
927 if (!$token = $DB->get_record('external_tokens', array('token'=>$this->token
, 'tokentype'=>$tokentype))) {
928 // log failed login attempts
929 add_to_log(SITEID
, 'webservice', get_string('tokenauthlog', 'webservice'), '' , get_string('failedtolog', 'webservice').": ".$this->token
. " - ".getremoteaddr() , 0);
930 throw new moodle_exception('invalidtoken', 'webservice');
933 if ($token->validuntil
and $token->validuntil
< time()) {
934 $DB->delete_records('external_tokens', array('token'=>$this->token
, 'tokentype'=>$tokentype));
935 throw new webservice_access_exception('Invalid token - token expired - check validuntil time for the token');
938 if ($token->sid
){//assumes that if sid is set then there must be a valid associated session no matter the token type
939 $session = session_get_instance();
940 if (!$session->session_exists($token->sid
)){
941 $DB->delete_records('external_tokens', array('sid'=>$token->sid
));
942 throw new webservice_access_exception('Invalid session based token - session not found or expired');
946 if ($token->iprestriction
and !address_in_subnet(getremoteaddr(), $token->iprestriction
)) {
947 add_to_log(SITEID
, 'webservice', get_string('tokenauthlog', 'webservice'), '' , get_string('failedtolog', 'webservice').": ".getremoteaddr() , 0);
948 throw new webservice_access_exception('Invalid service - IP:' . getremoteaddr()
949 . ' is not supported - check this allowed user');
952 $this->restricted_context
= context
::instance_by_id($token->contextid
);
953 $this->restricted_serviceid
= $token->externalserviceid
;
955 $user = $DB->get_record('user', array('id'=>$token->userid
), '*', MUST_EXIST
);
958 $DB->set_field('external_tokens', 'lastaccess', time(), array('id'=>$token->id
));
965 * Intercept some moodlewssettingXXX $_GET and $_POST parameter
966 * that are related to the web service call and are not the function parameters
968 protected function set_web_service_call_settings() {
971 // Default web service settings.
972 // Must be the same XXX key name as the external_settings::set_XXX function.
973 // Must be the same XXX ws parameter name as 'moodlewssettingXXX'.
974 $externalsettings = array(
979 // Load the external settings with the web service settings.
980 $settings = external_settings
::get_instance();
981 foreach ($externalsettings as $name => $default) {
983 $wsparamname = 'moodlewssetting' . $name;
985 // Retrieve and remove the setting parameter from the request.
986 $value = optional_param($wsparamname, $default, PARAM_BOOL
);
987 unset($_GET[$wsparamname]);
988 unset($_POST[$wsparamname]);
990 $functioname = 'set_' . $name;
991 $settings->$functioname($value);
998 * Special abstraction of our services that allows interaction with stock Zend ws servers.
1000 * @package core_webservice
1001 * @copyright 2009 Jerome Mouneyrac <jerome@moodle.com>
1002 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1004 abstract class webservice_zend_server
extends webservice_server
{
1006 /** @var string Name of the zend server class : Zend_Amf_Server, moodle_zend_soap_server, Zend_Soap_AutoDiscover, ...*/
1007 protected $zend_class;
1009 /** @var stdClass Zend server instance */
1010 protected $zend_server;
1012 /** @var string Virtual web service class with all functions user name execute, created on the fly */
1013 protected $service_class;
1018 * @param int $authmethod authentication method - one of WEBSERVICE_AUTHMETHOD_*
1019 * @param string $zend_class Name of the zend server class
1021 public function __construct($authmethod, $zend_class) {
1022 parent
::__construct($authmethod);
1023 $this->zend_class
= $zend_class;
1027 * Process request from client.
1031 public function run() {
1032 // we will probably need a lot of memory in some functions
1033 raise_memory_limit(MEMORY_EXTRA
);
1035 // set some longer timeout, this script is not sending any output,
1036 // this means we need to manually extend the timeout operations
1037 // that need longer time to finish
1038 external_api
::set_timeout();
1040 // now create the instance of zend server
1041 $this->init_zend_server();
1043 // set up exception handler first, we want to sent them back in correct format that
1044 // the other system understands
1045 // we do not need to call the original default handler because this ws handler does everything
1046 set_exception_handler(array($this, 'exception_handler'));
1048 // init all properties from the request data
1049 $this->parse_request();
1051 // this sets up $USER and $SESSION and context restrictions
1052 $this->authenticate_user();
1054 // make a list of all functions user is allowed to excecute
1055 $this->init_service_class();
1057 // tell server what functions are available
1058 $this->zend_server
->setClass($this->service_class
);
1060 //log the web service request
1061 add_to_log(SITEID
, 'webservice', '', '' , $this->zend_class
." ".getremoteaddr() , 0, $this->userid
);
1064 $this->send_headers();
1066 // execute and return response, this sends some headers too
1067 $response = $this->zend_server
->handle();
1070 $this->session_cleanup();
1072 //finally send the result
1078 * Load virtual class needed for Zend api
1080 protected function init_service_class() {
1083 // first ofall get a complete list of services user is allowed to access
1085 if ($this->restricted_serviceid
) {
1086 $params = array('sid1'=>$this->restricted_serviceid
, 'sid2'=>$this->restricted_serviceid
);
1087 $wscond1 = 'AND s.id = :sid1';
1088 $wscond2 = 'AND s.id = :sid2';
1095 // now make sure the function is listed in at least one service user is allowed to use
1096 // allow access only if:
1097 // 1/ entry in the external_services_users table if required
1098 // 2/ validuntil not reached
1099 // 3/ has capability if specified in service desc
1102 $sql = "SELECT s.*, NULL AS iprestriction
1103 FROM {external_services} s
1104 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0)
1105 WHERE s.enabled = 1 $wscond1
1109 SELECT s.*, su.iprestriction
1110 FROM {external_services} s
1111 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1)
1112 JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)
1113 WHERE s.enabled = 1 AND (su.validuntil IS NULL OR su.validuntil < :now) $wscond2";
1115 $params = array_merge($params, array('userid'=>$USER->id
, 'now'=>time()));
1117 $serviceids = array();
1118 $rs = $DB->get_recordset_sql($sql, $params);
1120 // now make sure user may access at least one service
1121 $remoteaddr = getremoteaddr();
1123 foreach ($rs as $service) {
1124 if (isset($serviceids[$service->id
])) {
1127 if ($service->requiredcapability
and !has_capability($service->requiredcapability
, $this->restricted_context
)) {
1128 continue; // cap required, sorry
1130 if ($service->iprestriction
and !address_in_subnet($remoteaddr, $service->iprestriction
)) {
1131 continue; // wrong request source ip, sorry
1133 $serviceids[$service->id
] = $service->id
;
1137 // now get the list of all functions
1138 $wsmanager = new webservice();
1139 $functions = $wsmanager->get_external_functions($serviceids);
1141 // now make the virtual WS class with all the fuctions for this particular user
1143 foreach ($functions as $function) {
1144 $methods .= $this->get_virtual_method_code($function);
1147 // let's use unique class name, there might be problem in unit tests
1148 $classname = 'webservices_virtual_class_000000';
1149 while(class_exists($classname)) {
1155 * Virtual class web services for user id '.$USER->id
.' in context '.$this->restricted_context
->id
.'.
1157 class '.$classname.' {
1162 // load the virtual class definition into memory
1164 $this->service_class
= $classname;
1168 * returns virtual method code
1170 * @param stdClass $function a record from external_function
1171 * @return string PHP code
1173 protected function get_virtual_method_code($function) {
1176 $function = external_function_info($function);
1178 //arguments in function declaration line with defaults.
1179 $paramanddefaults = array();
1180 //arguments used as parameters for external lib call.
1182 $params_desc = array();
1183 foreach ($function->parameters_desc
->keys
as $name=>$keydesc) {
1185 $paramanddefault = $param;
1186 //need to generate the default if there is any
1187 if ($keydesc instanceof external_value
) {
1188 if ($keydesc->required
== VALUE_DEFAULT
) {
1189 if ($keydesc->default===null) {
1190 $paramanddefault .= '=null';
1192 switch($keydesc->type
) {
1194 $paramanddefault .= '='. (int) $keydesc->default; break;
1196 $paramanddefault .= '='.$keydesc->default; break;
1198 $paramanddefault .= '='.$keydesc->default; break;
1200 $paramanddefault .= '=\''.$keydesc->default.'\'';
1203 } else if ($keydesc->required
== VALUE_OPTIONAL
) {
1204 //it does make sens to declare a parameter VALUE_OPTIONAL
1205 //VALUE_OPTIONAL is used only for array/object key
1206 throw new moodle_exception('parametercannotbevalueoptional');
1208 } else { //for the moment we do not support default for other structure types
1209 if ($keydesc->required
== VALUE_DEFAULT
) {
1210 //accept empty array as default
1211 if (isset($keydesc->default) and is_array($keydesc->default)
1212 and empty($keydesc->default)) {
1213 $paramanddefault .= '=array()';
1215 throw new moodle_exception('errornotemptydefaultparamarray', 'webservice', '', $name);
1218 if ($keydesc->required
== VALUE_OPTIONAL
) {
1219 throw new moodle_exception('erroroptionalparamarray', 'webservice', '', $name);
1223 $paramanddefaults[] = $paramanddefault;
1224 $type = $this->get_phpdoc_type($keydesc);
1225 $params_desc[] = ' * @param '.$type.' $'.$name.' '.$keydesc->desc
;
1227 $params = implode(', ', $params);
1228 $paramanddefaults = implode(', ', $paramanddefaults);
1229 $params_desc = implode("\n", $params_desc);
1231 $serviceclassmethodbody = $this->service_class_method_body($function, $params);
1233 if (is_null($function->returns_desc
)) {
1234 $return = ' * @return void';
1236 $type = $this->get_phpdoc_type($function->returns_desc
);
1237 $return = ' * @return '.$type.' '.$function->returns_desc
->desc
;
1240 // now crate the virtual method that calls the ext implementation
1244 * '.$function->description
.'
1249 public function '.$function->name
.'('.$paramanddefaults.') {
1250 '.$serviceclassmethodbody.'
1257 * Get the phpdoc type for an external_description
1258 * external_value => int, double or string
1259 * external_single_structure => object|struct, on-fly generated stdClass name, ...
1260 * external_multiple_structure => array
1262 * @param string $keydesc any of PARAM_*
1263 * @return string phpdoc type (string, double, int, array...)
1265 protected function get_phpdoc_type($keydesc) {
1266 if ($keydesc instanceof external_value
) {
1267 switch($keydesc->type
) {
1268 case PARAM_BOOL
: // 0 or 1 only for now
1270 $type = 'int'; break;
1272 $type = 'double'; break;
1277 } else if ($keydesc instanceof external_single_structure
) {
1278 $classname = $this->generate_simple_struct_class($keydesc);
1281 } else if ($keydesc instanceof external_multiple_structure
) {
1289 * Generate 'struct'/'object' type name
1290 * Some servers (our Zend ones) parse the phpdoc to know the parameter types.
1291 * The purpose to this function is to be overwritten when the common object|struct type are not understood by the server.
1292 * See webservice/soap/locallib.php - the SOAP server requires detailed structure)
1294 * @param external_single_structure $structdesc the structure for which we generate the phpdoc type
1295 * @return string the phpdoc type
1297 protected function generate_simple_struct_class(external_single_structure
$structdesc) {
1298 return 'object|struct'; //only 'object' is supported by SOAP, 'struct' by XML-RPC MDL-23083
1302 * You can override this function in your child class to add extra code into the dynamically
1303 * created service class. For example it is used in the amf server to cast types of parameters and to
1304 * cast the return value to the types as specified in the return value description.
1306 * @param stdClass $function a record from external_function
1307 * @param array $params web service function parameters
1308 * @return string body of the method for $function ie. everything within the {} of the method declaration.
1310 protected function service_class_method_body($function, $params){
1311 //cast the param from object to array (validate_parameters except array only)
1314 $paramstocast = explode(',', $params);
1315 foreach ($paramstocast as $paramtocast) {
1316 //clean the parameter from any white space
1317 $paramtocast = trim($paramtocast);
1318 $castingcode .= $paramtocast .
1319 '=webservice_zend_server::cast_objects_to_array('.$paramtocast.');';
1324 $descriptionmethod = $function->methodname
.'_returns()';
1325 $callforreturnvaluedesc = $function->classname
.'::'.$descriptionmethod;
1326 return $castingcode . ' if ('.$callforreturnvaluedesc.' == null) {'.
1327 $function->classname
.'::'.$function->methodname
.'('.$params.');
1330 return external_api::clean_returnvalue('.$callforreturnvaluedesc.', '.$function->classname
.'::'.$function->methodname
.'('.$params.'));';
1334 * Recursive function to recurse down into a complex variable and convert all
1335 * objects to arrays.
1337 * @param mixed $param value to cast
1338 * @return mixed Cast value
1340 public static function cast_objects_to_array($param){
1341 if (is_object($param)){
1342 $param = (array)$param;
1344 if (is_array($param)){
1345 $toreturn = array();
1346 foreach ($param as $key=> $param){
1347 $toreturn[$key] = self
::cast_objects_to_array($param);
1356 * Set up zend service class
1358 protected function init_zend_server() {
1359 $this->zend_server
= new $this->zend_class();
1363 * This method parses the $_POST and $_GET superglobals and looks for
1364 * the following information:
1365 * 1/ user authentication - username+password or token (wsusername, wspassword and wstoken parameters)
1369 protected function parse_request() {
1371 // We are going to clean the POST/GET parameters from the parameters specific to the server.
1372 parent
::set_web_service_call_settings();
1374 // Get GET and POST paramters.
1375 $methodvariables = array_merge($_GET,$_POST);
1377 if ($this->authmethod
== WEBSERVICE_AUTHMETHOD_USERNAME
) {
1378 //note: some clients have problems with entity encoding :-(
1379 if (isset($methodvariables['wsusername'])) {
1380 $this->username
= $methodvariables['wsusername'];
1382 if (isset($methodvariables['wspassword'])) {
1383 $this->password
= $methodvariables['wspassword'];
1386 if (isset($methodvariables['wstoken'])) {
1387 $this->token
= $methodvariables['wstoken'];
1393 * Internal implementation - sending of page headers.
1395 protected function send_headers() {
1396 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
1397 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1398 header('Pragma: no-cache');
1399 header('Accept-Ranges: none');
1403 * Specialised exception handler, we can not use the standard one because
1404 * it can not just print html to output.
1406 * @param exception $ex
1409 public function exception_handler($ex) {
1410 // detect active db transactions, rollback and log as error
1411 abort_all_db_transactions();
1413 // some hacks might need a cleanup hook
1414 $this->session_cleanup($ex);
1416 // now let the plugin send the exception to client
1417 $this->send_error($ex);
1419 // not much else we can do now, add some logging later
1424 * Send the error information to the WS client
1425 * formatted as XML document.
1427 * @param exception $ex
1429 protected function send_error($ex=null) {
1430 $this->send_headers();
1431 echo $this->zend_server
->fault($ex);
1435 * Future hook needed for emulated sessions.
1437 * @param exception $exception null means normal termination, $exception received when WS call failed
1439 protected function session_cleanup($exception=null) {
1440 if ($this->authmethod
== WEBSERVICE_AUTHMETHOD_USERNAME
) {
1441 // nothing needs to be done, there is no persistent session
1443 // close emulated session if used
1450 * Web Service server base class.
1452 * This class handles both simple and token authentication.
1454 * @package core_webservice
1455 * @copyright 2009 Petr Skodak
1456 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1458 abstract class webservice_base_server
extends webservice_server
{
1460 /** @var array The function parameters - the real values submitted in the request */
1461 protected $parameters = null;
1463 /** @var string The name of the function that is executed */
1464 protected $functionname = null;
1466 /** @var stdClass Full function description */
1467 protected $function = null;
1469 /** @var mixed Function return value */
1470 protected $returns = null;
1473 * This method parses the request input, it needs to get:
1474 * 1/ user authentication - username+password or token
1476 * 3/ function parameters
1478 abstract protected function parse_request();
1481 * Send the result of function call to the WS client.
1483 abstract protected function send_response();
1486 * Send the error information to the WS client.
1488 * @param exception $ex
1490 abstract protected function send_error($ex=null);
1493 * Process request from client.
1497 public function run() {
1498 // we will probably need a lot of memory in some functions
1499 raise_memory_limit(MEMORY_EXTRA
);
1501 // set some longer timeout, this script is not sending any output,
1502 // this means we need to manually extend the timeout operations
1503 // that need longer time to finish
1504 external_api
::set_timeout();
1506 // set up exception handler first, we want to sent them back in correct format that
1507 // the other system understands
1508 // we do not need to call the original default handler because this ws handler does everything
1509 set_exception_handler(array($this, 'exception_handler'));
1511 // init all properties from the request data
1512 $this->parse_request();
1514 // authenticate user, this has to be done after the request parsing
1515 // this also sets up $USER and $SESSION
1516 $this->authenticate_user();
1518 // find all needed function info and make sure user may actually execute the function
1519 $this->load_function_info();
1521 //log the web service request
1522 add_to_log(SITEID
, 'webservice', $this->functionname
, '' , getremoteaddr() , 0, $this->userid
);
1524 // finally, execute the function - any errors are catched by the default exception handler
1527 // send the results back in correct format
1528 $this->send_response();
1531 $this->session_cleanup();
1537 * Specialised exception handler, we can not use the standard one because
1538 * it can not just print html to output.
1540 * @param exception $ex
1543 public function exception_handler($ex) {
1544 // detect active db transactions, rollback and log as error
1545 abort_all_db_transactions();
1547 // some hacks might need a cleanup hook
1548 $this->session_cleanup($ex);
1550 // now let the plugin send the exception to client
1551 $this->send_error($ex);
1553 // not much else we can do now, add some logging later
1558 * Future hook needed for emulated sessions.
1560 * @param exception $exception null means normal termination, $exception received when WS call failed
1562 protected function session_cleanup($exception=null) {
1563 if ($this->authmethod
== WEBSERVICE_AUTHMETHOD_USERNAME
) {
1564 // nothing needs to be done, there is no persistent session
1566 // close emulated session if used
1571 * Fetches the function description from database,
1572 * verifies user is allowed to use this function and
1573 * loads all paremeters and return descriptions.
1575 protected function load_function_info() {
1576 global $DB, $USER, $CFG;
1578 if (empty($this->functionname
)) {
1579 throw new invalid_parameter_exception('Missing function name');
1582 // function must exist
1583 $function = external_function_info($this->functionname
);
1585 if ($this->restricted_serviceid
) {
1586 $params = array('sid1'=>$this->restricted_serviceid
, 'sid2'=>$this->restricted_serviceid
);
1587 $wscond1 = 'AND s.id = :sid1';
1588 $wscond2 = 'AND s.id = :sid2';
1595 // now let's verify access control
1597 // now make sure the function is listed in at least one service user is allowed to use
1598 // allow access only if:
1599 // 1/ entry in the external_services_users table if required
1600 // 2/ validuntil not reached
1601 // 3/ has capability if specified in service desc
1604 $sql = "SELECT s.*, NULL AS iprestriction
1605 FROM {external_services} s
1606 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0 AND sf.functionname = :name1)
1607 WHERE s.enabled = 1 $wscond1
1611 SELECT s.*, su.iprestriction
1612 FROM {external_services} s
1613 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1 AND sf.functionname = :name2)
1614 JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)
1615 WHERE s.enabled = 1 AND (su.validuntil IS NULL OR su.validuntil < :now) $wscond2";
1616 $params = array_merge($params, array('userid'=>$USER->id
, 'name1'=>$function->name
, 'name2'=>$function->name
, 'now'=>time()));
1618 $rs = $DB->get_recordset_sql($sql, $params);
1619 // now make sure user may access at least one service
1620 $remoteaddr = getremoteaddr();
1622 foreach ($rs as $service) {
1623 if ($service->requiredcapability
and !has_capability($service->requiredcapability
, $this->restricted_context
)) {
1624 continue; // cap required, sorry
1626 if ($service->iprestriction
and !address_in_subnet($remoteaddr, $service->iprestriction
)) {
1627 continue; // wrong request source ip, sorry
1630 break; // one service is enough, no need to continue
1634 throw new webservice_access_exception(
1635 'Access to the function '.$this->functionname
.'() is not allowed.
1636 Please check if a service containing the function is enabled.
1637 In the service settings: if the service is restricted check that
1638 the user is listed. Still in the service settings check for
1639 IP restriction or if the service requires a capability.');
1642 // we have all we need now
1643 $this->function = $function;
1647 * Execute previously loaded function using parameters parsed from the request data.
1649 protected function execute() {
1650 // validate params, this also sorts the params properly, we need the correct order in the next part
1651 $params = call_user_func(array($this->function->classname
, 'validate_parameters'), $this->function->parameters_desc
, $this->parameters
);
1654 $this->returns
= call_user_func_array(array($this->function->classname
, $this->function->methodname
), array_values($params));