weekly release 2.1.7+
[moodle.git] / lib / externallib.php
blob145a6afdaf4a112909cc80f44410a11d6a6c1d4e
1 <?php
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.
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/>.
18 /**
19 * Support for external API
21 * @package core
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();
29 /**
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) {
37 global $DB, $CFG;
39 if (!is_object($function)) {
40 if (!$function = $DB->get_record('external_functions', array('name'=>$function), '*', $strictness)) {
41 return false;
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)) {
87 $functions = null;
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'];
97 return $function;
101 * Exception indicating user is not allowed to use external function in
102 * the current context.
104 class restricted_context_exception extends moodle_exception {
106 * Constructor
108 function __construct() {
109 parent::__construct('restrictedcontextexception', 'error');
114 * Base class for external api methods.
116 class external_api {
117 private static $contextrestriction;
120 * Set context restriction for all following subsequent function calls.
121 * @param stdClass $contex
122 * @return void
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
133 * @return void
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(get_string('errorscalartype', 'webservice'));
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 return validate_param($params, $description->type, $description->allownull, get_string('errorinvalidparamsapi', 'webservice'));
163 } else if ($description instanceof external_single_structure) {
164 if (!is_array($params)) {
165 throw new invalid_parameter_exception(get_string('erroronlyarray', 'webservice'));
167 $result = array();
168 foreach ($description->keys as $key=>$subdesc) {
169 if (!array_key_exists($key, $params)) {
170 if ($subdesc->required == VALUE_REQUIRED) {
171 throw new invalid_parameter_exception(get_string('errormissingkey', 'webservice', $key));
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);
180 } else {
181 try {
182 $result[$key] = self::validate_parameters($subdesc, $params[$key]);
183 } catch (invalid_parameter_exception $e) {
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.")");
188 unset($params[$key]);
190 if (!empty($params)) {
191 //list all unexpected keys
192 $keys = '';
193 foreach($params as $key => $value) {
194 $keys .= $key . ',';
196 throw new invalid_parameter_exception(get_string('errorunexpectedkey', 'webservice', $keys));
198 return $result;
200 } else if ($description instanceof external_multiple_structure) {
201 if (!is_array($params)) {
202 throw new invalid_parameter_exception(get_string('erroronlyarray', 'webservice'));
204 $result = array();
205 foreach ($params as $param) {
206 $result[] = self::validate_parameters($description->content, $param);
208 return $result;
210 } else {
211 throw new invalid_parameter_exception(get_string('errorinvalidparamsdesc', 'webservice'));
216 * Clean response
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.
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
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'));
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;
237 return validate_param($response, $description->type, $description->allownull, get_string('errorinvalidresponseapi', 'webservice'));
239 } else if ($description instanceof external_single_structure) {
240 if (!is_array($response)) {
241 throw new invalid_response_exception(get_string('erroronlyarray', 'webservice'));
243 $result = array();
244 foreach ($description->keys as $key=>$subdesc) {
245 if (!array_key_exists($key, $response)) {
246 if ($subdesc->required == VALUE_REQUIRED) {
247 throw new webservice_parameter_exception('errorresponsemissingkey', $key);
249 if ($subdesc instanceof external_value) {
250 if ($subdesc->required == VALUE_DEFAULT) {
251 try {
252 $result[$key] = self::clean_returnvalue($subdesc, $subdesc->default);
253 } catch (Exception $e) {
254 throw new webservice_parameter_exception('invalidextresponse',$key." (".$e->debuginfo.")");
258 } else {
259 try {
260 $result[$key] = self::clean_returnvalue($subdesc, $response[$key]);
261 } catch (Exception $e) {
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.")");
266 unset($response[$key]);
269 return $result;
271 } else if ($description instanceof external_multiple_structure) {
272 if (!is_array($response)) {
273 throw new invalid_response_exception(get_string('erroronlyarray', 'webservice'));
275 $result = array();
276 foreach ($response as $param) {
277 $result[] = self::clean_returnvalue($description->content, $param);
279 return $result;
281 } else {
282 throw new invalid_response_exception(get_string('errorinvalidresponsedesc', 'webservice'));
287 * Makes sure user may execute functions in this context.
288 * @param object $context
289 * @return void
291 protected static function validate_context($context) {
292 global $CFG;
294 if (empty($context)) {
295 throw new invalid_parameter_exception('Context does not exist');
297 if (empty(self::$contextrestriction)) {
298 self::$contextrestriction = get_context_instance(CONTEXT_SYSTEM);
300 $rcontext = self::$contextrestriction;
302 if ($rcontext->contextlevel == $context->contextlevel) {
303 if ($rcontext->id != $context->id) {
304 throw new restricted_context_exception();
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();
315 if ($context->contextlevel >= CONTEXT_COURSE) {
316 list($context, $course, $cm) = get_context_info_array($context->id);
317 require_login($course, false, $cm, false, true);
323 * Common ancestor of all parameter description classes
325 abstract class external_description {
326 /** @property string $description description of element */
327 public $desc;
328 /** @property bool $required element value required, null not allowed */
329 public $required;
330 /** @property mixed $default default value */
331 public $default;
334 * Contructor
335 * @param string $desc
336 * @param bool $required
337 * @param mixed $default
339 public function __construct($desc, $required, $default) {
340 $this->desc = $desc;
341 $this->required = $required;
342 $this->default = $default;
347 * Scalar alue description class
349 class external_value extends external_description {
350 /** @property mixed $type value type PARAM_XX */
351 public $type;
352 /** @property bool $allownull allow null values */
353 public $allownull;
356 * Constructor
357 * @param mixed $type
358 * @param string $desc
359 * @param bool $required
360 * @param mixed $default
361 * @param bool $allownull
363 public function __construct($type, $desc='', $required=VALUE_REQUIRED,
364 $default=null, $allownull=NULL_ALLOWED) {
365 parent::__construct($desc, $required, $default);
366 $this->type = $type;
367 $this->allownull = $allownull;
372 * Associative array description class
374 class external_single_structure extends external_description {
375 /** @property array $keys description of array keys key=>external_description */
376 public $keys;
379 * Constructor
380 * @param array $keys
381 * @param string $desc
382 * @param bool $required
383 * @param array $default
385 public function __construct(array $keys, $desc='',
386 $required=VALUE_REQUIRED, $default=null) {
387 parent::__construct($desc, $required, $default);
388 $this->keys = $keys;
393 * Bulk array description class.
395 class external_multiple_structure extends external_description {
396 /** @property external_description $content */
397 public $content;
400 * Constructor
401 * @param external_description $content
402 * @param string $desc
403 * @param bool $required
404 * @param array $default
406 public function __construct(external_description $content, $desc='',
407 $required=VALUE_REQUIRED, $default=null) {
408 parent::__construct($desc, $required, $default);
409 $this->content = $content;
414 * Description of top level - PHP function parameters.
415 * @author skodak
418 class external_function_parameters extends external_single_structure {
421 function 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');
431 } while ($DB->record_exists('external_tokens', array('token'=>$generatedtoken)));
432 $newtoken = new stdClass();
433 $newtoken->token = $generatedtoken;
434 if (!is_object($serviceorid)){
435 $service = $DB->get_record('external_services', array('id' => $serviceorid));
436 } else {
437 $service = $serviceorid;
439 if (!is_object($contextorid)){
440 $context = get_context_instance_by_id($contextorid, MUST_EXIST);
441 } else {
442 $context = $contextorid;
444 if (empty($service->requiredcapability) || has_capability($service->requiredcapability, $context, $userid)) {
445 $newtoken->externalserviceid = $service->id;
446 } else {
447 throw new moodle_exception('nocapabilitytousethisservice');
449 $newtoken->tokentype = $tokentype;
450 $newtoken->userid = $userid;
451 if ($tokentype == EXTERNAL_TOKEN_EMBEDDED){
452 $newtoken->sid = session_id();
455 $newtoken->contextid = $context->id;
456 $newtoken->creatorid = $USER->id;
457 $newtoken->timecreated = time();
458 $newtoken->validuntil = $validuntil;
459 if (!empty($iprestriction)) {
460 $newtoken->iprestriction = $iprestriction;
462 $DB->insert_record('external_tokens', $newtoken);
463 return $newtoken->token;
466 * Create and return a session linked token. Token to be used for html embedded client apps that want to communicate
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.
474 function 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);
481 * Delete all pre-built services (+ related tokens) and external functions information defined in the specified component.
483 * @param string $component name of component (moodle, mod_assignment, etc.)
485 function external_delete_descriptions($component) {
486 global $DB;
488 $params = array($component);
490 $DB->delete_records_select('external_tokens',
491 "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
492 $DB->delete_records_select('external_services_users',
493 "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
494 $DB->delete_records_select('external_services_functions',
495 "functionname IN (SELECT name FROM {external_functions} WHERE component = ?)", $params);
496 $DB->delete_records('external_services', array('component'=>$component));
497 $DB->delete_records('external_functions', array('component'=>$component));