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