2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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();
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
37 function external_function_info($function, $strictness=MUST_EXIST) {
40 if (!is_object($function)) {
41 if (!$function = $DB->get_record('external_functions', array('name'=>$function), '*', $strictness)) {
46 // First try class autoloading.
47 if (!class_exists($function->classname)) {
48 // Fallback to explicit include of externallib.php.
49 $function->classpath = empty($function->classpath) ? core_component::get_component_directory($function->component).'/externallib.php' : $CFG->dirroot.'/'.$function->classpath;
50 if (!file_exists($function->classpath)) {
51 throw new coding_exception('Cannot find file with external function implementation');
53 require_once($function->classpath);
54 if (!class_exists($function->classname)) {
55 throw new coding_exception('Cannot find external class');
59 $function->ajax_method = $function->methodname.'_is_allowed_from_ajax';
60 $function->parameters_method = $function->methodname.'_parameters';
61 $function->returns_method = $function->methodname.'_returns';
62 $function->deprecated_method = $function->methodname.'_is_deprecated';
64 // make sure the implementaion class is ok
65 if (!method_exists($function->classname, $function->methodname)) {
66 throw new coding_exception('Missing implementation method of '.$function->classname.'::'.$function->methodname);
68 if (!method_exists($function->classname, $function->parameters_method)) {
69 throw new coding_exception('Missing parameters description');
71 if (!method_exists($function->classname, $function->returns_method)) {
72 throw new coding_exception('Missing returned values description');
74 if (method_exists($function->classname, $function->deprecated_method)) {
75 if (call_user_func(array($function->classname, $function->deprecated_method)) === true) {
76 $function->deprecated = true;
79 $function->allowed_from_ajax = false;
80 if (method_exists($function->classname, $function->ajax_method)) {
81 if (call_user_func(array($function->classname, $function->ajax_method)) === true) {
82 $function->allowed_from_ajax = true;
86 // fetch the parameters description
87 $function->parameters_desc = call_user_func(array($function->classname, $function->parameters_method));
88 if (!($function->parameters_desc instanceof external_function_parameters)) {
89 throw new coding_exception('Invalid parameters description');
92 // fetch the return values description
93 $function->returns_desc = call_user_func(array($function->classname, $function->returns_method));
94 // null means void result or result is ignored
95 if (!is_null($function->returns_desc) and !($function->returns_desc instanceof external_description)) {
96 throw new coding_exception('Invalid return description');
99 //now get the function description
100 //TODO MDL-31115 use localised lang pack descriptions, it would be nice to have
101 // easy to understand descriptions in admin UI,
102 // on the other hand this is still a bit in a flux and we need to find some new naming
103 // conventions for these descriptions in lang packs
104 $function->description = null;
105 $servicesfile = core_component::get_component_directory($function->component).'/db/services.php';
106 if (file_exists($servicesfile)) {
108 include($servicesfile);
109 if (isset($functions[$function->name]['description'])) {
110 $function->description = $functions[$function->name]['description'];
112 if (isset($functions[$function->name]['testclientpath'])) {
113 $function->testclientpath = $functions[$function->name]['testclientpath'];
115 if (isset($functions[$function->name]['type'])) {
116 $function->type = $functions[$function->name]['type'];
118 if (isset($functions[$function->name]['ajax'])) {
119 $function->allowed_from_ajax = $functions[$function->name]['ajax'];
121 if (isset($functions[$function->name]['loginrequired'])) {
122 $function->loginrequired = $functions[$function->name]['loginrequired'];
124 $function->loginrequired = true;
132 * Exception indicating user is not allowed to use external function in the current context.
134 * @package core_webservice
135 * @copyright 2009 Petr Skodak
136 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
139 class restricted_context_exception extends moodle_exception {
145 function __construct() {
146 parent::__construct('restrictedcontextexception', 'error');
151 * Base class for external api methods.
153 * @package core_webservice
154 * @copyright 2009 Petr Skodak
155 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
160 /** @var stdClass context where the function calls will be restricted */
161 private static $contextrestriction;
164 * Set context restriction for all following subsequent function calls.
166 * @param stdClass $context the context restriction
169 public static function set_context_restriction($context) {
170 self::$contextrestriction = $context;
174 * This method has to be called before every operation
175 * that takes a longer time to finish!
177 * @param int $seconds max expected time the next operation needs
180 public static function set_timeout($seconds=360) {
181 $seconds = ($seconds < 300) ? 300 : $seconds;
182 core_php_time_limit::raise($seconds);
186 * Validates submitted function parameters, if anything is incorrect
187 * invalid_parameter_exception is thrown.
188 * This is a simple recursive method which is intended to be called from
189 * each implementation method of external API.
191 * @param external_description $description description of parameters
192 * @param mixed $params the actual parameters
193 * @return mixed params with added defaults for optional items, invalid_parameters_exception thrown if any problem found
196 public static function validate_parameters(external_description $description, $params) {
197 if ($description instanceof external_value) {
198 if (is_array($params) or is_object($params)) {
199 throw new invalid_parameter_exception('Scalar type expected, array or object received.');
202 if ($description->type == PARAM_BOOL) {
203 // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
204 if (is_bool($params) or $params === 0 or $params === 1 or $params === '0' or $params === '1') {
205 return (bool)$params;
208 $debuginfo = 'Invalid external api parameter: the value is "' . $params .
209 '", the server was expecting "' . $description->type . '" type';
210 return validate_param($params, $description->type, $description->allownull, $debuginfo);
212 } else if ($description instanceof external_single_structure) {
213 if (!is_array($params)) {
214 throw new invalid_parameter_exception('Only arrays accepted. The bad value is: \''
215 . print_r($params, true) . '\'');
218 foreach ($description->keys as $key=>$subdesc) {
219 if (!array_key_exists($key, $params)) {
220 if ($subdesc->required == VALUE_REQUIRED) {
221 throw new invalid_parameter_exception('Missing required key in single structure: '. $key);
223 if ($subdesc->required == VALUE_DEFAULT) {
225 $result[$key] = self::validate_parameters($subdesc, $subdesc->default);
226 } catch (invalid_parameter_exception $e) {
227 //we are only interested by exceptions returned by validate_param() and validate_parameters()
228 //(in order to build the path to the faulty attribut)
229 throw new invalid_parameter_exception($key." => ".$e->getMessage() . ': ' .$e->debuginfo);
234 $result[$key] = self::validate_parameters($subdesc, $params[$key]);
235 } catch (invalid_parameter_exception $e) {
236 //we are only interested by exceptions returned by validate_param() and validate_parameters()
237 //(in order to build the path to the faulty attribut)
238 throw new invalid_parameter_exception($key." => ".$e->getMessage() . ': ' .$e->debuginfo);
241 unset($params[$key]);
243 if (!empty($params)) {
244 throw new invalid_parameter_exception('Unexpected keys (' . implode(', ', array_keys($params)) . ') detected in parameter array.');
248 } else if ($description instanceof external_multiple_structure) {
249 if (!is_array($params)) {
250 throw new invalid_parameter_exception('Only arrays accepted. The bad value is: \''
251 . print_r($params, true) . '\'');
254 foreach ($params as $param) {
255 $result[] = self::validate_parameters($description->content, $param);
260 throw new invalid_parameter_exception('Invalid external api description');
266 * If a response attribute is unknown from the description, we just ignore the attribute.
267 * If a response attribute is incorrect, invalid_response_exception is thrown.
268 * Note: this function is similar to validate parameters, however it is distinct because
269 * parameters validation must be distinct from cleaning return values.
271 * @param external_description $description description of the return values
272 * @param mixed $response the actual response
273 * @return mixed response with added defaults for optional items, invalid_response_exception thrown if any problem found
274 * @author 2010 Jerome Mouneyrac
277 public static function clean_returnvalue(external_description $description, $response) {
278 if ($description instanceof external_value) {
279 if (is_array($response) or is_object($response)) {
280 throw new invalid_response_exception('Scalar type expected, array or object received.');
283 if ($description->type == PARAM_BOOL) {
284 // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
285 if (is_bool($response) or $response === 0 or $response === 1 or $response === '0' or $response === '1') {
286 return (bool)$response;
289 $debuginfo = 'Invalid external api response: the value is "' . $response .
290 '", the server was expecting "' . $description->type . '" type';
292 return validate_param($response, $description->type, $description->allownull, $debuginfo);
293 } catch (invalid_parameter_exception $e) {
294 //proper exception name, to be recursively catched to build the path to the faulty attribut
295 throw new invalid_response_exception($e->debuginfo);
298 } else if ($description instanceof external_single_structure) {
299 if (!is_array($response) && !is_object($response)) {
300 throw new invalid_response_exception('Only arrays/objects accepted. The bad value is: \'' .
301 print_r($response, true) . '\'');
304 // Cast objects into arrays.
305 if (is_object($response)) {
306 $response = (array) $response;
310 foreach ($description->keys as $key=>$subdesc) {
311 if (!array_key_exists($key, $response)) {
312 if ($subdesc->required == VALUE_REQUIRED) {
313 throw new invalid_response_exception('Error in response - Missing following required key in a single structure: ' . $key);
315 if ($subdesc instanceof external_value) {
316 if ($subdesc->required == VALUE_DEFAULT) {
318 $result[$key] = self::clean_returnvalue($subdesc, $subdesc->default);
319 } catch (invalid_response_exception $e) {
320 //build the path to the faulty attribut
321 throw new invalid_response_exception($key." => ".$e->getMessage() . ': ' . $e->debuginfo);
327 $result[$key] = self::clean_returnvalue($subdesc, $response[$key]);
328 } catch (invalid_response_exception $e) {
329 //build the path to the faulty attribut
330 throw new invalid_response_exception($key." => ".$e->getMessage() . ': ' . $e->debuginfo);
333 unset($response[$key]);
338 } else if ($description instanceof external_multiple_structure) {
339 if (!is_array($response)) {
340 throw new invalid_response_exception('Only arrays accepted. The bad value is: \'' .
341 print_r($response, true) . '\'');
344 foreach ($response as $param) {
345 $result[] = self::clean_returnvalue($description->content, $param);
350 throw new invalid_response_exception('Invalid external api response description');
355 * Makes sure user may execute functions in this context.
357 * @param stdClass $context
360 protected static function validate_context($context) {
363 if (empty($context)) {
364 throw new invalid_parameter_exception('Context does not exist');
366 if (empty(self::$contextrestriction)) {
367 self::$contextrestriction = context_system::instance();
369 $rcontext = self::$contextrestriction;
371 if ($rcontext->contextlevel == $context->contextlevel) {
372 if ($rcontext->id != $context->id) {
373 throw new restricted_context_exception();
375 } else if ($rcontext->contextlevel > $context->contextlevel) {
376 throw new restricted_context_exception();
378 $parents = $context->get_parent_context_ids();
379 if (!in_array($rcontext->id, $parents)) {
380 throw new restricted_context_exception();
384 if ($context->contextlevel >= CONTEXT_COURSE) {
385 list($context, $course, $cm) = get_context_info_array($context->id);
386 require_login($course, false, $cm, false, true);
391 * Get context from passed parameters.
392 * The passed array must either contain a contextid or a combination of context level and instance id to fetch the context.
393 * For example, the context level can be "course" and instanceid can be courseid.
395 * See context_helper::get_all_levels() for a list of valid context levels.
397 * @param array $param
399 * @throws invalid_parameter_exception
402 protected static function get_context_from_params($param) {
403 $levels = context_helper::get_all_levels();
404 if (!empty($param['contextid'])) {
405 return context::instance_by_id($param['contextid'], IGNORE_MISSING);
406 } else if (!empty($param['contextlevel']) && isset($param['instanceid'])) {
407 $contextlevel = "context_".$param['contextlevel'];
408 if (!array_search($contextlevel, $levels)) {
409 throw new invalid_parameter_exception('Invalid context level = '.$param['contextlevel']);
411 return $contextlevel::instance($param['instanceid'], IGNORE_MISSING);
413 // No valid context info was found.
414 throw new invalid_parameter_exception('Missing parameters, please provide either context level with instance id or contextid');
420 * Common ancestor of all parameter description classes
422 * @package core_webservice
423 * @copyright 2009 Petr Skodak
424 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
427 abstract class external_description {
428 /** @var string Description of element */
431 /** @var bool Element value required, null not allowed */
434 /** @var mixed Default value */
440 * @param string $desc
441 * @param bool $required
442 * @param mixed $default
445 public function __construct($desc, $required, $default) {
447 $this->required = $required;
448 $this->default = $default;
453 * Scalar value description class
455 * @package core_webservice
456 * @copyright 2009 Petr Skodak
457 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
460 class external_value extends external_description {
462 /** @var mixed Value type PARAM_XX */
465 /** @var bool Allow null values */
472 * @param string $desc
473 * @param bool $required
474 * @param mixed $default
475 * @param bool $allownull
478 public function __construct($type, $desc='', $required=VALUE_REQUIRED,
479 $default=null, $allownull=NULL_ALLOWED) {
480 parent::__construct($desc, $required, $default);
482 $this->allownull = $allownull;
487 * Associative array description class
489 * @package core_webservice
490 * @copyright 2009 Petr Skodak
491 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
494 class external_single_structure extends external_description {
496 /** @var array Description of array keys key=>external_description */
503 * @param string $desc
504 * @param bool $required
505 * @param array $default
508 public function __construct(array $keys, $desc='',
509 $required=VALUE_REQUIRED, $default=null) {
510 parent::__construct($desc, $required, $default);
516 * Bulk array description class.
518 * @package core_webservice
519 * @copyright 2009 Petr Skodak
520 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
523 class external_multiple_structure extends external_description {
525 /** @var external_description content */
531 * @param external_description $content
532 * @param string $desc
533 * @param bool $required
534 * @param array $default
537 public function __construct(external_description $content, $desc='',
538 $required=VALUE_REQUIRED, $default=null) {
539 parent::__construct($desc, $required, $default);
540 $this->content = $content;
545 * Description of top level - PHP function parameters.
547 * @package core_webservice
548 * @copyright 2009 Petr Skodak
549 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
552 class external_function_parameters extends external_single_structure {
558 * @param string $tokentype EXTERNAL_TOKEN_EMBEDDED|EXTERNAL_TOKEN_PERMANENT
559 * @param stdClass|int $serviceorid service linked to the token
560 * @param int $userid user linked to the token
561 * @param stdClass|int $contextorid
562 * @param int $validuntil date when the token expired
563 * @param string $iprestriction allowed ip - if 0 or empty then all ips are allowed
564 * @return string generated token
565 * @author 2010 Jamie Pratt
568 function external_generate_token($tokentype, $serviceorid, $userid, $contextorid, $validuntil=0, $iprestriction=''){
570 // make sure the token doesn't exist (even if it should be almost impossible with the random generation)
574 $generatedtoken = md5(uniqid(rand(),1));
576 throw new moodle_exception('tokengenerationfailed');
578 } while ($DB->record_exists('external_tokens', array('token'=>$generatedtoken)));
579 $newtoken = new stdClass();
580 $newtoken->token = $generatedtoken;
581 if (!is_object($serviceorid)){
582 $service = $DB->get_record('external_services', array('id' => $serviceorid));
584 $service = $serviceorid;
586 if (!is_object($contextorid)){
587 $context = context::instance_by_id($contextorid, MUST_EXIST);
589 $context = $contextorid;
591 if (empty($service->requiredcapability) || has_capability($service->requiredcapability, $context, $userid)) {
592 $newtoken->externalserviceid = $service->id;
594 throw new moodle_exception('nocapabilitytousethisservice');
596 $newtoken->tokentype = $tokentype;
597 $newtoken->userid = $userid;
598 if ($tokentype == EXTERNAL_TOKEN_EMBEDDED){
599 $newtoken->sid = session_id();
602 $newtoken->contextid = $context->id;
603 $newtoken->creatorid = $USER->id;
604 $newtoken->timecreated = time();
605 $newtoken->validuntil = $validuntil;
606 if (!empty($iprestriction)) {
607 $newtoken->iprestriction = $iprestriction;
609 $DB->insert_record('external_tokens', $newtoken);
610 return $newtoken->token;
614 * Create and return a session linked token. Token to be used for html embedded client apps that want to communicate
615 * with the Moodle server through web services. The token is linked to the current session for the current page request.
616 * It is expected this will be called in the script generating the html page that is embedding the client app and that the
617 * returned token will be somehow passed into the client app being embedded in the page.
619 * @param string $servicename name of the web service. Service name as defined in db/services.php
620 * @param int $context context within which the web service can operate.
621 * @return int returns token id.
624 function external_create_service_token($servicename, $context){
626 $service = $DB->get_record('external_services', array('name'=>$servicename), '*', MUST_EXIST);
627 return external_generate_token(EXTERNAL_TOKEN_EMBEDDED, $service, $USER->id, $context, 0);
631 * Delete all pre-built services (+ related tokens) and external functions information defined in the specified component.
633 * @param string $component name of component (moodle, mod_assignment, etc.)
635 function external_delete_descriptions($component) {
638 $params = array($component);
640 $DB->delete_records_select('external_tokens',
641 "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
642 $DB->delete_records_select('external_services_users',
643 "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
644 $DB->delete_records_select('external_services_functions',
645 "functionname IN (SELECT name FROM {external_functions} WHERE component = ?)", $params);
646 $DB->delete_records('external_services', array('component'=>$component));
647 $DB->delete_records('external_functions', array('component'=>$component));
651 * Standard Moodle web service warnings
653 * @package core_webservice
654 * @copyright 2012 Jerome Mouneyrac
655 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
658 class external_warnings extends external_multiple_structure {
665 public function __construct($itemdesc = 'item', $itemiddesc = 'item id',
666 $warningcodedesc = 'the warning code can be used by the client app to implement specific behaviour') {
669 new external_single_structure(
671 'item' => new external_value(PARAM_TEXT, $itemdesc, VALUE_OPTIONAL),
672 'itemid' => new external_value(PARAM_INT, $itemiddesc, VALUE_OPTIONAL),
673 'warningcode' => new external_value(PARAM_ALPHANUM, $warningcodedesc),
674 'message' => new external_value(PARAM_TEXT,
675 'untranslated english message to explain the warning')
677 'list of warnings', VALUE_OPTIONAL);
682 * A pre-filled external_value class for text format.
684 * Default is FORMAT_HTML
685 * This should be used all the time in external xxx_params()/xxx_returns functions
686 * as it is the standard way to implement text format param/return values.
688 * @package core_webservice
689 * @copyright 2012 Jerome Mouneyrac
690 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
693 class external_format_value extends external_value {
698 * @param string $textfieldname Name of the text field
699 * @param int $required if VALUE_REQUIRED then set standard default FORMAT_HTML
702 public function __construct($textfieldname, $required = VALUE_REQUIRED) {
704 $default = ($required == VALUE_DEFAULT) ? FORMAT_HTML : null;
706 $desc = $textfieldname . ' format (' . FORMAT_HTML . ' = HTML, '
707 . FORMAT_MOODLE . ' = MOODLE, '
708 . FORMAT_PLAIN . ' = PLAIN or '
709 . FORMAT_MARKDOWN . ' = MARKDOWN)';
711 parent::__construct(PARAM_INT, $desc, $required, $default);
716 * Validate text field format against known FORMAT_XXX
718 * @param array $format the format to validate
719 * @return the validated format
720 * @throws coding_exception
723 function external_validate_format($format) {
724 $allowedformats = array(FORMAT_HTML, FORMAT_MOODLE, FORMAT_PLAIN, FORMAT_MARKDOWN);
725 if (!in_array($format, $allowedformats)) {
726 throw new moodle_exception('formatnotsupported', 'webservice', '' , null,
727 'The format with value=' . $format . ' is not supported by this Moodle site');
733 * Format the text to be returned properly as requested by the either the web service server,
734 * either by an internally call.
735 * The caller can change the format (raw, filter, file, fileurl) with the external_settings singleton
736 * All web service servers must set this singleton when parsing the $_GET and $_POST.
738 * @param string $text The content that may contain ULRs in need of rewriting.
739 * @param int $textformat The text format.
740 * @param int $contextid This parameter and the next two identify the file area to use.
741 * @param string $component
742 * @param string $filearea helps identify the file area.
743 * @param int $itemid helps identify the file area.
744 * @return array text + textformat
747 function external_format_text($text, $textformat, $contextid, $component, $filearea, $itemid) {
750 // Get settings (singleton).
751 $settings = external_settings::get_instance();
753 if ($settings->get_fileurl()) {
754 require_once($CFG->libdir . "/filelib.php");
755 $text = file_rewrite_pluginfile_urls($text, $settings->get_file(), $contextid, $component, $filearea, $itemid);
758 if (!$settings->get_raw()) {
759 $text = format_text($text, $textformat, array('para' => false, 'filter' => $settings->get_filter()));
760 $textformat = FORMAT_HTML; // Once converted to html (from markdown, plain... lets inform consumer this is already HTML).
763 return array($text, $textformat);
767 * Singleton to handle the external settings.
769 * We use singleton to encapsulate the "logic"
771 * @package core_webservice
772 * @copyright 2012 Jerome Mouneyrac
773 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
776 class external_settings {
778 /** @var object the singleton instance */
779 public static $instance = null;
781 /** @var boolean Should the external function return raw text or formatted */
782 private $raw = false;
784 /** @var boolean Should the external function filter the text */
785 private $filter = false;
787 /** @var boolean Should the external function rewrite plugin file url */
788 private $fileurl = true;
790 /** @var string In which file should the urls be rewritten */
791 private $file = 'webservice/pluginfile.php';
794 * Constructor - protected - can not be instanciated
796 protected function __construct() {
800 * Clone - private - can not be cloned
802 private final function __clone() {
806 * Return only one instance
810 public static function get_instance() {
811 if (self::$instance === null) {
812 self::$instance = new external_settings;
815 return self::$instance;
821 * @param boolean $raw
823 public function set_raw($raw) {
832 public function get_raw() {
839 * @param boolean $filter
841 public function set_filter($filter) {
842 $this->filter = $filter;
850 public function get_filter() {
851 return $this->filter;
857 * @param boolean $fileurl
859 public function set_fileurl($fileurl) {
860 $this->fileurl = $fileurl;
868 public function get_fileurl() {
869 return $this->fileurl;
875 * @param string $file
877 public function set_file($file) {
886 public function get_file() {