3 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
19 * Support for external API
22 * @subpackage webservice
23 * @copyright 2009 Moodle Pty Ltd (http://moodle.com)
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') || die();
30 * Returns detailed function information
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
36 function external_function_info($function, $strictness=MUST_EXIST) {
39 if (!is_object($function)) {
40 if (!$function = $DB->get_record('external_functions', array('name'=>$function), '*', $strictness)) {
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');
50 require_once($function->classpath);
52 $function->parameters_method = $function->methodname.'_parameters';
53 $function->returns_method = $function->methodname.'_returns';
55 // make sure the implementaion class is ok
56 if (!method_exists($function->classname, $function->methodname)) {
57 throw new coding_exception('Missing implementation method of '.$function->classname.'::'.$function->methodname);
59 if (!method_exists($function->classname, $function->parameters_method)) {
60 throw new coding_exception('Missing parameters description');
62 if (!method_exists($function->classname, $function->returns_method)) {
63 throw new coding_exception('Missing returned values description');
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');
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');
79 //now get the function description
80 //TODO: use localised lang pack descriptions, it would be nice to have
81 // easy to understand descriptions in admin UI,
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)) {
88 include($servicesfile);
89 if (isset($functions[$function->name]['description'])) {
90 $function->description = $functions[$function->name]['description'];
92 if (isset($functions[$function->name]['testclientpath'])) {
93 $function->testclientpath = $functions[$function->name]['testclientpath'];
101 * Exception indicating user is not allowed to use external function in
102 * the current context.
104 class restricted_context_exception extends moodle_exception {
108 function __construct() {
109 parent::__construct('restrictedcontextexception', 'error');
114 * Base class for external api methods.
117 private static $contextrestriction;
120 * Set context restriction for all following subsequent function calls.
121 * @param stdClass $contex
124 public static function set_context_restriction($context) {
125 self::$contextrestriction = $context;
129 * This method has to be called before every operation
130 * that takes a longer time to finish!
132 * @param int $seconds max expected time the next operation needs
135 public static function set_timeout($seconds=360) {
136 $seconds = ($seconds < 300) ? 300 : $seconds;
137 set_time_limit($seconds);
141 * Validates submitted function parameters, if anything is incorrect
142 * invalid_parameter_exception is thrown.
143 * This is a simple recursive method which is intended to be called from
144 * each implementation method of external API.
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
149 public static function validate_parameters(external_description $description, $params) {
150 if ($description instanceof external_value) {
151 if (is_array($params) or is_object($params)) {
152 throw new invalid_parameter_exception('Scalar type expected, array or object received.');
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;
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);
165 } else if ($description instanceof external_single_structure) {
166 if (!is_array($params)) {
167 throw new invalid_parameter_exception('Only arrays accepted. The bad value is: \''
168 . print_r($params, true) . '\'');
171 foreach ($description->keys as $key=>$subdesc) {
172 if (!array_key_exists($key, $params)) {
173 if ($subdesc->required == VALUE_REQUIRED) {
174 throw new invalid_parameter_exception('Missing required key in single structure: '. $key);
176 if ($subdesc->required == VALUE_DEFAULT) {
178 $result[$key] = self::validate_parameters($subdesc, $subdesc->default);
179 } catch (invalid_parameter_exception $e) {
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);
187 $result[$key] = self::validate_parameters($subdesc, $params[$key]);
188 } catch (invalid_parameter_exception $e) {
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);
194 unset($params[$key]);
196 if (!empty($params)) {
197 //list all unexpected keys
199 foreach($params as $key => $value) {
202 throw new invalid_parameter_exception('Unexpected keys (' . $keys . ') detected in parameter array.');
206 } else if ($description instanceof external_multiple_structure) {
207 if (!is_array($params)) {
208 throw new invalid_parameter_exception('Only arrays accepted. The bad value is: \''
209 . print_r($params, true) . '\'');
212 foreach ($params as $param) {
213 $result[] = self::validate_parameters($description->content, $param);
218 throw new invalid_parameter_exception('Invalid external api description');
224 * If a response attribute is unknown from the description, we just ignore the attribute.
225 * If a response attribute is incorrect, invalid_response_exception is thrown.
226 * Note: this function is similar to validate parameters, however it is distinct because
227 * parameters validation must be distinct from cleaning return values.
228 * @param external_description $description description of the return values
229 * @param mixed $response the actual response
230 * @return mixed response with added defaults for optional items, invalid_response_exception thrown if any problem found
232 public static function clean_returnvalue(external_description $description, $response) {
233 if ($description instanceof external_value) {
234 if (is_array($response) or is_object($response)) {
235 throw new invalid_response_exception('Scalar type expected, array or object received.');
238 if ($description->type == PARAM_BOOL) {
239 // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
240 if (is_bool($response) or $response === 0 or $response === 1 or $response === '0' or $response === '1') {
241 return (bool)$response;
244 $debuginfo = 'Invalid external api response: the value is "' . $response .
245 '", the server was expecting "' . $description->type . '" type';
247 return validate_param($response, $description->type, $description->allownull, $debuginfo);
248 } catch (invalid_parameter_exception $e) {
249 //proper exception name, to be recursively catched to build the path to the faulty attribut
250 throw new invalid_response_exception($e->debuginfo);
253 } else if ($description instanceof external_single_structure) {
254 if (!is_array($response)) {
255 throw new invalid_response_exception('Only arrays accepted. The bad value is: \'' .
256 print_r($response, true) . '\'');
259 foreach ($description->keys as $key=>$subdesc) {
260 if (!array_key_exists($key, $response)) {
261 if ($subdesc->required == VALUE_REQUIRED) {
262 throw new invalid_response_exception('Error in response - Missing following required key in a single structure: ' . $key);
264 if ($subdesc instanceof external_value) {
265 if ($subdesc->required == VALUE_DEFAULT) {
267 $result[$key] = self::clean_returnvalue($subdesc, $subdesc->default);
268 } catch (invalid_response_exception $e) {
269 //build the path to the faulty attribut
270 throw new invalid_response_exception($key." => ".$e->getMessage() . ': ' . $e->debuginfo);
276 $result[$key] = self::clean_returnvalue($subdesc, $response[$key]);
277 } catch (invalid_response_exception $e) {
278 //build the path to the faulty attribut
279 throw new invalid_response_exception($key." => ".$e->getMessage() . ': ' . $e->debuginfo);
282 unset($response[$key]);
287 } else if ($description instanceof external_multiple_structure) {
288 if (!is_array($response)) {
289 throw new invalid_response_exception('Only arrays accepted. The bad value is: \'' .
290 print_r($response, true) . '\'');
293 foreach ($response as $param) {
294 $result[] = self::clean_returnvalue($description->content, $param);
299 throw new invalid_response_exception('Invalid external api response description');
304 * Makes sure user may execute functions in this context.
305 * @param object $context
308 protected static function validate_context($context) {
311 if (empty($context)) {
312 throw new invalid_parameter_exception('Context does not exist');
314 if (empty(self::$contextrestriction)) {
315 self::$contextrestriction = get_context_instance(CONTEXT_SYSTEM);
317 $rcontext = self::$contextrestriction;
319 if ($rcontext->contextlevel == $context->contextlevel) {
320 if ($rcontext->id != $context->id) {
321 throw new restricted_context_exception();
323 } else if ($rcontext->contextlevel > $context->contextlevel) {
324 throw new restricted_context_exception();
326 $parents = get_parent_contexts($context);
327 if (!in_array($rcontext->id, $parents)) {
328 throw new restricted_context_exception();
332 if ($context->contextlevel >= CONTEXT_COURSE) {
333 list($context, $course, $cm) = get_context_info_array($context->id);
334 require_login($course, false, $cm, false, true);
340 * Common ancestor of all parameter description classes
342 abstract class external_description {
343 /** @property string $description description of element */
345 /** @property bool $required element value required, null not allowed */
347 /** @property mixed $default default value */
352 * @param string $desc
353 * @param bool $required
354 * @param mixed $default
356 public function __construct($desc, $required, $default) {
358 $this->required = $required;
359 $this->default = $default;
364 * Scalar alue description class
366 class external_value extends external_description {
367 /** @property mixed $type value type PARAM_XX */
369 /** @property bool $allownull allow null values */
375 * @param string $desc
376 * @param bool $required
377 * @param mixed $default
378 * @param bool $allownull
380 public function __construct($type, $desc='', $required=VALUE_REQUIRED,
381 $default=null, $allownull=NULL_ALLOWED) {
382 parent::__construct($desc, $required, $default);
384 $this->allownull = $allownull;
389 * Associative array description class
391 class external_single_structure extends external_description {
392 /** @property array $keys description of array keys key=>external_description */
398 * @param string $desc
399 * @param bool $required
400 * @param array $default
402 public function __construct(array $keys, $desc='',
403 $required=VALUE_REQUIRED, $default=null) {
404 parent::__construct($desc, $required, $default);
410 * Bulk array description class.
412 class external_multiple_structure extends external_description {
413 /** @property external_description $content */
418 * @param external_description $content
419 * @param string $desc
420 * @param bool $required
421 * @param array $default
423 public function __construct(external_description $content, $desc='',
424 $required=VALUE_REQUIRED, $default=null) {
425 parent::__construct($desc, $required, $default);
426 $this->content = $content;
431 * Description of top level - PHP function parameters.
435 class external_function_parameters extends external_single_structure {
438 function external_generate_token($tokentype, $serviceorid, $userid, $contextorid, $validuntil=0, $iprestriction=''){
440 // make sure the token doesn't exist (even if it should be almost impossible with the random generation)
444 $generatedtoken = md5(uniqid(rand(),1));
446 throw new moodle_exception('tokengenerationfailed');
448 } while ($DB->record_exists('external_tokens', array('token'=>$generatedtoken)));
449 $newtoken = new stdClass();
450 $newtoken->token = $generatedtoken;
451 if (!is_object($serviceorid)){
452 $service = $DB->get_record('external_services', array('id' => $serviceorid));
454 $service = $serviceorid;
456 if (!is_object($contextorid)){
457 $context = get_context_instance_by_id($contextorid, MUST_EXIST);
459 $context = $contextorid;
461 if (empty($service->requiredcapability) || has_capability($service->requiredcapability, $context, $userid)) {
462 $newtoken->externalserviceid = $service->id;
464 throw new moodle_exception('nocapabilitytousethisservice');
466 $newtoken->tokentype = $tokentype;
467 $newtoken->userid = $userid;
468 if ($tokentype == EXTERNAL_TOKEN_EMBEDDED){
469 $newtoken->sid = session_id();
472 $newtoken->contextid = $context->id;
473 $newtoken->creatorid = $USER->id;
474 $newtoken->timecreated = time();
475 $newtoken->validuntil = $validuntil;
476 if (!empty($iprestriction)) {
477 $newtoken->iprestriction = $iprestriction;
479 $DB->insert_record('external_tokens', $newtoken);
480 return $newtoken->token;
483 * Create and return a session linked token. Token to be used for html embedded client apps that want to communicate
484 * with the Moodle server through web services. The token is linked to the current session for the current page request.
485 * It is expected this will be called in the script generating the html page that is embedding the client app and that the
486 * returned token will be somehow passed into the client app being embedded in the page.
487 * @param string $servicename name of the web service. Service name as defined in db/services.php
488 * @param int $context context within which the web service can operate.
489 * @return int returns token id.
491 function external_create_service_token($servicename, $context){
493 $service = $DB->get_record('external_services', array('name'=>$servicename), '*', MUST_EXIST);
494 return external_generate_token(EXTERNAL_TOKEN_EMBEDDED, $service, $USER->id, $context, 0);