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'];
121 * Exception indicating user is not allowed to use external function in the current context.
123 * @package core_webservice
124 * @copyright 2009 Petr Skodak
125 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
128 class restricted_context_exception
extends moodle_exception
{
134 function __construct() {
135 parent
::__construct('restrictedcontextexception', 'error');
140 * Base class for external api methods.
142 * @package core_webservice
143 * @copyright 2009 Petr Skodak
144 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
149 /** @var stdClass context where the function calls will be restricted */
150 private static $contextrestriction;
153 * Set context restriction for all following subsequent function calls.
155 * @param stdClass $context the context restriction
158 public static function set_context_restriction($context) {
159 self
::$contextrestriction = $context;
163 * This method has to be called before every operation
164 * that takes a longer time to finish!
166 * @param int $seconds max expected time the next operation needs
169 public static function set_timeout($seconds=360) {
170 $seconds = ($seconds < 300) ?
300 : $seconds;
171 core_php_time_limit
::raise($seconds);
175 * Validates submitted function parameters, if anything is incorrect
176 * invalid_parameter_exception is thrown.
177 * This is a simple recursive method which is intended to be called from
178 * each implementation method of external API.
180 * @param external_description $description description of parameters
181 * @param mixed $params the actual parameters
182 * @return mixed params with added defaults for optional items, invalid_parameters_exception thrown if any problem found
185 public static function validate_parameters(external_description
$description, $params) {
186 if ($description instanceof external_value
) {
187 if (is_array($params) or is_object($params)) {
188 throw new invalid_parameter_exception('Scalar type expected, array or object received.');
191 if ($description->type
== PARAM_BOOL
) {
192 // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
193 if (is_bool($params) or $params === 0 or $params === 1 or $params === '0' or $params === '1') {
194 return (bool)$params;
197 $debuginfo = 'Invalid external api parameter: the value is "' . $params .
198 '", the server was expecting "' . $description->type
. '" type';
199 return validate_param($params, $description->type
, $description->allownull
, $debuginfo);
201 } else if ($description instanceof external_single_structure
) {
202 if (!is_array($params)) {
203 throw new invalid_parameter_exception('Only arrays accepted. The bad value is: \''
204 . print_r($params, true) . '\'');
207 foreach ($description->keys
as $key=>$subdesc) {
208 if (!array_key_exists($key, $params)) {
209 if ($subdesc->required
== VALUE_REQUIRED
) {
210 throw new invalid_parameter_exception('Missing required key in single structure: '. $key);
212 if ($subdesc->required
== VALUE_DEFAULT
) {
214 $result[$key] = self
::validate_parameters($subdesc, $subdesc->default);
215 } catch (invalid_parameter_exception
$e) {
216 //we are only interested by exceptions returned by validate_param() and validate_parameters()
217 //(in order to build the path to the faulty attribut)
218 throw new invalid_parameter_exception($key." => ".$e->getMessage() . ': ' .$e->debuginfo
);
223 $result[$key] = self
::validate_parameters($subdesc, $params[$key]);
224 } catch (invalid_parameter_exception
$e) {
225 //we are only interested by exceptions returned by validate_param() and validate_parameters()
226 //(in order to build the path to the faulty attribut)
227 throw new invalid_parameter_exception($key." => ".$e->getMessage() . ': ' .$e->debuginfo
);
230 unset($params[$key]);
232 if (!empty($params)) {
233 throw new invalid_parameter_exception('Unexpected keys (' . implode(', ', array_keys($params)) . ') detected in parameter array.');
237 } else if ($description instanceof external_multiple_structure
) {
238 if (!is_array($params)) {
239 throw new invalid_parameter_exception('Only arrays accepted. The bad value is: \''
240 . print_r($params, true) . '\'');
243 foreach ($params as $param) {
244 $result[] = self
::validate_parameters($description->content
, $param);
249 throw new invalid_parameter_exception('Invalid external api description');
255 * If a response attribute is unknown from the description, we just ignore the attribute.
256 * If a response attribute is incorrect, invalid_response_exception is thrown.
257 * Note: this function is similar to validate parameters, however it is distinct because
258 * parameters validation must be distinct from cleaning return values.
260 * @param external_description $description description of the return values
261 * @param mixed $response the actual response
262 * @return mixed response with added defaults for optional items, invalid_response_exception thrown if any problem found
263 * @author 2010 Jerome Mouneyrac
266 public static function clean_returnvalue(external_description
$description, $response) {
267 if ($description instanceof external_value
) {
268 if (is_array($response) or is_object($response)) {
269 throw new invalid_response_exception('Scalar type expected, array or object received.');
272 if ($description->type
== PARAM_BOOL
) {
273 // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
274 if (is_bool($response) or $response === 0 or $response === 1 or $response === '0' or $response === '1') {
275 return (bool)$response;
278 $debuginfo = 'Invalid external api response: the value is "' . $response .
279 '", the server was expecting "' . $description->type
. '" type';
281 return validate_param($response, $description->type
, $description->allownull
, $debuginfo);
282 } catch (invalid_parameter_exception
$e) {
283 //proper exception name, to be recursively catched to build the path to the faulty attribut
284 throw new invalid_response_exception($e->debuginfo
);
287 } else if ($description instanceof external_single_structure
) {
288 if (!is_array($response) && !is_object($response)) {
289 throw new invalid_response_exception('Only arrays/objects accepted. The bad value is: \'' .
290 print_r($response, true) . '\'');
293 // Cast objects into arrays.
294 if (is_object($response)) {
295 $response = (array) $response;
299 foreach ($description->keys
as $key=>$subdesc) {
300 if (!array_key_exists($key, $response)) {
301 if ($subdesc->required
== VALUE_REQUIRED
) {
302 throw new invalid_response_exception('Error in response - Missing following required key in a single structure: ' . $key);
304 if ($subdesc instanceof external_value
) {
305 if ($subdesc->required
== VALUE_DEFAULT
) {
307 $result[$key] = self
::clean_returnvalue($subdesc, $subdesc->default);
308 } catch (invalid_response_exception
$e) {
309 //build the path to the faulty attribut
310 throw new invalid_response_exception($key." => ".$e->getMessage() . ': ' . $e->debuginfo
);
316 $result[$key] = self
::clean_returnvalue($subdesc, $response[$key]);
317 } catch (invalid_response_exception
$e) {
318 //build the path to the faulty attribut
319 throw new invalid_response_exception($key." => ".$e->getMessage() . ': ' . $e->debuginfo
);
322 unset($response[$key]);
327 } else if ($description instanceof external_multiple_structure
) {
328 if (!is_array($response)) {
329 throw new invalid_response_exception('Only arrays accepted. The bad value is: \'' .
330 print_r($response, true) . '\'');
333 foreach ($response as $param) {
334 $result[] = self
::clean_returnvalue($description->content
, $param);
339 throw new invalid_response_exception('Invalid external api response description');
344 * Makes sure user may execute functions in this context.
346 * @param stdClass $context
349 protected static function validate_context($context) {
352 if (empty($context)) {
353 throw new invalid_parameter_exception('Context does not exist');
355 if (empty(self
::$contextrestriction)) {
356 self
::$contextrestriction = context_system
::instance();
358 $rcontext = self
::$contextrestriction;
360 if ($rcontext->contextlevel
== $context->contextlevel
) {
361 if ($rcontext->id
!= $context->id
) {
362 throw new restricted_context_exception();
364 } else if ($rcontext->contextlevel
> $context->contextlevel
) {
365 throw new restricted_context_exception();
367 $parents = $context->get_parent_context_ids();
368 if (!in_array($rcontext->id
, $parents)) {
369 throw new restricted_context_exception();
373 if ($context->contextlevel
>= CONTEXT_COURSE
) {
374 list($context, $course, $cm) = get_context_info_array($context->id
);
375 require_login($course, false, $cm, false, true);
380 * Get context from passed parameters.
381 * The passed array must either contain a contextid or a combination of context level and instance id to fetch the context.
382 * For example, the context level can be "course" and instanceid can be courseid.
384 * See context_helper::get_all_levels() for a list of valid context levels.
386 * @param array $param
388 * @throws invalid_parameter_exception
391 protected static function get_context_from_params($param) {
392 $levels = context_helper
::get_all_levels();
393 if (!empty($param['contextid'])) {
394 return context
::instance_by_id($param['contextid'], IGNORE_MISSING
);
395 } else if (!empty($param['contextlevel']) && isset($param['instanceid'])) {
396 $contextlevel = "context_".$param['contextlevel'];
397 if (!array_search($contextlevel, $levels)) {
398 throw new invalid_parameter_exception('Invalid context level = '.$param['contextlevel']);
400 return $contextlevel::instance($param['instanceid'], IGNORE_MISSING
);
402 // No valid context info was found.
403 throw new invalid_parameter_exception('Missing parameters, please provide either context level with instance id or contextid');
409 * Common ancestor of all parameter description classes
411 * @package core_webservice
412 * @copyright 2009 Petr Skodak
413 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
416 abstract class external_description
{
417 /** @var string Description of element */
420 /** @var bool Element value required, null not allowed */
423 /** @var mixed Default value */
429 * @param string $desc
430 * @param bool $required
431 * @param mixed $default
434 public function __construct($desc, $required, $default) {
436 $this->required
= $required;
437 $this->default = $default;
442 * Scalar value description class
444 * @package core_webservice
445 * @copyright 2009 Petr Skodak
446 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
449 class external_value
extends external_description
{
451 /** @var mixed Value type PARAM_XX */
454 /** @var bool Allow null values */
461 * @param string $desc
462 * @param bool $required
463 * @param mixed $default
464 * @param bool $allownull
467 public function __construct($type, $desc='', $required=VALUE_REQUIRED
,
468 $default=null, $allownull=NULL_ALLOWED
) {
469 parent
::__construct($desc, $required, $default);
471 $this->allownull
= $allownull;
476 * Associative array description class
478 * @package core_webservice
479 * @copyright 2009 Petr Skodak
480 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
483 class external_single_structure
extends external_description
{
485 /** @var array Description of array keys key=>external_description */
492 * @param string $desc
493 * @param bool $required
494 * @param array $default
497 public function __construct(array $keys, $desc='',
498 $required=VALUE_REQUIRED
, $default=null) {
499 parent
::__construct($desc, $required, $default);
505 * Bulk array description class.
507 * @package core_webservice
508 * @copyright 2009 Petr Skodak
509 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
512 class external_multiple_structure
extends external_description
{
514 /** @var external_description content */
520 * @param external_description $content
521 * @param string $desc
522 * @param bool $required
523 * @param array $default
526 public function __construct(external_description
$content, $desc='',
527 $required=VALUE_REQUIRED
, $default=null) {
528 parent
::__construct($desc, $required, $default);
529 $this->content
= $content;
534 * Description of top level - PHP function parameters.
536 * @package core_webservice
537 * @copyright 2009 Petr Skodak
538 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
541 class external_function_parameters
extends external_single_structure
{
547 * @param string $tokentype EXTERNAL_TOKEN_EMBEDDED|EXTERNAL_TOKEN_PERMANENT
548 * @param stdClass|int $serviceorid service linked to the token
549 * @param int $userid user linked to the token
550 * @param stdClass|int $contextorid
551 * @param int $validuntil date when the token expired
552 * @param string $iprestriction allowed ip - if 0 or empty then all ips are allowed
553 * @return string generated token
554 * @author 2010 Jamie Pratt
557 function external_generate_token($tokentype, $serviceorid, $userid, $contextorid, $validuntil=0, $iprestriction=''){
559 // make sure the token doesn't exist (even if it should be almost impossible with the random generation)
563 $generatedtoken = md5(uniqid(rand(),1));
565 throw new moodle_exception('tokengenerationfailed');
567 } while ($DB->record_exists('external_tokens', array('token'=>$generatedtoken)));
568 $newtoken = new stdClass();
569 $newtoken->token
= $generatedtoken;
570 if (!is_object($serviceorid)){
571 $service = $DB->get_record('external_services', array('id' => $serviceorid));
573 $service = $serviceorid;
575 if (!is_object($contextorid)){
576 $context = context
::instance_by_id($contextorid, MUST_EXIST
);
578 $context = $contextorid;
580 if (empty($service->requiredcapability
) ||
has_capability($service->requiredcapability
, $context, $userid)) {
581 $newtoken->externalserviceid
= $service->id
;
583 throw new moodle_exception('nocapabilitytousethisservice');
585 $newtoken->tokentype
= $tokentype;
586 $newtoken->userid
= $userid;
587 if ($tokentype == EXTERNAL_TOKEN_EMBEDDED
){
588 $newtoken->sid
= session_id();
591 $newtoken->contextid
= $context->id
;
592 $newtoken->creatorid
= $USER->id
;
593 $newtoken->timecreated
= time();
594 $newtoken->validuntil
= $validuntil;
595 if (!empty($iprestriction)) {
596 $newtoken->iprestriction
= $iprestriction;
598 $DB->insert_record('external_tokens', $newtoken);
599 return $newtoken->token
;
603 * Create and return a session linked token. Token to be used for html embedded client apps that want to communicate
604 * with the Moodle server through web services. The token is linked to the current session for the current page request.
605 * It is expected this will be called in the script generating the html page that is embedding the client app and that the
606 * returned token will be somehow passed into the client app being embedded in the page.
608 * @param string $servicename name of the web service. Service name as defined in db/services.php
609 * @param int $context context within which the web service can operate.
610 * @return int returns token id.
613 function external_create_service_token($servicename, $context){
615 $service = $DB->get_record('external_services', array('name'=>$servicename), '*', MUST_EXIST
);
616 return external_generate_token(EXTERNAL_TOKEN_EMBEDDED
, $service, $USER->id
, $context, 0);
620 * Delete all pre-built services (+ related tokens) and external functions information defined in the specified component.
622 * @param string $component name of component (moodle, mod_assignment, etc.)
624 function external_delete_descriptions($component) {
627 $params = array($component);
629 $DB->delete_records_select('external_tokens',
630 "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
631 $DB->delete_records_select('external_services_users',
632 "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
633 $DB->delete_records_select('external_services_functions',
634 "functionname IN (SELECT name FROM {external_functions} WHERE component = ?)", $params);
635 $DB->delete_records('external_services', array('component'=>$component));
636 $DB->delete_records('external_functions', array('component'=>$component));
640 * Standard Moodle web service warnings
642 * @package core_webservice
643 * @copyright 2012 Jerome Mouneyrac
644 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
647 class external_warnings
extends external_multiple_structure
{
654 public function __construct($itemdesc = 'item', $itemiddesc = 'item id',
655 $warningcodedesc = 'the warning code can be used by the client app to implement specific behaviour') {
658 new external_single_structure(
660 'item' => new external_value(PARAM_TEXT
, $itemdesc, VALUE_OPTIONAL
),
661 'itemid' => new external_value(PARAM_INT
, $itemiddesc, VALUE_OPTIONAL
),
662 'warningcode' => new external_value(PARAM_ALPHANUM
, $warningcodedesc),
663 'message' => new external_value(PARAM_TEXT
,
664 'untranslated english message to explain the warning')
666 'list of warnings', VALUE_OPTIONAL
);
671 * A pre-filled external_value class for text format.
673 * Default is FORMAT_HTML
674 * This should be used all the time in external xxx_params()/xxx_returns functions
675 * as it is the standard way to implement text format param/return values.
677 * @package core_webservice
678 * @copyright 2012 Jerome Mouneyrac
679 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
682 class external_format_value
extends external_value
{
687 * @param string $textfieldname Name of the text field
688 * @param int $required if VALUE_REQUIRED then set standard default FORMAT_HTML
691 public function __construct($textfieldname, $required = VALUE_REQUIRED
) {
693 $default = ($required == VALUE_DEFAULT
) ? FORMAT_HTML
: null;
695 $desc = $textfieldname . ' format (' . FORMAT_HTML
. ' = HTML, '
696 . FORMAT_MOODLE
. ' = MOODLE, '
697 . FORMAT_PLAIN
. ' = PLAIN or '
698 . FORMAT_MARKDOWN
. ' = MARKDOWN)';
700 parent
::__construct(PARAM_INT
, $desc, $required, $default);
705 * Validate text field format against known FORMAT_XXX
707 * @param array $format the format to validate
708 * @return the validated format
709 * @throws coding_exception
712 function external_validate_format($format) {
713 $allowedformats = array(FORMAT_HTML
, FORMAT_MOODLE
, FORMAT_PLAIN
, FORMAT_MARKDOWN
);
714 if (!in_array($format, $allowedformats)) {
715 throw new moodle_exception('formatnotsupported', 'webservice', '' , null,
716 'The format with value=' . $format . ' is not supported by this Moodle site');
722 * Format the text to be returned properly as requested by the either the web service server,
723 * either by an internally call.
724 * The caller can change the format (raw, filter, file, fileurl) with the external_settings singleton
725 * All web service servers must set this singleton when parsing the $_GET and $_POST.
727 * @param string $text The content that may contain ULRs in need of rewriting.
728 * @param int $textformat The text format.
729 * @param int $contextid This parameter and the next two identify the file area to use.
730 * @param string $component
731 * @param string $filearea helps identify the file area.
732 * @param int $itemid helps identify the file area.
733 * @return array text + textformat
736 function external_format_text($text, $textformat, $contextid, $component, $filearea, $itemid) {
739 // Get settings (singleton).
740 $settings = external_settings
::get_instance();
742 if ($settings->get_fileurl()) {
743 require_once($CFG->libdir
. "/filelib.php");
744 $text = file_rewrite_pluginfile_urls($text, $settings->get_file(), $contextid, $component, $filearea, $itemid);
747 if (!$settings->get_raw()) {
748 $text = format_text($text, $textformat, array('para' => false, 'filter' => $settings->get_filter()));
749 $textformat = FORMAT_HTML
; // Once converted to html (from markdown, plain... lets inform consumer this is already HTML).
752 return array($text, $textformat);
756 * Singleton to handle the external settings.
758 * We use singleton to encapsulate the "logic"
760 * @package core_webservice
761 * @copyright 2012 Jerome Mouneyrac
762 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
765 class external_settings
{
767 /** @var object the singleton instance */
768 public static $instance = null;
770 /** @var boolean Should the external function return raw text or formatted */
771 private $raw = false;
773 /** @var boolean Should the external function filter the text */
774 private $filter = false;
776 /** @var boolean Should the external function rewrite plugin file url */
777 private $fileurl = true;
779 /** @var string In which file should the urls be rewritten */
780 private $file = 'webservice/pluginfile.php';
783 * Constructor - protected - can not be instanciated
785 protected function __construct() {
789 * Clone - private - can not be cloned
791 private final function __clone() {
795 * Return only one instance
799 public static function get_instance() {
800 if (self
::$instance === null) {
801 self
::$instance = new external_settings
;
804 return self
::$instance;
810 * @param boolean $raw
812 public function set_raw($raw) {
821 public function get_raw() {
828 * @param boolean $filter
830 public function set_filter($filter) {
831 $this->filter
= $filter;
839 public function get_filter() {
840 return $this->filter
;
846 * @param boolean $fileurl
848 public function set_fileurl($fileurl) {
849 $this->fileurl
= $fileurl;
857 public function get_fileurl() {
858 return $this->fileurl
;
864 * @param string $file
866 public function set_file($file) {
875 public function get_file() {