9a867d2fcdb84fd2137436cdb5ee441089b93f83
[moodle.git] / webservice / lib.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
18 /**
19  * Web services utility functions and classes
20  *
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
24  */
26 require_once($CFG->libdir.'/externallib.php');
28 /**
29  * WEBSERVICE_AUTHMETHOD_USERNAME - username/password authentication (also called simple authentication)
30  */
31 define('WEBSERVICE_AUTHMETHOD_USERNAME', 0);
33 /**
34  * WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN - most common token authentication (external app, mobile app...)
35  */
36 define('WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN', 1);
38 /**
39  * WEBSERVICE_AUTHMETHOD_SESSION_TOKEN - token for embedded application (requires Moodle session)
40  */
41 define('WEBSERVICE_AUTHMETHOD_SESSION_TOKEN', 2);
43 /**
44  * General web service library
45  *
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
49  */
50 class webservice {
52     /**
53      * Authenticate user (used by download/upload file scripts)
54      *
55      * @param string $token
56      * @return array - contains the authenticated user, token and service objects
57      */
58     public function authenticate_user($token) {
59         global $DB, $CFG;
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.');
64         }
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');
70         }
72         $loginfaileddefaultparams = array(
73             'other' => array(
74                 'method' => WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN,
75                 'reason' => null,
76                 'tokenid' => $token->id
77             )
78         );
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));
88             $event->trigger();
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');
91         }
93         // Check ip
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));
101             $event->trigger();
102             throw new webservice_access_exception('Invalid token - IP:' . getremoteaddr()
103                     . ' is not supported');
104         }
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);
115         //assumes that if sid is set then there must be a valid associated session no matter the token type
116         if ($token->sid) {
117             if (!\core\session\manager::session_exists($token->sid)) {
118                 $DB->delete_records('external_tokens', array('sid' => $token->sid));
119                 throw new webservice_access_exception('Invalid session based token - session not found or expired');
120             }
121         }
123         //Non admin can not authenticate if maintenance mode
124         $hassiteconfig = has_capability('moodle/site:config', context_system::instance(), $user);
125         if (!empty($CFG->maintenance_enabled) and !$hassiteconfig) {
126             //this is usually temporary, client want to implement code logic  => moodle_exception
127             throw new moodle_exception('sitemaintenance', 'admin');
128         }
130         //retrieve web service record
131         $service = $DB->get_record('external_services', array('id' => $token->externalserviceid, 'enabled' => 1));
132         if (empty($service)) {
133             // will throw exception if no token found
134             throw new webservice_access_exception('Web service is not available (it doesn\'t exist or might be disabled)');
135         }
137         //check if there is any required system capability
138         if ($service->requiredcapability and !has_capability($service->requiredcapability, context_system::instance(), $user)) {
139             throw new webservice_access_exception('The capability ' . $service->requiredcapability . ' is required.');
140         }
142         //specific checks related to user restricted service
143         if ($service->restrictedusers) {
144             $authoriseduser = $DB->get_record('external_services_users', array('externalserviceid' => $service->id, 'userid' => $user->id));
146             if (empty($authoriseduser)) {
147                 throw new webservice_access_exception(
148                         'The user is not allowed for this service. First you need to allow this user on the '
149                         . $service->name . '\'s allowed users administration page.');
150             }
152             if (!empty($authoriseduser->validuntil) and $authoriseduser->validuntil < time()) {
153                 throw new webservice_access_exception('Invalid service - service expired - check validuntil time for this allowed user');
154             }
156             if (!empty($authoriseduser->iprestriction) and !address_in_subnet(getremoteaddr(), $authoriseduser->iprestriction)) {
157                 throw new webservice_access_exception('Invalid service - IP:' . getremoteaddr()
158                     . ' is not supported - check this allowed user');
159             }
160         }
162         //only confirmed user should be able to call web service
163         if (empty($user->confirmed)) {
164             $params = $loginfaileddefaultparams;
165             $params['other']['reason'] = 'user_unconfirmed';
166             $event = \core\event\webservice_login_failed::create($params);
167             $event->add_record_snapshot('external_tokens', $token);
168             $event->set_legacy_logdata(array(SITEID, 'webservice', 'user unconfirmed', '', $user->username));
169             $event->trigger();
170             throw new moodle_exception('usernotconfirmed', 'moodle', '', $user->username);
171         }
173         //check the user is suspended
174         if (!empty($user->suspended)) {
175             $params = $loginfaileddefaultparams;
176             $params['other']['reason'] = 'user_suspended';
177             $event = \core\event\webservice_login_failed::create($params);
178             $event->add_record_snapshot('external_tokens', $token);
179             $event->set_legacy_logdata(array(SITEID, 'webservice', 'user suspended', '', $user->username));
180             $event->trigger();
181             throw new webservice_access_exception('Refused web service access for suspended username: ' . $user->username);
182         }
184         //check if the auth method is nologin (in this case refuse connection)
185         if ($user->auth == 'nologin') {
186             $params = $loginfaileddefaultparams;
187             $params['other']['reason'] = 'nologin';
188             $event = \core\event\webservice_login_failed::create($params);
189             $event->add_record_snapshot('external_tokens', $token);
190             $event->set_legacy_logdata(array(SITEID, 'webservice', 'nologin auth attempt with web service', '', $user->username));
191             $event->trigger();
192             throw new webservice_access_exception('Refused web service access for nologin authentication username: ' . $user->username);
193         }
195         //Check if the user password is expired
196         $auth = get_auth_plugin($user->auth);
197         if (!empty($auth->config->expiration) and $auth->config->expiration == 1) {
198             $days2expire = $auth->password_expire($user->username);
199             if (intval($days2expire) < 0) {
200                 $params = $loginfaileddefaultparams;
201                 $params['other']['reason'] = 'password_expired';
202                 $event = \core\event\webservice_login_failed::create($params);
203                 $event->add_record_snapshot('external_tokens', $token);
204                 $event->set_legacy_logdata(array(SITEID, 'webservice', 'expired password', '', $user->username));
205                 $event->trigger();
206                 throw new moodle_exception('passwordisexpired', 'webservice');
207             }
208         }
210         // log token access
211         $DB->set_field('external_tokens', 'lastaccess', time(), array('id' => $token->id));
213         return array('user' => $user, 'token' => $token, 'service' => $service);
214     }
216     /**
217      * Allow user to call a service
218      *
219      * @param stdClass $user a user
220      */
221     public function add_ws_authorised_user($user) {
222         global $DB;
223         $user->timecreated = time();
224         $DB->insert_record('external_services_users', $user);
225     }
227     /**
228      * Disallow a user to call a service
229      *
230      * @param stdClass $user a user
231      * @param int $serviceid
232      */
233     public function remove_ws_authorised_user($user, $serviceid) {
234         global $DB;
235         $DB->delete_records('external_services_users',
236                 array('externalserviceid' => $serviceid, 'userid' => $user->id));
237     }
239     /**
240      * Update allowed user settings (ip restriction, valid until...)
241      *
242      * @param stdClass $user
243      */
244     public function update_ws_authorised_user($user) {
245         global $DB;
246         $DB->update_record('external_services_users', $user);
247     }
249     /**
250      * Return list of allowed users with their options (ip/timecreated / validuntil...)
251      * for a given service
252      *
253      * @param int $serviceid the service id to search against
254      * @return array $users
255      */
256     public function get_ws_authorised_users($serviceid) {
257         global $DB, $CFG;
258         $params = array($CFG->siteguest, $serviceid);
259         $sql = " SELECT u.id as id, esu.id as serviceuserid, u.email as email, u.firstname as firstname,
260                         u.lastname as lastname,
261                         esu.iprestriction as iprestriction, esu.validuntil as validuntil,
262                         esu.timecreated as timecreated
263                    FROM {user} u, {external_services_users} esu
264                   WHERE u.id <> ? AND u.deleted = 0 AND u.confirmed = 1
265                         AND esu.userid = u.id
266                         AND esu.externalserviceid = ?";
268         $users = $DB->get_records_sql($sql, $params);
269         return $users;
270     }
272     /**
273      * Return an authorised user with their options (ip/timecreated / validuntil...)
274      *
275      * @param int $serviceid the service id to search against
276      * @param int $userid the user to search against
277      * @return stdClass
278      */
279     public function get_ws_authorised_user($serviceid, $userid) {
280         global $DB, $CFG;
281         $params = array($CFG->siteguest, $serviceid, $userid);
282         $sql = " SELECT u.id as id, esu.id as serviceuserid, u.email as email, u.firstname as firstname,
283                         u.lastname as lastname,
284                         esu.iprestriction as iprestriction, esu.validuntil as validuntil,
285                         esu.timecreated as timecreated
286                    FROM {user} u, {external_services_users} esu
287                   WHERE u.id <> ? AND u.deleted = 0 AND u.confirmed = 1
288                         AND esu.userid = u.id
289                         AND esu.externalserviceid = ?
290                         AND u.id = ?";
291         $user = $DB->get_record_sql($sql, $params);
292         return $user;
293     }
295     /**
296      * Generate all tokens of a specific user
297      *
298      * @param int $userid user id
299      */
300     public function generate_user_ws_tokens($userid) {
301         global $CFG, $DB;
303         // generate a token for non admin if web service are enable and the user has the capability to create a token
304         if (!is_siteadmin() && has_capability('moodle/webservice:createtoken', context_system::instance(), $userid) && !empty($CFG->enablewebservices)) {
305             // for every service than the user is authorised on, create a token (if it doesn't already exist)
307             // get all services which are set to all user (no restricted to specific users)
308             $norestrictedservices = $DB->get_records('external_services', array('restrictedusers' => 0));
309             $serviceidlist = array();
310             foreach ($norestrictedservices as $service) {
311                 $serviceidlist[] = $service->id;
312             }
314             // get all services which are set to the current user (the current user is specified in the restricted user list)
315             $servicesusers = $DB->get_records('external_services_users', array('userid' => $userid));
316             foreach ($servicesusers as $serviceuser) {
317                 if (!in_array($serviceuser->externalserviceid,$serviceidlist)) {
318                      $serviceidlist[] = $serviceuser->externalserviceid;
319                 }
320             }
322             // get all services which already have a token set for the current user
323             $usertokens = $DB->get_records('external_tokens', array('userid' => $userid, 'tokentype' => EXTERNAL_TOKEN_PERMANENT));
324             $tokenizedservice = array();
325             foreach ($usertokens as $token) {
326                     $tokenizedservice[]  = $token->externalserviceid;
327             }
329             // create a token for the service which have no token already
330             foreach ($serviceidlist as $serviceid) {
331                 if (!in_array($serviceid, $tokenizedservice)) {
332                     // create the token for this service
333                     $newtoken = new stdClass();
334                     $newtoken->token = md5(uniqid(rand(),1));
335                     // check that the user has capability on this service
336                     $newtoken->tokentype = EXTERNAL_TOKEN_PERMANENT;
337                     $newtoken->userid = $userid;
338                     $newtoken->externalserviceid = $serviceid;
339                     // TODO MDL-31190 find a way to get the context - UPDATE FOLLOWING LINE
340                     $newtoken->contextid = context_system::instance()->id;
341                     $newtoken->creatorid = $userid;
342                     $newtoken->timecreated = time();
344                     $DB->insert_record('external_tokens', $newtoken);
345                 }
346             }
349         }
350     }
352     /**
353      * Return all tokens of a specific user
354      * + the service state (enabled/disabled)
355      * + the authorised user mode (restricted/not restricted)
356      *
357      * @param int $userid user id
358      * @return array
359      */
360     public function get_user_ws_tokens($userid) {
361         global $DB;
362         //here retrieve token list (including linked users firstname/lastname and linked services name)
363         $sql = "SELECT
364                     t.id, t.creatorid, t.token, u.firstname, u.lastname, s.id as wsid, s.name, s.enabled, s.restrictedusers, t.validuntil
365                 FROM
366                     {external_tokens} t, {user} u, {external_services} s
367                 WHERE
368                     t.userid=? AND t.tokentype = ".EXTERNAL_TOKEN_PERMANENT." AND s.id = t.externalserviceid AND t.userid = u.id";
369         $tokens = $DB->get_records_sql($sql, array( $userid));
370         return $tokens;
371     }
373     /**
374      * Return a token that has been created by the user (i.e. to created by an admin)
375      * If no tokens exist an exception is thrown
376      *
377      * The returned value is a stdClass:
378      * ->id token id
379      * ->token
380      * ->firstname user firstname
381      * ->lastname
382      * ->name service name
383      *
384      * @param int $userid user id
385      * @param int $tokenid token id
386      * @return stdClass
387      */
388     public function get_created_by_user_ws_token($userid, $tokenid) {
389         global $DB;
390         $sql = "SELECT
391                         t.id, t.token, u.firstname, u.lastname, s.name
392                     FROM
393                         {external_tokens} t, {user} u, {external_services} s
394                     WHERE
395                         t.creatorid=? AND t.id=? AND t.tokentype = "
396                 . EXTERNAL_TOKEN_PERMANENT
397                 . " AND s.id = t.externalserviceid AND t.userid = u.id";
398         //must be the token creator
399         $token = $DB->get_record_sql($sql, array($userid, $tokenid), MUST_EXIST);
400         return $token;
401     }
403     /**
404      * Return a database token record for a token id
405      *
406      * @param int $tokenid token id
407      * @return object token
408      */
409     public function get_token_by_id($tokenid) {
410         global $DB;
411         return $DB->get_record('external_tokens', array('id' => $tokenid));
412     }
414     /**
415      * Delete a token
416      *
417      * @param int $tokenid token id
418      */
419     public function delete_user_ws_token($tokenid) {
420         global $DB;
421         $DB->delete_records('external_tokens', array('id'=>$tokenid));
422     }
424     /**
425      * Delete a service
426      * Also delete function references and authorised user references.
427      *
428      * @param int $serviceid service id
429      */
430     public function delete_service($serviceid) {
431         global $DB;
432         $DB->delete_records('external_services_users', array('externalserviceid' => $serviceid));
433         $DB->delete_records('external_services_functions', array('externalserviceid' => $serviceid));
434         $DB->delete_records('external_tokens', array('externalserviceid' => $serviceid));
435         $DB->delete_records('external_services', array('id' => $serviceid));
436     }
438     /**
439      * Get a full database token record for a given token value
440      *
441      * @param string $token
442      * @throws moodle_exception if there is multiple result
443      */
444     public function get_user_ws_token($token) {
445         global $DB;
446         return $DB->get_record('external_tokens', array('token'=>$token), '*', MUST_EXIST);
447     }
449     /**
450      * Get the functions list of a service list (by id)
451      *
452      * @param array $serviceids service ids
453      * @return array of functions
454      */
455     public function get_external_functions($serviceids) {
456         global $DB;
457         if (!empty($serviceids)) {
458             list($serviceids, $params) = $DB->get_in_or_equal($serviceids);
459             $sql = "SELECT f.*
460                       FROM {external_functions} f
461                      WHERE f.name IN (SELECT sf.functionname
462                                         FROM {external_services_functions} sf
463                                        WHERE sf.externalserviceid $serviceids)";
464             $functions = $DB->get_records_sql($sql, $params);
465         } else {
466             $functions = array();
467         }
468         return $functions;
469     }
471     /**
472      * Get the functions of a service list (by shortname). It can return only enabled functions if required.
473      *
474      * @param array $serviceshortnames service shortnames
475      * @param bool $enabledonly if true then only return functions for services that have been enabled
476      * @return array functions
477      */
478     public function get_external_functions_by_enabled_services($serviceshortnames, $enabledonly = true) {
479         global $DB;
480         if (!empty($serviceshortnames)) {
481             $enabledonlysql = $enabledonly?' AND s.enabled = 1 ':'';
482             list($serviceshortnames, $params) = $DB->get_in_or_equal($serviceshortnames);
483             $sql = "SELECT f.*
484                       FROM {external_functions} f
485                      WHERE f.name IN (SELECT sf.functionname
486                                         FROM {external_services_functions} sf, {external_services} s
487                                        WHERE s.shortname $serviceshortnames
488                                              AND sf.externalserviceid = s.id
489                                              " . $enabledonlysql . ")";
490             $functions = $DB->get_records_sql($sql, $params);
491         } else {
492             $functions = array();
493         }
494         return $functions;
495     }
497     /**
498      * Get functions not included in a service
499      *
500      * @param int $serviceid service id
501      * @return array functions
502      */
503     public function get_not_associated_external_functions($serviceid) {
504         global $DB;
505         $select = "name NOT IN (SELECT s.functionname
506                                   FROM {external_services_functions} s
507                                  WHERE s.externalserviceid = :sid
508                                )";
510         $functions = $DB->get_records_select('external_functions',
511                         $select, array('sid' => $serviceid), 'name');
513         return $functions;
514     }
516     /**
517      * Get list of required capabilities of a service, sorted by functions
518      * Example of returned value:
519      *  Array
520      *  (
521      *    [moodle_group_create_groups] => Array
522      *    (
523      *       [0] => moodle/course:managegroups
524      *    )
525      *
526      *    [moodle_enrol_get_enrolled_users] => Array
527      *    (
528      *       [0] => moodle/site:viewparticipants
529      *       [1] => moodle/course:viewparticipants
530      *       [2] => moodle/role:review
531      *       [3] => moodle/site:accessallgroups
532      *       [4] => moodle/course:enrolreview
533      *    )
534      *  )
535      *
536      * @param int $serviceid service id
537      * @return array
538      */
539     public function get_service_required_capabilities($serviceid) {
540         $functions = $this->get_external_functions(array($serviceid));
541         $requiredusercaps = array();
542         foreach ($functions as $function) {
543             $functioncaps = explode(',', $function->capabilities);
544             if (!empty($functioncaps) and !empty($functioncaps[0])) {
545                 foreach ($functioncaps as $functioncap) {
546                     $requiredusercaps[$function->name][] = trim($functioncap);
547                 }
548             }
549         }
550         return $requiredusercaps;
551     }
553     /**
554      * Get user capabilities (with context)
555      * Only useful for documentation purpose
556      * WARNING: do not use this "broken" function. It was created in the goal to display some capabilities
557      * required by users. In theory we should not need to display this kind of information
558      * as the front end does not display it itself. In pratice,
559      * admins would like the info, for more info you can follow: MDL-29962
560      *
561      * @param int $userid user id
562      * @return array
563      */
564     public function get_user_capabilities($userid) {
565         global $DB;
566         //retrieve the user capabilities
567         $sql = "SELECT DISTINCT rc.id, rc.capability FROM {role_capabilities} rc, {role_assignments} ra
568             WHERE rc.roleid=ra.roleid AND ra.userid= ? AND rc.permission = ?";
569         $dbusercaps = $DB->get_records_sql($sql, array($userid, CAP_ALLOW));
570         $usercaps = array();
571         foreach ($dbusercaps as $usercap) {
572             $usercaps[$usercap->capability] = true;
573         }
574         return $usercaps;
575     }
577     /**
578      * Get missing user capabilities for a given service
579      * WARNING: do not use this "broken" function. It was created in the goal to display some capabilities
580      * required by users. In theory we should not need to display this kind of information
581      * as the front end does not display it itself. In pratice,
582      * admins would like the info, for more info you can follow: MDL-29962
583      *
584      * @param array $users users
585      * @param int $serviceid service id
586      * @return array of missing capabilities, keys being the user ids
587      */
588     public function get_missing_capabilities_by_users($users, $serviceid) {
589         global $DB;
590         $usersmissingcaps = array();
592         //retrieve capabilities required by the service
593         $servicecaps = $this->get_service_required_capabilities($serviceid);
595         //retrieve users missing capabilities
596         foreach ($users as $user) {
597             //cast user array into object to be a bit more flexible
598             if (is_array($user)) {
599                 $user = (object) $user;
600             }
601             $usercaps = $this->get_user_capabilities($user->id);
603             //detect the missing capabilities
604             foreach ($servicecaps as $functioname => $functioncaps) {
605                 foreach ($functioncaps as $functioncap) {
606                     if (!array_key_exists($functioncap, $usercaps)) {
607                         if (!isset($usersmissingcaps[$user->id])
608                                 or array_search($functioncap, $usersmissingcaps[$user->id]) === false) {
609                             $usersmissingcaps[$user->id][] = $functioncap;
610                         }
611                     }
612                 }
613             }
614         }
616         return $usersmissingcaps;
617     }
619     /**
620      * Get an external service for a given service id
621      *
622      * @param int $serviceid service id
623      * @param int $strictness IGNORE_MISSING, MUST_EXIST...
624      * @return stdClass external service
625      */
626     public function get_external_service_by_id($serviceid, $strictness=IGNORE_MISSING) {
627         global $DB;
628         $service = $DB->get_record('external_services',
629                         array('id' => $serviceid), '*', $strictness);
630         return $service;
631     }
633     /**
634      * Get an external service for a given shortname
635      *
636      * @param string $shortname service shortname
637      * @param int $strictness IGNORE_MISSING, MUST_EXIST...
638      * @return stdClass external service
639      */
640     public function get_external_service_by_shortname($shortname, $strictness=IGNORE_MISSING) {
641         global $DB;
642         $service = $DB->get_record('external_services',
643                         array('shortname' => $shortname), '*', $strictness);
644         return $service;
645     }
647     /**
648      * Get an external function for a given function id
649      *
650      * @param int $functionid function id
651      * @param int $strictness IGNORE_MISSING, MUST_EXIST...
652      * @return stdClass external function
653      */
654     public function get_external_function_by_id($functionid, $strictness=IGNORE_MISSING) {
655         global $DB;
656         $function = $DB->get_record('external_functions',
657                             array('id' => $functionid), '*', $strictness);
658         return $function;
659     }
661     /**
662      * Add a function to a service
663      *
664      * @param string $functionname function name
665      * @param int $serviceid service id
666      */
667     public function add_external_function_to_service($functionname, $serviceid) {
668         global $DB;
669         $addedfunction = new stdClass();
670         $addedfunction->externalserviceid = $serviceid;
671         $addedfunction->functionname = $functionname;
672         $DB->insert_record('external_services_functions', $addedfunction);
673     }
675     /**
676      * Add a service
677      * It generates the timecreated field automatically.
678      *
679      * @param stdClass $service
680      * @return serviceid integer
681      */
682     public function add_external_service($service) {
683         global $DB;
684         $service->timecreated = time();
685         $serviceid = $DB->insert_record('external_services', $service);
686         return $serviceid;
687     }
689     /**
690      * Update a service
691      * It modifies the timemodified automatically.
692      *
693      * @param stdClass $service
694      */
695     public function update_external_service($service) {
696         global $DB;
697         $service->timemodified = time();
698         $DB->update_record('external_services', $service);
699     }
701     /**
702      * Test whether an external function is already linked to a service
703      *
704      * @param string $functionname function name
705      * @param int $serviceid service id
706      * @return bool true if a matching function exists for the service, else false.
707      * @throws dml_exception if error
708      */
709     public function service_function_exists($functionname, $serviceid) {
710         global $DB;
711         return $DB->record_exists('external_services_functions',
712                             array('externalserviceid' => $serviceid,
713                                 'functionname' => $functionname));
714     }
716     /**
717      * Remove a function from a service
718      *
719      * @param string $functionname function name
720      * @param int $serviceid service id
721      */
722     public function remove_external_function_from_service($functionname, $serviceid) {
723         global $DB;
724         $DB->delete_records('external_services_functions',
725                     array('externalserviceid' => $serviceid, 'functionname' => $functionname));
727     }
732 /**
733  * Exception indicating access control problem in web service call
734  * This exception should return general errors about web service setup.
735  * Errors related to the user like wrong username/password should not use it,
736  * you should not use this exception if you want to let the client implement
737  * some code logic against an access error.
738  *
739  * @package    core_webservice
740  * @copyright  2009 Petr Skodak
741  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
742  */
743 class webservice_access_exception extends moodle_exception {
745     /**
746      * Constructor
747      *
748      * @param string $debuginfo the debug info
749      */
750     function __construct($debuginfo) {
751         parent::__construct('accessexception', 'webservice', '', null, $debuginfo);
752     }
755 /**
756  * Check if a protocol is enabled
757  *
758  * @param string $protocol name of WS protocol ('rest', 'soap', 'xmlrpc', 'amf'...)
759  * @return bool true if the protocol is enabled
760  */
761 function webservice_protocol_is_enabled($protocol) {
762     global $CFG;
764     if (empty($CFG->enablewebservices)) {
765         return false;
766     }
768     $active = explode(',', $CFG->webserviceprotocols);
770     return(in_array($protocol, $active));
773 /**
774  * Mandatory interface for all test client classes.
775  *
776  * @package    core_webservice
777  * @copyright  2009 Petr Skodak
778  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
779  */
780 interface webservice_test_client_interface {
782     /**
783      * Execute test client WS request
784      *
785      * @param string $serverurl server url (including the token param)
786      * @param string $function web service function name
787      * @param array $params parameters of the web service function
788      * @return mixed
789      */
790     public function simpletest($serverurl, $function, $params);
793 /**
794  * Mandatory interface for all web service protocol classes
795  *
796  * @package    core_webservice
797  * @copyright  2009 Petr Skodak
798  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
799  */
800 interface webservice_server_interface {
802     /**
803      * Process request from client.
804      */
805     public function run();
808 /**
809  * Abstract web service base class.
810  *
811  * @package    core_webservice
812  * @copyright  2009 Petr Skodak
813  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
814  */
815 abstract class webservice_server implements webservice_server_interface {
817     /** @var string Name of the web server plugin */
818     protected $wsname = null;
820     /** @var string Name of local user */
821     protected $username = null;
823     /** @var string Password of the local user */
824     protected $password = null;
826     /** @var int The local user */
827     protected $userid = null;
829     /** @var integer Authentication method one of WEBSERVICE_AUTHMETHOD_* */
830     protected $authmethod;
832     /** @var string Authentication token*/
833     protected $token = null;
835     /** @var stdClass Restricted context */
836     protected $restricted_context;
838     /** @var int Restrict call to one service id*/
839     protected $restricted_serviceid = null;
841     /**
842      * Constructor
843      *
844      * @param integer $authmethod authentication method one of WEBSERVICE_AUTHMETHOD_*
845      */
846     public function __construct($authmethod) {
847         $this->authmethod = $authmethod;
848     }
851     /**
852      * Authenticate user using username+password or token.
853      * This function sets up $USER global.
854      * It is safe to use has_capability() after this.
855      * This method also verifies user is allowed to use this
856      * server.
857      */
858     protected function authenticate_user() {
859         global $CFG, $DB;
861         if (!NO_MOODLE_COOKIES) {
862             throw new coding_exception('Cookies must be disabled in WS servers!');
863         }
865         $loginfaileddefaultparams = array(
866             'context' => context_system::instance(),
867             'other' => array(
868                 'method' => $this->authmethod,
869                 'reason' => null
870             )
871         );
873         if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
875             //we check that authentication plugin is enabled
876             //it is only required by simple authentication
877             if (!is_enabled_auth('webservice')) {
878                 throw new webservice_access_exception('The web service authentication plugin is disabled.');
879             }
881             if (!$auth = get_auth_plugin('webservice')) {
882                 throw new webservice_access_exception('The web service authentication plugin is missing.');
883             }
885             $this->restricted_context = context_system::instance();
887             if (!$this->username) {
888                 throw new moodle_exception('missingusername', 'webservice');
889             }
891             if (!$this->password) {
892                 throw new moodle_exception('missingpassword', 'webservice');
893             }
895             if (!$auth->user_login_webservice($this->username, $this->password)) {
897                 // Log failed login attempts.
898                 $params = $loginfaileddefaultparams;
899                 $params['other']['reason'] = 'password';
900                 $params['other']['username'] = $this->username;
901                 $event = \core\event\webservice_login_failed::create($params);
902                 $event->set_legacy_logdata(array(SITEID, 'webservice', get_string('simpleauthlog', 'webservice'), '' ,
903                     get_string('failedtolog', 'webservice').": ".$this->username."/".$this->password." - ".getremoteaddr() , 0));
904                 $event->trigger();
906                 throw new moodle_exception('wrongusernamepassword', 'webservice');
907             }
909             $user = $DB->get_record('user', array('username'=>$this->username, 'mnethostid'=>$CFG->mnet_localhost_id), '*', MUST_EXIST);
911         } else if ($this->authmethod == WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN){
912             $user = $this->authenticate_by_token(EXTERNAL_TOKEN_PERMANENT);
913         } else {
914             $user = $this->authenticate_by_token(EXTERNAL_TOKEN_EMBEDDED);
915         }
917         //Non admin can not authenticate if maintenance mode
918         $hassiteconfig = has_capability('moodle/site:config', context_system::instance(), $user);
919         if (!empty($CFG->maintenance_enabled) and !$hassiteconfig) {
920             throw new moodle_exception('sitemaintenance', 'admin');
921         }
923         //only confirmed user should be able to call web service
924         if (!empty($user->deleted)) {
925             $params = $loginfaileddefaultparams;
926             $params['other']['reason'] = 'user_deleted';
927             $params['other']['username'] = $user->username;
928             $event = \core\event\webservice_login_failed::create($params);
929             $event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessuserdeleted', 'webservice',
930                 $user->username) . " - ".getremoteaddr(), 0, $user->id));
931             $event->trigger();
932             throw new webservice_access_exception('Refused web service access for deleted username: ' . $user->username);
933         }
935         //only confirmed user should be able to call web service
936         if (empty($user->confirmed)) {
937             $params = $loginfaileddefaultparams;
938             $params['other']['reason'] = 'user_unconfirmed';
939             $params['other']['username'] = $user->username;
940             $event = \core\event\webservice_login_failed::create($params);
941             $event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessuserunconfirmed', 'webservice',
942                 $user->username) . " - ".getremoteaddr(), 0, $user->id));
943             $event->trigger();
944             throw new moodle_exception('wsaccessuserunconfirmed', 'webservice', '', $user->username);
945         }
947         //check the user is suspended
948         if (!empty($user->suspended)) {
949             $params = $loginfaileddefaultparams;
950             $params['other']['reason'] = 'user_unconfirmed';
951             $params['other']['username'] = $user->username;
952             $event = \core\event\webservice_login_failed::create($params);
953             $event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessusersuspended', 'webservice',
954                 $user->username) . " - ".getremoteaddr(), 0, $user->id));
955             $event->trigger();
956             throw new webservice_access_exception('Refused web service access for suspended username: ' . $user->username);
957         }
959         //retrieve the authentication plugin if no previously done
960         if (empty($auth)) {
961           $auth  = get_auth_plugin($user->auth);
962         }
964         // check if credentials have expired
965         if (!empty($auth->config->expiration) and $auth->config->expiration == 1) {
966             $days2expire = $auth->password_expire($user->username);
967             if (intval($days2expire) < 0 ) {
968                 $params = $loginfaileddefaultparams;
969                 $params['other']['reason'] = 'password_expired';
970                 $params['other']['username'] = $user->username;
971                 $event = \core\event\webservice_login_failed::create($params);
972                 $event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessuserexpired', 'webservice',
973                     $user->username) . " - ".getremoteaddr(), 0, $user->id));
974                 $event->trigger();
975                 throw new webservice_access_exception('Refused web service access for password expired username: ' . $user->username);
976             }
977         }
979         //check if the auth method is nologin (in this case refuse connection)
980         if ($user->auth=='nologin') {
981             $params = $loginfaileddefaultparams;
982             $params['other']['reason'] = 'login';
983             $params['other']['username'] = $user->username;
984             $event = \core\event\webservice_login_failed::create($params);
985             $event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessusernologin', 'webservice',
986                 $user->username) . " - ".getremoteaddr(), 0, $user->id));
987             $event->trigger();
988             throw new webservice_access_exception('Refused web service access for nologin authentication username: ' . $user->username);
989         }
991         // now fake user login, the session is completely empty too
992         enrol_check_plugins($user);
993         \core\session\manager::set_user($user);
994         $this->userid = $user->id;
996         if ($this->authmethod != WEBSERVICE_AUTHMETHOD_SESSION_TOKEN && !has_capability("webservice/$this->wsname:use", $this->restricted_context)) {
997             throw new webservice_access_exception('You are not allowed to use the {$a} protocol (missing capability: webservice/' . $this->wsname . ':use)');
998         }
1000         external_api::set_context_restriction($this->restricted_context);
1001     }
1003     /**
1004      * User authentication by token
1005      *
1006      * @param string $tokentype token type (EXTERNAL_TOKEN_EMBEDDED or EXTERNAL_TOKEN_PERMANENT)
1007      * @return stdClass the authenticated user
1008      * @throws webservice_access_exception
1009      */
1010     protected function authenticate_by_token($tokentype){
1011         global $DB;
1013         $loginfaileddefaultparams = array(
1014             'context' => context_system::instance(),
1015             'other' => array(
1016                 'method' => $this->authmethod,
1017                 'reason' => null
1018             )
1019         );
1021         if (!$token = $DB->get_record('external_tokens', array('token'=>$this->token, 'tokentype'=>$tokentype))) {
1022             // Log failed login attempts.
1023             $params = $loginfaileddefaultparams;
1024             $params['other']['reason'] = 'invalid_token';
1025             $event = \core\event\webservice_login_failed::create($params);
1026             $event->set_legacy_logdata(array(SITEID, 'webservice', get_string('tokenauthlog', 'webservice'), '' ,
1027                 get_string('failedtolog', 'webservice').": ".$this->token. " - ".getremoteaddr() , 0));
1028             $event->trigger();
1029             throw new moodle_exception('invalidtoken', 'webservice');
1030         }
1032         if ($token->validuntil and $token->validuntil < time()) {
1033             $DB->delete_records('external_tokens', array('token'=>$this->token, 'tokentype'=>$tokentype));
1034             throw new webservice_access_exception('Invalid token - token expired - check validuntil time for the token');
1035         }
1037         if ($token->sid){//assumes that if sid is set then there must be a valid associated session no matter the token type
1038             if (!\core\session\manager::session_exists($token->sid)){
1039                 $DB->delete_records('external_tokens', array('sid'=>$token->sid));
1040                 throw new webservice_access_exception('Invalid session based token - session not found or expired');
1041             }
1042         }
1044         if ($token->iprestriction and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
1045             $params = $loginfaileddefaultparams;
1046             $params['other']['reason'] = 'ip_restricted';
1047             $params['other']['tokenid'] = $token->id;
1048             $event = \core\event\webservice_login_failed::create($params);
1049             $event->add_record_snapshot('external_tokens', $token);
1050             $event->set_legacy_logdata(array(SITEID, 'webservice', get_string('tokenauthlog', 'webservice'), '' ,
1051                 get_string('failedtolog', 'webservice').": ".getremoteaddr() , 0));
1052             $event->trigger();
1053             throw new webservice_access_exception('Invalid service - IP:' . getremoteaddr()
1054                     . ' is not supported - check this allowed user');
1055         }
1057         $this->restricted_context = context::instance_by_id($token->contextid);
1058         $this->restricted_serviceid = $token->externalserviceid;
1060         $user = $DB->get_record('user', array('id'=>$token->userid), '*', MUST_EXIST);
1062         // log token access
1063         $DB->set_field('external_tokens', 'lastaccess', time(), array('id'=>$token->id));
1065         return $user;
1067     }
1069     /**
1070      * Intercept some moodlewssettingXXX $_GET and $_POST parameter
1071      * that are related to the web service call and are not the function parameters
1072      */
1073     protected function set_web_service_call_settings() {
1074         global $CFG;
1076         // Default web service settings.
1077         // Must be the same XXX key name as the external_settings::set_XXX function.
1078         // Must be the same XXX ws parameter name as 'moodlewssettingXXX'.
1079         $externalsettings = array(
1080             'raw' => false,
1081             'fileurl' => true,
1082             'filter' =>  false);
1084         // Load the external settings with the web service settings.
1085         $settings = external_settings::get_instance();
1086         foreach ($externalsettings as $name => $default) {
1088             $wsparamname = 'moodlewssetting' . $name;
1090             // Retrieve and remove the setting parameter from the request.
1091             $value = optional_param($wsparamname, $default, PARAM_BOOL);
1092             unset($_GET[$wsparamname]);
1093             unset($_POST[$wsparamname]);
1095             $functioname = 'set_' . $name;
1096             $settings->$functioname($value);
1097         }
1099     }
1102 /**
1103  * Special abstraction of our services that allows interaction with stock Zend ws servers.
1104  *
1105  * @package    core_webservice
1106  * @copyright  2009 Jerome Mouneyrac <jerome@moodle.com>
1107  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1108  */
1109 abstract class webservice_zend_server extends webservice_server {
1111     /** @var string Name of the zend server class : Zend_Amf_Server, moodle_zend_soap_server, Zend_Soap_AutoDiscover, ...*/
1112     protected $zend_class;
1114     /** @var stdClass Zend server instance */
1115     protected $zend_server;
1117     /** @var string Virtual web service class with all functions user name execute, created on the fly */
1118     protected $service_class;
1120     /**
1121      * Constructor
1122      *
1123      * @param int $authmethod authentication method - one of WEBSERVICE_AUTHMETHOD_*
1124      * @param string $zend_class Name of the zend server class
1125      */
1126     public function __construct($authmethod, $zend_class) {
1127         parent::__construct($authmethod);
1128         $this->zend_class = $zend_class;
1129     }
1131     /**
1132      * Process request from client.
1133      *
1134      * @uses die
1135      */
1136     public function run() {
1137         // we will probably need a lot of memory in some functions
1138         raise_memory_limit(MEMORY_EXTRA);
1140         // set some longer timeout, this script is not sending any output,
1141         // this means we need to manually extend the timeout operations
1142         // that need longer time to finish
1143         external_api::set_timeout();
1145         // now create the instance of zend server
1146         $this->init_zend_server();
1148         // set up exception handler first, we want to sent them back in correct format that
1149         // the other system understands
1150         // we do not need to call the original default handler because this ws handler does everything
1151         set_exception_handler(array($this, 'exception_handler'));
1153         // init all properties from the request data
1154         $this->parse_request();
1156         // this sets up $USER and $SESSION and context restrictions
1157         $this->authenticate_user();
1159         // make a list of all functions user is allowed to excecute
1160         $this->init_service_class();
1162         // tell server what functions are available
1163         $this->zend_server->setClass($this->service_class);
1165         // Log the web service request.
1166         $params = array(
1167             'other' => array(
1168                 'function' => 'unknown'
1169             )
1170         );
1171         $event = \core\event\webservice_function_called::create($params);
1172         $event->set_legacy_logdata(array(SITEID, 'webservice', '', '', $this->zend_class.' '.getremoteaddr(), 0, $this->userid));
1173         $event->trigger();
1175         //send headers
1176         $this->send_headers();
1178         // execute and return response, this sends some headers too
1179         $response = $this->zend_server->handle();
1181         // session cleanup
1182         $this->session_cleanup();
1184         //finally send the result
1185         echo $response;
1186         die;
1187     }
1189     /**
1190      * Load virtual class needed for Zend api
1191      */
1192     protected function init_service_class() {
1193         global $USER, $DB;
1195         // first ofall get a complete list of services user is allowed to access
1197         if ($this->restricted_serviceid) {
1198             $params = array('sid1'=>$this->restricted_serviceid, 'sid2'=>$this->restricted_serviceid);
1199             $wscond1 = 'AND s.id = :sid1';
1200             $wscond2 = 'AND s.id = :sid2';
1201         } else {
1202             $params = array();
1203             $wscond1 = '';
1204             $wscond2 = '';
1205         }
1207         // now make sure the function is listed in at least one service user is allowed to use
1208         // allow access only if:
1209         //  1/ entry in the external_services_users table if required
1210         //  2/ validuntil not reached
1211         //  3/ has capability if specified in service desc
1212         //  4/ iprestriction
1214         $sql = "SELECT s.*, NULL AS iprestriction
1215                   FROM {external_services} s
1216                   JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0)
1217                  WHERE s.enabled = 1 $wscond1
1219                  UNION
1221                 SELECT s.*, su.iprestriction
1222                   FROM {external_services} s
1223                   JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1)
1224                   JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)
1225                  WHERE s.enabled = 1 AND (su.validuntil IS NULL OR su.validuntil < :now) $wscond2";
1227         $params = array_merge($params, array('userid'=>$USER->id, 'now'=>time()));
1229         $serviceids = array();
1230         $rs = $DB->get_recordset_sql($sql, $params);
1232         // now make sure user may access at least one service
1233         $remoteaddr = getremoteaddr();
1234         $allowed = false;
1235         foreach ($rs as $service) {
1236             if (isset($serviceids[$service->id])) {
1237                 continue;
1238             }
1239             if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) {
1240                 continue; // cap required, sorry
1241             }
1242             if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) {
1243                 continue; // wrong request source ip, sorry
1244             }
1245             $serviceids[$service->id] = $service->id;
1246         }
1247         $rs->close();
1249         // now get the list of all functions
1250         $wsmanager = new webservice();
1251         $functions = $wsmanager->get_external_functions($serviceids);
1253         // now make the virtual WS class with all the fuctions for this particular user
1254         $methods = '';
1255         foreach ($functions as $function) {
1256             $methods .= $this->get_virtual_method_code($function);
1257         }
1259         // let's use unique class name, there might be problem in unit tests
1260         $classname = 'webservices_virtual_class_000000';
1261         while(class_exists($classname)) {
1262             $classname++;
1263         }
1265         $code = '
1266 /**
1267  * Virtual class web services for user id '.$USER->id.' in context '.$this->restricted_context->id.'.
1268  */
1269 class '.$classname.' {
1270 '.$methods.'
1272 ';
1274         // load the virtual class definition into memory
1275         eval($code);
1276         $this->service_class = $classname;
1277     }
1279     /**
1280      * returns virtual method code
1281      *
1282      * @param stdClass $function a record from external_function
1283      * @return string PHP code
1284      */
1285     protected function get_virtual_method_code($function) {
1286         global $CFG;
1288         $function = external_function_info($function);
1290         //arguments in function declaration line with defaults.
1291         $paramanddefaults      = array();
1292         //arguments used as parameters for external lib call.
1293         $params      = array();
1294         $params_desc = array();
1295         foreach ($function->parameters_desc->keys as $name=>$keydesc) {
1296             $param = '$'.$name;
1297             $paramanddefault = $param;
1298             //need to generate the default if there is any
1299             if ($keydesc instanceof external_value) {
1300                 if ($keydesc->required == VALUE_DEFAULT) {
1301                     if ($keydesc->default===null) {
1302                         $paramanddefault .= '=null';
1303                     } else {
1304                         switch($keydesc->type) {
1305                             case PARAM_BOOL:
1306                                 $paramanddefault .= '='. (int) $keydesc->default; break;
1307                             case PARAM_INT:
1308                                 $paramanddefault .= '='.$keydesc->default; break;
1309                             case PARAM_FLOAT;
1310                                 $paramanddefault .= '='.$keydesc->default; break;
1311                             default:
1312                                 $paramanddefault .= '=\''.$keydesc->default.'\'';
1313                         }
1314                     }
1315                 } else if ($keydesc->required == VALUE_OPTIONAL) {
1316                     //it does make sens to declare a parameter VALUE_OPTIONAL
1317                     //VALUE_OPTIONAL is used only for array/object key
1318                     throw new moodle_exception('parametercannotbevalueoptional');
1319                 }
1320             } else { //for the moment we do not support default for other structure types
1321                  if ($keydesc->required == VALUE_DEFAULT) {
1322                      //accept empty array as default
1323                      if (isset($keydesc->default) and is_array($keydesc->default)
1324                              and empty($keydesc->default)) {
1325                          $paramanddefault .= '=array()';
1326                      } else {
1327                         throw new moodle_exception('errornotemptydefaultparamarray', 'webservice', '', $name);
1328                      }
1329                  }
1330                  if ($keydesc->required == VALUE_OPTIONAL) {
1331                      throw new moodle_exception('erroroptionalparamarray', 'webservice', '', $name);
1332                  }
1333             }
1334             $params[] = $param;
1335             $paramanddefaults[] = $paramanddefault;
1336             $type = $this->get_phpdoc_type($keydesc);
1337             $params_desc[] = '     * @param '.$type.' $'.$name.' '.$keydesc->desc;
1338         }
1339         $params                = implode(', ', $params);
1340         $paramanddefaults      = implode(', ', $paramanddefaults);
1341         $params_desc           = implode("\n", $params_desc);
1343         $serviceclassmethodbody = $this->service_class_method_body($function, $params);
1345         if (is_null($function->returns_desc)) {
1346             $return = '     * @return void';
1347         } else {
1348             $type = $this->get_phpdoc_type($function->returns_desc);
1349             $return = '     * @return '.$type.' '.$function->returns_desc->desc;
1350         }
1352         // now crate the virtual method that calls the ext implementation
1354         $code = '
1355     /**
1356      * '.$function->description.'
1357      *
1358 '.$params_desc.'
1359 '.$return.'
1360      */
1361     public function '.$function->name.'('.$paramanddefaults.') {
1362 '.$serviceclassmethodbody.'
1363     }
1364 ';
1365         return $code;
1366     }
1368     /**
1369      * Get the phpdoc type for an external_description
1370      * external_value => int, double or string
1371      * external_single_structure => object|struct, on-fly generated stdClass name, ...
1372      * external_multiple_structure => array
1373      *
1374      * @param string $keydesc any of PARAM_*
1375      * @return string phpdoc type (string, double, int, array...)
1376      */
1377     protected function get_phpdoc_type($keydesc) {
1378         if ($keydesc instanceof external_value) {
1379             switch($keydesc->type) {
1380                 case PARAM_BOOL: // 0 or 1 only for now
1381                 case PARAM_INT:
1382                     $type = 'int'; break;
1383                 case PARAM_FLOAT;
1384                     $type = 'double'; break;
1385                 default:
1386                     $type = 'string';
1387             }
1389         } else if ($keydesc instanceof external_single_structure) {
1390             $classname = $this->generate_simple_struct_class($keydesc);
1391             $type = $classname;
1393         } else if ($keydesc instanceof external_multiple_structure) {
1394             $type = 'array';
1395         }
1397         return $type;
1398     }
1400     /**
1401      * Generate 'struct'/'object' type name
1402      * Some servers (our Zend ones) parse the phpdoc to know the parameter types.
1403      * The purpose to this function is to be overwritten when the common object|struct type are not understood by the server.
1404      * See webservice/soap/locallib.php - the SOAP server requires detailed structure)
1405      *
1406      * @param external_single_structure $structdesc the structure for which we generate the phpdoc type
1407      * @return string the phpdoc type
1408      */
1409     protected function generate_simple_struct_class(external_single_structure $structdesc) {
1410         return 'object|struct'; //only 'object' is supported by SOAP, 'struct' by XML-RPC MDL-23083
1411     }
1413     /**
1414      * You can override this function in your child class to add extra code into the dynamically
1415      * created service class. For example it is used in the amf server to cast types of parameters and to
1416      * cast the return value to the types as specified in the return value description.
1417      *
1418      * @param stdClass $function a record from external_function
1419      * @param array $params web service function parameters
1420      * @return string body of the method for $function ie. everything within the {} of the method declaration.
1421      */
1422     protected function service_class_method_body($function, $params){
1423         //cast the param from object to array (validate_parameters except array only)
1424         $castingcode = '';
1425         if ($params){
1426             $paramstocast = explode(',', $params);
1427             foreach ($paramstocast as $paramtocast) {
1428                 //clean the parameter from any white space
1429                 $paramtocast = trim($paramtocast);
1430                 $castingcode .= $paramtocast .
1431                 '=webservice_zend_server::cast_objects_to_array('.$paramtocast.');';
1432             }
1434         }
1436         $descriptionmethod = $function->methodname.'_returns()';
1437         $callforreturnvaluedesc = $function->classname.'::'.$descriptionmethod;
1438         return $castingcode . '    if ('.$callforreturnvaluedesc.' == null)  {'.
1439                         $function->classname.'::'.$function->methodname.'('.$params.');
1440                         return null;
1441                     }
1442                     return external_api::clean_returnvalue('.$callforreturnvaluedesc.', '.$function->classname.'::'.$function->methodname.'('.$params.'));';
1443     }
1445     /**
1446      * Recursive function to recurse down into a complex variable and convert all
1447      * objects to arrays.
1448      *
1449      * @param mixed $param value to cast
1450      * @return mixed Cast value
1451      */
1452     public static function cast_objects_to_array($param){
1453         if (is_object($param)){
1454             $param = (array)$param;
1455         }
1456         if (is_array($param)){
1457             $toreturn = array();
1458             foreach ($param as $key=> $param){
1459                 $toreturn[$key] = self::cast_objects_to_array($param);
1460             }
1461             return $toreturn;
1462         } else {
1463             return $param;
1464         }
1465     }
1467     /**
1468      * Set up zend service class
1469      */
1470     protected function init_zend_server() {
1471         $this->zend_server = new $this->zend_class();
1472     }
1474     /**
1475      * This method parses the $_POST and $_GET superglobals and looks for
1476      * the following information:
1477      *  1/ user authentication - username+password or token (wsusername, wspassword and wstoken parameters)
1478      *
1479      * @return void
1480      */
1481     protected function parse_request() {
1483         // We are going to clean the POST/GET parameters from the parameters specific to the server.
1484         parent::set_web_service_call_settings();
1486         // Get GET and POST paramters.
1487         $methodvariables = array_merge($_GET,$_POST);
1489         if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
1490             //note: some clients have problems with entity encoding :-(
1491             if (isset($methodvariables['wsusername'])) {
1492                 $this->username = $methodvariables['wsusername'];
1493             }
1494             if (isset($methodvariables['wspassword'])) {
1495                 $this->password = $methodvariables['wspassword'];
1496             }
1497         } else {
1498             if (isset($methodvariables['wstoken'])) {
1499                 $this->token = $methodvariables['wstoken'];
1500             }
1501         }
1502     }
1504     /**
1505      * Internal implementation - sending of page headers.
1506      */
1507     protected function send_headers() {
1508         header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
1509         header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1510         header('Pragma: no-cache');
1511         header('Accept-Ranges: none');
1512     }
1514     /**
1515      * Specialised exception handler, we can not use the standard one because
1516      * it can not just print html to output.
1517      *
1518      * @param exception $ex
1519      * @uses exit
1520      */
1521     public function exception_handler($ex) {
1522         // detect active db transactions, rollback and log as error
1523         abort_all_db_transactions();
1525         // some hacks might need a cleanup hook
1526         $this->session_cleanup($ex);
1528         // now let the plugin send the exception to client
1529         $this->send_error($ex);
1531         // not much else we can do now, add some logging later
1532         exit(1);
1533     }
1535     /**
1536      * Send the error information to the WS client
1537      * formatted as XML document.
1538      *
1539      * @param exception $ex
1540      */
1541     protected function send_error($ex=null) {
1542         $this->send_headers();
1543         echo $this->zend_server->fault($ex);
1544     }
1546     /**
1547      * Future hook needed for emulated sessions.
1548      *
1549      * @param exception $exception null means normal termination, $exception received when WS call failed
1550      */
1551     protected function session_cleanup($exception=null) {
1552         if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
1553             // nothing needs to be done, there is no persistent session
1554         } else {
1555             // close emulated session if used
1556         }
1557     }
1561 /**
1562  * Web Service server base class.
1563  *
1564  * This class handles both simple and token authentication.
1565  *
1566  * @package    core_webservice
1567  * @copyright  2009 Petr Skodak
1568  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1569  */
1570 abstract class webservice_base_server extends webservice_server {
1572     /** @var array The function parameters - the real values submitted in the request */
1573     protected $parameters = null;
1575     /** @var string The name of the function that is executed */
1576     protected $functionname = null;
1578     /** @var stdClass Full function description */
1579     protected $function = null;
1581     /** @var mixed Function return value */
1582     protected $returns = null;
1584     /**
1585      * This method parses the request input, it needs to get:
1586      *  1/ user authentication - username+password or token
1587      *  2/ function name
1588      *  3/ function parameters
1589      */
1590     abstract protected function parse_request();
1592     /**
1593      * Send the result of function call to the WS client.
1594      */
1595     abstract protected function send_response();
1597     /**
1598      * Send the error information to the WS client.
1599      *
1600      * @param exception $ex
1601      */
1602     abstract protected function send_error($ex=null);
1604     /**
1605      * Process request from client.
1606      *
1607      * @uses die
1608      */
1609     public function run() {
1610         // we will probably need a lot of memory in some functions
1611         raise_memory_limit(MEMORY_EXTRA);
1613         // set some longer timeout, this script is not sending any output,
1614         // this means we need to manually extend the timeout operations
1615         // that need longer time to finish
1616         external_api::set_timeout();
1618         // set up exception handler first, we want to sent them back in correct format that
1619         // the other system understands
1620         // we do not need to call the original default handler because this ws handler does everything
1621         set_exception_handler(array($this, 'exception_handler'));
1623         // init all properties from the request data
1624         $this->parse_request();
1626         // authenticate user, this has to be done after the request parsing
1627         // this also sets up $USER and $SESSION
1628         $this->authenticate_user();
1630         // find all needed function info and make sure user may actually execute the function
1631         $this->load_function_info();
1633         // Log the web service request.
1634         $params = array(
1635             'other' => array(
1636                 'function' => $this->functionname
1637             )
1638         );
1639         $event = \core\event\webservice_function_called::create($params);
1640         $event->set_legacy_logdata(array(SITEID, 'webservice', $this->functionname, '' , getremoteaddr() , 0, $this->userid));
1641         $event->trigger();
1643         // finally, execute the function - any errors are catched by the default exception handler
1644         $this->execute();
1646         // send the results back in correct format
1647         $this->send_response();
1649         // session cleanup
1650         $this->session_cleanup();
1652         die;
1653     }
1655     /**
1656      * Specialised exception handler, we can not use the standard one because
1657      * it can not just print html to output.
1658      *
1659      * @param exception $ex
1660      * $uses exit
1661      */
1662     public function exception_handler($ex) {
1663         // detect active db transactions, rollback and log as error
1664         abort_all_db_transactions();
1666         // some hacks might need a cleanup hook
1667         $this->session_cleanup($ex);
1669         // now let the plugin send the exception to client
1670         $this->send_error($ex);
1672         // not much else we can do now, add some logging later
1673         exit(1);
1674     }
1676     /**
1677      * Future hook needed for emulated sessions.
1678      *
1679      * @param exception $exception null means normal termination, $exception received when WS call failed
1680      */
1681     protected function session_cleanup($exception=null) {
1682         if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
1683             // nothing needs to be done, there is no persistent session
1684         } else {
1685             // close emulated session if used
1686         }
1687     }
1689     /**
1690      * Fetches the function description from database,
1691      * verifies user is allowed to use this function and
1692      * loads all paremeters and return descriptions.
1693      */
1694     protected function load_function_info() {
1695         global $DB, $USER, $CFG;
1697         if (empty($this->functionname)) {
1698             throw new invalid_parameter_exception('Missing function name');
1699         }
1701         // function must exist
1702         $function = external_function_info($this->functionname);
1704         if ($this->restricted_serviceid) {
1705             $params = array('sid1'=>$this->restricted_serviceid, 'sid2'=>$this->restricted_serviceid);
1706             $wscond1 = 'AND s.id = :sid1';
1707             $wscond2 = 'AND s.id = :sid2';
1708         } else {
1709             $params = array();
1710             $wscond1 = '';
1711             $wscond2 = '';
1712         }
1714         // now let's verify access control
1716         // now make sure the function is listed in at least one service user is allowed to use
1717         // allow access only if:
1718         //  1/ entry in the external_services_users table if required
1719         //  2/ validuntil not reached
1720         //  3/ has capability if specified in service desc
1721         //  4/ iprestriction
1723         $sql = "SELECT s.*, NULL AS iprestriction
1724                   FROM {external_services} s
1725                   JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0 AND sf.functionname = :name1)
1726                  WHERE s.enabled = 1 $wscond1
1728                  UNION
1730                 SELECT s.*, su.iprestriction
1731                   FROM {external_services} s
1732                   JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1 AND sf.functionname = :name2)
1733                   JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)
1734                  WHERE s.enabled = 1 AND (su.validuntil IS NULL OR su.validuntil < :now) $wscond2";
1735         $params = array_merge($params, array('userid'=>$USER->id, 'name1'=>$function->name, 'name2'=>$function->name, 'now'=>time()));
1737         $rs = $DB->get_recordset_sql($sql, $params);
1738         // now make sure user may access at least one service
1739         $remoteaddr = getremoteaddr();
1740         $allowed = false;
1741         foreach ($rs as $service) {
1742             if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) {
1743                 continue; // cap required, sorry
1744             }
1745             if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) {
1746                 continue; // wrong request source ip, sorry
1747             }
1748             $allowed = true;
1749             break; // one service is enough, no need to continue
1750         }
1751         $rs->close();
1752         if (!$allowed) {
1753             throw new webservice_access_exception(
1754                     'Access to the function '.$this->functionname.'() is not allowed.
1755                      There could be multiple reasons for this:
1756                      1. The service linked to the user token does not contain the function.
1757                      2. The service is user-restricted and the user is not listed.
1758                      3. The service is IP-restricted and the user IP is not listed.
1759                      4. The service is time-restricted and the time has expired.
1760                      5. The token is time-restricted and the time has expired.
1761                      6. The service requires a specific capability which the user does not have.
1762                      7. The function is called with username/password (no user token is sent)
1763                      and none of the services has the function to allow the user.
1764                      These settings can be found in Administration > Site administration
1765                      > Plugins > Web services > External services and Manage tokens.');
1766         }
1768         // we have all we need now
1769         $this->function = $function;
1770     }
1772     /**
1773      * Execute previously loaded function using parameters parsed from the request data.
1774      */
1775     protected function execute() {
1776         // validate params, this also sorts the params properly, we need the correct order in the next part
1777         $params = call_user_func(array($this->function->classname, 'validate_parameters'), $this->function->parameters_desc, $this->parameters);
1779         // execute - yay!
1780         $this->returns = call_user_func_array(array($this->function->classname, $this->function->methodname), array_values($params));
1781     }