2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * Web services utility functions and classes
21 * @package core_webservice
22 * @copyright 2009 Jerome Mouneyrac <jerome@moodle.com>
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 require_once($CFG->libdir
.'/externallib.php');
29 * WEBSERVICE_AUTHMETHOD_USERNAME - username/password authentication (also called simple authentication)
31 define('WEBSERVICE_AUTHMETHOD_USERNAME', 0);
34 * WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN - most common token authentication (external app, mobile app...)
36 define('WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN', 1);
39 * WEBSERVICE_AUTHMETHOD_SESSION_TOKEN - token for embedded application (requires Moodle session)
41 define('WEBSERVICE_AUTHMETHOD_SESSION_TOKEN', 2);
44 * General web service library
46 * @package core_webservice
47 * @copyright 2010 Jerome Mouneyrac <jerome@moodle.com>
48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
53 * Authenticate user (used by download/upload file scripts)
55 * @param string $token
56 * @return array - contains the authenticated user, token and service objects
58 public function authenticate_user($token) {
61 // web service must be enabled to use this script
62 if (!$CFG->enablewebservices
) {
63 throw new webservice_access_exception('Web services are not enabled in Advanced features.');
66 // Obtain token record
67 if (!$token = $DB->get_record('external_tokens', array('token' => $token))) {
68 //client may want to display login form => moodle_exception
69 throw new moodle_exception('invalidtoken', 'webservice');
72 $loginfaileddefaultparams = array(
74 'method' => WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN
,
76 'tokenid' => $token->id
80 // Validate token date
81 if ($token->validuntil
and $token->validuntil
< time()) {
82 $params = $loginfaileddefaultparams;
83 $params['other']['reason'] = 'token_expired';
84 $event = \core\event\webservice_login_failed
::create($params);
85 $event->add_record_snapshot('external_tokens', $token);
86 $event->set_legacy_logdata(array(SITEID
, 'webservice', get_string('tokenauthlog', 'webservice'), '',
87 get_string('invalidtimedtoken', 'webservice'), 0));
89 $DB->delete_records('external_tokens', array('token' => $token->token
));
90 throw new webservice_access_exception('Invalid token - token expired - check validuntil time for the token');
94 if ($token->iprestriction
and !address_in_subnet(getremoteaddr(), $token->iprestriction
)) {
95 $params = $loginfaileddefaultparams;
96 $params['other']['reason'] = 'ip_restricted';
97 $event = \core\event\webservice_login_failed
::create($params);
98 $event->add_record_snapshot('external_tokens', $token);
99 $event->set_legacy_logdata(array(SITEID
, 'webservice', get_string('tokenauthlog', 'webservice'), '',
100 get_string('failedtolog', 'webservice') . ": " . getremoteaddr(), 0));
102 throw new webservice_access_exception('Invalid token - IP:' . getremoteaddr()
103 . ' is not supported');
106 //retrieve user link to the token
107 $user = $DB->get_record('user', array('id' => $token->userid
, 'deleted' => 0), '*', MUST_EXIST
);
109 // let enrol plugins deal with new enrolments if necessary
110 enrol_check_plugins($user);
112 // setup user session to check capability
113 \core\session\manager
::set_user($user);
114 set_login_session_preferences();
116 //assumes that if sid is set then there must be a valid associated session no matter the token type
118 if (!\core\session\manager
::session_exists($token->sid
)) {
119 $DB->delete_records('external_tokens', array('sid' => $token->sid
));
120 throw new webservice_access_exception('Invalid session based token - session not found or expired');
124 // Cannot authenticate unless maintenance access is granted.
125 $hasmaintenanceaccess = has_capability('moodle/site:maintenanceaccess', context_system
::instance(), $user);
126 if (!empty($CFG->maintenance_enabled
) and !$hasmaintenanceaccess) {
127 //this is usually temporary, client want to implement code logic => moodle_exception
128 throw new moodle_exception('sitemaintenance', 'admin');
131 //retrieve web service record
132 $service = $DB->get_record('external_services', array('id' => $token->externalserviceid
, 'enabled' => 1));
133 if (empty($service)) {
134 // will throw exception if no token found
135 throw new webservice_access_exception('Web service is not available (it doesn\'t exist or might be disabled)');
138 //check if there is any required system capability
139 if ($service->requiredcapability
and !has_capability($service->requiredcapability
, context_system
::instance(), $user)) {
140 throw new webservice_access_exception('The capability ' . $service->requiredcapability
. ' is required.');
143 //specific checks related to user restricted service
144 if ($service->restrictedusers
) {
145 $authoriseduser = $DB->get_record('external_services_users', array('externalserviceid' => $service->id
, 'userid' => $user->id
));
147 if (empty($authoriseduser)) {
148 throw new webservice_access_exception(
149 'The user is not allowed for this service. First you need to allow this user on the '
150 . $service->name
. '\'s allowed users administration page.');
153 if (!empty($authoriseduser->validuntil
) and $authoriseduser->validuntil
< time()) {
154 throw new webservice_access_exception('Invalid service - service expired - check validuntil time for this allowed user');
157 if (!empty($authoriseduser->iprestriction
) and !address_in_subnet(getremoteaddr(), $authoriseduser->iprestriction
)) {
158 throw new webservice_access_exception('Invalid service - IP:' . getremoteaddr()
159 . ' is not supported - check this allowed user');
163 //only confirmed user should be able to call web service
164 if (empty($user->confirmed
)) {
165 $params = $loginfaileddefaultparams;
166 $params['other']['reason'] = 'user_unconfirmed';
167 $event = \core\event\webservice_login_failed
::create($params);
168 $event->add_record_snapshot('external_tokens', $token);
169 $event->set_legacy_logdata(array(SITEID
, 'webservice', 'user unconfirmed', '', $user->username
));
171 throw new moodle_exception('usernotconfirmed', 'moodle', '', $user->username
);
174 //check the user is suspended
175 if (!empty($user->suspended
)) {
176 $params = $loginfaileddefaultparams;
177 $params['other']['reason'] = 'user_suspended';
178 $event = \core\event\webservice_login_failed
::create($params);
179 $event->add_record_snapshot('external_tokens', $token);
180 $event->set_legacy_logdata(array(SITEID
, 'webservice', 'user suspended', '', $user->username
));
182 throw new webservice_access_exception('Refused web service access for suspended username: ' . $user->username
);
185 //check if the auth method is nologin (in this case refuse connection)
186 if ($user->auth
== 'nologin') {
187 $params = $loginfaileddefaultparams;
188 $params['other']['reason'] = 'nologin';
189 $event = \core\event\webservice_login_failed
::create($params);
190 $event->add_record_snapshot('external_tokens', $token);
191 $event->set_legacy_logdata(array(SITEID
, 'webservice', 'nologin auth attempt with web service', '', $user->username
));
193 throw new webservice_access_exception('Refused web service access for nologin authentication username: ' . $user->username
);
196 //Check if the user password is expired
197 $auth = get_auth_plugin($user->auth
);
198 if (!empty($auth->config
->expiration
) and $auth->config
->expiration
== 1) {
199 $days2expire = $auth->password_expire($user->username
);
200 if (intval($days2expire) < 0) {
201 $params = $loginfaileddefaultparams;
202 $params['other']['reason'] = 'password_expired';
203 $event = \core\event\webservice_login_failed
::create($params);
204 $event->add_record_snapshot('external_tokens', $token);
205 $event->set_legacy_logdata(array(SITEID
, 'webservice', 'expired password', '', $user->username
));
207 throw new moodle_exception('passwordisexpired', 'webservice');
212 $DB->set_field('external_tokens', 'lastaccess', time(), array('id' => $token->id
));
214 return array('user' => $user, 'token' => $token, 'service' => $service);
218 * Allow user to call a service
220 * @param stdClass $user a user
222 public function add_ws_authorised_user($user) {
224 $user->timecreated
= time();
225 $DB->insert_record('external_services_users', $user);
229 * Disallow a user to call a service
231 * @param stdClass $user a user
232 * @param int $serviceid
234 public function remove_ws_authorised_user($user, $serviceid) {
236 $DB->delete_records('external_services_users',
237 array('externalserviceid' => $serviceid, 'userid' => $user->id
));
241 * Update allowed user settings (ip restriction, valid until...)
243 * @param stdClass $user
245 public function update_ws_authorised_user($user) {
247 $DB->update_record('external_services_users', $user);
251 * Return list of allowed users with their options (ip/timecreated / validuntil...)
252 * for a given service
254 * @param int $serviceid the service id to search against
255 * @return array $users
257 public function get_ws_authorised_users($serviceid) {
259 $params = array($CFG->siteguest
, $serviceid);
260 $sql = " SELECT u.id as id, esu.id as serviceuserid, u.email as email, u.firstname as firstname,
261 u.lastname as lastname,
262 esu.iprestriction as iprestriction, esu.validuntil as validuntil,
263 esu.timecreated as timecreated
264 FROM {user} u, {external_services_users} esu
265 WHERE u.id <> ? AND u.deleted = 0 AND u.confirmed = 1
266 AND esu.userid = u.id
267 AND esu.externalserviceid = ?";
269 $users = $DB->get_records_sql($sql, $params);
274 * Return an authorised user with their options (ip/timecreated / validuntil...)
276 * @param int $serviceid the service id to search against
277 * @param int $userid the user to search against
280 public function get_ws_authorised_user($serviceid, $userid) {
282 $params = array($CFG->siteguest
, $serviceid, $userid);
283 $sql = " SELECT u.id as id, esu.id as serviceuserid, u.email as email, u.firstname as firstname,
284 u.lastname as lastname,
285 esu.iprestriction as iprestriction, esu.validuntil as validuntil,
286 esu.timecreated as timecreated
287 FROM {user} u, {external_services_users} esu
288 WHERE u.id <> ? AND u.deleted = 0 AND u.confirmed = 1
289 AND esu.userid = u.id
290 AND esu.externalserviceid = ?
292 $user = $DB->get_record_sql($sql, $params);
297 * Generate all tokens of a specific user
299 * @param int $userid user id
301 public function generate_user_ws_tokens($userid) {
304 // generate a token for non admin if web service are enable and the user has the capability to create a token
305 if (!is_siteadmin() && has_capability('moodle/webservice:createtoken', context_system
::instance(), $userid) && !empty($CFG->enablewebservices
)) {
306 // for every service than the user is authorised on, create a token (if it doesn't already exist)
308 // get all services which are set to all user (no restricted to specific users)
309 $norestrictedservices = $DB->get_records('external_services', array('restrictedusers' => 0));
310 $serviceidlist = array();
311 foreach ($norestrictedservices as $service) {
312 $serviceidlist[] = $service->id
;
315 // get all services which are set to the current user (the current user is specified in the restricted user list)
316 $servicesusers = $DB->get_records('external_services_users', array('userid' => $userid));
317 foreach ($servicesusers as $serviceuser) {
318 if (!in_array($serviceuser->externalserviceid
,$serviceidlist)) {
319 $serviceidlist[] = $serviceuser->externalserviceid
;
323 // get all services which already have a token set for the current user
324 $usertokens = $DB->get_records('external_tokens', array('userid' => $userid, 'tokentype' => EXTERNAL_TOKEN_PERMANENT
));
325 $tokenizedservice = array();
326 foreach ($usertokens as $token) {
327 $tokenizedservice[] = $token->externalserviceid
;
330 // create a token for the service which have no token already
331 foreach ($serviceidlist as $serviceid) {
332 if (!in_array($serviceid, $tokenizedservice)) {
333 // create the token for this service
334 $newtoken = new stdClass();
335 $newtoken->token
= md5(uniqid(rand(),1));
336 // check that the user has capability on this service
337 $newtoken->tokentype
= EXTERNAL_TOKEN_PERMANENT
;
338 $newtoken->userid
= $userid;
339 $newtoken->externalserviceid
= $serviceid;
340 // TODO MDL-31190 find a way to get the context - UPDATE FOLLOWING LINE
341 $newtoken->contextid
= context_system
::instance()->id
;
342 $newtoken->creatorid
= $userid;
343 $newtoken->timecreated
= time();
344 $newtoken->privatetoken
= null;
346 $DB->insert_record('external_tokens', $newtoken);
355 * Return all tokens of a specific user
356 * + the service state (enabled/disabled)
357 * + the authorised user mode (restricted/not restricted)
359 * @param int $userid user id
362 public function get_user_ws_tokens($userid) {
364 //here retrieve token list (including linked users firstname/lastname and linked services name)
366 t.id, t.creatorid, t.token, u.firstname, u.lastname, s.id as wsid, s.name, s.enabled, s.restrictedusers, t.validuntil
368 {external_tokens} t, {user} u, {external_services} s
370 t.userid=? AND t.tokentype = ".EXTERNAL_TOKEN_PERMANENT
." AND s.id = t.externalserviceid AND t.userid = u.id";
371 $tokens = $DB->get_records_sql($sql, array( $userid));
376 * Return a token that has been created by the user (i.e. to created by an admin)
377 * If no tokens exist an exception is thrown
379 * The returned value is a stdClass:
382 * ->firstname user firstname
384 * ->name service name
386 * @param int $userid user id
387 * @param int $tokenid token id
390 public function get_created_by_user_ws_token($userid, $tokenid) {
393 t.id, t.token, u.firstname, u.lastname, s.name
395 {external_tokens} t, {user} u, {external_services} s
397 t.creatorid=? AND t.id=? AND t.tokentype = "
398 . EXTERNAL_TOKEN_PERMANENT
399 . " AND s.id = t.externalserviceid AND t.userid = u.id";
400 //must be the token creator
401 $token = $DB->get_record_sql($sql, array($userid, $tokenid), MUST_EXIST
);
406 * Return a database token record for a token id
408 * @param int $tokenid token id
409 * @return object token
411 public function get_token_by_id($tokenid) {
413 return $DB->get_record('external_tokens', array('id' => $tokenid));
419 * @param int $tokenid token id
421 public function delete_user_ws_token($tokenid) {
423 $DB->delete_records('external_tokens', array('id'=>$tokenid));
427 * Delete all the tokens belonging to a user.
429 * @param int $userid the user id whose tokens must be deleted
431 public static function delete_user_ws_tokens($userid) {
433 $DB->delete_records('external_tokens', array('userid' => $userid));
438 * Also delete function references and authorised user references.
440 * @param int $serviceid service id
442 public function delete_service($serviceid) {
444 $DB->delete_records('external_services_users', array('externalserviceid' => $serviceid));
445 $DB->delete_records('external_services_functions', array('externalserviceid' => $serviceid));
446 $DB->delete_records('external_tokens', array('externalserviceid' => $serviceid));
447 $DB->delete_records('external_services', array('id' => $serviceid));
451 * Get a full database token record for a given token value
453 * @param string $token
454 * @throws moodle_exception if there is multiple result
456 public function get_user_ws_token($token) {
458 return $DB->get_record('external_tokens', array('token'=>$token), '*', MUST_EXIST
);
462 * Get the functions list of a service list (by id)
464 * @param array $serviceids service ids
465 * @return array of functions
467 public function get_external_functions($serviceids) {
469 if (!empty($serviceids)) {
470 list($serviceids, $params) = $DB->get_in_or_equal($serviceids);
472 FROM {external_functions} f
473 WHERE f.name IN (SELECT sf.functionname
474 FROM {external_services_functions} sf
475 WHERE sf.externalserviceid $serviceids)
476 ORDER BY f.name ASC";
477 $functions = $DB->get_records_sql($sql, $params);
479 $functions = array();
485 * Get the functions of a service list (by shortname). It can return only enabled functions if required.
487 * @param array $serviceshortnames service shortnames
488 * @param bool $enabledonly if true then only return functions for services that have been enabled
489 * @return array functions
491 public function get_external_functions_by_enabled_services($serviceshortnames, $enabledonly = true) {
493 if (!empty($serviceshortnames)) {
494 $enabledonlysql = $enabledonly?
' AND s.enabled = 1 ':'';
495 list($serviceshortnames, $params) = $DB->get_in_or_equal($serviceshortnames);
497 FROM {external_functions} f
498 WHERE f.name IN (SELECT sf.functionname
499 FROM {external_services_functions} sf, {external_services} s
500 WHERE s.shortname $serviceshortnames
501 AND sf.externalserviceid = s.id
502 " . $enabledonlysql . ")";
503 $functions = $DB->get_records_sql($sql, $params);
505 $functions = array();
511 * Get functions not included in a service
513 * @param int $serviceid service id
514 * @return array functions
516 public function get_not_associated_external_functions($serviceid) {
518 $select = "name NOT IN (SELECT s.functionname
519 FROM {external_services_functions} s
520 WHERE s.externalserviceid = :sid
523 $functions = $DB->get_records_select('external_functions',
524 $select, array('sid' => $serviceid), 'name');
530 * Get list of required capabilities of a service, sorted by functions
531 * Example of returned value:
534 * [core_group_create_groups] => Array
536 * [0] => moodle/course:managegroups
539 * [core_enrol_get_enrolled_users] => Array
541 * [0] => moodle/user:viewdetails
542 * [1] => moodle/user:viewhiddendetails
543 * [2] => moodle/course:useremail
544 * [3] => moodle/user:update
545 * [4] => moodle/site:accessallgroups
548 * @param int $serviceid service id
551 public function get_service_required_capabilities($serviceid) {
552 $functions = $this->get_external_functions(array($serviceid));
553 $requiredusercaps = array();
554 foreach ($functions as $function) {
555 $functioncaps = explode(',', $function->capabilities
);
556 if (!empty($functioncaps) and !empty($functioncaps[0])) {
557 foreach ($functioncaps as $functioncap) {
558 $requiredusercaps[$function->name
][] = trim($functioncap);
562 return $requiredusercaps;
566 * Get user capabilities (with context)
567 * Only useful for documentation purpose
568 * WARNING: do not use this "broken" function. It was created in the goal to display some capabilities
569 * required by users. In theory we should not need to display this kind of information
570 * as the front end does not display it itself. In pratice,
571 * admins would like the info, for more info you can follow: MDL-29962
573 * @param int $userid user id
576 public function get_user_capabilities($userid) {
578 //retrieve the user capabilities
579 $sql = "SELECT DISTINCT rc.id, rc.capability FROM {role_capabilities} rc, {role_assignments} ra
580 WHERE rc.roleid=ra.roleid AND ra.userid= ? AND rc.permission = ?";
581 $dbusercaps = $DB->get_records_sql($sql, array($userid, CAP_ALLOW
));
583 foreach ($dbusercaps as $usercap) {
584 $usercaps[$usercap->capability
] = true;
590 * Get missing user capabilities for a given service
591 * WARNING: do not use this "broken" function. It was created in the goal to display some capabilities
592 * required by users. In theory we should not need to display this kind of information
593 * as the front end does not display it itself. In pratice,
594 * admins would like the info, for more info you can follow: MDL-29962
596 * @param array $users users
597 * @param int $serviceid service id
598 * @return array of missing capabilities, keys being the user ids
600 public function get_missing_capabilities_by_users($users, $serviceid) {
602 $usersmissingcaps = array();
604 //retrieve capabilities required by the service
605 $servicecaps = $this->get_service_required_capabilities($serviceid);
607 //retrieve users missing capabilities
608 foreach ($users as $user) {
609 //cast user array into object to be a bit more flexible
610 if (is_array($user)) {
611 $user = (object) $user;
613 $usercaps = $this->get_user_capabilities($user->id
);
615 //detect the missing capabilities
616 foreach ($servicecaps as $functioname => $functioncaps) {
617 foreach ($functioncaps as $functioncap) {
618 if (!array_key_exists($functioncap, $usercaps)) {
619 if (!isset($usersmissingcaps[$user->id
])
620 or array_search($functioncap, $usersmissingcaps[$user->id
]) === false) {
621 $usersmissingcaps[$user->id
][] = $functioncap;
628 return $usersmissingcaps;
632 * Get an external service for a given service id
634 * @param int $serviceid service id
635 * @param int $strictness IGNORE_MISSING, MUST_EXIST...
636 * @return stdClass external service
638 public function get_external_service_by_id($serviceid, $strictness=IGNORE_MISSING
) {
640 $service = $DB->get_record('external_services',
641 array('id' => $serviceid), '*', $strictness);
646 * Get an external service for a given shortname
648 * @param string $shortname service shortname
649 * @param int $strictness IGNORE_MISSING, MUST_EXIST...
650 * @return stdClass external service
652 public function get_external_service_by_shortname($shortname, $strictness=IGNORE_MISSING
) {
654 $service = $DB->get_record('external_services',
655 array('shortname' => $shortname), '*', $strictness);
660 * Get an external function for a given function id
662 * @param int $functionid function id
663 * @param int $strictness IGNORE_MISSING, MUST_EXIST...
664 * @return stdClass external function
666 public function get_external_function_by_id($functionid, $strictness=IGNORE_MISSING
) {
668 $function = $DB->get_record('external_functions',
669 array('id' => $functionid), '*', $strictness);
674 * Add a function to a service
676 * @param string $functionname function name
677 * @param int $serviceid service id
679 public function add_external_function_to_service($functionname, $serviceid) {
681 $addedfunction = new stdClass();
682 $addedfunction->externalserviceid
= $serviceid;
683 $addedfunction->functionname
= $functionname;
684 $DB->insert_record('external_services_functions', $addedfunction);
689 * It generates the timecreated field automatically.
691 * @param stdClass $service
692 * @return serviceid integer
694 public function add_external_service($service) {
696 $service->timecreated
= time();
697 $serviceid = $DB->insert_record('external_services', $service);
703 * It modifies the timemodified automatically.
705 * @param stdClass $service
707 public function update_external_service($service) {
709 $service->timemodified
= time();
710 $DB->update_record('external_services', $service);
714 * Test whether an external function is already linked to a service
716 * @param string $functionname function name
717 * @param int $serviceid service id
718 * @return bool true if a matching function exists for the service, else false.
719 * @throws dml_exception if error
721 public function service_function_exists($functionname, $serviceid) {
723 return $DB->record_exists('external_services_functions',
724 array('externalserviceid' => $serviceid,
725 'functionname' => $functionname));
729 * Remove a function from a service
731 * @param string $functionname function name
732 * @param int $serviceid service id
734 public function remove_external_function_from_service($functionname, $serviceid) {
736 $DB->delete_records('external_services_functions',
737 array('externalserviceid' => $serviceid, 'functionname' => $functionname));
742 * Return a list with all the valid user tokens for the given user, it only excludes expired tokens.
744 * @param string $userid user id to retrieve tokens from
745 * @return array array of token entries
748 public static function get_active_tokens($userid) {
751 $sql = 'SELECT t.*, s.name as servicename FROM {external_tokens} t JOIN
752 {external_services} s ON t.externalserviceid = s.id WHERE
753 t.userid = :userid AND (t.validuntil IS NULL OR t.validuntil > :now)';
754 $params = array('userid' => $userid, 'now' => time());
755 return $DB->get_records_sql($sql, $params);
760 * Exception indicating access control problem in web service call
761 * This exception should return general errors about web service setup.
762 * Errors related to the user like wrong username/password should not use it,
763 * you should not use this exception if you want to let the client implement
764 * some code logic against an access error.
766 * @package core_webservice
767 * @copyright 2009 Petr Skodak
768 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
770 class webservice_access_exception
extends moodle_exception
{
775 * @param string $debuginfo the debug info
777 function __construct($debuginfo) {
778 parent
::__construct('accessexception', 'webservice', '', null, $debuginfo);
783 * Check if a protocol is enabled
785 * @param string $protocol name of WS protocol ('rest', 'soap', 'xmlrpc'...)
786 * @return bool true if the protocol is enabled
788 function webservice_protocol_is_enabled($protocol) {
791 if (empty($CFG->enablewebservices
)) {
795 $active = explode(',', $CFG->webserviceprotocols
);
797 return(in_array($protocol, $active));
801 * Mandatory interface for all test client classes.
803 * @package core_webservice
804 * @copyright 2009 Petr Skodak
805 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
807 interface webservice_test_client_interface
{
810 * Execute test client WS request
812 * @param string $serverurl server url (including the token param)
813 * @param string $function web service function name
814 * @param array $params parameters of the web service function
817 public function simpletest($serverurl, $function, $params);
821 * Mandatory interface for all web service protocol classes
823 * @package core_webservice
824 * @copyright 2009 Petr Skodak
825 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
827 interface webservice_server_interface
{
830 * Process request from client.
832 public function run();
836 * Abstract web service base class.
838 * @package core_webservice
839 * @copyright 2009 Petr Skodak
840 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
842 abstract class webservice_server
implements webservice_server_interface
{
844 /** @var string Name of the web server plugin */
845 protected $wsname = null;
847 /** @var string Name of local user */
848 protected $username = null;
850 /** @var string Password of the local user */
851 protected $password = null;
853 /** @var int The local user */
854 protected $userid = null;
856 /** @var integer Authentication method one of WEBSERVICE_AUTHMETHOD_* */
857 protected $authmethod;
859 /** @var string Authentication token*/
860 protected $token = null;
862 /** @var stdClass Restricted context */
863 protected $restricted_context;
865 /** @var int Restrict call to one service id*/
866 protected $restricted_serviceid = null;
871 * @param integer $authmethod authentication method one of WEBSERVICE_AUTHMETHOD_*
873 public function __construct($authmethod) {
874 $this->authmethod
= $authmethod;
879 * Authenticate user using username+password or token.
880 * This function sets up $USER global.
881 * It is safe to use has_capability() after this.
882 * This method also verifies user is allowed to use this
885 protected function authenticate_user() {
888 if (!NO_MOODLE_COOKIES
) {
889 throw new coding_exception('Cookies must be disabled in WS servers!');
892 $loginfaileddefaultparams = array(
894 'method' => $this->authmethod
,
899 if ($this->authmethod
== WEBSERVICE_AUTHMETHOD_USERNAME
) {
901 //we check that authentication plugin is enabled
902 //it is only required by simple authentication
903 if (!is_enabled_auth('webservice')) {
904 throw new webservice_access_exception('The web service authentication plugin is disabled.');
907 if (!$auth = get_auth_plugin('webservice')) {
908 throw new webservice_access_exception('The web service authentication plugin is missing.');
911 $this->restricted_context
= context_system
::instance();
913 if (!$this->username
) {
914 throw new moodle_exception('missingusername', 'webservice');
917 if (!$this->password
) {
918 throw new moodle_exception('missingpassword', 'webservice');
921 if (!$auth->user_login_webservice($this->username
, $this->password
)) {
923 // Log failed login attempts.
924 $params = $loginfaileddefaultparams;
925 $params['other']['reason'] = 'password';
926 $params['other']['username'] = $this->username
;
927 $event = \core\event\webservice_login_failed
::create($params);
928 $event->set_legacy_logdata(array(SITEID
, 'webservice', get_string('simpleauthlog', 'webservice'), '' ,
929 get_string('failedtolog', 'webservice').": ".$this->username
."/".$this->password
." - ".getremoteaddr() , 0));
932 throw new moodle_exception('wrongusernamepassword', 'webservice');
935 $user = $DB->get_record('user', array('username'=>$this->username
, 'mnethostid'=>$CFG->mnet_localhost_id
), '*', MUST_EXIST
);
937 } else if ($this->authmethod
== WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN
){
938 $user = $this->authenticate_by_token(EXTERNAL_TOKEN_PERMANENT
);
940 $user = $this->authenticate_by_token(EXTERNAL_TOKEN_EMBEDDED
);
943 // Cannot authenticate unless maintenance access is granted.
944 $hasmaintenanceaccess = has_capability('moodle/site:maintenanceaccess', context_system
::instance(), $user);
945 if (!empty($CFG->maintenance_enabled
) and !$hasmaintenanceaccess) {
946 throw new moodle_exception('sitemaintenance', 'admin');
949 //only confirmed user should be able to call web service
950 if (!empty($user->deleted
)) {
951 $params = $loginfaileddefaultparams;
952 $params['other']['reason'] = 'user_deleted';
953 $params['other']['username'] = $user->username
;
954 $event = \core\event\webservice_login_failed
::create($params);
955 $event->set_legacy_logdata(array(SITEID
, '', '', '', get_string('wsaccessuserdeleted', 'webservice',
956 $user->username
) . " - ".getremoteaddr(), 0, $user->id
));
958 throw new webservice_access_exception('Refused web service access for deleted username: ' . $user->username
);
961 //only confirmed user should be able to call web service
962 if (empty($user->confirmed
)) {
963 $params = $loginfaileddefaultparams;
964 $params['other']['reason'] = 'user_unconfirmed';
965 $params['other']['username'] = $user->username
;
966 $event = \core\event\webservice_login_failed
::create($params);
967 $event->set_legacy_logdata(array(SITEID
, '', '', '', get_string('wsaccessuserunconfirmed', 'webservice',
968 $user->username
) . " - ".getremoteaddr(), 0, $user->id
));
970 throw new moodle_exception('wsaccessuserunconfirmed', 'webservice', '', $user->username
);
973 //check the user is suspended
974 if (!empty($user->suspended
)) {
975 $params = $loginfaileddefaultparams;
976 $params['other']['reason'] = 'user_unconfirmed';
977 $params['other']['username'] = $user->username
;
978 $event = \core\event\webservice_login_failed
::create($params);
979 $event->set_legacy_logdata(array(SITEID
, '', '', '', get_string('wsaccessusersuspended', 'webservice',
980 $user->username
) . " - ".getremoteaddr(), 0, $user->id
));
982 throw new webservice_access_exception('Refused web service access for suspended username: ' . $user->username
);
985 //retrieve the authentication plugin if no previously done
987 $auth = get_auth_plugin($user->auth
);
990 // check if credentials have expired
991 if (!empty($auth->config
->expiration
) and $auth->config
->expiration
== 1) {
992 $days2expire = $auth->password_expire($user->username
);
993 if (intval($days2expire) < 0 ) {
994 $params = $loginfaileddefaultparams;
995 $params['other']['reason'] = 'password_expired';
996 $params['other']['username'] = $user->username
;
997 $event = \core\event\webservice_login_failed
::create($params);
998 $event->set_legacy_logdata(array(SITEID
, '', '', '', get_string('wsaccessuserexpired', 'webservice',
999 $user->username
) . " - ".getremoteaddr(), 0, $user->id
));
1001 throw new webservice_access_exception('Refused web service access for password expired username: ' . $user->username
);
1005 //check if the auth method is nologin (in this case refuse connection)
1006 if ($user->auth
=='nologin') {
1007 $params = $loginfaileddefaultparams;
1008 $params['other']['reason'] = 'login';
1009 $params['other']['username'] = $user->username
;
1010 $event = \core\event\webservice_login_failed
::create($params);
1011 $event->set_legacy_logdata(array(SITEID
, '', '', '', get_string('wsaccessusernologin', 'webservice',
1012 $user->username
) . " - ".getremoteaddr(), 0, $user->id
));
1014 throw new webservice_access_exception('Refused web service access for nologin authentication username: ' . $user->username
);
1017 // now fake user login, the session is completely empty too
1018 enrol_check_plugins($user);
1019 \core\session\manager
::set_user($user);
1020 set_login_session_preferences();
1021 $this->userid
= $user->id
;
1023 if ($this->authmethod
!= WEBSERVICE_AUTHMETHOD_SESSION_TOKEN
&& !has_capability("webservice/$this->wsname:use", $this->restricted_context
)) {
1024 throw new webservice_access_exception('You are not allowed to use the {$a} protocol (missing capability: webservice/' . $this->wsname
. ':use)');
1027 external_api
::set_context_restriction($this->restricted_context
);
1031 * User authentication by token
1033 * @param string $tokentype token type (EXTERNAL_TOKEN_EMBEDDED or EXTERNAL_TOKEN_PERMANENT)
1034 * @return stdClass the authenticated user
1035 * @throws webservice_access_exception
1037 protected function authenticate_by_token($tokentype){
1040 $loginfaileddefaultparams = array(
1042 'method' => $this->authmethod
,
1047 if (!$token = $DB->get_record('external_tokens', array('token'=>$this->token
, 'tokentype'=>$tokentype))) {
1048 // Log failed login attempts.
1049 $params = $loginfaileddefaultparams;
1050 $params['other']['reason'] = 'invalid_token';
1051 $event = \core\event\webservice_login_failed
::create($params);
1052 $event->set_legacy_logdata(array(SITEID
, 'webservice', get_string('tokenauthlog', 'webservice'), '' ,
1053 get_string('failedtolog', 'webservice').": ".$this->token
. " - ".getremoteaddr() , 0));
1055 throw new moodle_exception('invalidtoken', 'webservice');
1058 if ($token->validuntil
and $token->validuntil
< time()) {
1059 $DB->delete_records('external_tokens', array('token'=>$this->token
, 'tokentype'=>$tokentype));
1060 throw new webservice_access_exception('Invalid token - token expired - check validuntil time for the token');
1063 if ($token->sid
){//assumes that if sid is set then there must be a valid associated session no matter the token type
1064 if (!\core\session\manager
::session_exists($token->sid
)){
1065 $DB->delete_records('external_tokens', array('sid'=>$token->sid
));
1066 throw new webservice_access_exception('Invalid session based token - session not found or expired');
1070 if ($token->iprestriction
and !address_in_subnet(getremoteaddr(), $token->iprestriction
)) {
1071 $params = $loginfaileddefaultparams;
1072 $params['other']['reason'] = 'ip_restricted';
1073 $params['other']['tokenid'] = $token->id
;
1074 $event = \core\event\webservice_login_failed
::create($params);
1075 $event->add_record_snapshot('external_tokens', $token);
1076 $event->set_legacy_logdata(array(SITEID
, 'webservice', get_string('tokenauthlog', 'webservice'), '' ,
1077 get_string('failedtolog', 'webservice').": ".getremoteaddr() , 0));
1079 throw new webservice_access_exception('Invalid service - IP:' . getremoteaddr()
1080 . ' is not supported - check this allowed user');
1083 $this->restricted_context
= context
::instance_by_id($token->contextid
);
1084 $this->restricted_serviceid
= $token->externalserviceid
;
1086 $user = $DB->get_record('user', array('id'=>$token->userid
), '*', MUST_EXIST
);
1089 $DB->set_field('external_tokens', 'lastaccess', time(), array('id'=>$token->id
));
1096 * Intercept some moodlewssettingXXX $_GET and $_POST parameter
1097 * that are related to the web service call and are not the function parameters
1099 protected function set_web_service_call_settings() {
1102 // Default web service settings.
1103 // Must be the same XXX key name as the external_settings::set_XXX function.
1104 // Must be the same XXX ws parameter name as 'moodlewssettingXXX'.
1105 $externalsettings = array(
1110 // Load the external settings with the web service settings.
1111 $settings = external_settings
::get_instance();
1112 foreach ($externalsettings as $name => $default) {
1114 $wsparamname = 'moodlewssetting' . $name;
1116 // Retrieve and remove the setting parameter from the request.
1117 $value = optional_param($wsparamname, $default, PARAM_BOOL
);
1118 unset($_GET[$wsparamname]);
1119 unset($_POST[$wsparamname]);
1121 $functioname = 'set_' . $name;
1122 $settings->$functioname($value);
1129 * Web Service server base class.
1131 * This class handles both simple and token authentication.
1133 * @package core_webservice
1134 * @copyright 2009 Petr Skodak
1135 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1137 abstract class webservice_base_server
extends webservice_server
{
1139 /** @var array The function parameters - the real values submitted in the request */
1140 protected $parameters = null;
1142 /** @var string The name of the function that is executed */
1143 protected $functionname = null;
1145 /** @var stdClass Full function description */
1146 protected $function = null;
1148 /** @var mixed Function return value */
1149 protected $returns = null;
1151 /** @var array List of methods and their information provided by the web service. */
1152 protected $servicemethods;
1154 /** @var array List of struct classes generated for the web service methods. */
1155 protected $servicestructs;
1158 * This method parses the request input, it needs to get:
1159 * 1/ user authentication - username+password or token
1161 * 3/ function parameters
1163 abstract protected function parse_request();
1166 * Send the result of function call to the WS client.
1168 abstract protected function send_response();
1171 * Send the error information to the WS client.
1173 * @param exception $ex
1175 abstract protected function send_error($ex=null);
1178 * Process request from client.
1182 public function run() {
1183 // we will probably need a lot of memory in some functions
1184 raise_memory_limit(MEMORY_EXTRA
);
1186 // set some longer timeout, this script is not sending any output,
1187 // this means we need to manually extend the timeout operations
1188 // that need longer time to finish
1189 external_api
::set_timeout();
1191 // set up exception handler first, we want to sent them back in correct format that
1192 // the other system understands
1193 // we do not need to call the original default handler because this ws handler does everything
1194 set_exception_handler(array($this, 'exception_handler'));
1196 // init all properties from the request data
1197 $this->parse_request();
1199 // authenticate user, this has to be done after the request parsing
1200 // this also sets up $USER and $SESSION
1201 $this->authenticate_user();
1203 // find all needed function info and make sure user may actually execute the function
1204 $this->load_function_info();
1206 // Log the web service request.
1209 'function' => $this->functionname
1212 $event = \core\event\webservice_function_called
::create($params);
1213 $event->set_legacy_logdata(array(SITEID
, 'webservice', $this->functionname
, '' , getremoteaddr() , 0, $this->userid
));
1216 // finally, execute the function - any errors are catched by the default exception handler
1219 // send the results back in correct format
1220 $this->send_response();
1223 $this->session_cleanup();
1229 * Specialised exception handler, we can not use the standard one because
1230 * it can not just print html to output.
1232 * @param exception $ex
1235 public function exception_handler($ex) {
1236 // detect active db transactions, rollback and log as error
1237 abort_all_db_transactions();
1239 // some hacks might need a cleanup hook
1240 $this->session_cleanup($ex);
1242 // now let the plugin send the exception to client
1243 $this->send_error($ex);
1245 // not much else we can do now, add some logging later
1250 * Future hook needed for emulated sessions.
1252 * @param exception $exception null means normal termination, $exception received when WS call failed
1254 protected function session_cleanup($exception=null) {
1255 if ($this->authmethod
== WEBSERVICE_AUTHMETHOD_USERNAME
) {
1256 // nothing needs to be done, there is no persistent session
1258 // close emulated session if used
1263 * Fetches the function description from database,
1264 * verifies user is allowed to use this function and
1265 * loads all paremeters and return descriptions.
1267 protected function load_function_info() {
1268 global $DB, $USER, $CFG;
1270 if (empty($this->functionname
)) {
1271 throw new invalid_parameter_exception('Missing function name');
1274 // function must exist
1275 $function = external_api
::external_function_info($this->functionname
);
1277 if ($this->restricted_serviceid
) {
1278 $params = array('sid1'=>$this->restricted_serviceid
, 'sid2'=>$this->restricted_serviceid
);
1279 $wscond1 = 'AND s.id = :sid1';
1280 $wscond2 = 'AND s.id = :sid2';
1287 // now let's verify access control
1289 // now make sure the function is listed in at least one service user is allowed to use
1290 // allow access only if:
1291 // 1/ entry in the external_services_users table if required
1292 // 2/ validuntil not reached
1293 // 3/ has capability if specified in service desc
1296 $sql = "SELECT s.*, NULL AS iprestriction
1297 FROM {external_services} s
1298 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0 AND sf.functionname = :name1)
1299 WHERE s.enabled = 1 $wscond1
1303 SELECT s.*, su.iprestriction
1304 FROM {external_services} s
1305 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1 AND sf.functionname = :name2)
1306 JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)
1307 WHERE s.enabled = 1 AND (su.validuntil IS NULL OR su.validuntil < :now) $wscond2";
1308 $params = array_merge($params, array('userid'=>$USER->id
, 'name1'=>$function->name
, 'name2'=>$function->name
, 'now'=>time()));
1310 $rs = $DB->get_recordset_sql($sql, $params);
1311 // now make sure user may access at least one service
1312 $remoteaddr = getremoteaddr();
1314 foreach ($rs as $service) {
1315 if ($service->requiredcapability
and !has_capability($service->requiredcapability
, $this->restricted_context
)) {
1316 continue; // cap required, sorry
1318 if ($service->iprestriction
and !address_in_subnet($remoteaddr, $service->iprestriction
)) {
1319 continue; // wrong request source ip, sorry
1322 break; // one service is enough, no need to continue
1326 throw new webservice_access_exception(
1327 'Access to the function '.$this->functionname
.'() is not allowed.
1328 There could be multiple reasons for this:
1329 1. The service linked to the user token does not contain the function.
1330 2. The service is user-restricted and the user is not listed.
1331 3. The service is IP-restricted and the user IP is not listed.
1332 4. The service is time-restricted and the time has expired.
1333 5. The token is time-restricted and the time has expired.
1334 6. The service requires a specific capability which the user does not have.
1335 7. The function is called with username/password (no user token is sent)
1336 and none of the services has the function to allow the user.
1337 These settings can be found in Administration > Site administration
1338 > Plugins > Web services > External services and Manage tokens.');
1341 // we have all we need now
1342 $this->function = $function;
1346 * Execute previously loaded function using parameters parsed from the request data.
1348 protected function execute() {
1349 // validate params, this also sorts the params properly, we need the correct order in the next part
1350 $params = call_user_func(array($this->function->classname
, 'validate_parameters'), $this->function->parameters_desc
, $this->parameters
);
1353 $this->returns
= call_user_func_array(array($this->function->classname
, $this->function->methodname
), array_values($params));
1357 * Load the virtual class needed for the web service.
1359 * Initialises the virtual class that contains the web service functions that the user is allowed to use.
1360 * The web service function will be available if the user:
1361 * - is validly registered in the external_services_users table.
1362 * - has the required capability.
1363 * - meets the IP restriction requirement.
1364 * This virtual class can be used by web service protocols such as SOAP, especially when generating WSDL.
1366 protected function init_service_class() {
1369 // Initialise service methods and struct classes.
1370 $this->servicemethods
= array();
1371 $this->servicestructs
= array();
1376 if ($this->restricted_serviceid
) {
1377 $params = array('sid1' => $this->restricted_serviceid
, 'sid2' => $this->restricted_serviceid
);
1378 $wscond1 = 'AND s.id = :sid1';
1379 $wscond2 = 'AND s.id = :sid2';
1382 $sql = "SELECT s.*, NULL AS iprestriction
1383 FROM {external_services} s
1384 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0)
1385 WHERE s.enabled = 1 $wscond1
1389 SELECT s.*, su.iprestriction
1390 FROM {external_services} s
1391 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1)
1392 JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)
1393 WHERE s.enabled = 1 AND (su.validuntil IS NULL OR su.validuntil < :now) $wscond2";
1394 $params = array_merge($params, array('userid' => $USER->id
, 'now' => time()));
1396 $serviceids = array();
1397 $remoteaddr = getremoteaddr();
1399 // Query list of external services for the user.
1400 $rs = $DB->get_recordset_sql($sql, $params);
1402 // Check which service ID to include.
1403 foreach ($rs as $service) {
1404 if (isset($serviceids[$service->id
])) {
1405 continue; // Service already added.
1407 if ($service->requiredcapability
and !has_capability($service->requiredcapability
, $this->restricted_context
)) {
1408 continue; // Cap required, sorry.
1410 if ($service->iprestriction
and !address_in_subnet($remoteaddr, $service->iprestriction
)) {
1411 continue; // Wrong request source ip, sorry.
1413 $serviceids[$service->id
] = $service->id
;
1417 // Generate the virtual class name.
1418 $classname = 'webservices_virtual_class_000000';
1419 while (class_exists($classname)) {
1422 $this->serviceclass
= $classname;
1424 // Get the list of all available external functions.
1425 $wsmanager = new webservice();
1426 $functions = $wsmanager->get_external_functions($serviceids);
1428 // Generate code for the virtual methods for this web service.
1430 foreach ($functions as $function) {
1431 $methods .= $this->get_virtual_method_code($function);
1436 * Virtual class web services for user id $USER->id in context {$this->restricted_context->id}.
1442 // Load the virtual class definition into memory.
1447 * Generates a struct class.
1449 * @param external_single_structure $structdesc The basis of the struct class to be generated.
1450 * @return string The class name of the generated struct class.
1452 protected function generate_simple_struct_class(external_single_structure
$structdesc) {
1455 $propeties = array();
1457 foreach ($structdesc->keys
as $name => $fieldsdesc) {
1458 $type = $this->get_phpdoc_type($fieldsdesc);
1459 $propertytype = array('type' => $type);
1460 if (empty($fieldsdesc->allownull
) ||
$fieldsdesc->allownull
== NULL_ALLOWED
) {
1461 $propertytype['nillable'] = true;
1463 $propeties[$name] = $propertytype;
1464 $fields[] = ' /** @var ' . $type . ' $' . $name . '*/';
1465 $fields[] = ' public $' . $name .';';
1467 $fieldsstr = implode("\n", $fields);
1469 // We do this after the call to get_phpdoc_type() to avoid duplicate class creation.
1470 $classname = 'webservices_struct_class_000000';
1471 while (class_exists($classname)) {
1476 * Virtual struct class for web services for user id $USER->id in context {$this->restricted_context->id}.
1482 // Load into memory.
1485 // Prepare struct info.
1486 $structinfo = new stdClass();
1487 $structinfo->classname
= $classname;
1488 $structinfo->properties
= $propeties;
1489 // Add the struct info the the list of service struct classes.
1490 $this->servicestructs
[] = $structinfo;
1496 * Returns a virtual method code for a web service function.
1498 * @param stdClass $function a record from external_function
1499 * @return string The PHP code of the virtual method.
1500 * @throws coding_exception
1501 * @throws moodle_exception
1503 protected function get_virtual_method_code($function) {
1504 $function = external_api
::external_function_info($function);
1506 // Parameters and their defaults for the method signature.
1507 $paramanddefaults = array();
1508 // Parameters for external lib call.
1510 $paramdesc = array();
1511 // The method's input parameters and their respective types.
1512 $inputparams = array();
1513 // The method's output parameters and their respective types.
1514 $outputparams = array();
1516 foreach ($function->parameters_desc
->keys
as $name => $keydesc) {
1517 $param = '$' . $name;
1518 $paramanddefault = $param;
1519 if ($keydesc->required
== VALUE_OPTIONAL
) {
1520 // It does not make sense to declare a parameter VALUE_OPTIONAL. VALUE_OPTIONAL is used only for array/object key.
1521 throw new moodle_exception('erroroptionalparamarray', 'webservice', '', $name);
1522 } else if ($keydesc->required
== VALUE_DEFAULT
) {
1523 // Need to generate the default, if there is any.
1524 if ($keydesc instanceof external_value
) {
1525 if ($keydesc->default === null) {
1526 $paramanddefault .= ' = null';
1528 switch ($keydesc->type
) {
1530 $default = (int)$keydesc->default;
1533 $default = $keydesc->default;
1536 $default = $keydesc->default;
1539 $default = "'$keydesc->default'";
1541 $paramanddefault .= " = $default";
1544 // Accept empty array as default.
1545 if (isset($keydesc->default) && is_array($keydesc->default) && empty($keydesc->default)) {
1546 $paramanddefault .= ' = array()';
1548 // For the moment we do not support default for other structure types.
1549 throw new moodle_exception('errornotemptydefaultparamarray', 'webservice', '', $name);
1555 $paramanddefaults[] = $paramanddefault;
1556 $type = $this->get_phpdoc_type($keydesc);
1557 $inputparams[$name]['type'] = $type;
1559 $paramdesc[] = '* @param ' . $type . ' $' . $name . ' ' . $keydesc->desc
;
1561 $paramanddefaults = implode(', ', $paramanddefaults);
1562 $paramdescstr = implode("\n ", $paramdesc);
1564 $serviceclassmethodbody = $this->service_class_method_body($function, $params);
1566 if (empty($function->returns_desc
)) {
1567 $return = '* @return void';
1569 $type = $this->get_phpdoc_type($function->returns_desc
);
1570 $outputparams['return']['type'] = $type;
1571 $return = '* @return ' . $type . ' ' . $function->returns_desc
->desc
;
1574 // Now create the virtual method that calls the ext implementation.
1577 * $function->description.
1582 public function $function->name($paramanddefaults) {
1583 $serviceclassmethodbody
1587 // Prepare the method information.
1588 $methodinfo = new stdClass();
1589 $methodinfo->name
= $function->name
;
1590 $methodinfo->inputparams
= $inputparams;
1591 $methodinfo->outputparams
= $outputparams;
1592 $methodinfo->description
= $function->description
;
1593 // Add the method information into the list of service methods.
1594 $this->servicemethods
[] = $methodinfo;
1600 * Get the phpdoc type for an external_description object.
1601 * external_value => int, double or string
1602 * external_single_structure => object|struct, on-fly generated stdClass name.
1603 * external_multiple_structure => array
1605 * @param mixed $keydesc The type description.
1606 * @return string The PHP doc type of the external_description object.
1608 protected function get_phpdoc_type($keydesc) {
1610 if ($keydesc instanceof external_value
) {
1611 switch ($keydesc->type
) {
1612 case PARAM_BOOL
: // 0 or 1 only for now.
1622 } else if ($keydesc instanceof external_single_structure
) {
1623 $type = $this->generate_simple_struct_class($keydesc);
1624 } else if ($keydesc instanceof external_multiple_structure
) {
1632 * Generates the method body of the virtual external function.
1634 * @param stdClass $function a record from external_function.
1635 * @param array $params web service function parameters.
1636 * @return string body of the method for $function ie. everything within the {} of the method declaration.
1638 protected function service_class_method_body($function, $params) {
1639 // Cast the param from object to array (validate_parameters except array only).
1642 if (!empty($params)) {
1643 foreach ($params as $paramtocast) {
1644 // Clean the parameter from any white space.
1645 $paramtocast = trim($paramtocast);
1646 $castingcode .= " $paramtocast = json_decode(json_encode($paramtocast), true);\n";
1648 $paramsstr = implode(', ', $params);
1651 $descriptionmethod = $function->methodname
. '_returns()';
1652 $callforreturnvaluedesc = $function->classname
. '::' . $descriptionmethod;
1654 $methodbody = <<<EOD
1656 if ($callforreturnvaluedesc == null) {
1657 $function->classname::$function->methodname($paramsstr);
1660 return external_api::clean_returnvalue($callforreturnvaluedesc, $function->classname::$function->methodname($paramsstr));