on-demand release 2.3dev
[moodle.git] / lib / externallib.php
CommitLineData
9a0df45a 1<?php
9a0df45a 2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
4615817d 17
9a0df45a 18/**
19 * Support for external API
20 *
4615817d
JM
21 * @package core_webservice
22 * @copyright 2009 Petr Skodak
9a0df45a 23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
25
78bfb562 26defined('MOODLE_INTERNAL') || die();
1942103f 27
5593d2dc 28/**
bff11d29 29 * Returns detailed function information
4615817d 30 *
5593d2dc 31 * @param string|object $function name of external function or record from external_function
32 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
33 * MUST_EXIST means throw exception if no record or multiple records found
4615817d
JM
34 * @return stdClass description or false if not found or exception thrown
35 * @since Moodle 2.0
5593d2dc 36 */
37function external_function_info($function, $strictness=MUST_EXIST) {
38 global $DB, $CFG;
39
40 if (!is_object($function)) {
41 if (!$function = $DB->get_record('external_functions', array('name'=>$function), '*', $strictness)) {
42 return false;
43 }
44 }
45
46 //first find and include the ext implementation class
47 $function->classpath = empty($function->classpath) ? get_component_directory($function->component).'/externallib.php' : $CFG->dirroot.'/'.$function->classpath;
48 if (!file_exists($function->classpath)) {
49 throw new coding_exception('Can not find file with external function implementation');
50 }
51 require_once($function->classpath);
52
53 $function->parameters_method = $function->methodname.'_parameters';
54 $function->returns_method = $function->methodname.'_returns';
55
56 // make sure the implementaion class is ok
57 if (!method_exists($function->classname, $function->methodname)) {
203fda8a 58 throw new coding_exception('Missing implementation method of '.$function->classname.'::'.$function->methodname);
5593d2dc 59 }
60 if (!method_exists($function->classname, $function->parameters_method)) {
61 throw new coding_exception('Missing parameters description');
62 }
63 if (!method_exists($function->classname, $function->returns_method)) {
64 throw new coding_exception('Missing returned values description');
65 }
66
67 // fetch the parameters description
68 $function->parameters_desc = call_user_func(array($function->classname, $function->parameters_method));
69 if (!($function->parameters_desc instanceof external_function_parameters)) {
70 throw new coding_exception('Invalid parameters description');
71 }
72
73 // fetch the return values description
74 $function->returns_desc = call_user_func(array($function->classname, $function->returns_method));
75 // null means void result or result is ignored
76 if (!is_null($function->returns_desc) and !($function->returns_desc instanceof external_description)) {
77 throw new coding_exception('Invalid return description');
78 }
79
80 //now get the function description
4615817d 81 //TODO MDL-31115 use localised lang pack descriptions, it would be nice to have
23e7b7cc 82 // easy to understand descriptions in admin UI,
5593d2dc 83 // on the other hand this is still a bit in a flux and we need to find some new naming
84 // conventions for these descriptions in lang packs
85 $function->description = null;
86 $servicesfile = get_component_directory($function->component).'/db/services.php';
87 if (file_exists($servicesfile)) {
88 $functions = null;
89 include($servicesfile);
90 if (isset($functions[$function->name]['description'])) {
91 $function->description = $functions[$function->name]['description'];
92 }
048f3d32
TH
93 if (isset($functions[$function->name]['testclientpath'])) {
94 $function->testclientpath = $functions[$function->name]['testclientpath'];
95 }
5593d2dc 96 }
97
98 return $function;
99}
100
9a0df45a 101/**
4615817d
JM
102 * Exception indicating user is not allowed to use external function in the current context.
103 *
104 * @package core_webservice
105 * @copyright 2009 Petr Skodak
106 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
107 * @since Moodle 2.0
9a0df45a 108 */
109class restricted_context_exception extends moodle_exception {
110 /**
111 * Constructor
4615817d
JM
112 *
113 * @since Moodle 2.0
9a0df45a 114 */
115 function __construct() {
116 parent::__construct('restrictedcontextexception', 'error');
117 }
118}
119
120/**
121 * Base class for external api methods.
4615817d
JM
122 *
123 * @package core_webservice
124 * @copyright 2009 Petr Skodak
125 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
126 * @since Moodle 2.0
9a0df45a 127 */
128class external_api {
4615817d
JM
129
130 /** @var stdClass context where the function calls will be restricted */
9a0df45a 131 private static $contextrestriction;
132
1bea0c27 133 /**
23e7b7cc 134 * Set context restriction for all following subsequent function calls.
4615817d
JM
135 *
136 * @param stdClass $context the context restriction
137 * @since Moodle 2.0
1bea0c27 138 */
2965d271 139 public static function set_context_restriction($context) {
9a0df45a 140 self::$contextrestriction = $context;
141 }
142
2965d271 143 /**
144 * This method has to be called before every operation
145 * that takes a longer time to finish!
146 *
147 * @param int $seconds max expected time the next operation needs
4615817d 148 * @since Moodle 2.0
2965d271 149 */
150 public static function set_timeout($seconds=360) {
151 $seconds = ($seconds < 300) ? 300 : $seconds;
152 set_time_limit($seconds);
153 }
154
1bea0c27 155 /**
c9c5cc81 156 * Validates submitted function parameters, if anything is incorrect
1bea0c27 157 * invalid_parameter_exception is thrown.
1d7db36f 158 * This is a simple recursive method which is intended to be called from
159 * each implementation method of external API.
4615817d 160 *
c9c5cc81 161 * @param external_description $description description of parameters
162 * @param mixed $params the actual parameters
163 * @return mixed params with added defaults for optional items, invalid_parameters_exception thrown if any problem found
4615817d 164 * @since Moodle 2.0
1bea0c27 165 */
c9c5cc81 166 public static function validate_parameters(external_description $description, $params) {
04d212ce 167 if ($description instanceof external_value) {
c9c5cc81 168 if (is_array($params) or is_object($params)) {
93602569 169 throw new invalid_parameter_exception('Scalar type expected, array or object received.');
c9c5cc81 170 }
4f0c6ad1
PS
171
172 if ($description->type == PARAM_BOOL) {
173 // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
174 if (is_bool($params) or $params === 0 or $params === 1 or $params === '0' or $params === '1') {
175 return (bool)$params;
176 }
177 }
93602569
JM
178 $debuginfo = 'Invalid external api parameter: the value is "' . $params .
179 '", the server was expecting "' . $description->type . '" type';
180 return validate_param($params, $description->type, $description->allownull, $debuginfo);
4f0c2d00 181
c9c5cc81 182 } else if ($description instanceof external_single_structure) {
183 if (!is_array($params)) {
93602569
JM
184 throw new invalid_parameter_exception('Only arrays accepted. The bad value is: \''
185 . print_r($params, true) . '\'');
c9c5cc81 186 }
187 $result = array();
188 foreach ($description->keys as $key=>$subdesc) {
189 if (!array_key_exists($key, $params)) {
382b9cea 190 if ($subdesc->required == VALUE_REQUIRED) {
93602569 191 throw new invalid_parameter_exception('Missing required key in single structure: '. $key);
c9c5cc81 192 }
774b1b0f 193 if ($subdesc->required == VALUE_DEFAULT) {
194 try {
195 $result[$key] = self::validate_parameters($subdesc, $subdesc->default);
196 } catch (invalid_parameter_exception $e) {
93602569
JM
197 //we are only interested by exceptions returned by validate_param() and validate_parameters()
198 //(in order to build the path to the faulty attribut)
199 throw new invalid_parameter_exception($key." => ".$e->getMessage() . ': ' .$e->debuginfo);
382b9cea 200 }
774b1b0f 201 }
c9c5cc81 202 } else {
559a5dbd 203 try {
204 $result[$key] = self::validate_parameters($subdesc, $params[$key]);
205 } catch (invalid_parameter_exception $e) {
93602569
JM
206 //we are only interested by exceptions returned by validate_param() and validate_parameters()
207 //(in order to build the path to the faulty attribut)
208 throw new invalid_parameter_exception($key." => ".$e->getMessage() . ': ' .$e->debuginfo);
559a5dbd 209 }
c9c5cc81 210 }
211 unset($params[$key]);
212 }
213 if (!empty($params)) {
92fe97f9 214 throw new invalid_parameter_exception('Unexpected keys (' . implode(', ', array_keys($params)) . ') detected in parameter array.');
c9c5cc81 215 }
216 return $result;
1bea0c27 217
c9c5cc81 218 } else if ($description instanceof external_multiple_structure) {
219 if (!is_array($params)) {
93602569
JM
220 throw new invalid_parameter_exception('Only arrays accepted. The bad value is: \''
221 . print_r($params, true) . '\'');
c9c5cc81 222 }
223 $result = array();
224 foreach ($params as $param) {
225 $result[] = self::validate_parameters($description->content, $param);
226 }
227 return $result;
228
229 } else {
93602569 230 throw new invalid_parameter_exception('Invalid external api description');
c9c5cc81 231 }
1bea0c27 232 }
233
d07ff72d 234 /**
235 * Clean response
23e7b7cc
PS
236 * If a response attribute is unknown from the description, we just ignore the attribute.
237 * If a response attribute is incorrect, invalid_response_exception is thrown.
d07ff72d 238 * Note: this function is similar to validate parameters, however it is distinct because
239 * parameters validation must be distinct from cleaning return values.
4615817d 240 *
d07ff72d 241 * @param external_description $description description of the return values
242 * @param mixed $response the actual response
243 * @return mixed response with added defaults for optional items, invalid_response_exception thrown if any problem found
4615817d
JM
244 * @author 2010 Jerome Mouneyrac
245 * @since Moodle 2.0
d07ff72d 246 */
247 public static function clean_returnvalue(external_description $description, $response) {
248 if ($description instanceof external_value) {
249 if (is_array($response) or is_object($response)) {
93602569 250 throw new invalid_response_exception('Scalar type expected, array or object received.');
d07ff72d 251 }
252
253 if ($description->type == PARAM_BOOL) {
254 // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
255 if (is_bool($response) or $response === 0 or $response === 1 or $response === '0' or $response === '1') {
256 return (bool)$response;
257 }
258 }
93602569
JM
259 $debuginfo = 'Invalid external api response: the value is "' . $response .
260 '", the server was expecting "' . $description->type . '" type';
261 try {
262 return validate_param($response, $description->type, $description->allownull, $debuginfo);
263 } catch (invalid_parameter_exception $e) {
264 //proper exception name, to be recursively catched to build the path to the faulty attribut
265 throw new invalid_response_exception($e->debuginfo);
266 }
d07ff72d 267
268 } else if ($description instanceof external_single_structure) {
269 if (!is_array($response)) {
93602569
JM
270 throw new invalid_response_exception('Only arrays accepted. The bad value is: \'' .
271 print_r($response, true) . '\'');
d07ff72d 272 }
273 $result = array();
274 foreach ($description->keys as $key=>$subdesc) {
275 if (!array_key_exists($key, $response)) {
276 if ($subdesc->required == VALUE_REQUIRED) {
93602569 277 throw new invalid_response_exception('Error in response - Missing following required key in a single structure: ' . $key);
d07ff72d 278 }
279 if ($subdesc instanceof external_value) {
143c0abe 280 if ($subdesc->required == VALUE_DEFAULT) {
281 try {
d07ff72d 282 $result[$key] = self::clean_returnvalue($subdesc, $subdesc->default);
93602569
JM
283 } catch (invalid_response_exception $e) {
284 //build the path to the faulty attribut
285 throw new invalid_response_exception($key." => ".$e->getMessage() . ': ' . $e->debuginfo);
d07ff72d 286 }
287 }
143c0abe 288 }
d07ff72d 289 } else {
290 try {
291 $result[$key] = self::clean_returnvalue($subdesc, $response[$key]);
93602569
JM
292 } catch (invalid_response_exception $e) {
293 //build the path to the faulty attribut
294 throw new invalid_response_exception($key." => ".$e->getMessage() . ': ' . $e->debuginfo);
d07ff72d 295 }
296 }
297 unset($response[$key]);
298 }
299
300 return $result;
301
302 } else if ($description instanceof external_multiple_structure) {
303 if (!is_array($response)) {
93602569
JM
304 throw new invalid_response_exception('Only arrays accepted. The bad value is: \'' .
305 print_r($response, true) . '\'');
d07ff72d 306 }
307 $result = array();
308 foreach ($response as $param) {
309 $result[] = self::clean_returnvalue($description->content, $param);
310 }
311 return $result;
312
313 } else {
93602569 314 throw new invalid_response_exception('Invalid external api response description');
d07ff72d 315 }
316 }
317
9a0df45a 318 /**
319 * Makes sure user may execute functions in this context.
4615817d
JM
320 *
321 * @param stdClass $context
322 * @since Moodle 2.0
9a0df45a 323 */
324 protected static function validate_context($context) {
4f0c2d00
PS
325 global $CFG;
326
ab9a01f2 327 if (empty($context)) {
328 throw new invalid_parameter_exception('Context does not exist');
329 }
9a0df45a 330 if (empty(self::$contextrestriction)) {
331 self::$contextrestriction = get_context_instance(CONTEXT_SYSTEM);
332 }
333 $rcontext = self::$contextrestriction;
334
335 if ($rcontext->contextlevel == $context->contextlevel) {
aa7fbebd 336 if ($rcontext->id != $context->id) {
9a0df45a 337 throw new restricted_context_exception();
338 }
339 } else if ($rcontext->contextlevel > $context->contextlevel) {
340 throw new restricted_context_exception();
341 } else {
342 $parents = get_parent_contexts($context);
343 if (!in_array($rcontext->id, $parents)) {
344 throw new restricted_context_exception();
345 }
346 }
347
348 if ($context->contextlevel >= CONTEXT_COURSE) {
4f0c2d00 349 list($context, $course, $cm) = get_context_info_array($context->id);
df997f84 350 require_login($course, false, $cm, false, true);
9a0df45a 351 }
352 }
9a0df45a 353}
354
b038c32c 355/**
356 * Common ancestor of all parameter description classes
4615817d
JM
357 *
358 * @package core_webservice
359 * @copyright 2009 Petr Skodak
360 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
361 * @since Moodle 2.0
b038c32c 362 */
363abstract class external_description {
4615817d 364 /** @var string Description of element */
b038c32c 365 public $desc;
4615817d
JM
366
367 /** @var bool Element value required, null not allowed */
b038c32c 368 public $required;
4615817d
JM
369
370 /** @var mixed Default value */
774b1b0f 371 public $default;
b038c32c 372
373 /**
374 * Contructor
4615817d 375 *
b038c32c 376 * @param string $desc
377 * @param bool $required
774b1b0f 378 * @param mixed $default
4615817d 379 * @since Moodle 2.0
b038c32c 380 */
774b1b0f 381 public function __construct($desc, $required, $default) {
b038c32c 382 $this->desc = $desc;
383 $this->required = $required;
774b1b0f 384 $this->default = $default;
b038c32c 385 }
386}
387
388/**
4615817d
JM
389 * Scalar value description class
390 *
391 * @package core_webservice
392 * @copyright 2009 Petr Skodak
393 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
394 * @since Moodle 2.0
b038c32c 395 */
04d212ce 396class external_value extends external_description {
4615817d
JM
397
398 /** @var mixed Value type PARAM_XX */
b038c32c 399 public $type;
4615817d
JM
400
401 /** @var bool Allow null values */
b038c32c 402 public $allownull;
403
404 /**
405 * Constructor
4615817d 406 *
b038c32c 407 * @param mixed $type
408 * @param string $desc
409 * @param bool $required
410 * @param mixed $default
411 * @param bool $allownull
4615817d 412 * @since Moodle 2.0
b038c32c 413 */
774b1b0f 414 public function __construct($type, $desc='', $required=VALUE_REQUIRED,
415 $default=null, $allownull=NULL_ALLOWED) {
416 parent::__construct($desc, $required, $default);
78bfb562 417 $this->type = $type;
b038c32c 418 $this->allownull = $allownull;
419 }
420}
421
422/**
423 * Associative array description class
4615817d
JM
424 *
425 * @package core_webservice
426 * @copyright 2009 Petr Skodak
427 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
428 * @since Moodle 2.0
b038c32c 429 */
430class external_single_structure extends external_description {
4615817d
JM
431
432 /** @var array Description of array keys key=>external_description */
b038c32c 433 public $keys;
434
435 /**
436 * Constructor
4615817d 437 *
b038c32c 438 * @param array $keys
439 * @param string $desc
440 * @param bool $required
774b1b0f 441 * @param array $default
4615817d 442 * @since Moodle 2.0
b038c32c 443 */
774b1b0f 444 public function __construct(array $keys, $desc='',
445 $required=VALUE_REQUIRED, $default=null) {
446 parent::__construct($desc, $required, $default);
b038c32c 447 $this->keys = $keys;
448 }
449}
450
451/**
452 * Bulk array description class.
4615817d
JM
453 *
454 * @package core_webservice
455 * @copyright 2009 Petr Skodak
456 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
457 * @since Moodle 2.0
b038c32c 458 */
459class external_multiple_structure extends external_description {
4615817d
JM
460
461 /** @var external_description content */
b038c32c 462 public $content;
463
464 /**
465 * Constructor
4615817d 466 *
b038c32c 467 * @param external_description $content
468 * @param string $desc
469 * @param bool $required
774b1b0f 470 * @param array $default
4615817d 471 * @since Moodle 2.0
b038c32c 472 */
774b1b0f 473 public function __construct(external_description $content, $desc='',
474 $required=VALUE_REQUIRED, $default=null) {
475 parent::__construct($desc, $required, $default);
b038c32c 476 $this->content = $content;
477 }
478}
c29cca30 479
480/**
481 * Description of top level - PHP function parameters.
c29cca30 482 *
4615817d
JM
483 * @package core_webservice
484 * @copyright 2009 Petr Skodak
485 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
486 * @since Moodle 2.0
c29cca30 487 */
488class external_function_parameters extends external_single_structure {
489}
2822f40a 490
4615817d
JM
491/**
492 * Generate a token
493 *
494 * @param string $tokentype EXTERNAL_TOKEN_EMBEDDED|EXTERNAL_TOKEN_PERMANENT
495 * @param stdClass|int $serviceorid service linked to the token
496 * @param int $userid user linked to the token
497 * @param stdClass|int $contextorid
498 * @param int $validuntil date when the token expired
499 * @param string $iprestriction allowed ip - if 0 or empty then all ips are allowed
500 * @return string generated token
501 * @author 2010 Jamie Pratt
502 * @since Moodle 2.0
503 */
2822f40a
JP
504function external_generate_token($tokentype, $serviceorid, $userid, $contextorid, $validuntil=0, $iprestriction=''){
505 global $DB, $USER;
506 // make sure the token doesn't exist (even if it should be almost impossible with the random generation)
507 $numtries = 0;
508 do {
509 $numtries ++;
510 $generatedtoken = md5(uniqid(rand(),1));
511 if ($numtries > 5){
512 throw new moodle_exception('tokengenerationfailed');
513 }
514 } while ($DB->record_exists('external_tokens', array('token'=>$generatedtoken)));
365a5941 515 $newtoken = new stdClass();
2822f40a
JP
516 $newtoken->token = $generatedtoken;
517 if (!is_object($serviceorid)){
518 $service = $DB->get_record('external_services', array('id' => $serviceorid));
519 } else {
520 $service = $serviceorid;
521 }
522 if (!is_object($contextorid)){
523 $context = get_context_instance_by_id($contextorid, MUST_EXIST);
524 } else {
525 $context = $contextorid;
526 }
527 if (empty($service->requiredcapability) || has_capability($service->requiredcapability, $context, $userid)) {
528 $newtoken->externalserviceid = $service->id;
529 } else {
530 throw new moodle_exception('nocapabilitytousethisservice');
531 }
532 $newtoken->tokentype = $tokentype;
533 $newtoken->userid = $userid;
2d0acbd5
JP
534 if ($tokentype == EXTERNAL_TOKEN_EMBEDDED){
535 $newtoken->sid = session_id();
536 }
4f0c2d00
PS
537
538 $newtoken->contextid = $context->id;
2822f40a
JP
539 $newtoken->creatorid = $USER->id;
540 $newtoken->timecreated = time();
541 $newtoken->validuntil = $validuntil;
542 if (!empty($iprestriction)) {
543 $newtoken->iprestriction = $iprestriction;
544 }
545 $DB->insert_record('external_tokens', $newtoken);
546 return $newtoken->token;
2d0acbd5 547}
4615817d 548
2d0acbd5 549/**
df997f84 550 * Create and return a session linked token. Token to be used for html embedded client apps that want to communicate
2d0acbd5
JP
551 * with the Moodle server through web services. The token is linked to the current session for the current page request.
552 * It is expected this will be called in the script generating the html page that is embedding the client app and that the
553 * returned token will be somehow passed into the client app being embedded in the page.
4615817d 554 *
2d0acbd5
JP
555 * @param string $servicename name of the web service. Service name as defined in db/services.php
556 * @param int $context context within which the web service can operate.
557 * @return int returns token id.
4615817d 558 * @since Moodle 2.0
2d0acbd5
JP
559 */
560function external_create_service_token($servicename, $context){
561 global $USER, $DB;
562 $service = $DB->get_record('external_services', array('name'=>$servicename), '*', MUST_EXIST);
563 return external_generate_token(EXTERNAL_TOKEN_EMBEDDED, $service, $USER->id, $context, 0);
bc81eadb
JM
564}
565
566/**
567 * Delete all pre-built services (+ related tokens) and external functions information defined in the specified component.
568 *
569 * @param string $component name of component (moodle, mod_assignment, etc.)
570 */
571function external_delete_descriptions($component) {
572 global $DB;
573
574 $params = array($component);
575
576 $DB->delete_records_select('external_tokens',
577 "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
578 $DB->delete_records_select('external_services_users',
579 "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
580 $DB->delete_records_select('external_services_functions',
581 "functionname IN (SELECT name FROM {external_functions} WHERE component = ?)", $params);
582 $DB->delete_records('external_services', array('component'=>$component));
583 $DB->delete_records('external_functions', array('component'=>$component));
03d38b92
Y
584}
585
586/**
50f9449f 587 * Creates a warnings external_multiple_structure
03d38b92 588 *
50f9449f 589 * @return external_multiple_structure
03d38b92
Y
590 * @since Moodle 2.3
591 */
50f9449f
JM
592function external_warnings() {
593 return new external_multiple_structure(
594 new external_single_structure(array(
595 'item' => new external_value(PARAM_TEXT, 'item', VALUE_OPTIONAL),
596 'itemid' => new external_value(PARAM_INT, 'item id', VALUE_OPTIONAL),
597 'warningcode' => new external_value(PARAM_ALPHANUM, 'the warning code can be used by
598 the client app to implement specific behaviour'),
599 'message' => new external_value(PARAM_TEXT, 'untranslated english message to explain the warning')
600 ), 'warning'), 'list of warnings', VALUE_OPTIONAL
601 );
602}