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