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