Merge branch 'MDL-32780-CLEAN' of git://github.com/netspotau/moodle-mod_assign
[moodle.git] / lib / externallib.php
blob3eb1f1fce7dd795e3f106dbbbe958d028a263f1f
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Support for external API
21 * @package core_webservice
22 * @copyright 2009 Petr Skodak
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
28 /**
29 * 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 stdClass description or false if not found or exception thrown
35 * @since Moodle 2.0
37 function external_function_info($function, $strictness=MUST_EXIST) {
38 global $DB, $CFG;
40 if (!is_object($function)) {
41 if (!$function = $DB->get_record('external_functions', array('name'=>$function), '*', $strictness)) {
42 return false;
46 //first find and include the ext implementation class
47 $function->classpath = empty($function->classpath) ? get_component_directory($function->component).'/externallib.php' : $CFG->dirroot.'/'.$function->classpath;
48 if (!file_exists($function->classpath)) {
49 throw new coding_exception('Can not find file with external function implementation');
51 require_once($function->classpath);
53 $function->parameters_method = $function->methodname.'_parameters';
54 $function->returns_method = $function->methodname.'_returns';
56 // make sure the implementaion class is ok
57 if (!method_exists($function->classname, $function->methodname)) {
58 throw new coding_exception('Missing implementation method of '.$function->classname.'::'.$function->methodname);
60 if (!method_exists($function->classname, $function->parameters_method)) {
61 throw new coding_exception('Missing parameters description');
63 if (!method_exists($function->classname, $function->returns_method)) {
64 throw new coding_exception('Missing returned values description');
67 // fetch the parameters description
68 $function->parameters_desc = call_user_func(array($function->classname, $function->parameters_method));
69 if (!($function->parameters_desc instanceof external_function_parameters)) {
70 throw new coding_exception('Invalid parameters description');
73 // fetch the return values description
74 $function->returns_desc = call_user_func(array($function->classname, $function->returns_method));
75 // null means void result or result is ignored
76 if (!is_null($function->returns_desc) and !($function->returns_desc instanceof external_description)) {
77 throw new coding_exception('Invalid return description');
80 //now get the function description
81 //TODO MDL-31115 use localised lang pack descriptions, it would be nice to have
82 // easy to understand descriptions in admin UI,
83 // on the other hand this is still a bit in a flux and we need to find some new naming
84 // conventions for these descriptions in lang packs
85 $function->description = null;
86 $servicesfile = get_component_directory($function->component).'/db/services.php';
87 if (file_exists($servicesfile)) {
88 $functions = null;
89 include($servicesfile);
90 if (isset($functions[$function->name]['description'])) {
91 $function->description = $functions[$function->name]['description'];
93 if (isset($functions[$function->name]['testclientpath'])) {
94 $function->testclientpath = $functions[$function->name]['testclientpath'];
98 return $function;
102 * Exception indicating user is not allowed to use external function in the current context.
104 * @package core_webservice
105 * @copyright 2009 Petr Skodak
106 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
107 * @since Moodle 2.0
109 class restricted_context_exception extends moodle_exception {
111 * Constructor
113 * @since Moodle 2.0
115 function __construct() {
116 parent::__construct('restrictedcontextexception', 'error');
121 * Base class for external api methods.
123 * @package core_webservice
124 * @copyright 2009 Petr Skodak
125 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
126 * @since Moodle 2.0
128 class external_api {
130 /** @var stdClass context where the function calls will be restricted */
131 private static $contextrestriction;
134 * Set context restriction for all following subsequent function calls.
136 * @param stdClass $context the context restriction
137 * @since Moodle 2.0
139 public static function set_context_restriction($context) {
140 self::$contextrestriction = $context;
144 * This method has to be called before every operation
145 * that takes a longer time to finish!
147 * @param int $seconds max expected time the next operation needs
148 * @since Moodle 2.0
150 public static function set_timeout($seconds=360) {
151 $seconds = ($seconds < 300) ? 300 : $seconds;
152 set_time_limit($seconds);
156 * Validates submitted function parameters, if anything is incorrect
157 * invalid_parameter_exception is thrown.
158 * This is a simple recursive method which is intended to be called from
159 * each implementation method of external API.
161 * @param external_description $description description of parameters
162 * @param mixed $params the actual parameters
163 * @return mixed params with added defaults for optional items, invalid_parameters_exception thrown if any problem found
164 * @since Moodle 2.0
166 public static function validate_parameters(external_description $description, $params) {
167 if ($description instanceof external_value) {
168 if (is_array($params) or is_object($params)) {
169 throw new invalid_parameter_exception('Scalar type expected, array or object received.');
172 if ($description->type == PARAM_BOOL) {
173 // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
174 if (is_bool($params) or $params === 0 or $params === 1 or $params === '0' or $params === '1') {
175 return (bool)$params;
178 $debuginfo = 'Invalid external api parameter: the value is "' . $params .
179 '", the server was expecting "' . $description->type . '" type';
180 return validate_param($params, $description->type, $description->allownull, $debuginfo);
182 } else if ($description instanceof external_single_structure) {
183 if (!is_array($params)) {
184 throw new invalid_parameter_exception('Only arrays accepted. The bad value is: \''
185 . print_r($params, true) . '\'');
187 $result = array();
188 foreach ($description->keys as $key=>$subdesc) {
189 if (!array_key_exists($key, $params)) {
190 if ($subdesc->required == VALUE_REQUIRED) {
191 throw new invalid_parameter_exception('Missing required key in single structure: '. $key);
193 if ($subdesc->required == VALUE_DEFAULT) {
194 try {
195 $result[$key] = self::validate_parameters($subdesc, $subdesc->default);
196 } catch (invalid_parameter_exception $e) {
197 //we are only interested by exceptions returned by validate_param() and validate_parameters()
198 //(in order to build the path to the faulty attribut)
199 throw new invalid_parameter_exception($key." => ".$e->getMessage() . ': ' .$e->debuginfo);
202 } else {
203 try {
204 $result[$key] = self::validate_parameters($subdesc, $params[$key]);
205 } catch (invalid_parameter_exception $e) {
206 //we are only interested by exceptions returned by validate_param() and validate_parameters()
207 //(in order to build the path to the faulty attribut)
208 throw new invalid_parameter_exception($key." => ".$e->getMessage() . ': ' .$e->debuginfo);
211 unset($params[$key]);
213 if (!empty($params)) {
214 throw new invalid_parameter_exception('Unexpected keys (' . implode(', ', array_keys($params)) . ') detected in parameter array.');
216 return $result;
218 } else if ($description instanceof external_multiple_structure) {
219 if (!is_array($params)) {
220 throw new invalid_parameter_exception('Only arrays accepted. The bad value is: \''
221 . print_r($params, true) . '\'');
223 $result = array();
224 foreach ($params as $param) {
225 $result[] = self::validate_parameters($description->content, $param);
227 return $result;
229 } else {
230 throw new invalid_parameter_exception('Invalid external api description');
235 * Clean response
236 * If a response attribute is unknown from the description, we just ignore the attribute.
237 * If a response attribute is incorrect, invalid_response_exception is thrown.
238 * Note: this function is similar to validate parameters, however it is distinct because
239 * parameters validation must be distinct from cleaning return values.
241 * @param external_description $description description of the return values
242 * @param mixed $response the actual response
243 * @return mixed response with added defaults for optional items, invalid_response_exception thrown if any problem found
244 * @author 2010 Jerome Mouneyrac
245 * @since Moodle 2.0
247 public static function clean_returnvalue(external_description $description, $response) {
248 if ($description instanceof external_value) {
249 if (is_array($response) or is_object($response)) {
250 throw new invalid_response_exception('Scalar type expected, array or object received.');
253 if ($description->type == PARAM_BOOL) {
254 // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
255 if (is_bool($response) or $response === 0 or $response === 1 or $response === '0' or $response === '1') {
256 return (bool)$response;
259 $debuginfo = 'Invalid external api response: the value is "' . $response .
260 '", the server was expecting "' . $description->type . '" type';
261 try {
262 return validate_param($response, $description->type, $description->allownull, $debuginfo);
263 } catch (invalid_parameter_exception $e) {
264 //proper exception name, to be recursively catched to build the path to the faulty attribut
265 throw new invalid_response_exception($e->debuginfo);
268 } else if ($description instanceof external_single_structure) {
269 if (!is_array($response)) {
270 throw new invalid_response_exception('Only arrays accepted. The bad value is: \'' .
271 print_r($response, true) . '\'');
273 $result = array();
274 foreach ($description->keys as $key=>$subdesc) {
275 if (!array_key_exists($key, $response)) {
276 if ($subdesc->required == VALUE_REQUIRED) {
277 throw new invalid_response_exception('Error in response - Missing following required key in a single structure: ' . $key);
279 if ($subdesc instanceof external_value) {
280 if ($subdesc->required == VALUE_DEFAULT) {
281 try {
282 $result[$key] = self::clean_returnvalue($subdesc, $subdesc->default);
283 } catch (invalid_response_exception $e) {
284 //build the path to the faulty attribut
285 throw new invalid_response_exception($key." => ".$e->getMessage() . ': ' . $e->debuginfo);
289 } else {
290 try {
291 $result[$key] = self::clean_returnvalue($subdesc, $response[$key]);
292 } catch (invalid_response_exception $e) {
293 //build the path to the faulty attribut
294 throw new invalid_response_exception($key." => ".$e->getMessage() . ': ' . $e->debuginfo);
297 unset($response[$key]);
300 return $result;
302 } else if ($description instanceof external_multiple_structure) {
303 if (!is_array($response)) {
304 throw new invalid_response_exception('Only arrays accepted. The bad value is: \'' .
305 print_r($response, true) . '\'');
307 $result = array();
308 foreach ($response as $param) {
309 $result[] = self::clean_returnvalue($description->content, $param);
311 return $result;
313 } else {
314 throw new invalid_response_exception('Invalid external api response description');
319 * Makes sure user may execute functions in this context.
321 * @param stdClass $context
322 * @since Moodle 2.0
324 protected static function validate_context($context) {
325 global $CFG;
327 if (empty($context)) {
328 throw new invalid_parameter_exception('Context does not exist');
330 if (empty(self::$contextrestriction)) {
331 self::$contextrestriction = get_context_instance(CONTEXT_SYSTEM);
333 $rcontext = self::$contextrestriction;
335 if ($rcontext->contextlevel == $context->contextlevel) {
336 if ($rcontext->id != $context->id) {
337 throw new restricted_context_exception();
339 } else if ($rcontext->contextlevel > $context->contextlevel) {
340 throw new restricted_context_exception();
341 } else {
342 $parents = get_parent_contexts($context);
343 if (!in_array($rcontext->id, $parents)) {
344 throw new restricted_context_exception();
348 if ($context->contextlevel >= CONTEXT_COURSE) {
349 list($context, $course, $cm) = get_context_info_array($context->id);
350 require_login($course, false, $cm, false, true);
356 * Common ancestor of all parameter description classes
358 * @package core_webservice
359 * @copyright 2009 Petr Skodak
360 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
361 * @since Moodle 2.0
363 abstract class external_description {
364 /** @var string Description of element */
365 public $desc;
367 /** @var bool Element value required, null not allowed */
368 public $required;
370 /** @var mixed Default value */
371 public $default;
374 * Contructor
376 * @param string $desc
377 * @param bool $required
378 * @param mixed $default
379 * @since Moodle 2.0
381 public function __construct($desc, $required, $default) {
382 $this->desc = $desc;
383 $this->required = $required;
384 $this->default = $default;
389 * Scalar value description class
391 * @package core_webservice
392 * @copyright 2009 Petr Skodak
393 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
394 * @since Moodle 2.0
396 class external_value extends external_description {
398 /** @var mixed Value type PARAM_XX */
399 public $type;
401 /** @var bool Allow null values */
402 public $allownull;
405 * Constructor
407 * @param mixed $type
408 * @param string $desc
409 * @param bool $required
410 * @param mixed $default
411 * @param bool $allownull
412 * @since Moodle 2.0
414 public function __construct($type, $desc='', $required=VALUE_REQUIRED,
415 $default=null, $allownull=NULL_ALLOWED) {
416 parent::__construct($desc, $required, $default);
417 $this->type = $type;
418 $this->allownull = $allownull;
423 * Associative array description class
425 * @package core_webservice
426 * @copyright 2009 Petr Skodak
427 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
428 * @since Moodle 2.0
430 class external_single_structure extends external_description {
432 /** @var array Description of array keys key=>external_description */
433 public $keys;
436 * Constructor
438 * @param array $keys
439 * @param string $desc
440 * @param bool $required
441 * @param array $default
442 * @since Moodle 2.0
444 public function __construct(array $keys, $desc='',
445 $required=VALUE_REQUIRED, $default=null) {
446 parent::__construct($desc, $required, $default);
447 $this->keys = $keys;
452 * Bulk array description class.
454 * @package core_webservice
455 * @copyright 2009 Petr Skodak
456 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
457 * @since Moodle 2.0
459 class external_multiple_structure extends external_description {
461 /** @var external_description content */
462 public $content;
465 * Constructor
467 * @param external_description $content
468 * @param string $desc
469 * @param bool $required
470 * @param array $default
471 * @since Moodle 2.0
473 public function __construct(external_description $content, $desc='',
474 $required=VALUE_REQUIRED, $default=null) {
475 parent::__construct($desc, $required, $default);
476 $this->content = $content;
481 * Description of top level - PHP function parameters.
483 * @package core_webservice
484 * @copyright 2009 Petr Skodak
485 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
486 * @since Moodle 2.0
488 class external_function_parameters extends external_single_structure {
492 * Generate a token
494 * @param string $tokentype EXTERNAL_TOKEN_EMBEDDED|EXTERNAL_TOKEN_PERMANENT
495 * @param stdClass|int $serviceorid service linked to the token
496 * @param int $userid user linked to the token
497 * @param stdClass|int $contextorid
498 * @param int $validuntil date when the token expired
499 * @param string $iprestriction allowed ip - if 0 or empty then all ips are allowed
500 * @return string generated token
501 * @author 2010 Jamie Pratt
502 * @since Moodle 2.0
504 function external_generate_token($tokentype, $serviceorid, $userid, $contextorid, $validuntil=0, $iprestriction=''){
505 global $DB, $USER;
506 // make sure the token doesn't exist (even if it should be almost impossible with the random generation)
507 $numtries = 0;
508 do {
509 $numtries ++;
510 $generatedtoken = md5(uniqid(rand(),1));
511 if ($numtries > 5){
512 throw new moodle_exception('tokengenerationfailed');
514 } while ($DB->record_exists('external_tokens', array('token'=>$generatedtoken)));
515 $newtoken = new stdClass();
516 $newtoken->token = $generatedtoken;
517 if (!is_object($serviceorid)){
518 $service = $DB->get_record('external_services', array('id' => $serviceorid));
519 } else {
520 $service = $serviceorid;
522 if (!is_object($contextorid)){
523 $context = get_context_instance_by_id($contextorid, MUST_EXIST);
524 } else {
525 $context = $contextorid;
527 if (empty($service->requiredcapability) || has_capability($service->requiredcapability, $context, $userid)) {
528 $newtoken->externalserviceid = $service->id;
529 } else {
530 throw new moodle_exception('nocapabilitytousethisservice');
532 $newtoken->tokentype = $tokentype;
533 $newtoken->userid = $userid;
534 if ($tokentype == EXTERNAL_TOKEN_EMBEDDED){
535 $newtoken->sid = session_id();
538 $newtoken->contextid = $context->id;
539 $newtoken->creatorid = $USER->id;
540 $newtoken->timecreated = time();
541 $newtoken->validuntil = $validuntil;
542 if (!empty($iprestriction)) {
543 $newtoken->iprestriction = $iprestriction;
545 $DB->insert_record('external_tokens', $newtoken);
546 return $newtoken->token;
550 * Create and return a session linked token. Token to be used for html embedded client apps that want to communicate
551 * with the Moodle server through web services. The token is linked to the current session for the current page request.
552 * It is expected this will be called in the script generating the html page that is embedding the client app and that the
553 * returned token will be somehow passed into the client app being embedded in the page.
555 * @param string $servicename name of the web service. Service name as defined in db/services.php
556 * @param int $context context within which the web service can operate.
557 * @return int returns token id.
558 * @since Moodle 2.0
560 function external_create_service_token($servicename, $context){
561 global $USER, $DB;
562 $service = $DB->get_record('external_services', array('name'=>$servicename), '*', MUST_EXIST);
563 return external_generate_token(EXTERNAL_TOKEN_EMBEDDED, $service, $USER->id, $context, 0);
567 * Delete all pre-built services (+ related tokens) and external functions information defined in the specified component.
569 * @param string $component name of component (moodle, mod_assignment, etc.)
571 function external_delete_descriptions($component) {
572 global $DB;
574 $params = array($component);
576 $DB->delete_records_select('external_tokens',
577 "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
578 $DB->delete_records_select('external_services_users',
579 "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
580 $DB->delete_records_select('external_services_functions',
581 "functionname IN (SELECT name FROM {external_functions} WHERE component = ?)", $params);
582 $DB->delete_records('external_services', array('component'=>$component));
583 $DB->delete_records('external_functions', array('component'=>$component));