Updated the HEAD build version to 20100401
[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
5593d2dc 28/**
29 * Exception indicating access control problem in web service call
01482a4a 30 * @author Petr Skoda (skodak)
5593d2dc 31 */
32class webservice_access_exception extends moodle_exception {
33 /**
34 * Constructor
35 */
36 function __construct($debuginfo) {
e8b21670 37 parent::__construct('accessexception', 'webservice', '', null, $debuginfo);
5593d2dc 38 }
39}
40
f0dafb3c 41/**
42 * Is protocol enabled?
43 * @param string $protocol name of WS protocol
44 * @return bool
45 */
cc93c7da 46function webservice_protocol_is_enabled($protocol) {
47 global $CFG;
893d7f0f 48
cc93c7da 49 if (empty($CFG->enablewebservices)) {
50 return false;
893d7f0f 51 }
52
cc93c7da 53 $active = explode(',', $CFG->webserviceprotocols);
893d7f0f 54
cc93c7da 55 return(in_array($protocol, $active));
56}
893d7f0f 57
01482a4a 58//=== WS classes ===
893d7f0f 59
f0dafb3c 60/**
3f599588 61 * Mandatory interface for all test client classes.
01482a4a 62 * @author Petr Skoda (skodak)
f0dafb3c 63 */
64interface webservice_test_client_interface {
65 /**
66 * Execute test client WS request
67 * @param string $serverurl
68 * @param string $function
69 * @param array $params
70 * @return mixed
71 */
72 public function simpletest($serverurl, $function, $params);
73}
74
06e7fadc 75/**
3f599588 76 * Mandatory interface for all web service protocol classes
01482a4a 77 * @author Petr Skoda (skodak)
06e7fadc 78 */
01482a4a
PS
79interface webservice_server_interface {
80 /**
81 * Process request from client.
82 * @return void
83 */
84 public function run();
85}
88098133 86
01482a4a
PS
87/**
88 * Abstract web service base class.
89 * @author Petr Skoda (skodak)
90 */
91abstract class webservice_server implements webservice_server_interface {
88098133 92
93 /** @property string $wsname name of the web server plugin */
94 protected $wsname = null;
95
c187722c
PS
96 /** @property string $username name of local user */
97 protected $username = null;
98
99 /** @property string $password password of the local user */
100 protected $password = null;
b107e647 101
c3517f05 102 /** @property int $userid the local user */
103 protected $userid = null;
104
88098133 105 /** @property bool $simple true if simple auth used */
106 protected $simple;
107
01482a4a
PS
108 /** @property string $token authentication token*/
109 protected $token = null;
88098133 110
111 /** @property object restricted context */
112 protected $restricted_context;
113
01482a4a
PS
114 /** @property int restrict call to one service id*/
115 protected $restricted_serviceid = null;
116
117 /**
118 * Authenticate user using username+password or token.
119 * This function sets up $USER global.
120 * It is safe to use has_capability() after this.
121 * This method also verifies user is allowed to use this
122 * server.
123 * @return void
124 */
125 protected function authenticate_user() {
126 global $CFG, $DB;
127
128 if (!NO_MOODLE_COOKIES) {
129 throw new coding_exception('Cookies must be disabled in WS servers!');
130 }
131
1839e2f0 132 if ($this->simple) {
01482a4a 133
1839e2f0 134 //we check that authentication plugin is enabled
135 //it is only required by simple authentication
136 if (!is_enabled_auth('webservice')) {
137 throw new webservice_access_exception(get_string('wsauthnotenabled', 'webservice'));
138 }
01482a4a 139
1839e2f0 140 if (!$auth = get_auth_plugin('webservice')) {
141 throw new webservice_access_exception(get_string('wsauthmissing', 'webservice'));
142 }
01482a4a 143
01482a4a
PS
144 $this->restricted_context = get_context_instance(CONTEXT_SYSTEM);
145
146 if (!$this->username) {
b0a9a0cd 147 throw new webservice_access_exception(get_string('missingusername', 'webservice'));
01482a4a
PS
148 }
149
150 if (!$this->password) {
b0a9a0cd 151 throw new webservice_access_exception(get_string('missingpassword', 'webservice'));
01482a4a
PS
152 }
153
154 if (!$auth->user_login_webservice($this->username, $this->password)) {
1e29fe3f 155 // log failed login attempts
7e0eac79 156 add_to_log(1, 'webservice', get_string('simpleauthlog', 'webservice'), '' , get_string('failedtolog', 'webservice').": ".$this->username."/".$this->password." - ".getremoteaddr() , 0);
b0a9a0cd 157 throw new webservice_access_exception(get_string('wrongusernamepassword', 'webservice'));
01482a4a
PS
158 }
159
160 $user = $DB->get_record('user', array('username'=>$this->username, 'mnethostid'=>$CFG->mnet_localhost_id, 'deleted'=>0), '*', MUST_EXIST);
161
162 } else {
163 if (!$token = $DB->get_record('external_tokens', array('token'=>$this->token, 'tokentype'=>EXTERNAL_TOKEN_PERMANENT))) {
1e29fe3f 164 // log failed login attempts
7e0eac79 165 add_to_log(1, 'webservice', get_string('tokenauthlog', 'webservice'), '' , get_string('failedtolog', 'webservice').": ".$this->token. " - ".getremoteaddr() , 0);
3785c9e2 166 throw new webservice_access_exception(get_string('invalidtoken', 'webservice'));
01482a4a
PS
167 }
168
4ba8df5c 169 if ($token->validuntil and $token->validuntil < time()) {
3785c9e2 170 throw new webservice_access_exception(get_string('invalidtimedtoken', 'webservice'));
01482a4a
PS
171 }
172
173 if ($token->iprestriction and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
1e29fe3f 174 add_to_log(1, 'webservice', get_string('tokenauthlog', 'webservice'), '' , get_string('failedtolog', 'webservice').": ".getremoteaddr() , 0);
3785c9e2 175 throw new webservice_access_exception(get_string('invalidiptoken', 'webservice'));
01482a4a
PS
176 }
177
178 $this->restricted_context = get_context_instance_by_id($token->contextid);
4a355d18 179 $this->restricted_serviceid = $token->externalserviceid;
01482a4a
PS
180
181 $user = $DB->get_record('user', array('id'=>$token->userid, 'deleted'=>0), '*', MUST_EXIST);
182
183 // log token access
184 $DB->set_field('external_tokens', 'lastaccess', time(), array('id'=>$token->id));
185 }
186
187 // now fake user login, the session is completely empty too
188 session_set_user($user);
c3517f05 189 $this->userid = $user->id;
01482a4a
PS
190
191 if (!has_capability("webservice/$this->wsname:use", $this->restricted_context)) {
b0a9a0cd 192 throw new webservice_access_exception(get_string('accessnotallowed', 'webservice'));
01482a4a
PS
193 }
194
195 external_api::set_context_restriction($this->restricted_context);
196 }
197}
198
199/**
200 * Special abstraction of our srvices that allows
201 * interaction with stock Zend ws servers.
202 * @author Petr Skoda (skodak)
203 */
204abstract class webservice_zend_server extends webservice_server {
205
abf7dc44 206 /** @property string name of the zend server class : Zend_XmlRpc_Server, Zend_Soap_Server, Zend_Soap_AutoDiscover, ...*/
01482a4a
PS
207 protected $zend_class;
208
209 /** @property object Zend server instance */
210 protected $zend_server;
211
212 /** @property string $service_class virtual web service class with all functions user name execute, created on the fly */
213 protected $service_class;
214
88098133 215 /**
216 * Contructor
2458e30a 217 * @param bool $simple use simple authentication
88098133 218 */
2458e30a
PS
219 public function __construct($simple, $zend_class) {
220 $this->simple = $simple;
88098133 221 $this->zend_class = $zend_class;
222 }
223
224 /**
225 * Process request from client.
226 * @param bool $simple use simple authentication
227 * @return void
228 */
2458e30a 229 public function run() {
88098133 230 // we will probably need a lot of memory in some functions
231 @raise_memory_limit('128M');
232
233 // set some longer timeout, this script is not sending any output,
234 // this means we need to manually extend the timeout operations
235 // that need longer time to finish
236 external_api::set_timeout();
237
e8b21670 238 // now create the instance of zend server
239 $this->init_zend_server();
240
88098133 241 // set up exception handler first, we want to sent them back in correct format that
242 // the other system understands
243 // we do not need to call the original default handler because this ws handler does everything
244 set_exception_handler(array($this, 'exception_handler'));
245
c187722c
PS
246 // init all properties from the request data
247 $this->parse_request();
248
88098133 249 // this sets up $USER and $SESSION and context restrictions
250 $this->authenticate_user();
251
252 // make a list of all functions user is allowed to excecute
253 $this->init_service_class();
254
2458e30a 255 // tell server what functions are available
88098133 256 $this->zend_server->setClass($this->service_class);
eae18ab6 257
1e29fe3f 258 //log the web service request
7e0eac79 259 add_to_log(1, 'webservice', '', '' , $this->zend_class." ".getremoteaddr() , 0, $this->userid);
1e29fe3f 260
2458e30a 261 // execute and return response, this sends some headers too
88098133 262 $response = $this->zend_server->handle();
2458e30a 263
88098133 264 // session cleanup
265 $this->session_cleanup();
266
ca6340bf 267 //finally send the result
268 $this->send_headers();
88098133 269 echo $response;
270 die;
271 }
272
273 /**
274 * Load virtual class needed for Zend api
275 * @return void
276 */
277 protected function init_service_class() {
278 global $USER, $DB;
279
280 // first ofall get a complete list of services user is allowed to access
88098133 281
01482a4a
PS
282 if ($this->restricted_serviceid) {
283 $params = array('sid1'=>$this->restricted_serviceid, 'sid2'=>$this->restricted_serviceid);
284 $wscond1 = 'AND s.id = :sid1';
285 $wscond2 = 'AND s.id = :sid2';
286 } else {
287 $params = array();
288 $wscond1 = '';
289 $wscond2 = '';
290 }
88098133 291
01482a4a
PS
292 // now make sure the function is listed in at least one service user is allowed to use
293 // allow access only if:
294 // 1/ entry in the external_services_users table if required
295 // 2/ validuntil not reached
296 // 3/ has capability if specified in service desc
297 // 4/ iprestriction
88098133 298
01482a4a
PS
299 $sql = "SELECT s.*, NULL AS iprestriction
300 FROM {external_services} s
301 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0)
302 WHERE s.enabled = 1 $wscond1
88098133 303
01482a4a
PS
304 UNION
305
306 SELECT s.*, su.iprestriction
307 FROM {external_services} s
308 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1)
309 JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)
310 WHERE s.enabled = 1 AND su.validuntil IS NULL OR su.validuntil < :now $wscond2";
311
312 $params = array_merge($params, array('userid'=>$USER->id, 'now'=>time()));
88098133 313
314 $serviceids = array();
315 $rs = $DB->get_recordset_sql($sql, $params);
316
317 // now make sure user may access at least one service
318 $remoteaddr = getremoteaddr();
319 $allowed = false;
320 foreach ($rs as $service) {
321 if (isset($serviceids[$service->id])) {
322 continue;
323 }
324 if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) {
325 continue; // cap required, sorry
326 }
327 if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) {
328 continue; // wrong request source ip, sorry
329 }
330 $serviceids[$service->id] = $service->id;
331 }
332 $rs->close();
333
334 // now get the list of all functions
335 if ($serviceids) {
336 list($serviceids, $params) = $DB->get_in_or_equal($serviceids);
337 $sql = "SELECT f.*
338 FROM {external_functions} f
339 WHERE f.name IN (SELECT sf.functionname
340 FROM {external_services_functions} sf
341 WHERE sf.externalserviceid $serviceids)";
342 $functions = $DB->get_records_sql($sql, $params);
343 } else {
344 $functions = array();
345 }
346
347 // now make the virtual WS class with all the fuctions for this particular user
348 $methods = '';
349 foreach ($functions as $function) {
350 $methods .= $this->get_virtual_method_code($function);
351 }
352
5593d2dc 353 // let's use unique class name, there might be problem in unit tests
88098133 354 $classname = 'webservices_virtual_class_000000';
355 while(class_exists($classname)) {
356 $classname++;
357 }
358
359 $code = '
360/**
361 * Virtual class web services for user id '.$USER->id.' in context '.$this->restricted_context->id.'.
362 */
363class '.$classname.' {
364'.$methods.'
365}
366';
f0dafb3c 367
88098133 368 // load the virtual class definition into memory
369 eval($code);
88098133 370 $this->service_class = $classname;
371 }
372
373 /**
374 * returns virtual method code
375 * @param object $function
376 * @return string PHP code
377 */
378 protected function get_virtual_method_code($function) {
379 global $CFG;
380
5593d2dc 381 $function = external_function_info($function);
88098133 382
383 $params = array();
384 $params_desc = array();
453a7a85 385 foreach ($function->parameters_desc->keys as $name=>$keydesc) {
88098133 386 $params[] = '$'.$name;
453a7a85 387 $type = 'string';
388 if ($keydesc instanceof external_value) {
389 switch($keydesc->type) {
390 case PARAM_BOOL: // 0 or 1 only for now
391 case PARAM_INT:
392 $type = 'int'; break;
393 case PARAM_FLOAT;
394 $type = 'double'; break;
395 default:
396 $type = 'string';
397 }
398 } else if ($keydesc instanceof external_single_structure) {
399 $type = 'struct';
400 } else if ($keydesc instanceof external_multiple_structure) {
401 $type = 'array';
402 }
403 $params_desc[] = ' * @param '.$type.' $'.$name.' '.$keydesc->desc;
88098133 404 }
405 $params = implode(', ', $params);
406 $params_desc = implode("\n", $params_desc);
94a9b9e7
JP
407
408 $serviceclassmethodbody = $this->service_class_method_body($function, $params);
88098133 409
453a7a85 410 if (is_null($function->returns_desc)) {
411 $return = ' * @return void';
412 } else {
413 $type = 'string';
414 if ($function->returns_desc instanceof external_value) {
415 switch($function->returns_desc->type) {
416 case PARAM_BOOL: // 0 or 1 only for now
417 case PARAM_INT:
418 $type = 'int'; break;
419 case PARAM_FLOAT;
420 $type = 'double'; break;
421 default:
422 $type = 'string';
423 }
424 } else if ($function->returns_desc instanceof external_single_structure) {
425 $type = 'struct';
426 } else if ($function->returns_desc instanceof external_multiple_structure) {
427 $type = 'array';
428 }
429 $return = ' * @return '.$type.' '.$function->returns_desc->desc;
430 }
d4e764ab 431
01482a4a 432 // now crate the virtual method that calls the ext implementation
88098133 433
434 $code = '
435 /**
5593d2dc 436 * '.$function->description.'
437 *
88098133 438'.$params_desc.'
453a7a85 439'.$return.'
88098133 440 */
441 public function '.$function->name.'('.$params.') {
c77e75a3 442'.$serviceclassmethodbody.'
88098133 443 }
444';
445 return $code;
446 }
94a9b9e7
JP
447
448 /**
449 * You can override this function in your child class to add extra code into the dynamically
450 * created service class. For example it is used in the amf server to cast types of parameters and to
451 * cast the return value to the types as specified in the return value description.
452 * @param unknown_type $function
453 * @param unknown_type $params
454 * @return string body of the method for $function ie. everything within the {} of the method declaration.
455 */
456 protected function service_class_method_body($function, $params){
d07ff72d 457 $descriptionmethod = $function->methodname.'_returns()';
458 $callforreturnvaluedesc = $function->classname.'::'.$descriptionmethod;
99152d09 459 return ' if ('.$callforreturnvaluedesc.' == null) {
460 return null;
461 }
462 return external_api::clean_returnvalue('.$callforreturnvaluedesc.', '.$function->classname.'::'.$function->methodname.'('.$params.'));';
94a9b9e7 463 }
d07ff72d 464
88098133 465 /**
b107e647 466 * Set up zend service class
88098133 467 * @return void
468 */
469 protected function init_zend_server() {
88098133 470 $this->zend_server = new $this->zend_class();
88098133 471 }
472
c187722c
PS
473 /**
474 * This method parses the $_REQUEST superglobal and looks for
475 * the following information:
476 * 1/ user authentication - username+password or token (wsusername, wspassword and wstoken parameters)
477 *
478 * @return void
479 */
480 protected function parse_request() {
481 if ($this->simple) {
01482a4a 482 //note: some clients have problems with entity encoding :-(
c187722c
PS
483 if (isset($_REQUEST['wsusername'])) {
484 $this->username = $_REQUEST['wsusername'];
c187722c
PS
485 }
486 if (isset($_REQUEST['wspassword'])) {
487 $this->password = $_REQUEST['wspassword'];
c187722c
PS
488 }
489 } else {
01482a4a
PS
490 if (isset($_REQUEST['wstoken'])) {
491 $this->token = $_REQUEST['wstoken'];
88098133 492 }
88098133 493 }
88098133 494 }
495
ca6340bf 496 /**
497 * Internal implementation - sending of page headers.
498 * @return void
499 */
500 protected function send_headers() {
501 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
502 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
503 header('Pragma: no-cache');
504 header('Accept-Ranges: none');
505 }
506
88098133 507 /**
508 * Specialised exception handler, we can not use the standard one because
509 * it can not just print html to output.
510 *
511 * @param exception $ex
512 * @return void does not return
513 */
514 public function exception_handler($ex) {
88098133 515 // detect active db transactions, rollback and log as error
3086dd59 516 abort_all_db_transactions();
88098133 517
88098133 518 // some hacks might need a cleanup hook
519 $this->session_cleanup($ex);
520
ca6340bf 521 // now let the plugin send the exception to client
b107e647 522 $this->send_error($ex);
ca6340bf 523
88098133 524 // not much else we can do now, add some logging later
525 exit(1);
526 }
527
b107e647
PS
528 /**
529 * Send the error information to the WS client
530 * formatted as XML document.
531 * @param exception $ex
532 * @return void
533 */
534 protected function send_error($ex=null) {
535 $this->send_headers();
536 echo $this->zend_server->fault($ex);
537 }
01482a4a 538
88098133 539 /**
540 * Future hook needed for emulated sessions.
541 * @param exception $exception null means normal termination, $exception received when WS call failed
542 * @return void
543 */
544 protected function session_cleanup($exception=null) {
545 if ($this->simple) {
546 // nothing needs to be done, there is no persistent session
547 } else {
548 // close emulated session if used
549 }
550 }
551
cc93c7da 552}
553
886d7556 554/**
cc93c7da 555 * Web Service server base class, this class handles both
556 * simple and token authentication.
557 * @author Petr Skoda (skodak)
886d7556 558 */
01482a4a 559abstract class webservice_base_server extends webservice_server {
88098133 560
cc93c7da 561 /** @property array $parameters the function parameters - the real values submitted in the request */
562 protected $parameters = null;
563
564 /** @property string $functionname the name of the function that is executed */
565 protected $functionname = null;
566
567 /** @property object $function full function description */
568 protected $function = null;
569
570 /** @property mixed $returns function return value */
571 protected $returns = null;
06e7fadc 572
573 /**
cc93c7da 574 * Contructor
2458e30a 575 * @param bool $simple use simple authentication
06e7fadc 576 */
2458e30a
PS
577 public function __construct($simple) {
578 $this->simple = $simple;
06e7fadc 579 }
580
24350e06 581 /**
cc93c7da 582 * This method parses the request input, it needs to get:
583 * 1/ user authentication - username+password or token
584 * 2/ function name
585 * 3/ function parameters
586 *
587 * @return void
24350e06 588 */
cc93c7da 589 abstract protected function parse_request();
24350e06 590
cc93c7da 591 /**
592 * Send the result of function call to the WS client.
593 * @return void
594 */
595 abstract protected function send_response();
24350e06 596
fa0797ec 597 /**
cc93c7da 598 * Send the error information to the WS client.
599 * @param exception $ex
600 * @return void
fa0797ec 601 */
cc93c7da 602 abstract protected function send_error($ex=null);
fa0797ec 603
cc93c7da 604 /**
605 * Process request from client.
cc93c7da 606 * @return void
607 */
2458e30a 608 public function run() {
cc93c7da 609 // we will probably need a lot of memory in some functions
610 @raise_memory_limit('128M');
fa0797ec 611
cc93c7da 612 // set some longer timeout, this script is not sending any output,
613 // this means we need to manually extend the timeout operations
614 // that need longer time to finish
615 external_api::set_timeout();
fa0797ec 616
cc93c7da 617 // set up exception handler first, we want to sent them back in correct format that
618 // the other system understands
619 // we do not need to call the original default handler because this ws handler does everything
620 set_exception_handler(array($this, 'exception_handler'));
06e7fadc 621
cc93c7da 622 // init all properties from the request data
623 $this->parse_request();
06e7fadc 624
cc93c7da 625 // authenticate user, this has to be done after the request parsing
626 // this also sets up $USER and $SESSION
627 $this->authenticate_user();
06e7fadc 628
cc93c7da 629 // find all needed function info and make sure user may actually execute the function
630 $this->load_function_info();
c3517f05 631
632 //log the web service request
7e0eac79 633 add_to_log(1, 'webservice', $this->functionname, '' , getremoteaddr() , 0, $this->userid);
f7631e73 634
cc93c7da 635 // finally, execute the function - any errors are catched by the default exception handler
636 $this->execute();
06e7fadc 637
cc93c7da 638 // send the results back in correct format
639 $this->send_response();
06e7fadc 640
cc93c7da 641 // session cleanup
642 $this->session_cleanup();
06e7fadc 643
cc93c7da 644 die;
f7631e73 645 }
646
cc93c7da 647 /**
648 * Specialised exception handler, we can not use the standard one because
649 * it can not just print html to output.
650 *
651 * @param exception $ex
652 * @return void does not return
653 */
654 public function exception_handler($ex) {
cc93c7da 655 // detect active db transactions, rollback and log as error
3086dd59 656 abort_all_db_transactions();
06e7fadc 657
cc93c7da 658 // some hacks might need a cleanup hook
659 $this->session_cleanup($ex);
06e7fadc 660
ca6340bf 661 // now let the plugin send the exception to client
662 $this->send_error($ex);
663
cc93c7da 664 // not much else we can do now, add some logging later
665 exit(1);
f7631e73 666 }
667
668 /**
cc93c7da 669 * Future hook needed for emulated sessions.
670 * @param exception $exception null means normal termination, $exception received when WS call failed
671 * @return void
f7631e73 672 */
cc93c7da 673 protected function session_cleanup($exception=null) {
674 if ($this->simple) {
675 // nothing needs to be done, there is no persistent session
676 } else {
677 // close emulated session if used
678 }
f7631e73 679 }
680
24350e06 681 /**
cc93c7da 682 * Fetches the function description from database,
683 * verifies user is allowed to use this function and
684 * loads all paremeters and return descriptions.
685 * @return void
24350e06 686 */
cc93c7da 687 protected function load_function_info() {
688 global $DB, $USER, $CFG;
40f024c9 689
cc93c7da 690 if (empty($this->functionname)) {
691 throw new invalid_parameter_exception('Missing function name');
692 }
24350e06 693
cc93c7da 694 // function must exist
5593d2dc 695 $function = external_function_info($this->functionname);
cc93c7da 696
01482a4a
PS
697 if ($this->restricted_serviceid) {
698 $params = array('sid1'=>$this->restricted_serviceid, 'sid2'=>$this->restricted_serviceid);
699 $wscond1 = 'AND s.id = :sid1';
700 $wscond2 = 'AND s.id = :sid2';
701 } else {
702 $params = array();
703 $wscond1 = '';
704 $wscond2 = '';
705 }
706
cc93c7da 707 // now let's verify access control
b8c5309e 708
709 // now make sure the function is listed in at least one service user is allowed to use
710 // allow access only if:
711 // 1/ entry in the external_services_users table if required
712 // 2/ validuntil not reached
713 // 3/ has capability if specified in service desc
714 // 4/ iprestriction
715
716 $sql = "SELECT s.*, NULL AS iprestriction
717 FROM {external_services} s
718 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0 AND sf.functionname = :name1)
719 WHERE s.enabled = 1 $wscond1
720
721 UNION
722
723 SELECT s.*, su.iprestriction
724 FROM {external_services} s
725 JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1 AND sf.functionname = :name2)
726 JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)
727 WHERE s.enabled = 1 AND su.validuntil IS NULL OR su.validuntil < :now $wscond2";
728 $params = array_merge($params, array('userid'=>$USER->id, 'name1'=>$function->name, 'name2'=>$function->name, 'now'=>time()));
88098133 729
730 $rs = $DB->get_recordset_sql($sql, $params);
731 // now make sure user may access at least one service
732 $remoteaddr = getremoteaddr();
733 $allowed = false;
734 foreach ($rs as $service) {
735 if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) {
736 continue; // cap required, sorry
cc93c7da 737 }
88098133 738 if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) {
739 continue; // wrong request source ip, sorry
cc93c7da 740 }
88098133 741 $allowed = true;
742 break; // one service is enough, no need to continue
743 }
744 $rs->close();
745 if (!$allowed) {
c91cc5ef 746 throw new webservice_access_exception('Access to external function not allowed');
cc93c7da 747 }
9baf6825 748
cc93c7da 749 // we have all we need now
750 $this->function = $function;
751 }
752
753 /**
754 * Execute previously loaded function using parameters parsed from the request data.
755 * @return void
756 */
757 protected function execute() {
758 // validate params, this also sorts the params properly, we need the correct order in the next part
759 $params = call_user_func(array($this->function->classname, 'validate_parameters'), $this->function->parameters_desc, $this->parameters);
9baf6825 760
cc93c7da 761 // execute - yay!
762 $this->returns = call_user_func_array(array($this->function->classname, $this->function->methodname), array_values($params));
9baf6825 763 }
764}
765
766