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