MDL-20808 Fixing default param handling.
[moodle.git] / webservice / lib.php
CommitLineData
06e7fadc 1<?php
cc93c7da 2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
06e7fadc 18/**
cc93c7da 19 * Web services utility functions and classes
06e7fadc 20 *
06e7fadc 21 * @package webservice
551f4420 22 * @copyright 2009 Moodle Pty Ltd (http://moodle.com)
cc93c7da 23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
06e7fadc 24 */
25
cc93c7da 26require_once($CFG->libdir.'/externallib.php');
893d7f0f 27
2d0acbd5
JP
28define('WEBSERVICE_AUTHMETHOD_USERNAME', 0);
29define('WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN', 1);
30define('WEBSERVICE_AUTHMETHOD_SESSION_TOKEN', 2);
31
229a7099 32/**
33 * General web service library
34 */
35class webservice {
36
86dcc6f0 37 /**
38 * Add a user to the list of authorised user of a given service
39 * @param object $user
40 */
41 public function add_ws_authorised_user($user) {
42 global $DB;
43 $serviceuser->timecreated = mktime();
44 $DB->insert_record('external_services_users', $user);
45 }
46
47 /**
48 * Remove a user from a list of allowed user of a service
49 * @param object $user
50 * @param int $serviceid
51 */
52 public function remove_ws_authorised_user($user, $serviceid) {
53 global $DB;
54 $DB->delete_records('external_services_users',
55 array('externalserviceid' => $serviceid, 'userid' => $user->id));
56 }
57
58 /**
59 * Update service allowed user settings
60 * @param object $user
61 */
62 public function update_ws_authorised_user($user) {
63 global $DB;
64 $DB->update_record('external_services_users', $user);
65 }
66
67 /**
68 * Return list of allowed users with their options (ip/timecreated / validuntil...)
69 * for a given service
70 * @param int $serviceid
71 * @return array $users
72 */
73 public function get_ws_authorised_users($serviceid) {
74 global $DB;
75 $params = array($serviceid);
76 $sql = " SELECT u.id as id, esu.id as serviceuserid, u.email as email, u.firstname as firstname,
77 u.lastname as lastname,
78 esu.iprestriction as iprestriction, esu.validuntil as validuntil,
79 esu.timecreated as timecreated
80 FROM {user} u, {external_services_users} esu
81 WHERE username <> 'guest' AND deleted = 0 AND confirmed = 1
82 AND esu.userid = u.id
83 AND esu.externalserviceid = ?";
84 if (!empty($userid)) {
85 $sql .= ' AND u.id = ?';
86 $params[] = $userid;
87 }
88
89 $users = $DB->get_records_sql($sql, $params);
90 return $users;
91 }
92
93 /**
94 * Return a authorised user with his options (ip/timecreated / validuntil...)
95 * @param int $serviceid
96 * @param int $userid
97 * @return object
98 */
99 public function get_ws_authorised_user($serviceid, $userid) {
100 global $DB;
101 $params = array($serviceid, $userid);
102 $sql = " SELECT u.id as id, esu.id as serviceuserid, u.email as email, u.firstname as firstname,
103 u.lastname as lastname,
104 esu.iprestriction as iprestriction, esu.validuntil as validuntil,
105 esu.timecreated as timecreated
106 FROM {user} u, {external_services_users} esu
107 WHERE username <> 'guest' AND deleted = 0 AND confirmed = 1
108 AND esu.userid = u.id
109 AND esu.externalserviceid = ?
110 AND u.id = ?";
111 $user = $DB->get_record_sql($sql, $params);
112 return $user;
113 }
114
229a7099 115 /**
116 * Generate all ws token needed by a user
117 * @param int $userid
118 */
119 public function generate_user_ws_tokens($userid) {
120 global $CFG, $DB;
121
122 /// generate a token for non admin if web service are enable and the user has the capability to create a token
123 if (!is_siteadmin() && has_capability('moodle/webservice:createtoken', get_context_instance(CONTEXT_SYSTEM), $userid) && !empty($CFG->enablewebservices)) {
124 /// for every service than the user is authorised on, create a token (if it doesn't already exist)
125
126 ///get all services which are set to all user (no restricted to specific users)
127 $norestrictedservices = $DB->get_records('external_services', array('restrictedusers' => 0));
128 $serviceidlist = array();
129 foreach ($norestrictedservices as $service) {
130 $serviceidlist[] = $service->id;
131 }
132
133 //get all services which are set to the current user (the current user is specified in the restricted user list)
134 $servicesusers = $DB->get_records('external_services_users', array('userid' => $userid));
135 foreach ($servicesusers as $serviceuser) {
136 if (!in_array($serviceuser->externalserviceid,$serviceidlist)) {
137 $serviceidlist[] = $serviceuser->externalserviceid;
138 }
139 }
140
141 //get all services which already have a token set for the current user
142 $usertokens = $DB->get_records('external_tokens', array('userid' => $userid, 'tokentype' => EXTERNAL_TOKEN_PERMANENT));
143 $tokenizedservice = array();
144 foreach ($usertokens as $token) {
145 $tokenizedservice[] = $token->externalserviceid;
146 }
147
148 //create a token for the service which have no token already
149 foreach ($serviceidlist as $serviceid) {
150 if (!in_array($serviceid, $tokenizedservice)) {
151 //create the token for this service
152 $newtoken = new object();
153 $newtoken->token = md5(uniqid(rand(),1));
154 //check that the user has capability on this service
155 $newtoken->tokentype = EXTERNAL_TOKEN_PERMANENT;
156 $newtoken->userid = $userid;
157 $newtoken->externalserviceid = $serviceid;
158 //TODO: find a way to get the context - UPDATE FOLLOWING LINE
159 $newtoken->contextid = get_context_instance(CONTEXT_SYSTEM)->id;
160 $newtoken->creatorid = $userid;
161 $newtoken->timecreated = time();
162
163 $DB->insert_record('external_tokens', $newtoken);
164 }
165 }
166
167
168 }
169 }
170
171 /**
172 * Return all ws user token
173 * @param integer $userid
174 * @return array of token
175 */
176 public function get_user_ws_tokens($userid) {
177 global $DB;
178 //here retrieve token list (including linked users firstname/lastname and linked services name)
179 $sql = "SELECT
180 t.id, t.creatorid, t.token, u.firstname, u.lastname, s.name, t.validuntil
181 FROM
182 {external_tokens} t, {user} u, {external_services} s
183 WHERE
184 t.userid=? AND t.tokentype = ".EXTERNAL_TOKEN_PERMANENT." AND s.id = t.externalserviceid AND t.userid = u.id";
185 $tokens = $DB->get_records_sql($sql, array( $userid));
186 return $tokens;
187 }
188
189 /**
190 * Return a user token that has been created by the user
191 * If doesn't exist a exception is thrown
192 * @param integer $userid
193 * @param integer $tokenid
194 * @return object
195 */
196 public function get_created_by_user_ws_token($userid, $tokenid) {
197 global $DB;
198 $sql = "SELECT
199 t.id, t.token, u.firstname, u.lastname, s.name
200 FROM
201 {external_tokens} t, {user} u, {external_services} s
202 WHERE
203 t.creatorid=? AND t.id=? AND t.tokentype = ".EXTERNAL_TOKEN_PERMANENT." AND s.id = t.externalserviceid AND t.userid = u.id";
204 $token = $DB->get_record_sql($sql, array($userid, $tokenid), MUST_EXIST); //must be the token creator
205 return $token;
206
207 }
208
209 /**
210 * Delete a user token
211 * @param int $tokenid
212 */
213 public function delete_user_ws_token($tokenid) {
214 global $DB;
215 $DB->delete_records('external_tokens', array('id'=>$tokenid));
216 }
bb98a5b2 217
218 /**
219 * Get a user token by token
220 * @param string $token
221 * @throws moodle_exception if there is multiple result
222 */
223 public function get_user_ws_token($token) {
224 global $DB;
225 return $DB->get_record('external_tokens', array('token'=>$token), '*', MUST_EXIST);
226 }
229a7099 227}
228
229
5593d2dc 230/**
231 * Exception indicating access control problem in web service call
01482a4a 232 * @author Petr Skoda (skodak)
5593d2dc 233 */
234class webservice_access_exception extends moodle_exception {
235 /**
236 * Constructor
237 */
238 function __construct($debuginfo) {
e8b21670 239 parent::__construct('accessexception', 'webservice', '', null, $debuginfo);
5593d2dc 240 }
241}
242
f0dafb3c 243/**
244 * Is protocol enabled?
245 * @param string $protocol name of WS protocol
246 * @return bool
247 */
cc93c7da 248function webservice_protocol_is_enabled($protocol) {
249 global $CFG;
893d7f0f 250
cc93c7da 251 if (empty($CFG->enablewebservices)) {
252 return false;
893d7f0f 253 }
254
cc93c7da 255 $active = explode(',', $CFG->webserviceprotocols);
893d7f0f 256
cc93c7da 257 return(in_array($protocol, $active));
258}
893d7f0f 259
01482a4a 260//=== WS classes ===
893d7f0f 261
f0dafb3c 262/**
3f599588 263 * Mandatory interface for all test client classes.
01482a4a 264 * @author Petr Skoda (skodak)
f0dafb3c 265 */
266interface webservice_test_client_interface {
267 /**
268 * Execute test client WS request
269 * @param string $serverurl
270 * @param string $function
271 * @param array $params
272 * @return mixed
273 */
274 public function simpletest($serverurl, $function, $params);
275}
276
06e7fadc 277/**
3f599588 278 * Mandatory interface for all web service protocol classes
01482a4a 279 * @author Petr Skoda (skodak)
06e7fadc 280 */
01482a4a
PS
281interface webservice_server_interface {
282 /**
283 * Process request from client.
284 * @return void
285 */
286 public function run();
287}
88098133 288
01482a4a
PS
289/**
290 * Abstract web service base class.
291 * @author Petr Skoda (skodak)
292 */
293abstract class webservice_server implements webservice_server_interface {
88098133 294
295 /** @property string $wsname name of the web server plugin */
296 protected $wsname = null;
297
c187722c
PS
298 /** @property string $username name of local user */
299 protected $username = null;
300
301 /** @property string $password password of the local user */
302 protected $password = null;
b107e647 303
c3517f05 304 /** @property int $userid the local user */
305 protected $userid = null;
306
2d0acbd5
JP
307 /** @property integer $authmethod authentication method one of WEBSERVICE_AUTHMETHOD_* */
308 protected $authmethod;
88098133 309
01482a4a
PS
310 /** @property string $token authentication token*/
311 protected $token = null;
88098133 312
313 /** @property object restricted context */
314 protected $restricted_context;
315
01482a4a
PS
316 /** @property int restrict call to one service id*/
317 protected $restricted_serviceid = null;
318
2d0acbd5
JP
319 /**
320 * Contructor
321 * @param integer $authmethod authentication method one of WEBSERVICE_AUTHMETHOD_*
322 */
323 public function __construct($authmethod) {
324 $this->authmethod = $authmethod;
325 }
326
327
01482a4a
PS
328 /**
329 * Authenticate user using username+password or token.
330 * This function sets up $USER global.
331 * It is safe to use has_capability() after this.
332 * This method also verifies user is allowed to use this
333 * server.
334 * @return void
335 */
336 protected function authenticate_user() {
337 global $CFG, $DB;
338
339 if (!NO_MOODLE_COOKIES) {
340 throw new coding_exception('Cookies must be disabled in WS servers!');
341 }
342
2d0acbd5 343 if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
01482a4a 344
1839e2f0 345 //we check that authentication plugin is enabled
346 //it is only required by simple authentication
347 if (!is_enabled_auth('webservice')) {
348 throw new webservice_access_exception(get_string('wsauthnotenabled', 'webservice'));
349 }
01482a4a 350
1839e2f0 351 if (!$auth = get_auth_plugin('webservice')) {
352 throw new webservice_access_exception(get_string('wsauthmissing', 'webservice'));
353 }
01482a4a 354
01482a4a
PS
355 $this->restricted_context = get_context_instance(CONTEXT_SYSTEM);
356
357 if (!$this->username) {
b0a9a0cd 358 throw new webservice_access_exception(get_string('missingusername', 'webservice'));
01482a4a
PS
359 }
360
361 if (!$this->password) {
b0a9a0cd 362 throw new webservice_access_exception(get_string('missingpassword', 'webservice'));
01482a4a
PS
363 }
364
365 if (!$auth->user_login_webservice($this->username, $this->password)) {
1e29fe3f 366 // log failed login attempts
7e0eac79 367 add_to_log(1, 'webservice', get_string('simpleauthlog', 'webservice'), '' , get_string('failedtolog', 'webservice').": ".$this->username."/".$this->password." - ".getremoteaddr() , 0);
b0a9a0cd 368 throw new webservice_access_exception(get_string('wrongusernamepassword', 'webservice'));
01482a4a
PS
369 }
370
371 $user = $DB->get_record('user', array('username'=>$this->username, 'mnethostid'=>$CFG->mnet_localhost_id, 'deleted'=>0), '*', MUST_EXIST);
372
2d0acbd5
JP
373 } else if ($this->authmethod == WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN){
374 $user = $this->authenticate_by_token(EXTERNAL_TOKEN_PERMANENT);
01482a4a 375 } else {
2d0acbd5 376 $user = $this->authenticate_by_token(EXTERNAL_TOKEN_EMBEDDED);
01482a4a 377 }
2d0acbd5 378
01482a4a
PS
379 // now fake user login, the session is completely empty too
380 session_set_user($user);
c3517f05 381 $this->userid = $user->id;
01482a4a 382
0f1e3914 383 if ($this->authmethod != WEBSERVICE_AUTHMETHOD_SESSION_TOKEN && !has_capability("webservice/$this->wsname:use", $this->restricted_context)) {
b0a9a0cd 384 throw new webservice_access_exception(get_string('accessnotallowed', 'webservice'));
01482a4a
PS
385 }
386
387 external_api::set_context_restriction($this->restricted_context);
388 }
2d0acbd5
JP
389
390 protected function authenticate_by_token($tokentype){
391 global $DB;
392 if (!$token = $DB->get_record('external_tokens', array('token'=>$this->token, 'tokentype'=>$tokentype))) {
393 // log failed login attempts
394 add_to_log(1, 'webservice', get_string('tokenauthlog', 'webservice'), '' , get_string('failedtolog', 'webservice').": ".$this->token. " - ".getremoteaddr() , 0);
395 throw new webservice_access_exception(get_string('invalidtoken', 'webservice'));
396 }
397
398 if ($token->validuntil and $token->validuntil < time()) {
399 $DB->delete_records('external_tokens', array('token'=>$this->token, 'tokentype'=>$tokentype));
400 throw new webservice_access_exception(get_string('invalidtimedtoken', 'webservice'));
401 }
402
403 if ($token->sid){//assumes that if sid is set then there must be a valid associated session no matter the token type
404 $session = session_get_instance();
405 if (!$session->session_exists($token->sid)){
406 $DB->delete_records('external_tokens', array('sid'=>$token->sid));
407 throw new webservice_access_exception(get_string('invalidtokensession', 'webservice'));
408 }
409 }
410
411 if ($token->iprestriction and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
412 add_to_log(1, 'webservice', get_string('tokenauthlog', 'webservice'), '' , get_string('failedtolog', 'webservice').": ".getremoteaddr() , 0);
413 throw new webservice_access_exception(get_string('invalidiptoken', 'webservice'));
414 }
415
416 $this->restricted_context = get_context_instance_by_id($token->contextid);
417 $this->restricted_serviceid = $token->externalserviceid;
418
419 $user = $DB->get_record('user', array('id'=>$token->userid, 'deleted'=>0), '*', MUST_EXIST);
420
421 // log token access
422 $DB->set_field('external_tokens', 'lastaccess', time(), array('id'=>$token->id));
423
424 return $user;
425
426 }
01482a4a
PS
427}
428
429/**
430 * Special abstraction of our srvices that allows
431 * interaction with stock Zend ws servers.
432 * @author Petr Skoda (skodak)
433 */
434abstract class webservice_zend_server extends webservice_server {
435
abf7dc44 436 /** @property string name of the zend server class : Zend_XmlRpc_Server, Zend_Soap_Server, Zend_Soap_AutoDiscover, ...*/
01482a4a
PS
437 protected $zend_class;
438
439 /** @property object Zend server instance */
440 protected $zend_server;
441
442 /** @property string $service_class virtual web service class with all functions user name execute, created on the fly */
443 protected $service_class;
444
88098133 445 /**
446 * Contructor
2d0acbd5 447 * @param integer $authmethod authentication method - one of WEBSERVICE_AUTHMETHOD_*
88098133 448 */
2d0acbd5
JP
449 public function __construct($authmethod, $zend_class) {
450 parent::__construct($authmethod);
88098133 451 $this->zend_class = $zend_class;
452 }
453
454 /**
455 * Process request from client.
456 * @param bool $simple use simple authentication
457 * @return void
458 */
2458e30a 459 public function run() {
88098133 460 // we will probably need a lot of memory in some functions
461 @raise_memory_limit('128M');
462
463 // set some longer timeout, this script is not sending any output,
464 // this means we need to manually extend the timeout operations
465 // that need longer time to finish
466 external_api::set_timeout();
467
e8b21670 468 // now create the instance of zend server
469 $this->init_zend_server();
470
88098133 471 // set up exception handler first, we want to sent them back in correct format that
472 // the other system understands
473 // we do not need to call the original default handler because this ws handler does everything
474 set_exception_handler(array($this, 'exception_handler'));
475
c187722c
PS
476 // init all properties from the request data
477 $this->parse_request();
478
88098133 479 // this sets up $USER and $SESSION and context restrictions
480 $this->authenticate_user();
481
482 // make a list of all functions user is allowed to excecute
483 $this->init_service_class();
484
2458e30a 485 // tell server what functions are available
88098133 486 $this->zend_server->setClass($this->service_class);
d9ad0103 487
1e29fe3f 488 //log the web service request
7e0eac79 489 add_to_log(1, 'webservice', '', '' , $this->zend_class." ".getremoteaddr() , 0, $this->userid);
1e29fe3f 490
2458e30a 491 // execute and return response, this sends some headers too
88098133 492 $response = $this->zend_server->handle();
2458e30a 493
88098133 494 // session cleanup
495 $this->session_cleanup();
496
ca6340bf 497 //finally send the result
498 $this->send_headers();
88098133 499 echo $response;
500 die;
501 }
502
503 /**
504 * Load virtual class needed for Zend api
505 * @return void
506 */
507 protected function init_service_class() {
508 global $USER, $DB;
509
510 // first ofall get a complete list of services user is allowed to access
88098133 511
01482a4a
PS
512 if ($this->restricted_serviceid) {
513 $params = array('sid1'=>$this->restricted_serviceid, 'sid2'=>$this->restricted_serviceid);
514 $wscond1 = 'AND s.id = :sid1';
515 $wscond2 = 'AND s.id = :sid2';
516 } else {
517 $params = array();
518 $wscond1 = '';
519 $wscond2 = '';
520 }
88098133 521
01482a4a
PS
522 // now make sure the function is listed in at least one service user is allowed to use
523 // allow access only if:
524 // 1/ entry in the external_services_users table if required
525 // 2/ validuntil not reached
526 // 3/ has capability if specified in service desc
527 // 4/ iprestriction
88098133 528
01482a4a
PS
529 $sql = "SELECT s.*, NULL AS iprestriction
530 FROM {external_services} s
531 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0)
532 WHERE s.enabled = 1 $wscond1
88098133 533
01482a4a
PS
534 UNION
535
536 SELECT s.*, su.iprestriction
537 FROM {external_services} s
538 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1)
539 JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)
540 WHERE s.enabled = 1 AND su.validuntil IS NULL OR su.validuntil < :now $wscond2";
541
542 $params = array_merge($params, array('userid'=>$USER->id, 'now'=>time()));
88098133 543
544 $serviceids = array();
545 $rs = $DB->get_recordset_sql($sql, $params);
546
547 // now make sure user may access at least one service
548 $remoteaddr = getremoteaddr();
549 $allowed = false;
550 foreach ($rs as $service) {
551 if (isset($serviceids[$service->id])) {
552 continue;
553 }
554 if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) {
555 continue; // cap required, sorry
556 }
557 if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) {
558 continue; // wrong request source ip, sorry
559 }
560 $serviceids[$service->id] = $service->id;
561 }
562 $rs->close();
563
564 // now get the list of all functions
565 if ($serviceids) {
566 list($serviceids, $params) = $DB->get_in_or_equal($serviceids);
567 $sql = "SELECT f.*
568 FROM {external_functions} f
569 WHERE f.name IN (SELECT sf.functionname
570 FROM {external_services_functions} sf
571 WHERE sf.externalserviceid $serviceids)";
572 $functions = $DB->get_records_sql($sql, $params);
573 } else {
574 $functions = array();
575 }
576
577 // now make the virtual WS class with all the fuctions for this particular user
578 $methods = '';
579 foreach ($functions as $function) {
580 $methods .= $this->get_virtual_method_code($function);
581 }
582
5593d2dc 583 // let's use unique class name, there might be problem in unit tests
88098133 584 $classname = 'webservices_virtual_class_000000';
585 while(class_exists($classname)) {
586 $classname++;
587 }
588
589 $code = '
590/**
591 * Virtual class web services for user id '.$USER->id.' in context '.$this->restricted_context->id.'.
592 */
593class '.$classname.' {
594'.$methods.'
595}
596';
f0dafb3c 597
88098133 598 // load the virtual class definition into memory
599 eval($code);
88098133 600 $this->service_class = $classname;
601 }
602
603 /**
604 * returns virtual method code
605 * @param object $function
606 * @return string PHP code
607 */
608 protected function get_virtual_method_code($function) {
609 global $CFG;
610
5593d2dc 611 $function = external_function_info($function);
88098133 612
b437f681
JP
613 //arguments in function declaration line with defaults.
614 $paramanddefaults = array();
615 //arguments used as parameters for external lib call.
88098133 616 $params = array();
617 $params_desc = array();
453a7a85 618 foreach ($function->parameters_desc->keys as $name=>$keydesc) {
a8dd0325 619 $param = '$'.$name;
b437f681 620 $paramanddefault = $param;
a8dd0325 621 //need to generate the default if there is any
622 if ($keydesc instanceof external_value) {
623 if ($keydesc->required == VALUE_DEFAULT) {
624 if ($keydesc->default===null) {
b437f681 625 $paramanddefault .= '=null';
a8dd0325 626 } else {
627 switch($keydesc->type) {
628 case PARAM_BOOL:
b437f681 629 $paramanddefault .= '='.$keydesc->default; break;
a8dd0325 630 case PARAM_INT:
b437f681 631 $paramanddefault .= '='.$keydesc->default; break;
a8dd0325 632 case PARAM_FLOAT;
b437f681 633 $paramanddefault .= '='.$keydesc->default; break;
a8dd0325 634 default:
b437f681 635 $paramanddefault .= '=\''.$keydesc->default.'\'';
a8dd0325 636 }
637 }
638 } else if ($keydesc->required == VALUE_OPTIONAL) {
639 //it does make sens to declare a parameter VALUE_OPTIONAL
640 //VALUE_OPTIONAL is used only for array/object key
641 throw new moodle_exception('parametercannotbevalueoptional');
642 }
643 } else { //for the moment we do not support default for other structure types
774b1b0f 644 if ($keydesc->required == VALUE_DEFAULT) {
645 //accept empty array as default
646 if (isset($keydesc->default) and is_array($keydesc->default)
647 and empty($keydesc->default)) {
648 $param .= '=array()';
649 } else {
650 throw new moodle_exception('errornotemptydefaultparamarray', 'webservice', '', $name);
651 }
652 }
653 if ($keydesc->required == VALUE_OPTIONAL) {
654 throw new moodle_exception('erroroptionalparamarray', 'webservice', '', $name);
a8dd0325 655 }
656 }
b437f681
JP
657 $params[] = $param;
658 $paramanddefaults[] = $paramanddefault;
453a7a85 659 $type = 'string';
660 if ($keydesc instanceof external_value) {
661 switch($keydesc->type) {
662 case PARAM_BOOL: // 0 or 1 only for now
663 case PARAM_INT:
664 $type = 'int'; break;
665 case PARAM_FLOAT;
666 $type = 'double'; break;
667 default:
668 $type = 'string';
669 }
670 } else if ($keydesc instanceof external_single_structure) {
c06503b8 671 $type = 'object|struct';
453a7a85 672 } else if ($keydesc instanceof external_multiple_structure) {
673 $type = 'array';
674 }
675 $params_desc[] = ' * @param '.$type.' $'.$name.' '.$keydesc->desc;
88098133 676 }
b437f681
JP
677 $params = implode(', ', $params);
678 $paramanddefaults = implode(', ', $paramanddefaults);
679 $params_desc = implode("\n", $params_desc);
94a9b9e7
JP
680
681 $serviceclassmethodbody = $this->service_class_method_body($function, $params);
88098133 682
453a7a85 683 if (is_null($function->returns_desc)) {
684 $return = ' * @return void';
685 } else {
686 $type = 'string';
687 if ($function->returns_desc instanceof external_value) {
688 switch($function->returns_desc->type) {
689 case PARAM_BOOL: // 0 or 1 only for now
690 case PARAM_INT:
691 $type = 'int'; break;
692 case PARAM_FLOAT;
693 $type = 'double'; break;
694 default:
695 $type = 'string';
696 }
697 } else if ($function->returns_desc instanceof external_single_structure) {
e93b82d7 698 $type = 'object|struct'; //only 'object' is supported by SOAP, 'struct' by XML-RPC MDL-23083
453a7a85 699 } else if ($function->returns_desc instanceof external_multiple_structure) {
700 $type = 'array';
701 }
702 $return = ' * @return '.$type.' '.$function->returns_desc->desc;
703 }
d4e764ab 704
01482a4a 705 // now crate the virtual method that calls the ext implementation
88098133 706
707 $code = '
708 /**
5593d2dc 709 * '.$function->description.'
710 *
88098133 711'.$params_desc.'
453a7a85 712'.$return.'
88098133 713 */
b437f681 714 public function '.$function->name.'('.$paramanddefaults.') {
c77e75a3 715'.$serviceclassmethodbody.'
88098133 716 }
717';
718 return $code;
719 }
94a9b9e7
JP
720
721 /**
722 * You can override this function in your child class to add extra code into the dynamically
723 * created service class. For example it is used in the amf server to cast types of parameters and to
724 * cast the return value to the types as specified in the return value description.
725 * @param unknown_type $function
726 * @param unknown_type $params
727 * @return string body of the method for $function ie. everything within the {} of the method declaration.
728 */
729 protected function service_class_method_body($function, $params){
c06503b8 730 //cast the param from object to array (validate_parameters except array only)
731 $castingcode = '';
732 if ($params){
733 $paramstocast = split(',', $params);
734 foreach ($paramstocast as $paramtocast) {
02998b3f 735 //clean the parameter from any white space
736 $paramtocast = trim($paramtocast);
c06503b8 737 $castingcode .= $paramtocast .
738 '=webservice_zend_server::cast_objects_to_array('.$paramtocast.');';
739 }
740
741 }
742
d07ff72d 743 $descriptionmethod = $function->methodname.'_returns()';
2d0acbd5 744 $callforreturnvaluedesc = $function->classname.'::'.$descriptionmethod;
c06503b8 745 return $castingcode . ' if ('.$callforreturnvaluedesc.' == null) {'.
746 $function->classname.'::'.$function->methodname.'('.$params.');
99152d09 747 return null;
748 }
749 return external_api::clean_returnvalue('.$callforreturnvaluedesc.', '.$function->classname.'::'.$function->methodname.'('.$params.'));';
94a9b9e7 750 }
d07ff72d 751
88098133 752 /**
c06503b8 753 * Recursive function to recurse down into a complex variable and convert all
754 * objects to arrays.
755 * @param mixed $param value to cast
756 * @return mixed Cast value
757 */
758 public static function cast_objects_to_array($param){
759 if (is_object($param)){
760 $param = (array)$param;
761 }
762 if (is_array($param)){
763 $toreturn = array();
764 foreach ($param as $key=> $param){
765 $toreturn[$key] = self::cast_objects_to_array($param);
766 }
767 return $toreturn;
768 } else {
769 return $param;
770 }
771 }
772
773 /**
b107e647 774 * Set up zend service class
88098133 775 * @return void
776 */
777 protected function init_zend_server() {
88098133 778 $this->zend_server = new $this->zend_class();
88098133 779 }
780
c187722c
PS
781 /**
782 * This method parses the $_REQUEST superglobal and looks for
783 * the following information:
784 * 1/ user authentication - username+password or token (wsusername, wspassword and wstoken parameters)
785 *
786 * @return void
787 */
788 protected function parse_request() {
2d0acbd5 789 if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
01482a4a 790 //note: some clients have problems with entity encoding :-(
c187722c
PS
791 if (isset($_REQUEST['wsusername'])) {
792 $this->username = $_REQUEST['wsusername'];
c187722c
PS
793 }
794 if (isset($_REQUEST['wspassword'])) {
795 $this->password = $_REQUEST['wspassword'];
c187722c
PS
796 }
797 } else {
01482a4a
PS
798 if (isset($_REQUEST['wstoken'])) {
799 $this->token = $_REQUEST['wstoken'];
88098133 800 }
88098133 801 }
88098133 802 }
803
ca6340bf 804 /**
805 * Internal implementation - sending of page headers.
806 * @return void
807 */
808 protected function send_headers() {
809 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
810 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
811 header('Pragma: no-cache');
812 header('Accept-Ranges: none');
813 }
814
88098133 815 /**
816 * Specialised exception handler, we can not use the standard one because
817 * it can not just print html to output.
818 *
819 * @param exception $ex
820 * @return void does not return
821 */
822 public function exception_handler($ex) {
88098133 823 // detect active db transactions, rollback and log as error
3086dd59 824 abort_all_db_transactions();
88098133 825
88098133 826 // some hacks might need a cleanup hook
827 $this->session_cleanup($ex);
828
ca6340bf 829 // now let the plugin send the exception to client
b107e647 830 $this->send_error($ex);
ca6340bf 831
88098133 832 // not much else we can do now, add some logging later
833 exit(1);
834 }
835
b107e647
PS
836 /**
837 * Send the error information to the WS client
838 * formatted as XML document.
839 * @param exception $ex
840 * @return void
841 */
842 protected function send_error($ex=null) {
843 $this->send_headers();
844 echo $this->zend_server->fault($ex);
845 }
01482a4a 846
88098133 847 /**
848 * Future hook needed for emulated sessions.
849 * @param exception $exception null means normal termination, $exception received when WS call failed
850 * @return void
851 */
852 protected function session_cleanup($exception=null) {
2d0acbd5 853 if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
88098133 854 // nothing needs to be done, there is no persistent session
855 } else {
856 // close emulated session if used
857 }
858 }
859
cc93c7da 860}
861
886d7556 862/**
cc93c7da 863 * Web Service server base class, this class handles both
864 * simple and token authentication.
865 * @author Petr Skoda (skodak)
886d7556 866 */
01482a4a 867abstract class webservice_base_server extends webservice_server {
88098133 868
cc93c7da 869 /** @property array $parameters the function parameters - the real values submitted in the request */
870 protected $parameters = null;
871
872 /** @property string $functionname the name of the function that is executed */
873 protected $functionname = null;
874
875 /** @property object $function full function description */
876 protected $function = null;
877
878 /** @property mixed $returns function return value */
879 protected $returns = null;
06e7fadc 880
24350e06 881 /**
cc93c7da 882 * This method parses the request input, it needs to get:
883 * 1/ user authentication - username+password or token
884 * 2/ function name
885 * 3/ function parameters
886 *
887 * @return void
24350e06 888 */
cc93c7da 889 abstract protected function parse_request();
24350e06 890
cc93c7da 891 /**
892 * Send the result of function call to the WS client.
893 * @return void
894 */
895 abstract protected function send_response();
24350e06 896
fa0797ec 897 /**
cc93c7da 898 * Send the error information to the WS client.
899 * @param exception $ex
900 * @return void
fa0797ec 901 */
cc93c7da 902 abstract protected function send_error($ex=null);
fa0797ec 903
cc93c7da 904 /**
905 * Process request from client.
cc93c7da 906 * @return void
907 */
2458e30a 908 public function run() {
cc93c7da 909 // we will probably need a lot of memory in some functions
910 @raise_memory_limit('128M');
fa0797ec 911
cc93c7da 912 // set some longer timeout, this script is not sending any output,
913 // this means we need to manually extend the timeout operations
914 // that need longer time to finish
915 external_api::set_timeout();
fa0797ec 916
cc93c7da 917 // set up exception handler first, we want to sent them back in correct format that
918 // the other system understands
919 // we do not need to call the original default handler because this ws handler does everything
920 set_exception_handler(array($this, 'exception_handler'));
06e7fadc 921
cc93c7da 922 // init all properties from the request data
923 $this->parse_request();
06e7fadc 924
cc93c7da 925 // authenticate user, this has to be done after the request parsing
926 // this also sets up $USER and $SESSION
927 $this->authenticate_user();
06e7fadc 928
cc93c7da 929 // find all needed function info and make sure user may actually execute the function
930 $this->load_function_info();
c3517f05 931
932 //log the web service request
7e0eac79 933 add_to_log(1, 'webservice', $this->functionname, '' , getremoteaddr() , 0, $this->userid);
f7631e73 934
cc93c7da 935 // finally, execute the function - any errors are catched by the default exception handler
936 $this->execute();
06e7fadc 937
cc93c7da 938 // send the results back in correct format
939 $this->send_response();
06e7fadc 940
cc93c7da 941 // session cleanup
942 $this->session_cleanup();
06e7fadc 943
cc93c7da 944 die;
f7631e73 945 }
946
cc93c7da 947 /**
948 * Specialised exception handler, we can not use the standard one because
949 * it can not just print html to output.
950 *
951 * @param exception $ex
952 * @return void does not return
953 */
954 public function exception_handler($ex) {
cc93c7da 955 // detect active db transactions, rollback and log as error
3086dd59 956 abort_all_db_transactions();
06e7fadc 957
cc93c7da 958 // some hacks might need a cleanup hook
959 $this->session_cleanup($ex);
06e7fadc 960
ca6340bf 961 // now let the plugin send the exception to client
962 $this->send_error($ex);
963
cc93c7da 964 // not much else we can do now, add some logging later
965 exit(1);
f7631e73 966 }
967
968 /**
cc93c7da 969 * Future hook needed for emulated sessions.
970 * @param exception $exception null means normal termination, $exception received when WS call failed
971 * @return void
f7631e73 972 */
cc93c7da 973 protected function session_cleanup($exception=null) {
ad8b5ba2 974 if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
cc93c7da 975 // nothing needs to be done, there is no persistent session
976 } else {
977 // close emulated session if used
978 }
f7631e73 979 }
980
24350e06 981 /**
cc93c7da 982 * Fetches the function description from database,
983 * verifies user is allowed to use this function and
984 * loads all paremeters and return descriptions.
985 * @return void
24350e06 986 */
cc93c7da 987 protected function load_function_info() {
988 global $DB, $USER, $CFG;
40f024c9 989
cc93c7da 990 if (empty($this->functionname)) {
991 throw new invalid_parameter_exception('Missing function name');
992 }
24350e06 993
cc93c7da 994 // function must exist
5593d2dc 995 $function = external_function_info($this->functionname);
cc93c7da 996
01482a4a
PS
997 if ($this->restricted_serviceid) {
998 $params = array('sid1'=>$this->restricted_serviceid, 'sid2'=>$this->restricted_serviceid);
999 $wscond1 = 'AND s.id = :sid1';
1000 $wscond2 = 'AND s.id = :sid2';
1001 } else {
1002 $params = array();
1003 $wscond1 = '';
1004 $wscond2 = '';
1005 }
1006
cc93c7da 1007 // now let's verify access control
b8c5309e 1008
1009 // now make sure the function is listed in at least one service user is allowed to use
1010 // allow access only if:
1011 // 1/ entry in the external_services_users table if required
1012 // 2/ validuntil not reached
1013 // 3/ has capability if specified in service desc
1014 // 4/ iprestriction
1015
1016 $sql = "SELECT s.*, NULL AS iprestriction
1017 FROM {external_services} s
1018 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0 AND sf.functionname = :name1)
1019 WHERE s.enabled = 1 $wscond1
1020
1021 UNION
1022
1023 SELECT s.*, su.iprestriction
1024 FROM {external_services} s
1025 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1 AND sf.functionname = :name2)
1026 JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)
1027 WHERE s.enabled = 1 AND su.validuntil IS NULL OR su.validuntil < :now $wscond2";
1028 $params = array_merge($params, array('userid'=>$USER->id, 'name1'=>$function->name, 'name2'=>$function->name, 'now'=>time()));
88098133 1029
1030 $rs = $DB->get_recordset_sql($sql, $params);
1031 // now make sure user may access at least one service
1032 $remoteaddr = getremoteaddr();
1033 $allowed = false;
1034 foreach ($rs as $service) {
1035 if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) {
1036 continue; // cap required, sorry
cc93c7da 1037 }
88098133 1038 if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) {
1039 continue; // wrong request source ip, sorry
cc93c7da 1040 }
88098133 1041 $allowed = true;
1042 break; // one service is enough, no need to continue
1043 }
1044 $rs->close();
1045 if (!$allowed) {
c91cc5ef 1046 throw new webservice_access_exception('Access to external function not allowed');
cc93c7da 1047 }
9baf6825 1048
cc93c7da 1049 // we have all we need now
1050 $this->function = $function;
1051 }
1052
1053 /**
1054 * Execute previously loaded function using parameters parsed from the request data.
1055 * @return void
1056 */
1057 protected function execute() {
1058 // validate params, this also sorts the params properly, we need the correct order in the next part
1059 $params = call_user_func(array($this->function->classname, 'validate_parameters'), $this->function->parameters_desc, $this->parameters);
9baf6825 1060
cc93c7da 1061 // execute - yay!
1062 $this->returns = call_user_func_array(array($this->function->classname, $this->function->methodname), array_values($params));
9baf6825 1063 }
1064}
1065
1066