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