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