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'];
98 * Exception indicating user is not allowed to use external function in
99 * the current context.
101 class restricted_context_exception
extends moodle_exception
{
105 function __construct() {
106 parent
::__construct('restrictedcontextexception', 'error');
111 * Base class for external api methods.
114 private static $contextrestriction;
117 * Set context restriction for all following subsequent function calls.
118 * @param stdClass $contex
121 public static function set_context_restriction($context) {
122 self
::$contextrestriction = $context;
126 * This method has to be called before every operation
127 * that takes a longer time to finish!
129 * @param int $seconds max expected time the next operation needs
132 public static function set_timeout($seconds=360) {
133 $seconds = ($seconds < 300) ?
300 : $seconds;
134 set_time_limit($seconds);
138 * Validates submitted function parameters, if anything is incorrect
139 * invalid_parameter_exception is thrown.
140 * This is a simple recursive method which is intended to be called from
141 * each implementation method of external API.
142 * @param external_description $description description of parameters
143 * @param mixed $params the actual parameters
144 * @return mixed params with added defaults for optional items, invalid_parameters_exception thrown if any problem found
146 public static function validate_parameters(external_description
$description, $params) {
147 if ($description instanceof external_value
) {
148 if (is_array($params) or is_object($params)) {
149 throw new invalid_parameter_exception(get_string('errorscalartype', 'webservice'));
152 if ($description->type
== PARAM_BOOL
) {
153 // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
154 if (is_bool($params) or $params === 0 or $params === 1 or $params === '0' or $params === '1') {
155 return (bool)$params;
158 return validate_param($params, $description->type
, $description->allownull
, get_string('errorinvalidparamsapi', 'webservice'));
160 } else if ($description instanceof external_single_structure
) {
161 if (!is_array($params)) {
162 throw new invalid_parameter_exception(get_string('erroronlyarray', 'webservice'));
165 foreach ($description->keys
as $key=>$subdesc) {
166 if (!array_key_exists($key, $params)) {
167 if ($subdesc->required
== VALUE_REQUIRED
) {
168 throw new invalid_parameter_exception(get_string('errormissingkey', 'webservice', $key));
170 if ($subdesc->required
== VALUE_DEFAULT
) {
172 $result[$key] = self
::validate_parameters($subdesc, $subdesc->default);
173 } catch (invalid_parameter_exception
$e) {
174 throw new webservice_parameter_exception('invalidextparam',$key);
179 $result[$key] = self
::validate_parameters($subdesc, $params[$key]);
180 } catch (invalid_parameter_exception
$e) {
181 //it's ok to display debug info as here the information is useful for ws client/dev
182 throw new webservice_parameter_exception('invalidextparam',$key." (".$e->debuginfo
.")");
185 unset($params[$key]);
187 if (!empty($params)) {
188 //list all unexpected keys
190 foreach($params as $key => $value) {
193 throw new invalid_parameter_exception(get_string('errorunexpectedkey', 'webservice', $keys));
197 } else if ($description instanceof external_multiple_structure
) {
198 if (!is_array($params)) {
199 throw new invalid_parameter_exception(get_string('erroronlyarray', 'webservice'));
202 foreach ($params as $param) {
203 $result[] = self
::validate_parameters($description->content
, $param);
208 throw new invalid_parameter_exception(get_string('errorinvalidparamsdesc', 'webservice'));
214 * If a response attribute is unknown from the description, we just ignore the attribute.
215 * If a response attribute is incorrect, invalid_response_exception is thrown.
216 * Note: this function is similar to validate parameters, however it is distinct because
217 * parameters validation must be distinct from cleaning return values.
218 * @param external_description $description description of the return values
219 * @param mixed $response the actual response
220 * @return mixed response with added defaults for optional items, invalid_response_exception thrown if any problem found
222 public static function clean_returnvalue(external_description
$description, $response) {
223 if ($description instanceof external_value
) {
224 if (is_array($response) or is_object($response)) {
225 throw new invalid_response_exception(get_string('errorscalartype', 'webservice'));
228 if ($description->type
== PARAM_BOOL
) {
229 // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
230 if (is_bool($response) or $response === 0 or $response === 1 or $response === '0' or $response === '1') {
231 return (bool)$response;
234 return validate_param($response, $description->type
, $description->allownull
, get_string('errorinvalidresponseapi', 'webservice'));
236 } else if ($description instanceof external_single_structure
) {
237 if (!is_array($response)) {
238 throw new invalid_response_exception(get_string('erroronlyarray', 'webservice'));
241 foreach ($description->keys
as $key=>$subdesc) {
242 if (!array_key_exists($key, $response)) {
243 if ($subdesc->required
== VALUE_REQUIRED
) {
244 throw new webservice_parameter_exception('errorresponsemissingkey', $key);
246 if ($subdesc instanceof external_value
) {
247 if ($subdesc->required
== VALUE_DEFAULT
) {
249 $result[$key] = self
::clean_returnvalue($subdesc, $subdesc->default);
250 } catch (Exception
$e) {
251 throw new webservice_parameter_exception('invalidextresponse',$key." (".$e->debuginfo
.")");
257 $result[$key] = self
::clean_returnvalue($subdesc, $response[$key]);
258 } catch (Exception
$e) {
259 //it's ok to display debug info as here the information is useful for ws client/dev
260 throw new webservice_parameter_exception('invalidextresponse',$key." (".$e->debuginfo
.")");
263 unset($response[$key]);
268 } else if ($description instanceof external_multiple_structure
) {
269 if (!is_array($response)) {
270 throw new invalid_response_exception(get_string('erroronlyarray', 'webservice'));
273 foreach ($response as $param) {
274 $result[] = self
::clean_returnvalue($description->content
, $param);
279 throw new invalid_response_exception(get_string('errorinvalidresponsedesc', 'webservice'));
284 * Makes sure user may execute functions in this context.
285 * @param object $context
288 protected static function validate_context($context) {
291 if (empty($context)) {
292 throw new invalid_parameter_exception('Context does not exist');
294 if (empty(self
::$contextrestriction)) {
295 self
::$contextrestriction = get_context_instance(CONTEXT_SYSTEM
);
297 $rcontext = self
::$contextrestriction;
299 if ($rcontext->contextlevel
== $context->contextlevel
) {
300 if ($rcontext->id
!= $context->id
) {
301 throw new restricted_context_exception();
303 } else if ($rcontext->contextlevel
> $context->contextlevel
) {
304 throw new restricted_context_exception();
306 $parents = get_parent_contexts($context);
307 if (!in_array($rcontext->id
, $parents)) {
308 throw new restricted_context_exception();
312 if ($context->contextlevel
>= CONTEXT_COURSE
) {
313 list($context, $course, $cm) = get_context_info_array($context->id
);
314 require_login($course, false, $cm, false, true);
320 * Common ancestor of all parameter description classes
322 abstract class external_description
{
323 /** @property string $description description of element */
325 /** @property bool $required element value required, null not allowed */
327 /** @property mixed $default default value */
332 * @param string $desc
333 * @param bool $required
334 * @param mixed $default
336 public function __construct($desc, $required, $default) {
338 $this->required
= $required;
339 $this->default = $default;
344 * Scalar alue description class
346 class external_value
extends external_description
{
347 /** @property mixed $type value type PARAM_XX */
349 /** @property bool $allownull allow null values */
355 * @param string $desc
356 * @param bool $required
357 * @param mixed $default
358 * @param bool $allownull
360 public function __construct($type, $desc='', $required=VALUE_REQUIRED
,
361 $default=null, $allownull=NULL_ALLOWED
) {
362 parent
::__construct($desc, $required, $default);
364 $this->allownull
= $allownull;
369 * Associative array description class
371 class external_single_structure
extends external_description
{
372 /** @property array $keys description of array keys key=>external_description */
378 * @param string $desc
379 * @param bool $required
380 * @param array $default
382 public function __construct(array $keys, $desc='',
383 $required=VALUE_REQUIRED
, $default=null) {
384 parent
::__construct($desc, $required, $default);
390 * Bulk array description class.
392 class external_multiple_structure
extends external_description
{
393 /** @property external_description $content */
398 * @param external_description $content
399 * @param string $desc
400 * @param bool $required
401 * @param array $default
403 public function __construct(external_description
$content, $desc='',
404 $required=VALUE_REQUIRED
, $default=null) {
405 parent
::__construct($desc, $required, $default);
406 $this->content
= $content;
411 * Description of top level - PHP function parameters.
415 class external_function_parameters
extends external_single_structure
{
418 function external_generate_token($tokentype, $serviceorid, $userid, $contextorid, $validuntil=0, $iprestriction=''){
420 // make sure the token doesn't exist (even if it should be almost impossible with the random generation)
424 $generatedtoken = md5(uniqid(rand(),1));
426 throw new moodle_exception('tokengenerationfailed');
428 } while ($DB->record_exists('external_tokens', array('token'=>$generatedtoken)));
429 $newtoken = new stdClass();
430 $newtoken->token
= $generatedtoken;
431 if (!is_object($serviceorid)){
432 $service = $DB->get_record('external_services', array('id' => $serviceorid));
434 $service = $serviceorid;
436 if (!is_object($contextorid)){
437 $context = get_context_instance_by_id($contextorid, MUST_EXIST
);
439 $context = $contextorid;
441 if (empty($service->requiredcapability
) ||
has_capability($service->requiredcapability
, $context, $userid)) {
442 $newtoken->externalserviceid
= $service->id
;
444 throw new moodle_exception('nocapabilitytousethisservice');
446 $newtoken->tokentype
= $tokentype;
447 $newtoken->userid
= $userid;
448 if ($tokentype == EXTERNAL_TOKEN_EMBEDDED
){
449 $newtoken->sid
= session_id();
452 $newtoken->contextid
= $context->id
;
453 $newtoken->creatorid
= $USER->id
;
454 $newtoken->timecreated
= time();
455 $newtoken->validuntil
= $validuntil;
456 if (!empty($iprestriction)) {
457 $newtoken->iprestriction
= $iprestriction;
459 $DB->insert_record('external_tokens', $newtoken);
460 return $newtoken->token
;
463 * Create and return a session linked token. Token to be used for html embedded client apps that want to communicate
464 * with the Moodle server through web services. The token is linked to the current session for the current page request.
465 * It is expected this will be called in the script generating the html page that is embedding the client app and that the
466 * returned token will be somehow passed into the client app being embedded in the page.
467 * @param string $servicename name of the web service. Service name as defined in db/services.php
468 * @param int $context context within which the web service can operate.
469 * @return int returns token id.
471 function external_create_service_token($servicename, $context){
473 $service = $DB->get_record('external_services', array('name'=>$servicename), '*', MUST_EXIST
);
474 return external_generate_token(EXTERNAL_TOKEN_EMBEDDED
, $service, $USER->id
, $context, 0);