MDL-51177 core: Ignore built files in stylelint
[moodle.git] / lib / externallib.php
blob50a88f1b07874e85e79cfa8355e93b23012166f5
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 * Exception indicating user is not allowed to use external function in the current context.
31 * @package core_webservice
32 * @copyright 2009 Petr Skodak
33 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
34 * @since Moodle 2.0
36 class restricted_context_exception extends moodle_exception {
37 /**
38 * Constructor
40 * @since Moodle 2.0
42 function __construct() {
43 parent::__construct('restrictedcontextexception', 'error');
47 /**
48 * Base class for external api methods.
50 * @package core_webservice
51 * @copyright 2009 Petr Skodak
52 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
53 * @since Moodle 2.0
55 class external_api {
57 /** @var stdClass context where the function calls will be restricted */
58 private static $contextrestriction;
60 /**
61 * Returns detailed function information
63 * @param string|object $function name of external function or record from external_function
64 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
65 * MUST_EXIST means throw exception if no record or multiple records found
66 * @return stdClass description or false if not found or exception thrown
67 * @since Moodle 2.0
69 public static function external_function_info($function, $strictness=MUST_EXIST) {
70 global $DB, $CFG;
72 if (!is_object($function)) {
73 if (!$function = $DB->get_record('external_functions', array('name' => $function), '*', $strictness)) {
74 return false;
78 // First try class autoloading.
79 if (!class_exists($function->classname)) {
80 // Fallback to explicit include of externallib.php.
81 if (empty($function->classpath)) {
82 $function->classpath = core_component::get_component_directory($function->component).'/externallib.php';
83 } else {
84 $function->classpath = $CFG->dirroot.'/'.$function->classpath;
86 if (!file_exists($function->classpath)) {
87 throw new coding_exception('Cannot find file with external function implementation');
89 require_once($function->classpath);
90 if (!class_exists($function->classname)) {
91 throw new coding_exception('Cannot find external class');
95 $function->ajax_method = $function->methodname.'_is_allowed_from_ajax';
96 $function->parameters_method = $function->methodname.'_parameters';
97 $function->returns_method = $function->methodname.'_returns';
98 $function->deprecated_method = $function->methodname.'_is_deprecated';
100 // Make sure the implementaion class is ok.
101 if (!method_exists($function->classname, $function->methodname)) {
102 throw new coding_exception('Missing implementation method of '.$function->classname.'::'.$function->methodname);
104 if (!method_exists($function->classname, $function->parameters_method)) {
105 throw new coding_exception('Missing parameters description');
107 if (!method_exists($function->classname, $function->returns_method)) {
108 throw new coding_exception('Missing returned values description');
110 if (method_exists($function->classname, $function->deprecated_method)) {
111 if (call_user_func(array($function->classname, $function->deprecated_method)) === true) {
112 $function->deprecated = true;
115 $function->allowed_from_ajax = false;
117 // Fetch the parameters description.
118 $function->parameters_desc = call_user_func(array($function->classname, $function->parameters_method));
119 if (!($function->parameters_desc instanceof external_function_parameters)) {
120 throw new coding_exception('Invalid parameters description');
123 // Fetch the return values description.
124 $function->returns_desc = call_user_func(array($function->classname, $function->returns_method));
125 // Null means void result or result is ignored.
126 if (!is_null($function->returns_desc) and !($function->returns_desc instanceof external_description)) {
127 throw new coding_exception('Invalid return description');
130 // Now get the function description.
132 // TODO MDL-31115 use localised lang pack descriptions, it would be nice to have
133 // easy to understand descriptions in admin UI,
134 // on the other hand this is still a bit in a flux and we need to find some new naming
135 // conventions for these descriptions in lang packs.
136 $function->description = null;
137 $servicesfile = core_component::get_component_directory($function->component).'/db/services.php';
138 if (file_exists($servicesfile)) {
139 $functions = null;
140 include($servicesfile);
141 if (isset($functions[$function->name]['description'])) {
142 $function->description = $functions[$function->name]['description'];
144 if (isset($functions[$function->name]['testclientpath'])) {
145 $function->testclientpath = $functions[$function->name]['testclientpath'];
147 if (isset($functions[$function->name]['type'])) {
148 $function->type = $functions[$function->name]['type'];
150 if (isset($functions[$function->name]['ajax'])) {
151 $function->allowed_from_ajax = $functions[$function->name]['ajax'];
152 } else if (method_exists($function->classname, $function->ajax_method)) {
153 if (call_user_func(array($function->classname, $function->ajax_method)) === true) {
154 debugging('External function ' . $function->ajax_method . '() function is deprecated.' .
155 'Set ajax=>true in db/service.php instead.', DEBUG_DEVELOPER);
156 $function->allowed_from_ajax = true;
159 if (isset($functions[$function->name]['loginrequired'])) {
160 $function->loginrequired = $functions[$function->name]['loginrequired'];
161 } else {
162 $function->loginrequired = true;
166 return $function;
170 * Call an external function validating all params/returns correctly.
172 * Note that an external function may modify the state of the current page, so this wrapper
173 * saves and restores tha PAGE and COURSE global variables before/after calling the external function.
175 * @param string $function A webservice function name.
176 * @param array $args Params array (named params)
177 * @param boolean $ajaxonly If true, an extra check will be peformed to see if ajax is required.
178 * @return array containing keys for error (bool), exception and data.
180 public static function call_external_function($function, $args, $ajaxonly=false) {
181 global $PAGE, $COURSE, $CFG, $SITE;
183 require_once($CFG->libdir . "/pagelib.php");
185 $externalfunctioninfo = self::external_function_info($function);
187 $currentpage = $PAGE;
188 $currentcourse = $COURSE;
189 $response = array();
191 try {
192 // Taken straight from from setup.php.
193 if (!empty($CFG->moodlepageclass)) {
194 if (!empty($CFG->moodlepageclassfile)) {
195 require_once($CFG->moodlepageclassfile);
197 $classname = $CFG->moodlepageclass;
198 } else {
199 $classname = 'moodle_page';
201 $PAGE = new $classname();
202 $COURSE = clone($SITE);
204 if ($ajaxonly && !$externalfunctioninfo->allowed_from_ajax) {
205 throw new moodle_exception('servicenotavailable', 'webservice');
208 // Do not allow access to write or delete webservices as a public user.
209 if ($externalfunctioninfo->loginrequired) {
210 if (defined('NO_MOODLE_COOKIES') && NO_MOODLE_COOKIES && !PHPUNIT_TEST) {
211 throw new moodle_exception('servicerequireslogin', 'webservice');
213 if (!isloggedin()) {
214 throw new moodle_exception('servicerequireslogin', 'webservice');
215 } else {
216 require_sesskey();
219 // Validate params, this also sorts the params properly, we need the correct order in the next part.
220 $callable = array($externalfunctioninfo->classname, 'validate_parameters');
221 $params = call_user_func($callable,
222 $externalfunctioninfo->parameters_desc,
223 $args);
224 $params = array_values($params);
226 // Allow any Moodle plugin a chance to override this call. This is a convenient spot to
227 // make arbitrary behaviour customisations. The overriding plugin could call the 'real'
228 // function first and then modify the results, or it could do a completely separate
229 // thing.
230 $callbacks = get_plugins_with_function('override_webservice_execution');
231 $result = false;
232 foreach ($callbacks as $plugintype => $plugins) {
233 foreach ($plugins as $plugin => $callback) {
234 $result = $callback($externalfunctioninfo, $params);
235 if ($result !== false) {
236 break;
241 // If the function was not overridden, call the real one.
242 if ($result === false) {
243 $callable = array($externalfunctioninfo->classname, $externalfunctioninfo->methodname);
244 $result = call_user_func_array($callable, $params);
247 // Validate the return parameters.
248 if ($externalfunctioninfo->returns_desc !== null) {
249 $callable = array($externalfunctioninfo->classname, 'clean_returnvalue');
250 $result = call_user_func($callable, $externalfunctioninfo->returns_desc, $result);
253 $response['error'] = false;
254 $response['data'] = $result;
255 } catch (Exception $e) {
256 $exception = get_exception_info($e);
257 unset($exception->a);
258 $exception->backtrace = format_backtrace($exception->backtrace, true);
259 if (!debugging('', DEBUG_DEVELOPER)) {
260 unset($exception->debuginfo);
261 unset($exception->backtrace);
263 $response['error'] = true;
264 $response['exception'] = $exception;
265 // Do not process the remaining requests.
268 $PAGE = $currentpage;
269 $COURSE = $currentcourse;
271 return $response;
275 * Set context restriction for all following subsequent function calls.
277 * @param stdClass $context the context restriction
278 * @since Moodle 2.0
280 public static function set_context_restriction($context) {
281 self::$contextrestriction = $context;
285 * This method has to be called before every operation
286 * that takes a longer time to finish!
288 * @param int $seconds max expected time the next operation needs
289 * @since Moodle 2.0
291 public static function set_timeout($seconds=360) {
292 $seconds = ($seconds < 300) ? 300 : $seconds;
293 core_php_time_limit::raise($seconds);
297 * Validates submitted function parameters, if anything is incorrect
298 * invalid_parameter_exception is thrown.
299 * This is a simple recursive method which is intended to be called from
300 * each implementation method of external API.
302 * @param external_description $description description of parameters
303 * @param mixed $params the actual parameters
304 * @return mixed params with added defaults for optional items, invalid_parameters_exception thrown if any problem found
305 * @since Moodle 2.0
307 public static function validate_parameters(external_description $description, $params) {
308 if ($description instanceof external_value) {
309 if (is_array($params) or is_object($params)) {
310 throw new invalid_parameter_exception('Scalar type expected, array or object received.');
313 if ($description->type == PARAM_BOOL) {
314 // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
315 if (is_bool($params) or $params === 0 or $params === 1 or $params === '0' or $params === '1') {
316 return (bool)$params;
319 $debuginfo = 'Invalid external api parameter: the value is "' . $params .
320 '", the server was expecting "' . $description->type . '" type';
321 return validate_param($params, $description->type, $description->allownull, $debuginfo);
323 } else if ($description instanceof external_single_structure) {
324 if (!is_array($params)) {
325 throw new invalid_parameter_exception('Only arrays accepted. The bad value is: \''
326 . print_r($params, true) . '\'');
328 $result = array();
329 foreach ($description->keys as $key=>$subdesc) {
330 if (!array_key_exists($key, $params)) {
331 if ($subdesc->required == VALUE_REQUIRED) {
332 throw new invalid_parameter_exception('Missing required key in single structure: '. $key);
334 if ($subdesc->required == VALUE_DEFAULT) {
335 try {
336 $result[$key] = static::validate_parameters($subdesc, $subdesc->default);
337 } catch (invalid_parameter_exception $e) {
338 //we are only interested by exceptions returned by validate_param() and validate_parameters()
339 //(in order to build the path to the faulty attribut)
340 throw new invalid_parameter_exception($key." => ".$e->getMessage() . ': ' .$e->debuginfo);
343 } else {
344 try {
345 $result[$key] = static::validate_parameters($subdesc, $params[$key]);
346 } catch (invalid_parameter_exception $e) {
347 //we are only interested by exceptions returned by validate_param() and validate_parameters()
348 //(in order to build the path to the faulty attribut)
349 throw new invalid_parameter_exception($key." => ".$e->getMessage() . ': ' .$e->debuginfo);
352 unset($params[$key]);
354 if (!empty($params)) {
355 throw new invalid_parameter_exception('Unexpected keys (' . implode(', ', array_keys($params)) . ') detected in parameter array.');
357 return $result;
359 } else if ($description instanceof external_multiple_structure) {
360 if (!is_array($params)) {
361 throw new invalid_parameter_exception('Only arrays accepted. The bad value is: \''
362 . print_r($params, true) . '\'');
364 $result = array();
365 foreach ($params as $param) {
366 $result[] = static::validate_parameters($description->content, $param);
368 return $result;
370 } else {
371 throw new invalid_parameter_exception('Invalid external api description');
376 * Clean response
377 * If a response attribute is unknown from the description, we just ignore the attribute.
378 * If a response attribute is incorrect, invalid_response_exception is thrown.
379 * Note: this function is similar to validate parameters, however it is distinct because
380 * parameters validation must be distinct from cleaning return values.
382 * @param external_description $description description of the return values
383 * @param mixed $response the actual response
384 * @return mixed response with added defaults for optional items, invalid_response_exception thrown if any problem found
385 * @author 2010 Jerome Mouneyrac
386 * @since Moodle 2.0
388 public static function clean_returnvalue(external_description $description, $response) {
389 if ($description instanceof external_value) {
390 if (is_array($response) or is_object($response)) {
391 throw new invalid_response_exception('Scalar type expected, array or object received.');
394 if ($description->type == PARAM_BOOL) {
395 // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
396 if (is_bool($response) or $response === 0 or $response === 1 or $response === '0' or $response === '1') {
397 return (bool)$response;
400 $debuginfo = 'Invalid external api response: the value is "' . $response .
401 '", the server was expecting "' . $description->type . '" type';
402 try {
403 return validate_param($response, $description->type, $description->allownull, $debuginfo);
404 } catch (invalid_parameter_exception $e) {
405 //proper exception name, to be recursively catched to build the path to the faulty attribut
406 throw new invalid_response_exception($e->debuginfo);
409 } else if ($description instanceof external_single_structure) {
410 if (!is_array($response) && !is_object($response)) {
411 throw new invalid_response_exception('Only arrays/objects accepted. The bad value is: \'' .
412 print_r($response, true) . '\'');
415 // Cast objects into arrays.
416 if (is_object($response)) {
417 $response = (array) $response;
420 $result = array();
421 foreach ($description->keys as $key=>$subdesc) {
422 if (!array_key_exists($key, $response)) {
423 if ($subdesc->required == VALUE_REQUIRED) {
424 throw new invalid_response_exception('Error in response - Missing following required key in a single structure: ' . $key);
426 if ($subdesc instanceof external_value) {
427 if ($subdesc->required == VALUE_DEFAULT) {
428 try {
429 $result[$key] = static::clean_returnvalue($subdesc, $subdesc->default);
430 } catch (invalid_response_exception $e) {
431 //build the path to the faulty attribut
432 throw new invalid_response_exception($key." => ".$e->getMessage() . ': ' . $e->debuginfo);
436 } else {
437 try {
438 $result[$key] = static::clean_returnvalue($subdesc, $response[$key]);
439 } catch (invalid_response_exception $e) {
440 //build the path to the faulty attribut
441 throw new invalid_response_exception($key." => ".$e->getMessage() . ': ' . $e->debuginfo);
444 unset($response[$key]);
447 return $result;
449 } else if ($description instanceof external_multiple_structure) {
450 if (!is_array($response)) {
451 throw new invalid_response_exception('Only arrays accepted. The bad value is: \'' .
452 print_r($response, true) . '\'');
454 $result = array();
455 foreach ($response as $param) {
456 $result[] = static::clean_returnvalue($description->content, $param);
458 return $result;
460 } else {
461 throw new invalid_response_exception('Invalid external api response description');
466 * Makes sure user may execute functions in this context.
468 * @param stdClass $context
469 * @since Moodle 2.0
471 public static function validate_context($context) {
472 global $CFG, $PAGE;
474 if (empty($context)) {
475 throw new invalid_parameter_exception('Context does not exist');
477 if (empty(self::$contextrestriction)) {
478 self::$contextrestriction = context_system::instance();
480 $rcontext = self::$contextrestriction;
482 if ($rcontext->contextlevel == $context->contextlevel) {
483 if ($rcontext->id != $context->id) {
484 throw new restricted_context_exception();
486 } else if ($rcontext->contextlevel > $context->contextlevel) {
487 throw new restricted_context_exception();
488 } else {
489 $parents = $context->get_parent_context_ids();
490 if (!in_array($rcontext->id, $parents)) {
491 throw new restricted_context_exception();
495 $PAGE->reset_theme_and_output();
496 list($unused, $course, $cm) = get_context_info_array($context->id);
497 require_login($course, false, $cm, false, true);
498 $PAGE->set_context($context);
502 * Get context from passed parameters.
503 * The passed array must either contain a contextid or a combination of context level and instance id to fetch the context.
504 * For example, the context level can be "course" and instanceid can be courseid.
506 * See context_helper::get_all_levels() for a list of valid context levels.
508 * @param array $param
509 * @since Moodle 2.6
510 * @throws invalid_parameter_exception
511 * @return context
513 protected static function get_context_from_params($param) {
514 $levels = context_helper::get_all_levels();
515 if (!empty($param['contextid'])) {
516 return context::instance_by_id($param['contextid'], IGNORE_MISSING);
517 } else if (!empty($param['contextlevel']) && isset($param['instanceid'])) {
518 $contextlevel = "context_".$param['contextlevel'];
519 if (!array_search($contextlevel, $levels)) {
520 throw new invalid_parameter_exception('Invalid context level = '.$param['contextlevel']);
522 return $contextlevel::instance($param['instanceid'], IGNORE_MISSING);
523 } else {
524 // No valid context info was found.
525 throw new invalid_parameter_exception('Missing parameters, please provide either context level with instance id or contextid');
530 * Returns a prepared structure to use a context parameters.
531 * @return external_single_structure
533 protected static function get_context_parameters() {
534 $id = new external_value(
535 PARAM_INT,
536 'Context ID. Either use this value, or level and instanceid.',
537 VALUE_DEFAULT,
540 $level = new external_value(
541 PARAM_ALPHA,
542 'Context level. To be used with instanceid.',
543 VALUE_DEFAULT,
546 $instanceid = new external_value(
547 PARAM_INT,
548 'Context instance ID. To be used with level',
549 VALUE_DEFAULT,
552 return new external_single_structure(array(
553 'contextid' => $id,
554 'contextlevel' => $level,
555 'instanceid' => $instanceid,
562 * Common ancestor of all parameter description classes
564 * @package core_webservice
565 * @copyright 2009 Petr Skodak
566 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
567 * @since Moodle 2.0
569 abstract class external_description {
570 /** @var string Description of element */
571 public $desc;
573 /** @var bool Element value required, null not allowed */
574 public $required;
576 /** @var mixed Default value */
577 public $default;
580 * Contructor
582 * @param string $desc
583 * @param bool $required
584 * @param mixed $default
585 * @since Moodle 2.0
587 public function __construct($desc, $required, $default) {
588 $this->desc = $desc;
589 $this->required = $required;
590 $this->default = $default;
595 * Scalar value description class
597 * @package core_webservice
598 * @copyright 2009 Petr Skodak
599 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
600 * @since Moodle 2.0
602 class external_value extends external_description {
604 /** @var mixed Value type PARAM_XX */
605 public $type;
607 /** @var bool Allow null values */
608 public $allownull;
611 * Constructor
613 * @param mixed $type
614 * @param string $desc
615 * @param bool $required
616 * @param mixed $default
617 * @param bool $allownull
618 * @since Moodle 2.0
620 public function __construct($type, $desc='', $required=VALUE_REQUIRED,
621 $default=null, $allownull=NULL_ALLOWED) {
622 parent::__construct($desc, $required, $default);
623 $this->type = $type;
624 $this->allownull = $allownull;
629 * Associative array description class
631 * @package core_webservice
632 * @copyright 2009 Petr Skodak
633 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
634 * @since Moodle 2.0
636 class external_single_structure extends external_description {
638 /** @var array Description of array keys key=>external_description */
639 public $keys;
642 * Constructor
644 * @param array $keys
645 * @param string $desc
646 * @param bool $required
647 * @param array $default
648 * @since Moodle 2.0
650 public function __construct(array $keys, $desc='',
651 $required=VALUE_REQUIRED, $default=null) {
652 parent::__construct($desc, $required, $default);
653 $this->keys = $keys;
658 * Bulk array description class.
660 * @package core_webservice
661 * @copyright 2009 Petr Skodak
662 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
663 * @since Moodle 2.0
665 class external_multiple_structure extends external_description {
667 /** @var external_description content */
668 public $content;
671 * Constructor
673 * @param external_description $content
674 * @param string $desc
675 * @param bool $required
676 * @param array $default
677 * @since Moodle 2.0
679 public function __construct(external_description $content, $desc='',
680 $required=VALUE_REQUIRED, $default=null) {
681 parent::__construct($desc, $required, $default);
682 $this->content = $content;
687 * Description of top level - PHP function parameters.
689 * @package core_webservice
690 * @copyright 2009 Petr Skodak
691 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
692 * @since Moodle 2.0
694 class external_function_parameters extends external_single_structure {
697 * Constructor - does extra checking to prevent top level optional parameters.
699 * @param array $keys
700 * @param string $desc
701 * @param bool $required
702 * @param array $default
704 public function __construct(array $keys, $desc='', $required=VALUE_REQUIRED, $default=null) {
705 global $CFG;
707 if ($CFG->debugdeveloper) {
708 foreach ($keys as $key => $value) {
709 if ($value instanceof external_value) {
710 if ($value->required == VALUE_OPTIONAL) {
711 debugging('External function parameters: invalid OPTIONAL value specified.', DEBUG_DEVELOPER);
712 break;
717 parent::__construct($keys, $desc, $required, $default);
722 * Generate a token
724 * @param string $tokentype EXTERNAL_TOKEN_EMBEDDED|EXTERNAL_TOKEN_PERMANENT
725 * @param stdClass|int $serviceorid service linked to the token
726 * @param int $userid user linked to the token
727 * @param stdClass|int $contextorid
728 * @param int $validuntil date when the token expired
729 * @param string $iprestriction allowed ip - if 0 or empty then all ips are allowed
730 * @return string generated token
731 * @author 2010 Jamie Pratt
732 * @since Moodle 2.0
734 function external_generate_token($tokentype, $serviceorid, $userid, $contextorid, $validuntil=0, $iprestriction=''){
735 global $DB, $USER;
736 // make sure the token doesn't exist (even if it should be almost impossible with the random generation)
737 $numtries = 0;
738 do {
739 $numtries ++;
740 $generatedtoken = md5(uniqid(rand(),1));
741 if ($numtries > 5){
742 throw new moodle_exception('tokengenerationfailed');
744 } while ($DB->record_exists('external_tokens', array('token'=>$generatedtoken)));
745 $newtoken = new stdClass();
746 $newtoken->token = $generatedtoken;
747 if (!is_object($serviceorid)){
748 $service = $DB->get_record('external_services', array('id' => $serviceorid));
749 } else {
750 $service = $serviceorid;
752 if (!is_object($contextorid)){
753 $context = context::instance_by_id($contextorid, MUST_EXIST);
754 } else {
755 $context = $contextorid;
757 if (empty($service->requiredcapability) || has_capability($service->requiredcapability, $context, $userid)) {
758 $newtoken->externalserviceid = $service->id;
759 } else {
760 throw new moodle_exception('nocapabilitytousethisservice');
762 $newtoken->tokentype = $tokentype;
763 $newtoken->userid = $userid;
764 if ($tokentype == EXTERNAL_TOKEN_EMBEDDED){
765 $newtoken->sid = session_id();
768 $newtoken->contextid = $context->id;
769 $newtoken->creatorid = $USER->id;
770 $newtoken->timecreated = time();
771 $newtoken->validuntil = $validuntil;
772 if (!empty($iprestriction)) {
773 $newtoken->iprestriction = $iprestriction;
775 $newtoken->privatetoken = null;
776 $DB->insert_record('external_tokens', $newtoken);
777 return $newtoken->token;
781 * Create and return a session linked token. Token to be used for html embedded client apps that want to communicate
782 * with the Moodle server through web services. The token is linked to the current session for the current page request.
783 * It is expected this will be called in the script generating the html page that is embedding the client app and that the
784 * returned token will be somehow passed into the client app being embedded in the page.
786 * @param string $servicename name of the web service. Service name as defined in db/services.php
787 * @param int $context context within which the web service can operate.
788 * @return int returns token id.
789 * @since Moodle 2.0
791 function external_create_service_token($servicename, $context){
792 global $USER, $DB;
793 $service = $DB->get_record('external_services', array('name'=>$servicename), '*', MUST_EXIST);
794 return external_generate_token(EXTERNAL_TOKEN_EMBEDDED, $service, $USER->id, $context, 0);
798 * Delete all pre-built services (+ related tokens) and external functions information defined in the specified component.
800 * @param string $component name of component (moodle, mod_assignment, etc.)
802 function external_delete_descriptions($component) {
803 global $DB;
805 $params = array($component);
807 $DB->delete_records_select('external_tokens',
808 "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
809 $DB->delete_records_select('external_services_users',
810 "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
811 $DB->delete_records_select('external_services_functions',
812 "functionname IN (SELECT name FROM {external_functions} WHERE component = ?)", $params);
813 $DB->delete_records('external_services', array('component'=>$component));
814 $DB->delete_records('external_functions', array('component'=>$component));
818 * Standard Moodle web service warnings
820 * @package core_webservice
821 * @copyright 2012 Jerome Mouneyrac
822 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
823 * @since Moodle 2.3
825 class external_warnings extends external_multiple_structure {
828 * Constructor
830 * @since Moodle 2.3
832 public function __construct($itemdesc = 'item', $itemiddesc = 'item id',
833 $warningcodedesc = 'the warning code can be used by the client app to implement specific behaviour') {
835 parent::__construct(
836 new external_single_structure(
837 array(
838 'item' => new external_value(PARAM_TEXT, $itemdesc, VALUE_OPTIONAL),
839 'itemid' => new external_value(PARAM_INT, $itemiddesc, VALUE_OPTIONAL),
840 'warningcode' => new external_value(PARAM_ALPHANUM, $warningcodedesc),
841 'message' => new external_value(PARAM_TEXT,
842 'untranslated english message to explain the warning')
843 ), 'warning'),
844 'list of warnings', VALUE_OPTIONAL);
849 * A pre-filled external_value class for text format.
851 * Default is FORMAT_HTML
852 * This should be used all the time in external xxx_params()/xxx_returns functions
853 * as it is the standard way to implement text format param/return values.
855 * @package core_webservice
856 * @copyright 2012 Jerome Mouneyrac
857 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
858 * @since Moodle 2.3
860 class external_format_value extends external_value {
863 * Constructor
865 * @param string $textfieldname Name of the text field
866 * @param int $required if VALUE_REQUIRED then set standard default FORMAT_HTML
867 * @param int $default Default value.
868 * @since Moodle 2.3
870 public function __construct($textfieldname, $required = VALUE_REQUIRED, $default = null) {
872 if ($default == null && $required == VALUE_DEFAULT) {
873 $default = FORMAT_HTML;
876 $desc = $textfieldname . ' format (' . FORMAT_HTML . ' = HTML, '
877 . FORMAT_MOODLE . ' = MOODLE, '
878 . FORMAT_PLAIN . ' = PLAIN or '
879 . FORMAT_MARKDOWN . ' = MARKDOWN)';
881 parent::__construct(PARAM_INT, $desc, $required, $default);
886 * Validate text field format against known FORMAT_XXX
888 * @param array $format the format to validate
889 * @return the validated format
890 * @throws coding_exception
891 * @since Moodle 2.3
893 function external_validate_format($format) {
894 $allowedformats = array(FORMAT_HTML, FORMAT_MOODLE, FORMAT_PLAIN, FORMAT_MARKDOWN);
895 if (!in_array($format, $allowedformats)) {
896 throw new moodle_exception('formatnotsupported', 'webservice', '' , null,
897 'The format with value=' . $format . ' is not supported by this Moodle site');
899 return $format;
903 * Format the string to be returned properly as requested by the either the web service server,
904 * either by an internally call.
905 * The caller can change the format (raw) with the external_settings singleton
906 * All web service servers must set this singleton when parsing the $_GET and $_POST.
908 * <pre>
909 * Options are the same that in {@link format_string()} with some changes:
910 * filter : Can be set to false to force filters off, else observes {@link external_settings}.
911 * </pre>
913 * @param string $str The string to be filtered. Should be plain text, expect
914 * possibly for multilang tags.
915 * @param boolean $striplinks To strip any link in the result text. Moodle 1.8 default changed from false to true! MDL-8713
916 * @param context|int $contextorid The id of the context for the string or the context (affects filters).
917 * @param array $options options array/object or courseid
918 * @return string text
919 * @since Moodle 3.0
921 function external_format_string($str, $contextorid, $striplinks = true, $options = array()) {
923 // Get settings (singleton).
924 $settings = external_settings::get_instance();
925 if (empty($contextorid)) {
926 throw new coding_exception('contextid is required');
929 if (!$settings->get_raw()) {
930 if (is_object($contextorid) && is_a($contextorid, 'context')) {
931 $context = $contextorid;
932 } else {
933 $context = context::instance_by_id($contextorid);
935 $options['context'] = $context;
936 $options['filter'] = isset($options['filter']) && !$options['filter'] ? false : $settings->get_filter();
937 $str = format_string($str, $striplinks, $options);
940 return $str;
944 * Format the text to be returned properly as requested by the either the web service server,
945 * either by an internally call.
946 * The caller can change the format (raw, filter, file, fileurl) with the external_settings singleton
947 * All web service servers must set this singleton when parsing the $_GET and $_POST.
949 * <pre>
950 * Options are the same that in {@link format_text()} with some changes in defaults to provide backwards compatibility:
951 * trusted : If true the string won't be cleaned. Default false.
952 * noclean : If true the string won't be cleaned only if trusted is also true. Default false.
953 * nocache : If true the string will not be cached and will be formatted every call. Default false.
954 * filter : Can be set to false to force filters off, else observes {@link external_settings}.
955 * para : If true then the returned string will be wrapped in div tags. Default (different from format_text) false.
956 * Default changed because div tags are not commonly needed.
957 * newlines : If true then lines newline breaks will be converted to HTML newline breaks. Default true.
958 * context : Not used! Using contextid parameter instead.
959 * overflowdiv : If set to true the formatted text will be encased in a div with the class no-overflow before being
960 * returned. Default false.
961 * allowid : If true then id attributes will not be removed, even when using htmlpurifier. Default (different from
962 * format_text) true. Default changed id attributes are commonly needed.
963 * blanktarget : If true all <a> tags will have target="_blank" added unless target is explicitly specified.
964 * </pre>
966 * @param string $text The content that may contain ULRs in need of rewriting.
967 * @param int $textformat The text format.
968 * @param context|int $contextorid This parameter and the next two identify the file area to use.
969 * @param string $component
970 * @param string $filearea helps identify the file area.
971 * @param int $itemid helps identify the file area.
972 * @param object/array $options text formatting options
973 * @return array text + textformat
974 * @since Moodle 2.3
975 * @since Moodle 3.2 component, filearea and itemid are optional parameters
977 function external_format_text($text, $textformat, $contextorid, $component = null, $filearea = null, $itemid = null,
978 $options = null) {
979 global $CFG;
981 // Get settings (singleton).
982 $settings = external_settings::get_instance();
984 if (is_object($contextorid) && is_a($contextorid, 'context')) {
985 $context = $contextorid;
986 $contextid = $context->id;
987 } else {
988 $context = null;
989 $contextid = $contextorid;
992 if ($component and $filearea and $settings->get_fileurl()) {
993 require_once($CFG->libdir . "/filelib.php");
994 $text = file_rewrite_pluginfile_urls($text, $settings->get_file(), $contextid, $component, $filearea, $itemid);
997 // Note that $CFG->forceclean does not apply here if the client requests for the raw database content.
998 // This is consistent with web clients that are still able to load non-cleaned text into editors, too.
1000 if (!$settings->get_raw()) {
1001 $options = (array)$options;
1003 // If context is passed in options, check that is the same to show a debug message.
1004 if (isset($options['context'])) {
1005 if ((is_object($options['context']) && $options['context']->id != $contextid)
1006 || (!is_object($options['context']) && $options['context'] != $contextid)) {
1007 debugging('Different contexts found in external_format_text parameters. $options[\'context\'] not allowed.
1008 Using $contextid parameter...', DEBUG_DEVELOPER);
1012 $options['filter'] = isset($options['filter']) && !$options['filter'] ? false : $settings->get_filter();
1013 $options['para'] = isset($options['para']) ? $options['para'] : false;
1014 $options['context'] = !is_null($context) ? $context : context::instance_by_id($contextid);
1015 $options['allowid'] = isset($options['allowid']) ? $options['allowid'] : true;
1017 $text = format_text($text, $textformat, $options);
1018 $textformat = FORMAT_HTML; // Once converted to html (from markdown, plain... lets inform consumer this is already HTML).
1021 return array($text, $textformat);
1025 * Generate or return an existing token for the current authenticated user.
1026 * This function is used for creating a valid token for users authenticathing via login/token.php or admin/tool/mobile/launch.php.
1028 * @param stdClass $service external service object
1029 * @return stdClass token object
1030 * @since Moodle 3.2
1031 * @throws moodle_exception
1033 function external_generate_token_for_current_user($service) {
1034 global $DB, $USER, $CFG;
1036 core_user::require_active_user($USER, true, true);
1038 // Check if there is any required system capability.
1039 if ($service->requiredcapability and !has_capability($service->requiredcapability, context_system::instance())) {
1040 throw new moodle_exception('missingrequiredcapability', 'webservice', '', $service->requiredcapability);
1043 // Specific checks related to user restricted service.
1044 if ($service->restrictedusers) {
1045 $authoriseduser = $DB->get_record('external_services_users',
1046 array('externalserviceid' => $service->id, 'userid' => $USER->id));
1048 if (empty($authoriseduser)) {
1049 throw new moodle_exception('usernotallowed', 'webservice', '', $service->shortname);
1052 if (!empty($authoriseduser->validuntil) and $authoriseduser->validuntil < time()) {
1053 throw new moodle_exception('invalidtimedtoken', 'webservice');
1056 if (!empty($authoriseduser->iprestriction) and !address_in_subnet(getremoteaddr(), $authoriseduser->iprestriction)) {
1057 throw new moodle_exception('invalidiptoken', 'webservice');
1061 // Check if a token has already been created for this user and this service.
1062 $conditions = array(
1063 'userid' => $USER->id,
1064 'externalserviceid' => $service->id,
1065 'tokentype' => EXTERNAL_TOKEN_PERMANENT
1067 $tokens = $DB->get_records('external_tokens', $conditions, 'timecreated ASC');
1069 // A bit of sanity checks.
1070 foreach ($tokens as $key => $token) {
1072 // Checks related to a specific token. (script execution continue).
1073 $unsettoken = false;
1074 // If sid is set then there must be a valid associated session no matter the token type.
1075 if (!empty($token->sid)) {
1076 if (!\core\session\manager::session_exists($token->sid)) {
1077 // This token will never be valid anymore, delete it.
1078 $DB->delete_records('external_tokens', array('sid' => $token->sid));
1079 $unsettoken = true;
1083 // Remove token is not valid anymore.
1084 if (!empty($token->validuntil) and $token->validuntil < time()) {
1085 $DB->delete_records('external_tokens', array('token' => $token->token, 'tokentype' => EXTERNAL_TOKEN_PERMANENT));
1086 $unsettoken = true;
1089 // Remove token if its ip not in whitelist.
1090 if (isset($token->iprestriction) and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
1091 $unsettoken = true;
1094 if ($unsettoken) {
1095 unset($tokens[$key]);
1099 // If some valid tokens exist then use the most recent.
1100 if (count($tokens) > 0) {
1101 $token = array_pop($tokens);
1102 } else {
1103 $context = context_system::instance();
1104 $isofficialservice = $service->shortname == MOODLE_OFFICIAL_MOBILE_SERVICE;
1106 if (($isofficialservice and has_capability('moodle/webservice:createmobiletoken', $context)) or
1107 (!is_siteadmin($USER) && has_capability('moodle/webservice:createtoken', $context))) {
1109 // Create a new token.
1110 $token = new stdClass;
1111 $token->token = md5(uniqid(rand(), 1));
1112 $token->userid = $USER->id;
1113 $token->tokentype = EXTERNAL_TOKEN_PERMANENT;
1114 $token->contextid = context_system::instance()->id;
1115 $token->creatorid = $USER->id;
1116 $token->timecreated = time();
1117 $token->externalserviceid = $service->id;
1118 // By default tokens are valid for 12 weeks.
1119 $token->validuntil = $token->timecreated + $CFG->tokenduration;
1120 $token->iprestriction = null;
1121 $token->sid = null;
1122 $token->lastaccess = null;
1123 // Generate the private token, it must be transmitted only via https.
1124 $token->privatetoken = random_string(64);
1125 $token->id = $DB->insert_record('external_tokens', $token);
1127 $eventtoken = clone $token;
1128 $eventtoken->privatetoken = null;
1129 $params = array(
1130 'objectid' => $eventtoken->id,
1131 'relateduserid' => $USER->id,
1132 'other' => array(
1133 'auto' => true
1136 $event = \core\event\webservice_token_created::create($params);
1137 $event->add_record_snapshot('external_tokens', $eventtoken);
1138 $event->trigger();
1139 } else {
1140 throw new moodle_exception('cannotcreatetoken', 'webservice', '', $service->shortname);
1143 return $token;
1147 * Set the last time a token was sent and trigger the \core\event\webservice_token_sent event.
1149 * This function is used when a token is generated by the user via login/token.php or admin/tool/mobile/launch.php.
1150 * In order to protect the privatetoken, we remove it from the event params.
1152 * @param stdClass $token token object
1153 * @since Moodle 3.2
1155 function external_log_token_request($token) {
1156 global $DB;
1158 $token->privatetoken = null;
1160 // Log token access.
1161 $DB->set_field('external_tokens', 'lastaccess', time(), array('id' => $token->id));
1163 $params = array(
1164 'objectid' => $token->id,
1166 $event = \core\event\webservice_token_sent::create($params);
1167 $event->add_record_snapshot('external_tokens', $token);
1168 $event->trigger();
1172 * Singleton to handle the external settings.
1174 * We use singleton to encapsulate the "logic"
1176 * @package core_webservice
1177 * @copyright 2012 Jerome Mouneyrac
1178 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1179 * @since Moodle 2.3
1181 class external_settings {
1183 /** @var object the singleton instance */
1184 public static $instance = null;
1186 /** @var boolean Should the external function return raw text or formatted */
1187 private $raw = false;
1189 /** @var boolean Should the external function filter the text */
1190 private $filter = false;
1192 /** @var boolean Should the external function rewrite plugin file url */
1193 private $fileurl = true;
1195 /** @var string In which file should the urls be rewritten */
1196 private $file = 'webservice/pluginfile.php';
1198 /** @var string The session lang */
1199 private $lang = '';
1202 * Constructor - protected - can not be instanciated
1204 protected function __construct() {
1205 if ((AJAX_SCRIPT == false) && (CLI_SCRIPT == false) && (WS_SERVER == false)) {
1206 // For normal pages, the default should match the default for format_text.
1207 $this->filter = true;
1208 // Use pluginfile.php for web requests.
1209 $this->file = 'pluginfile.php';
1214 * Clone - private - can not be cloned
1216 private final function __clone() {
1220 * Return only one instance
1222 * @return \external_settings
1224 public static function get_instance() {
1225 if (self::$instance === null) {
1226 self::$instance = new external_settings;
1229 return self::$instance;
1233 * Set raw
1235 * @param boolean $raw
1237 public function set_raw($raw) {
1238 $this->raw = $raw;
1242 * Get raw
1244 * @return boolean
1246 public function get_raw() {
1247 return $this->raw;
1251 * Set filter
1253 * @param boolean $filter
1255 public function set_filter($filter) {
1256 $this->filter = $filter;
1260 * Get filter
1262 * @return boolean
1264 public function get_filter() {
1265 return $this->filter;
1269 * Set fileurl
1271 * @param boolean $fileurl
1273 public function set_fileurl($fileurl) {
1274 $this->fileurl = $fileurl;
1278 * Get fileurl
1280 * @return boolean
1282 public function get_fileurl() {
1283 return $this->fileurl;
1287 * Set file
1289 * @param string $file
1291 public function set_file($file) {
1292 $this->file = $file;
1296 * Get file
1298 * @return string
1300 public function get_file() {
1301 return $this->file;
1305 * Set lang
1307 * @param string $lang
1309 public function set_lang($lang) {
1310 $this->lang = $lang;
1314 * Get lang
1316 * @return string
1318 public function get_lang() {
1319 return $this->lang;
1324 * Utility functions for the external API.
1326 * @package core_webservice
1327 * @copyright 2015 Juan Leyva
1328 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1329 * @since Moodle 3.0
1331 class external_util {
1334 * Validate a list of courses, returning the complete course objects for valid courses.
1336 * @param array $courseids A list of course ids
1337 * @param array $courses An array of courses already pre-fetched, indexed by course id.
1338 * @param bool $addcontext True if the returned course object should include the full context object.
1339 * @return array An array of courses and the validation warnings
1341 public static function validate_courses($courseids, $courses = array(), $addcontext = false) {
1342 // Delete duplicates.
1343 $courseids = array_unique($courseids);
1344 $warnings = array();
1346 // Remove courses which are not even requested.
1347 $courses = array_intersect_key($courses, array_flip($courseids));
1349 foreach ($courseids as $cid) {
1350 // Check the user can function in this context.
1351 try {
1352 $context = context_course::instance($cid);
1353 external_api::validate_context($context);
1355 if (!isset($courses[$cid])) {
1356 $courses[$cid] = get_course($cid);
1358 if ($addcontext) {
1359 $courses[$cid]->context = $context;
1361 } catch (Exception $e) {
1362 unset($courses[$cid]);
1363 $warnings[] = array(
1364 'item' => 'course',
1365 'itemid' => $cid,
1366 'warningcode' => '1',
1367 'message' => 'No access rights in course context'
1372 return array($courses, $warnings);
1376 * Returns all area files (optionally limited by itemid).
1378 * @param int $contextid context ID
1379 * @param string $component component
1380 * @param string $filearea file area
1381 * @param int $itemid item ID or all files if not specified
1382 * @param bool $useitemidinurl wether to use the item id in the file URL (modules intro don't use it)
1383 * @return array of files, compatible with the external_files structure.
1384 * @since Moodle 3.2
1386 public static function get_area_files($contextid, $component, $filearea, $itemid = false, $useitemidinurl = true) {
1387 $files = array();
1388 $fs = get_file_storage();
1390 if ($areafiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'itemid, filepath, filename', false)) {
1391 foreach ($areafiles as $areafile) {
1392 $file = array();
1393 $file['filename'] = $areafile->get_filename();
1394 $file['filepath'] = $areafile->get_filepath();
1395 $file['mimetype'] = $areafile->get_mimetype();
1396 $file['filesize'] = $areafile->get_filesize();
1397 $file['timemodified'] = $areafile->get_timemodified();
1398 $file['isexternalfile'] = $areafile->is_external_file();
1399 if ($file['isexternalfile']) {
1400 $file['repositorytype'] = $areafile->get_repository_type();
1402 $fileitemid = $useitemidinurl ? $areafile->get_itemid() : null;
1403 $file['fileurl'] = moodle_url::make_webservice_pluginfile_url($contextid, $component, $filearea,
1404 $fileitemid, $areafile->get_filepath(), $areafile->get_filename())->out(false);
1405 $files[] = $file;
1408 return $files;
1413 * External structure representing a set of files.
1415 * @package core_webservice
1416 * @copyright 2016 Juan Leyva
1417 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1418 * @since Moodle 3.2
1420 class external_files extends external_multiple_structure {
1423 * Constructor
1424 * @param string $desc Description for the multiple structure.
1425 * @param int $required The type of value (VALUE_REQUIRED OR VALUE_OPTIONAL).
1427 public function __construct($desc = 'List of files.', $required = VALUE_REQUIRED) {
1429 parent::__construct(
1430 new external_single_structure(
1431 array(
1432 'filename' => new external_value(PARAM_FILE, 'File name.', VALUE_OPTIONAL),
1433 'filepath' => new external_value(PARAM_PATH, 'File path.', VALUE_OPTIONAL),
1434 'filesize' => new external_value(PARAM_INT, 'File size.', VALUE_OPTIONAL),
1435 'fileurl' => new external_value(PARAM_URL, 'Downloadable file url.', VALUE_OPTIONAL),
1436 'timemodified' => new external_value(PARAM_INT, 'Time modified.', VALUE_OPTIONAL),
1437 'mimetype' => new external_value(PARAM_RAW, 'File mime type.', VALUE_OPTIONAL),
1438 'isexternalfile' => new external_value(PARAM_BOOL, 'Whether is an external file.', VALUE_OPTIONAL),
1439 'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for external files.', VALUE_OPTIONAL),
1441 'File.'
1443 $desc,
1444 $required
1449 * Return the properties ready to be used by an exporter.
1451 * @return array properties
1452 * @since Moodle 3.3
1454 public static function get_properties_for_exporter() {
1455 return [
1456 'filename' => array(
1457 'type' => PARAM_FILE,
1458 'description' => 'File name.',
1459 'optional' => true,
1460 'null' => NULL_NOT_ALLOWED,
1462 'filepath' => array(
1463 'type' => PARAM_PATH,
1464 'description' => 'File path.',
1465 'optional' => true,
1466 'null' => NULL_NOT_ALLOWED,
1468 'filesize' => array(
1469 'type' => PARAM_INT,
1470 'description' => 'File size.',
1471 'optional' => true,
1472 'null' => NULL_NOT_ALLOWED,
1474 'fileurl' => array(
1475 'type' => PARAM_URL,
1476 'description' => 'Downloadable file url.',
1477 'optional' => true,
1478 'null' => NULL_NOT_ALLOWED,
1480 'timemodified' => array(
1481 'type' => PARAM_INT,
1482 'description' => 'Time modified.',
1483 'optional' => true,
1484 'null' => NULL_NOT_ALLOWED,
1486 'mimetype' => array(
1487 'type' => PARAM_RAW,
1488 'description' => 'File mime type.',
1489 'optional' => true,
1490 'null' => NULL_NOT_ALLOWED,
1492 'isexternalfile' => array(
1493 'type' => PARAM_BOOL,
1494 'description' => 'Whether is an external file.',
1495 'optional' => true,
1496 'null' => NULL_NOT_ALLOWED,
1498 'repositorytype' => array(
1499 'type' => PARAM_PLUGIN,
1500 'description' => 'The repository type for the external files.',
1501 'optional' => true,
1502 'null' => NULL_ALLOWED,