weekly release 2.2dev
[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)) {
eae18ab6 152 throw new invalid_parameter_exception(get_string('errorscalartype', 'webservice'));
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 }
eae18ab6 161 return validate_param($params, $description->type, $description->allownull, get_string('errorinvalidparamsapi', 'webservice'));
4f0c2d00 162
c9c5cc81 163 } else if ($description instanceof external_single_structure) {
164 if (!is_array($params)) {
eae18ab6 165 throw new invalid_parameter_exception(get_string('erroronlyarray', 'webservice'));
c9c5cc81 166 }
167 $result = array();
168 foreach ($description->keys as $key=>$subdesc) {
169 if (!array_key_exists($key, $params)) {
382b9cea 170 if ($subdesc->required == VALUE_REQUIRED) {
eae18ab6 171 throw new invalid_parameter_exception(get_string('errormissingkey', 'webservice', $key));
c9c5cc81 172 }
774b1b0f 173 if ($subdesc->required == VALUE_DEFAULT) {
174 try {
175 $result[$key] = self::validate_parameters($subdesc, $subdesc->default);
176 } catch (invalid_parameter_exception $e) {
177 throw new webservice_parameter_exception('invalidextparam',$key);
382b9cea 178 }
774b1b0f 179 }
c9c5cc81 180 } else {
559a5dbd 181 try {
182 $result[$key] = self::validate_parameters($subdesc, $params[$key]);
183 } catch (invalid_parameter_exception $e) {
e5752b7d 184 //it's ok to display debug info as here the information is useful for ws client/dev
185 throw new webservice_parameter_exception('invalidextparam',$key." (".$e->debuginfo.")");
559a5dbd 186 }
c9c5cc81 187 }
188 unset($params[$key]);
189 }
190 if (!empty($params)) {
ceb1bad4 191 //list all unexpected keys
192 $keys = '';
193 foreach($params as $key => $value) {
194 $keys .= $key . ',';
195 }
196 throw new invalid_parameter_exception(get_string('errorunexpectedkey', 'webservice', $keys));
c9c5cc81 197 }
198 return $result;
1bea0c27 199
c9c5cc81 200 } else if ($description instanceof external_multiple_structure) {
201 if (!is_array($params)) {
eae18ab6 202 throw new invalid_parameter_exception(get_string('erroronlyarray', 'webservice'));
c9c5cc81 203 }
204 $result = array();
205 foreach ($params as $param) {
206 $result[] = self::validate_parameters($description->content, $param);
207 }
208 return $result;
209
210 } else {
eae18ab6 211 throw new invalid_parameter_exception(get_string('errorinvalidparamsdesc', 'webservice'));
c9c5cc81 212 }
1bea0c27 213 }
214
d07ff72d 215 /**
216 * Clean response
23e7b7cc
PS
217 * If a response attribute is unknown from the description, we just ignore the attribute.
218 * If a response attribute is incorrect, invalid_response_exception is thrown.
d07ff72d 219 * Note: this function is similar to validate parameters, however it is distinct because
220 * parameters validation must be distinct from cleaning return values.
221 * @param external_description $description description of the return values
222 * @param mixed $response the actual response
223 * @return mixed response with added defaults for optional items, invalid_response_exception thrown if any problem found
224 */
225 public static function clean_returnvalue(external_description $description, $response) {
226 if ($description instanceof external_value) {
227 if (is_array($response) or is_object($response)) {
228 throw new invalid_response_exception(get_string('errorscalartype', 'webservice'));
229 }
230
231 if ($description->type == PARAM_BOOL) {
232 // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
233 if (is_bool($response) or $response === 0 or $response === 1 or $response === '0' or $response === '1') {
234 return (bool)$response;
235 }
236 }
237 return validate_param($response, $description->type, $description->allownull, get_string('errorinvalidresponseapi', 'webservice'));
238
239 } else if ($description instanceof external_single_structure) {
240 if (!is_array($response)) {
241 throw new invalid_response_exception(get_string('erroronlyarray', 'webservice'));
242 }
243 $result = array();
244 foreach ($description->keys as $key=>$subdesc) {
245 if (!array_key_exists($key, $response)) {
246 if ($subdesc->required == VALUE_REQUIRED) {
476c0e82 247 throw new webservice_parameter_exception('errorresponsemissingkey', $key);
d07ff72d 248 }
249 if ($subdesc instanceof external_value) {
143c0abe 250 if ($subdesc->required == VALUE_DEFAULT) {
251 try {
d07ff72d 252 $result[$key] = self::clean_returnvalue($subdesc, $subdesc->default);
143c0abe 253 } catch (Exception $e) {
254 throw new webservice_parameter_exception('invalidextresponse',$key." (".$e->debuginfo.")");
d07ff72d 255 }
256 }
143c0abe 257 }
d07ff72d 258 } else {
259 try {
260 $result[$key] = self::clean_returnvalue($subdesc, $response[$key]);
143c0abe 261 } catch (Exception $e) {
d07ff72d 262 //it's ok to display debug info as here the information is useful for ws client/dev
263 throw new webservice_parameter_exception('invalidextresponse',$key." (".$e->debuginfo.")");
264 }
265 }
266 unset($response[$key]);
267 }
268
269 return $result;
270
271 } else if ($description instanceof external_multiple_structure) {
272 if (!is_array($response)) {
273 throw new invalid_response_exception(get_string('erroronlyarray', 'webservice'));
274 }
275 $result = array();
276 foreach ($response as $param) {
277 $result[] = self::clean_returnvalue($description->content, $param);
278 }
279 return $result;
280
281 } else {
282 throw new invalid_response_exception(get_string('errorinvalidresponsedesc', 'webservice'));
283 }
284 }
285
9a0df45a 286 /**
287 * Makes sure user may execute functions in this context.
288 * @param object $context
289 * @return void
290 */
291 protected static function validate_context($context) {
4f0c2d00
PS
292 global $CFG;
293
ab9a01f2 294 if (empty($context)) {
295 throw new invalid_parameter_exception('Context does not exist');
296 }
9a0df45a 297 if (empty(self::$contextrestriction)) {
298 self::$contextrestriction = get_context_instance(CONTEXT_SYSTEM);
299 }
300 $rcontext = self::$contextrestriction;
301
302 if ($rcontext->contextlevel == $context->contextlevel) {
aa7fbebd 303 if ($rcontext->id != $context->id) {
9a0df45a 304 throw new restricted_context_exception();
305 }
306 } else if ($rcontext->contextlevel > $context->contextlevel) {
307 throw new restricted_context_exception();
308 } else {
309 $parents = get_parent_contexts($context);
310 if (!in_array($rcontext->id, $parents)) {
311 throw new restricted_context_exception();
312 }
313 }
314
315 if ($context->contextlevel >= CONTEXT_COURSE) {
4f0c2d00 316 list($context, $course, $cm) = get_context_info_array($context->id);
df997f84 317 require_login($course, false, $cm, false, true);
9a0df45a 318 }
319 }
9a0df45a 320}
321
b038c32c 322/**
323 * Common ancestor of all parameter description classes
324 */
325abstract class external_description {
326 /** @property string $description description of element */
327 public $desc;
23e7b7cc 328 /** @property bool $required element value required, null not allowed */
b038c32c 329 public $required;
774b1b0f 330 /** @property mixed $default default value */
331 public $default;
b038c32c 332
333 /**
334 * Contructor
335 * @param string $desc
336 * @param bool $required
774b1b0f 337 * @param mixed $default
b038c32c 338 */
774b1b0f 339 public function __construct($desc, $required, $default) {
b038c32c 340 $this->desc = $desc;
341 $this->required = $required;
774b1b0f 342 $this->default = $default;
b038c32c 343 }
344}
345
346/**
04d212ce 347 * Scalar alue description class
b038c32c 348 */
04d212ce 349class external_value extends external_description {
350 /** @property mixed $type value type PARAM_XX */
b038c32c 351 public $type;
b038c32c 352 /** @property bool $allownull allow null values */
353 public $allownull;
354
355 /**
356 * Constructor
357 * @param mixed $type
358 * @param string $desc
359 * @param bool $required
360 * @param mixed $default
361 * @param bool $allownull
362 */
774b1b0f 363 public function __construct($type, $desc='', $required=VALUE_REQUIRED,
364 $default=null, $allownull=NULL_ALLOWED) {
365 parent::__construct($desc, $required, $default);
78bfb562 366 $this->type = $type;
b038c32c 367 $this->allownull = $allownull;
368 }
369}
370
371/**
372 * Associative array description class
373 */
374class external_single_structure extends external_description {
375 /** @property array $keys description of array keys key=>external_description */
376 public $keys;
377
378 /**
379 * Constructor
380 * @param array $keys
381 * @param string $desc
382 * @param bool $required
774b1b0f 383 * @param array $default
b038c32c 384 */
774b1b0f 385 public function __construct(array $keys, $desc='',
386 $required=VALUE_REQUIRED, $default=null) {
387 parent::__construct($desc, $required, $default);
b038c32c 388 $this->keys = $keys;
389 }
390}
391
392/**
393 * Bulk array description class.
394 */
395class external_multiple_structure extends external_description {
396 /** @property external_description $content */
397 public $content;
398
399 /**
400 * Constructor
401 * @param external_description $content
402 * @param string $desc
403 * @param bool $required
774b1b0f 404 * @param array $default
b038c32c 405 */
774b1b0f 406 public function __construct(external_description $content, $desc='',
407 $required=VALUE_REQUIRED, $default=null) {
408 parent::__construct($desc, $required, $default);
b038c32c 409 $this->content = $content;
410 }
411}
c29cca30 412
413/**
414 * Description of top level - PHP function parameters.
415 * @author skodak
416 *
417 */
418class external_function_parameters extends external_single_structure {
419}
2822f40a
JP
420
421function external_generate_token($tokentype, $serviceorid, $userid, $contextorid, $validuntil=0, $iprestriction=''){
422 global $DB, $USER;
423 // make sure the token doesn't exist (even if it should be almost impossible with the random generation)
424 $numtries = 0;
425 do {
426 $numtries ++;
427 $generatedtoken = md5(uniqid(rand(),1));
428 if ($numtries > 5){
429 throw new moodle_exception('tokengenerationfailed');
430 }
431 } while ($DB->record_exists('external_tokens', array('token'=>$generatedtoken)));
365a5941 432 $newtoken = new stdClass();
2822f40a
JP
433 $newtoken->token = $generatedtoken;
434 if (!is_object($serviceorid)){
435 $service = $DB->get_record('external_services', array('id' => $serviceorid));
436 } else {
437 $service = $serviceorid;
438 }
439 if (!is_object($contextorid)){
440 $context = get_context_instance_by_id($contextorid, MUST_EXIST);
441 } else {
442 $context = $contextorid;
443 }
444 if (empty($service->requiredcapability) || has_capability($service->requiredcapability, $context, $userid)) {
445 $newtoken->externalserviceid = $service->id;
446 } else {
447 throw new moodle_exception('nocapabilitytousethisservice');
448 }
449 $newtoken->tokentype = $tokentype;
450 $newtoken->userid = $userid;
2d0acbd5
JP
451 if ($tokentype == EXTERNAL_TOKEN_EMBEDDED){
452 $newtoken->sid = session_id();
453 }
4f0c2d00
PS
454
455 $newtoken->contextid = $context->id;
2822f40a
JP
456 $newtoken->creatorid = $USER->id;
457 $newtoken->timecreated = time();
458 $newtoken->validuntil = $validuntil;
459 if (!empty($iprestriction)) {
460 $newtoken->iprestriction = $iprestriction;
461 }
462 $DB->insert_record('external_tokens', $newtoken);
463 return $newtoken->token;
2d0acbd5
JP
464}
465/**
df997f84 466 * Create and return a session linked token. Token to be used for html embedded client apps that want to communicate
2d0acbd5
JP
467 * with the Moodle server through web services. The token is linked to the current session for the current page request.
468 * It is expected this will be called in the script generating the html page that is embedding the client app and that the
469 * returned token will be somehow passed into the client app being embedded in the page.
470 * @param string $servicename name of the web service. Service name as defined in db/services.php
471 * @param int $context context within which the web service can operate.
472 * @return int returns token id.
473 */
474function external_create_service_token($servicename, $context){
475 global $USER, $DB;
476 $service = $DB->get_record('external_services', array('name'=>$servicename), '*', MUST_EXIST);
477 return external_generate_token(EXTERNAL_TOKEN_EMBEDDED, $service, $USER->id, $context, 0);
2822f40a 478}