Merge branch 'MDL-34647_22' of git://github.com/aolley/moodle into MOODLE_22_STABLE
[moodle.git] / lib / externallib.php
blobc3eb57406e7ea705a1e901ae561b3dfee741bf35
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('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) . '\'');
170 $result = array();
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) {
177 try {
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);
185 } else {
186 try {
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 throw new invalid_parameter_exception('Unexpected keys (' . implode(', ', array_keys($params)) . ') detected in parameter array.');
199 return $result;
201 } else if ($description instanceof external_multiple_structure) {
202 if (!is_array($params)) {
203 throw new invalid_parameter_exception('Only arrays accepted. The bad value is: \''
204 . print_r($params, true) . '\'');
206 $result = array();
207 foreach ($params as $param) {
208 $result[] = self::validate_parameters($description->content, $param);
210 return $result;
212 } else {
213 throw new invalid_parameter_exception('Invalid external api description');
218 * Clean response
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.
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
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)) {
230 throw new invalid_response_exception('Scalar type expected, array or object received.');
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;
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);
248 } else if ($description instanceof external_single_structure) {
249 if (!is_array($response)) {
250 throw new invalid_response_exception('Only arrays accepted. The bad value is: \'' .
251 print_r($response, true) . '\'');
253 $result = array();
254 foreach ($description->keys as $key=>$subdesc) {
255 if (!array_key_exists($key, $response)) {
256 if ($subdesc->required == VALUE_REQUIRED) {
257 throw new invalid_response_exception('Error in response - Missing following required key in a single structure: ' . $key);
259 if ($subdesc instanceof external_value) {
260 if ($subdesc->required == VALUE_DEFAULT) {
261 try {
262 $result[$key] = self::clean_returnvalue($subdesc, $subdesc->default);
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);
269 } else {
270 try {
271 $result[$key] = self::clean_returnvalue($subdesc, $response[$key]);
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);
277 unset($response[$key]);
280 return $result;
282 } else if ($description instanceof external_multiple_structure) {
283 if (!is_array($response)) {
284 throw new invalid_response_exception('Only arrays accepted. The bad value is: \'' .
285 print_r($response, true) . '\'');
287 $result = array();
288 foreach ($response as $param) {
289 $result[] = self::clean_returnvalue($description->content, $param);
291 return $result;
293 } else {
294 throw new invalid_response_exception('Invalid external api response description');
299 * Makes sure user may execute functions in this context.
300 * @param object $context
301 * @return void
303 protected static function validate_context($context) {
304 global $CFG;
306 if (empty($context)) {
307 throw new invalid_parameter_exception('Context does not exist');
309 if (empty(self::$contextrestriction)) {
310 self::$contextrestriction = get_context_instance(CONTEXT_SYSTEM);
312 $rcontext = self::$contextrestriction;
314 if ($rcontext->contextlevel == $context->contextlevel) {
315 if ($rcontext->id != $context->id) {
316 throw new restricted_context_exception();
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();
327 if ($context->contextlevel >= CONTEXT_COURSE) {
328 list($context, $course, $cm) = get_context_info_array($context->id);
329 require_login($course, false, $cm, false, true);
335 * Common ancestor of all parameter description classes
337 abstract class external_description {
338 /** @property string $description description of element */
339 public $desc;
340 /** @property bool $required element value required, null not allowed */
341 public $required;
342 /** @property mixed $default default value */
343 public $default;
346 * Contructor
347 * @param string $desc
348 * @param bool $required
349 * @param mixed $default
351 public function __construct($desc, $required, $default) {
352 $this->desc = $desc;
353 $this->required = $required;
354 $this->default = $default;
359 * Scalar alue description class
361 class external_value extends external_description {
362 /** @property mixed $type value type PARAM_XX */
363 public $type;
364 /** @property bool $allownull allow null values */
365 public $allownull;
368 * Constructor
369 * @param mixed $type
370 * @param string $desc
371 * @param bool $required
372 * @param mixed $default
373 * @param bool $allownull
375 public function __construct($type, $desc='', $required=VALUE_REQUIRED,
376 $default=null, $allownull=NULL_ALLOWED) {
377 parent::__construct($desc, $required, $default);
378 $this->type = $type;
379 $this->allownull = $allownull;
384 * Associative array description class
386 class external_single_structure extends external_description {
387 /** @property array $keys description of array keys key=>external_description */
388 public $keys;
391 * Constructor
392 * @param array $keys
393 * @param string $desc
394 * @param bool $required
395 * @param array $default
397 public function __construct(array $keys, $desc='',
398 $required=VALUE_REQUIRED, $default=null) {
399 parent::__construct($desc, $required, $default);
400 $this->keys = $keys;
405 * Bulk array description class.
407 class external_multiple_structure extends external_description {
408 /** @property external_description $content */
409 public $content;
412 * Constructor
413 * @param external_description $content
414 * @param string $desc
415 * @param bool $required
416 * @param array $default
418 public function __construct(external_description $content, $desc='',
419 $required=VALUE_REQUIRED, $default=null) {
420 parent::__construct($desc, $required, $default);
421 $this->content = $content;
426 * Description of top level - PHP function parameters.
427 * @author skodak
430 class external_function_parameters extends external_single_structure {
433 function 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');
443 } while ($DB->record_exists('external_tokens', array('token'=>$generatedtoken)));
444 $newtoken = new stdClass();
445 $newtoken->token = $generatedtoken;
446 if (!is_object($serviceorid)){
447 $service = $DB->get_record('external_services', array('id' => $serviceorid));
448 } else {
449 $service = $serviceorid;
451 if (!is_object($contextorid)){
452 $context = get_context_instance_by_id($contextorid, MUST_EXIST);
453 } else {
454 $context = $contextorid;
456 if (empty($service->requiredcapability) || has_capability($service->requiredcapability, $context, $userid)) {
457 $newtoken->externalserviceid = $service->id;
458 } else {
459 throw new moodle_exception('nocapabilitytousethisservice');
461 $newtoken->tokentype = $tokentype;
462 $newtoken->userid = $userid;
463 if ($tokentype == EXTERNAL_TOKEN_EMBEDDED){
464 $newtoken->sid = session_id();
467 $newtoken->contextid = $context->id;
468 $newtoken->creatorid = $USER->id;
469 $newtoken->timecreated = time();
470 $newtoken->validuntil = $validuntil;
471 if (!empty($iprestriction)) {
472 $newtoken->iprestriction = $iprestriction;
474 $DB->insert_record('external_tokens', $newtoken);
475 return $newtoken->token;
478 * Create and return a session linked token. Token to be used for html embedded client apps that want to communicate
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.
486 function 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);
493 * Delete all pre-built services (+ related tokens) and external functions information defined in the specified component.
495 * @param string $component name of component (moodle, mod_assignment, etc.)
497 function external_delete_descriptions($component) {
498 global $DB;
500 $params = array($component);
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));